Skip to content

Commit

Permalink
Add unittests
Browse files Browse the repository at this point in the history
  • Loading branch information
hatrx committed Sep 26, 2024
1 parent 9198125 commit 5b42b38
Show file tree
Hide file tree
Showing 8 changed files with 1,385 additions and 2 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,5 @@ go build cmd/webhook/
[tidydns-go](https://github.com/neticdk/tidydns-go) instead of the local
tidydns package
- So far the record types are A, AAAA and CNAME
- Needs some unit tests
- More GitHub actions
- Unit tests
- Relase pipeline
77 changes: 77 additions & 0 deletions cmd/webhook/logging_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

import (
"bytes"
"testing"
)

func TestLoggingSetup(t *testing.T) {
tests := []struct {
name string
logFormat string
logLevel string
addSource bool
expectErr bool
expectText string
}{
{
name: "JSON format with info level",
logFormat: "json",
logLevel: "info",
addSource: false,
expectErr: false,
expectText: `"level":"INFO"`,
},
{
name: "Text format with debug level",
logFormat: "text",
logLevel: "debug",
addSource: false,
expectErr: false,
expectText: "level=DEBUG",
},
{
name: "Invalid log level",
logFormat: "json",
logLevel: "invalid",
addSource: false,
expectErr: true,
expectText: `"level":"INFO"`,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var buf bytes.Buffer
out := &buf

logger := loggingSetup(test.logFormat, test.logLevel, out, test.addSource)

if test.expectErr {
if buf.Len() == 0 {
t.Errorf("Expected error log, got none")
}
}

logger.Info("test log")
logOutput := buf.String()

if !bytes.Contains([]byte(logOutput), []byte(test.expectText)) {
t.Errorf("Expected log output to contain %q, got %q", test.expectText, logOutput)
}
})
}
}

func TestLoggingSetupWithSource(t *testing.T) {
var buf bytes.Buffer
out := &buf

logger := loggingSetup("text", "info", out, true)
logger.Info("test log with source")

logOutput := buf.String()
if !bytes.Contains([]byte(logOutput), []byte("logging_test.go")) {
t.Errorf("Expected log output to contain source file info, got %q", logOutput)
}
}
116 changes: 116 additions & 0 deletions cmd/webhook/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package main

import (
"flag"
"os"
"testing"
"time"
)

func TestParseConfig(t *testing.T) {
// Save the original command-line arguments and defer restoring them
origArgs := os.Args
defer func() { os.Args = origArgs }()

// Save the original environment variables and defer restoring them
origTidyUser := os.Getenv("TIDYDNS_USER")
origTidyPass := os.Getenv("TIDYDNS_PASS")
defer func() {
os.Setenv("TIDYDNS_USER", origTidyUser)
os.Setenv("TIDYDNS_PASS", origTidyPass)
}()

// Set up test cases
tests := []struct {
name string
args []string
envUser string
envPass string
expectedConfig *config
expectError bool
}{
{
name: "default values",
args: []string{"cmd"},
envUser: "testuser",
envPass: "testpass",
expectedConfig: &config{
logLevel: "info",
logFormat: "text",
tidyEndpoint: "",
readTimeout: 5 * time.Second,
writeTimeout: 10 * time.Second,
zoneUpdateInterval: 10 * time.Minute,
tidyUsername: "testuser",
tidyPassword: "testpass",
},
expectError: false,
},
{
name: "custom values",
args: []string{"cmd", "--log-level=debug", "--log-format=json", "--tidydns-endpoint=http://example.com", "--read-timeout=3s", "--write-timeout=6s", "--zone-update-interval=15m"},
envUser: "customuser",
envPass: "custompass",
expectedConfig: &config{
logLevel: "debug",
logFormat: "json",
tidyEndpoint: "http://example.com",
readTimeout: 3 * time.Second,
writeTimeout: 6 * time.Second,
zoneUpdateInterval: 15 * time.Minute,
tidyUsername: "customuser",
tidyPassword: "custompass",
},
expectError: false,
},
{
name: "invalid duration",
args: []string{"cmd", "--zone-update-interval=invalid"},
envUser: "testuser",
envPass: "testpass",
expectedConfig: nil,
expectError: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Set command-line arguments
os.Args = tt.args

// Set environment variables
os.Setenv("TIDYDNS_USER", tt.envUser)
os.Setenv("TIDYDNS_PASS", tt.envPass)

// Reset the flag package to avoid conflicts
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)

// Call parseConfig
cfg, err := parseConfig()

// Check for errors
if tt.expectError {
if err == nil {
t.Fatalf("expected an error but got none")
}
return
} else {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}

// Compare the result with the expected config
if cfg.logLevel != tt.expectedConfig.logLevel ||
cfg.logFormat != tt.expectedConfig.logFormat ||
cfg.tidyEndpoint != tt.expectedConfig.tidyEndpoint ||
cfg.readTimeout != tt.expectedConfig.readTimeout ||
cfg.writeTimeout != tt.expectedConfig.writeTimeout ||
cfg.zoneUpdateInterval != tt.expectedConfig.zoneUpdateInterval ||
cfg.tidyUsername != tt.expectedConfig.tidyUsername ||
cfg.tidyPassword != tt.expectedConfig.tidyPassword {
t.Errorf("expected config %+v, but got %+v", tt.expectedConfig, cfg)
}
})
}
}
Loading

0 comments on commit 5b42b38

Please sign in to comment.