confage/confage_test.go

91 lines
1.8 KiB
Go

package confage
import (
"encoding/json"
"testing"
"github.com/matryer/is"
)
const (
passphrase = "passphrase"
secretKey = "AGE-SECRET-KEY-1F7SU7MXLVHU0SWQ3L2ZMW7G2NN2YTH88NLU6LVDHENTZLMCT3M5S799RDK"
)
type Struct struct {
String string
Int int
Bool bool
}
func TestType(t *testing.T) {
t.Run("string", func(t *testing.T) {
assert := is.New(t)
val := "foo"
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
t.Run("int", func(t *testing.T) {
assert := is.New(t)
val := 123
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
t.Run("bool", func(t *testing.T) {
assert := is.New(t)
val := true
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
t.Run("map", func(t *testing.T) {
assert := is.New(t)
val := map[string]any{
"foo": "bar",
"baz": 123.0,
"bux": false,
}
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
t.Run("struct", func(t *testing.T) {
assert := is.New(t)
val := Struct{
String: "string",
Int: 123,
Bool: true,
}
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
t.Run("pointer", func(t *testing.T) {
assert := is.New(t)
val := &Struct{
String: "string",
Int: 123,
Bool: true,
}
testEncryption(assert, passphrase, val)
testEncryption(assert, secretKey, val)
})
}
func testEncryption[T any](assert *is.I, key string, value T) {
assert.Helper()
enc := MustNew(key, value)
payload, err := json.Marshal(enc)
assert.NoErr(err) // Should be able to marshal JSON
var t T
dec := MustNew(key, t)
err = json.Unmarshal(payload, &dec)
assert.NoErr(err) // Should be able to unmarshal JSON
assert.Equal(enc.Value, dec.Value) // Values should match
}