Skip to content

Commit

Permalink
More and better testing for types
Browse files Browse the repository at this point in the history
  • Loading branch information
tjayrush committed Jan 6, 2025
1 parent 6f782fe commit b09b8ec
Show file tree
Hide file tree
Showing 9 changed files with 251 additions and 178 deletions.
5 changes: 2 additions & 3 deletions pkg/config/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import (
)

func TestConfigMustLoad(t *testing.T) {
var configFile string
defer types.SetupTestOld(t, &configFile, types.GetConfigFn, types.EstablishConfig)()
assert.FileExists(t, configFile)
defer types.SetupTest([]string{})()
assert.FileExists(t, types.GetConfigFn())
}

func TestConfigMustLoadDefaults(t *testing.T) {
Expand Down
79 changes: 16 additions & 63 deletions pkg/types/chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,19 @@ package types
import (
"os"
"testing"

coreFile "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
"github.com/knadh/koanf/maps"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
yamlv2 "gopkg.in/yaml.v2"
"github.com/stretchr/testify/assert"
)

func TestChainNewChain(t *testing.T) {
c := NewChain("TestChain")

expectedName := "TestChain"
if c.Name != expectedName {
t.Errorf("Expected Name to be '%s', got '%s'", expectedName, c.Name)
}
assert.Equal(t, expectedName, c.Name, "Expected Name to be '%s', got '%s'", expectedName, c.Name)

expectedRPCs := []string{"http://localhost:8545"}
if len(c.RPCs) != len(expectedRPCs) || c.RPCs[0] != expectedRPCs[0] {
t.Errorf("Expected RPCs to be '%v', got '%v'", expectedRPCs, c.RPCs)
}
assert.Equal(t, expectedRPCs, c.RPCs, "Expected RPCs to be '%v', got '%v'", expectedRPCs, c.RPCs)

if !c.Enabled {
t.Errorf("Expected Enabled to be true, got %v", c.Enabled)
}
assert.True(t, c.Enabled, "Expected Enabled to be true, got %v", c.Enabled)
}

func TestChainValidation(t *testing.T) {
Expand Down Expand Up @@ -97,19 +85,19 @@ func TestChainValidation(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Validate.Struct(tt.chain)
checkValidationErrors(t, tt.name, err, tt.wantErr)
if tt.wantErr {
assert.Error(t, err, "Expected error for test case '%s'", tt.name)
} else {
assert.NoError(t, err, "Did not expect error for test case '%s'", tt.name)
}
})
}
}

func TestChainValidation2(t *testing.T) {
os.Setenv("TEST_MODE", "true")
invalidChain := Chain{}

err := Validate.Struct(invalidChain)
if err == nil {
t.Errorf("Expected validation error for missing Name and RPCs, got nil")
}
assert.Error(t, err, "Expected validation error for missing Name and RPCs, got nil")

validChain := Chain{
Name: "ValidChain",
Expand All @@ -118,58 +106,23 @@ func TestChainValidation2(t *testing.T) {
}

err = Validate.Struct(validChain)
if err != nil {
t.Errorf("Expected no validation error, but got: %s", err)
}
assert.NoError(t, err, "Expected no validation error, but got: %s", err)
}

func TestChainReadAndWrite(t *testing.T) {
tempFilePath := "temp_chain_config.yaml"
defer os.Remove(tempFilePath)

content := `
name: "TestChain"
rpcs:
- "http://localhost:8545"
enabled: true
`
err := coreFile.StringToAsciiFile(tempFilePath, content)
if err != nil {
t.Fatalf("Failed to write temporary file: %s", err)
}

k := koanf.New(".")
err = k.Load(file.Provider(tempFilePath), yaml.Parser())
if err != nil {
t.Fatalf("Failed to load configuration using koanf: %s", err)
assertions := func(t *testing.T, chain *Chain) {
assert.Equal(t, "TestChain", chain.Name, "Expected name to be 'TestChain', got '%s'", chain.Name)
assert.Equal(t, []string{"http://localhost:8545"}, chain.RPCs, "Expected RPCs to contain 'http://localhost:8545', got '%v'", chain.RPCs)
assert.True(t, chain.Enabled, "Expected enabled to be true, got %v", chain.Enabled)
}

name := k.String("name")
if name != "TestChain" {
t.Errorf("Expected name to be 'TestChain', got '%s'", name)
}

rpcs := k.Strings("rpcs")
if len(rpcs) != 1 || rpcs[0] != "http://localhost:8545" {
t.Errorf("Expected RPCs to contain 'http://localhost:8545', got '%v'", rpcs)
}

enabled := k.Bool("enabled")
if !enabled {
t.Errorf("Expected enabled to be true, got %v", enabled)
}

output := maps.Unflatten(k.All(), ".")
outputFilePath := "output_chain_config.yaml"
defer os.Remove(outputFilePath)

yamlContent, err := yamlv2.Marshal(output)
if err != nil {
t.Fatalf("Failed to marshal config to YAML: %s", err)
}

err = coreFile.StringToAsciiFile(outputFilePath, string(yamlContent))
if err != nil {
t.Fatalf("Failed to write output file: %s", err)
}
ReadAndWriteTest[Chain](t, tempFilePath, content, assertions)
}
1 change: 1 addition & 0 deletions pkg/types/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ func TestConfigEstablish(t *testing.T) {
assert.True(t, created)
assert.FileExists(t, configFile)
}

67 changes: 20 additions & 47 deletions pkg/types/general_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,22 @@ package types

import (
"fmt"
"os"
"testing"

coreFile "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
"github.com/knadh/koanf/maps"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
yamlv2 "gopkg.in/yaml.v2"
"github.com/stretchr/testify/assert"
)

// TestGeneralNew tests the initialization of the General type to ensure it is
// created correctly with valid default or input values.
func TestGeneralNew(t *testing.T) {
defer SetTestEnv([]string{"TEST_MODE=true"})()
g := NewGeneral()
expected := "~/.khedra/data"
if g.DataDir != expected {
t.Errorf("Expected DataDir to be '%s', got '%s'", expected, g.DataDir)
}
assert.Equal(t, expected, g.DataDir, "Expected DataDir to be '%s', got '%s'", expected, g.DataDir)
}

// TestGeneralValidation validates the functionality of the General type to ensure
// that invalid data is caught and proper validation rules are applied.
func TestGeneralValidation(t *testing.T) {
defer SetTestEnv([]string{"TEST_MODE=true"})()
tests := []struct {
Expand Down Expand Up @@ -62,60 +58,37 @@ func TestGeneralValidation(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Validate.Struct(tt.general)
checkValidationErrors(t, tt.name, err, tt.wantErr)
if tt.wantErr {
assert.Error(t, err, "Expected error for test case '%s'", tt.name)
} else {
assert.NoError(t, err, "Did not expect error for test case '%s'", tt.name)
}
fmt.Println()
})
}

invalidGeneral := General{}
err := Validate.Struct(invalidGeneral)
if err == nil {
t.Errorf("Expected validation error for missing DataDir, got nil")
}
assert.Error(t, err, "Expected validation error for missing DataDir, got nil")

validGeneral := General{
DataDir: "/valid/path",
}
err = Validate.Struct(validGeneral)
if err != nil {
t.Errorf("Expected no validation error, but got: %s", err)
}
assert.NoError(t, err, "Expected no validation error, but got: %s", err)
}

func TestReadAndWrite(t *testing.T) {
// TestGeneralReadAndWrite tests the reading and writing operations of the General type
// to confirm accurate data handling and storage.
func TestGeneralReadAndWrite(t *testing.T) {
tempFilePath := "temp_config.yaml"
defer os.Remove(tempFilePath)

content := `
data_dir: "/tmp/khedra/data"
data_dir: "expected/folder/name"
`
err := coreFile.StringToAsciiFile(tempFilePath, content)
if err != nil {
t.Fatalf("Failed to write temporary file: %s", err)
}

k := koanf.New(".")
err = k.Load(file.Provider(tempFilePath), yaml.Parser())
if err != nil {
t.Fatalf("Failed to load configuration using koanf: %s", err)
assertions := func(t *testing.T, general *General) {
assert.Equal(t, "expected/folder/name", general.DataDir, "Expected data_dir to be 'expected/folder/name', got '%s'", general.DataDir)
}

dataDir := k.String("data_dir")
if dataDir != "/tmp/khedra/data" {
t.Errorf("Expected data_dir to be '/tmp/khedra/data', got '%s'", dataDir)
}

output := maps.Unflatten(k.All(), ".")
outputFilePath := "output_config.yaml"
defer os.Remove(outputFilePath)

yamlContent, err := yamlv2.Marshal(output)
if err != nil {
t.Fatalf("Failed to marshal config to YAML: %s", err)
}

err = coreFile.StringToAsciiFile(outputFilePath, string(yamlContent))
if err != nil {
t.Fatalf("Failed to write output file: %s", err)
}
ReadAndWriteTest[General](t, tempFilePath, content, assertions)
}
33 changes: 31 additions & 2 deletions pkg/types/logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,37 @@ func TestLoggingValidation(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Validate.Struct(tt.logging) // or any struct being validated
checkValidationErrors(t, tt.name, err, tt.wantErr)
err := Validate.Struct(tt.logging)
if tt.wantErr {
assert.Error(t, err, "Expected error for test case '%s'", tt.name)
} else {
assert.NoError(t, err, "Did not expect error for test case '%s'", tt.name)
}
})
}
}

func TestLoggingReadAndWrite(t *testing.T) {
tempFilePath := "temp_config.yaml"
content := `
folder: ~/.khedra/logs
filename: khedra.log
log_level: debug
max_size_mb: 10
max_backups: 3
max_age_days: 10
compress: true
`

assertions := func(t *testing.T, logging *Logging) {
assert.Equal(t, "~/.khedra/logs", logging.Folder, "Folder should match the expected value")
assert.Equal(t, "khedra.log", logging.Filename, "Filename should match the expected value")
assert.Equal(t, "debug", logging.LogLevel, "LogLevel should match the expected value")
assert.Equal(t, 10, logging.MaxSizeMb, "MaxSizeMb should match the expected value")
assert.Equal(t, 3, logging.MaxBackups, "MaxBackups should match the expected value")
assert.Equal(t, 10, logging.MaxAgeDays, "MaxAgeDays should match the expected value")
assert.True(t, logging.Compress, "Compress should be true")
}

ReadAndWriteTest[Logging](t, tempFilePath, content, assertions)
}
4 changes: 1 addition & 3 deletions pkg/types/service.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package types

import "log"

type Service struct {
Name string `koanf:"name" validate:"required,oneof=api scraper monitor ipfs"`
Enabled bool `koanf:"enabled"`
Expand Down Expand Up @@ -40,6 +38,6 @@ func NewService(serviceType string) Service {
}
}

log.Fatal("Unknown service type: ", serviceType)
panic("Unknown service type: " + serviceType)
return Service{}
}
Loading

0 comments on commit b09b8ec

Please sign in to comment.