♻️ Use uint8 for Env

This commit is contained in:
Dan Jones 2025-01-27 15:23:46 -06:00
commit 917f919401
6 changed files with 135 additions and 21 deletions

View file

@ -1,21 +1,81 @@
package config
import (
"encoding"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
var _ encoding.TextMarshaler = Env(0)
var _ encoding.TextUnmarshaler = new(Env)
var _ fmt.Stringer = Env(0)
func TestEnvString(t *testing.T) {
cases := Envs[:]
cases = append(cases, Env("foobar"), Env(""), Env("42"), Env("✨"))
for _, e := range cases {
t.Run(string(e), func(t *testing.T) {
assert.Equal(t, string(e), e.String())
testcases := []struct {
expected string
val Env
}{
{"Dev", Dev},
{"Prod", Prod},
{"Qa", Qa},
{"Test", Test},
{"Env(0)", Env(0)},
{"Env(255)", Env(255)},
}
for _, testcase := range testcases {
t.Run(testcase.expected, func(sub *testing.T) {
assert.Equal(t, testcase.expected, testcase.val.String())
by, er := testcase.val.MarshalText()
assert.NoError(t, er)
assert.Equal(t, []byte(testcase.expected), by)
})
}
}
type unmarshaltest struct {
name string
in []byte
exp Env
err string
}
func TestEnvUnmarshalText(t *testing.T) {
testcases := []unmarshaltest{
{"empty", []byte{}, Env(0), "invalid value: "},
{"bad value", []byte("foobar"), Env(0), "invalid value: foobar"},
}
for _, e := range Envs {
testcases = append(testcases, unmarshaltest{e.String() + "-lower", []byte(strings.ToLower(e.String())), e, ""})
testcases = append(testcases, unmarshaltest{e.String() + "-upper", []byte(strings.ToUpper(e.String())), e, ""})
testcases = append(testcases, unmarshaltest{e.String(), []byte(e.String()), e, ""})
}
for _, testcase := range testcases {
t.Run(testcase.name, func(sub *testing.T) {
var e Env
er := (&e).UnmarshalText(testcase.in)
if testcase.err == "" {
assert.NoError(t, er)
assert.Equal(t, testcase.exp, e)
} else {
assert.Empty(t, e)
assert.ErrorContains(t, er, testcase.err)
assert.ErrorIs(t, er, ErrEnvUnmarshal)
}
})
}
}
func TestEnvUnmarshalTextNil(t *testing.T) {
var e *Env
er := e.UnmarshalText([]byte("prod"))
assert.ErrorContains(t, er, "nil pointer")
assert.ErrorIs(t, er, ErrEnvUnmarshal)
}
func TestValidEnv(t *testing.T) {
cases := [...]struct {
e Env
@ -25,9 +85,8 @@ func TestValidEnv(t *testing.T) {
{Prod, true},
{Qa, true},
{Test, true},
{Env("foobar"), false},
{Env(""), false},
{Env("✨"), false},
{Env(0), false},
{Env(255), false},
}
for _, c := range cases {
@ -46,9 +105,8 @@ func TestValidEnvOrDev(t *testing.T) {
{Prod, Prod},
{Qa, Qa},
{Test, Test},
{Env("foobar"), Dev},
{Env(""), Dev},
{Env("✨"), Dev},
{Env(0), Dev},
{Env(255), Dev},
}
for _, c := range cases {