config: add Duration test coverage and fix error wrapping

Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: I5c08e63297f90acdedd9744de904c36b6a6a6964
This commit is contained in:
raf 2026-03-05 23:49:11 +03:00
commit 9f264fbef1
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
4 changed files with 54 additions and 44 deletions

View file

@ -21,7 +21,7 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
// Try decoding as a raw int64 (nanoseconds) as fallback.
var ns int64
if err2 := value.Decode(&ns); err2 != nil {
return fmt.Errorf("cannot unmarshal duration: %w", err)
return fmt.Errorf("cannot unmarshal duration (tried string: %v): %w", err, err2)
}
d.Duration = time.Duration(ns)
return nil

View file

@ -3,6 +3,7 @@ package config_test
import (
"os"
"testing"
"time"
"notashelf.dev/ncro/internal/config"
)
@ -61,3 +62,53 @@ func TestEnvOverride(t *testing.T) {
t.Errorf("env override listen = %q, want :1234", cfg.Server.Listen)
}
}
func TestDurationParsing(t *testing.T) {
yamlContent := `
server:
listen: ":8080"
read_timeout: 30s
write_timeout: 1m
cache:
ttl: 2h
mesh:
gossip_interval: 45s
`
f, _ := os.CreateTemp("", "ncro-dur-*.yaml")
defer os.Remove(f.Name())
f.WriteString(yamlContent)
f.Close()
cfg, err := config.Load(f.Name())
if err != nil {
t.Fatalf("Load error: %v", err)
}
if cfg.Server.ReadTimeout.Duration != 30*time.Second {
t.Errorf("read_timeout = %v, want 30s", cfg.Server.ReadTimeout.Duration)
}
if cfg.Server.WriteTimeout.Duration != time.Minute {
t.Errorf("write_timeout = %v, want 1m", cfg.Server.WriteTimeout.Duration)
}
if cfg.Cache.TTL.Duration != 2*time.Hour {
t.Errorf("ttl = %v, want 2h", cfg.Cache.TTL.Duration)
}
if cfg.Mesh.GossipInterval.Duration != 45*time.Second {
t.Errorf("gossip_interval = %v, want 45s", cfg.Mesh.GossipInterval.Duration)
}
}
func TestInvalidDuration(t *testing.T) {
yamlContent := `
server:
read_timeout: "bananas"
`
f, _ := os.CreateTemp("", "ncro-bad-*.yaml")
defer os.Remove(f.Name())
f.WriteString(yamlContent)
f.Close()
_, err := config.Load(f.Name())
if err == nil {
t.Error("expected error for invalid duration string, got nil")
}
}