1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
|
package fs
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type choices struct{}
func (choices) Choices() []string {
return []string{
choiceA: "A",
choiceB: "B",
choiceC: "C",
}
}
type choice = Enum[choices]
const (
choiceA choice = iota
choiceB
choiceC
)
// Check it satisfies the interfaces
var (
_ flagger = (*choice)(nil)
_ flaggerNP = choice(0)
)
func TestEnumString(t *testing.T) {
for _, test := range []struct {
in choice
want string
}{
{choiceA, "A"},
{choiceB, "B"},
{choiceC, "C"},
{choice(100), "Unknown(100)"},
} {
got := test.in.String()
assert.Equal(t, test.want, got)
}
}
func TestEnumType(t *testing.T) {
assert.Equal(t, "A|B|C", choiceA.Type())
}
// Enum with Type() on the choices
type choicestype struct{}
func (choicestype) Choices() []string {
return []string{}
}
func (choicestype) Type() string {
return "potato"
}
type choicetype = Enum[choicestype]
func TestEnumTypeWithFunction(t *testing.T) {
assert.Equal(t, "potato", choicetype(0).Type())
}
func TestEnumHelp(t *testing.T) {
assert.Equal(t, "A, B, C", choice(0).Help())
}
func TestEnumSet(t *testing.T) {
for _, test := range []struct {
in string
want choice
err bool
}{
{"A", choiceA, false},
{"B", choiceB, false},
{"C", choiceC, false},
{"D", choice(100), true},
} {
var got choice
err := got.Set(test.in)
if test.err {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, test.want, got)
}
}
}
func TestEnumScan(t *testing.T) {
var v choice
n, err := fmt.Sscan(" A ", &v)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, choiceA, v)
}
func TestEnumUnmarshalJSON(t *testing.T) {
for _, test := range []struct {
in string
want choice
err string
}{
{`"A"`, choiceA, ""},
{`"B"`, choiceB, ""},
{`0`, choiceA, ""},
{`1`, choiceB, ""},
{`"D"`, choice(0), `invalid choice "D" from: A, B, C`},
{`100`, choice(0), `100 is out of range: must be 0..3`},
} {
var got choice
err := json.Unmarshal([]byte(test.in), &got)
if test.err != "" {
require.Error(t, err, test.in)
assert.ErrorContains(t, err, test.err)
} else {
require.NoError(t, err, test.in)
}
assert.Equal(t, test.want, got, test.in)
}
}
func TestEnumMarshalJSON(t *testing.T) {
for _, test := range []struct {
in choice
want string
}{
{choiceA, `"A"`},
{choiceB, `"B"`},
} {
got, err := json.Marshal(&test.in)
require.NoError(t, err)
assert.Equal(t, test.want, string(got), fmt.Sprintf("%#v", test.in))
}
}
|