provide 'testing' package and a first simple test for config

This commit is contained in:
Helmut Merz 2023-06-01 09:35:05 +02:00
parent c42569e7b0
commit 87e9bb5fc4
3 changed files with 115 additions and 0 deletions

72
testing/testing.go Normal file
View file

@ -0,0 +1,72 @@
// Package testing provides a testing object T
// with functions for classical unit testing.
package testing
import (
"regexp"
"testing"
)
type Map map[string]interface{}
type T struct {
Base *testing.T
}
func MakeT(tbase *testing.T) *T {
return &T{
Base: tbase,
}
}
func SetUp(tbase *testing.T) *T {
t := MakeT(tbase)
return t
}
// testing methods
func (t *T) Run(name string, f func(*T)) bool {
return t.Base.Run(name, func(_ *testing.T) {
f(t)
})
}
func (t *T) LogErr(txt string, fields Map) {
t.Base.Helper()
t.Base.Errorf("%v, %+v", txt, fields)
}
func (t *T) AssertEqual(have interface{}, want interface{}) {
t.Base.Helper()
if have != want {
t.LogErr("AssertEqual", Map{"have": have, "want": want})
}
}
func (t *T) AssertMatch(have string, want string) {
t.Base.Helper()
match, _ := regexp.MatchString(Normalize(want), Normalize(have))
if !match {
t.LogErr("AssertMatch", Map{"have": have, "want": want})
}
}
// testing functions: generic functions may not be methods
func AssertOneOf[V comparable](t *T, have V, want []V) {
t.Base.Helper()
for _, w := range want {
if have == w {
return
}
}
t.LogErr("AssertOneOf", Map{"have": have, "want": want})
}
// helpers
func Normalize(s string) string {
re, _ := regexp.Compile(`\s*`)
return re.ReplaceAllString(s, "")
}

23
tests/etc/etc.go Normal file
View file

@ -0,0 +1,23 @@
package etc
import "git.sr.ht/~cco/go-scopes"
func Config() *scopes.Config {
return &scopes.Config{
Name: "dummy",
}
}
// collect here the names of fields that may be overridden via
// explicit Override() or SCOPES_* environment settings.
const (
NAME = "name"
)
// in a production scenario this should be put in separate file `settings.go`
// that should not be stored in code repository.
func Override() map[string]string {
return map[string]string{
NAME: "overridden",
}
}

20
tests/scopes_test.go Normal file
View file

@ -0,0 +1,20 @@
package scopes_test
import (
tbase "testing"
"git.sr.ht/~cco/go-scopes"
"git.sr.ht/~cco/go-scopes/testing"
"git.sr.ht/~cco/go-scopes/tests/etc"
)
func TestConfig(tb *tbase.T) {
t := testing.SetUp(tb)
t.Run("config", ConfigTest)
}
func ConfigTest(t *testing.T) {
scopes.Setup()
t.AssertEqual(etc.Config().Name, "dummy")
t.AssertEqual(etc.Override()[etc.NAME], "overridden")
}