package list import ( "regexp" "strings" "testing" "github.com/stretchr/testify/assert" "pgregory.net/rapid" ) func intListGen() *rapid.Generator[IList] { return rapid.OneOf(rapid.Custom(func(t *rapid.T) IList { myList := Empty() t.Repeat(map[string]func(*rapid.T){ "conj": func(t *rapid.T) { myList = myList.Conj(rapid.Int().Draw(t, "el")) }, }) return myList }), rapid.Just(Empty())) } func TestConjIncreasesLength(t *testing.T) { rapid.Check(t, func(t *rapid.T) { myList := intListGen().Draw(t, "myList") newElem := rapid.Int().Draw(t, "newElem") assert.Equal(t, myList.Len()+1, myList.Conj(newElem).Len(), "conj increases length") }) } func TestRestDecreasesLength(t *testing.T) { rapid.Check(t, func(t *rapid.T) { myList := intListGen().Draw(t, "myList") if myList.IsEmpty() { assert.Equal(t, myList.Len(), myList.Rest().Len(), "rest does not change length for empty list") } else { assert.Equal(t, myList.Len()-1, myList.Rest().Len(), "rest decreases length of non-empty list") } }) } func TestFirstIsNilOnlyWhenEmpty(t *testing.T) { assert.Equal(t, 1, New(3).Conj(2).Conj(1).First()) rapid.Check(t, func(t *rapid.T) { myList := intListGen().Draw(t, "myList") assert.Equal(t, myList.IsEmpty(), myList.First() == nil, "first is nil only when list is empty") }) } func TestStringifyIntList(t *testing.T) { assert.Equal(t, "(1 2 3)", New(3).Conj(2).Conj(1).String()) rapid.Check(t, func(t *rapid.T) { myList := intListGen().Draw(t, "myList") s := myList.String() r := regexp.MustCompile(`^\([\d\s-]*\)$`) assert.Equal(t, true, r.Match([]byte(s)), s + " looks like a string") if !myList.IsEmpty() { assert.Equal(t, myList.Len(), strings.Count(s, " ")+1, "number of spaces in string should match count of elements") } else { assert.Equal(t, 0, strings.Count(s, " "), "no spaces in string for empty list") } }) }