Move SliceOfNZero to test/generator package

This commit is contained in:
Brandon Dyck 2024-09-13 11:24:43 -06:00
parent c9ee9916eb
commit a223f18f02
2 changed files with 14 additions and 12 deletions

View File

@ -7,7 +7,7 @@ import (
"git.codemonkeysoftware.net/b/gigaparsec/cursor"
ptest "git.codemonkeysoftware.net/b/gigaparsec/test"
"git.codemonkeysoftware.net/b/gigaparsec/test/generator"
pgen "git.codemonkeysoftware.net/b/gigaparsec/test/generator"
"github.com/shoenig/test"
"github.com/shoenig/test/must"
"pgregory.net/rapid"
@ -17,18 +17,11 @@ func Todo(t *testing.T) {
t.Errorf("TODO")
}
// TODO move this to generator
func SliceOfNZero[T any](minLen, maxLen int) *rapid.Generator[[]T] {
return rapid.Map(rapid.IntRange(minLen, maxLen), func(n int) []T {
return make([]T, n)
})
}
func testCursor[C cursor.Cursor[byte]](t *testing.T, makeCursor func([]byte) C) {
t.Helper()
t.Run("cursor reads the same position every time", rapid.MakeCheck(func(t *rapid.T) {
data := rapid.SliceOfN(rapid.Byte(), 1, 100).Draw(t, "data")
dst := SliceOfNZero[byte](0, len(data)-1).Draw(t, "dst")
dst := pgen.SliceOfNZero[byte](0, len(data)-1).Draw(t, "dst")
expected := data[:len(dst)]
c := makeCursor(data)
@ -43,7 +36,7 @@ func testCursor[C cursor.Cursor[byte]](t *testing.T, makeCursor func([]byte) C)
}))
t.Run("Read returns io.EOF iff it overruns source", rapid.MakeCheck(func(t *rapid.T) {
data := rapid.SliceOfN(rapid.Byte(), 0, 100).Draw(t, "data")
dst := SliceOfNZero[byte](0, 200).Draw(t, "dst")
dst := pgen.SliceOfNZero[byte](0, 200).Draw(t, "dst")
c := makeCursor(data)
n, _, err := c.Read(dst)
@ -114,9 +107,9 @@ func TestReaderAtCursor(t *testing.T) {
return cursor.NewReaderAt(bytes.NewReader(b))
})
t.Run("Read returns an error if the ReaderAt fails", rapid.MakeCheck(func(t *rapid.T) {
expectedErr := generator.Error().Draw(t, "expectedErr")
expectedErr := pgen.Error().Draw(t, "expectedErr")
startPos := rapid.Uint64().Draw(t, "startPos")
dst := SliceOfNZero[byte](0, 100).Draw(t, "dst")
dst := pgen.SliceOfNZero[byte](0, 100).Draw(t, "dst")
c := cursor.NewReaderAt(ptest.ErrReaderAt(expectedErr)).At(startPos)
n, next, err := c.Read(dst)
test.ErrorIs(t, err, expectedErr)

View File

@ -6,6 +6,15 @@ import (
"pgregory.net/rapid"
)
// Error returns a new error created by calling [errors.New] with a random string.
func Error() *rapid.Generator[error] {
return rapid.Map(rapid.String(), errors.New)
}
// SliceOfNZero returns a generator that makes slices of the zero value of T.
// The range of slice lengths are determined as in [rapid.SliceOfN].
func SliceOfNZero[T any](minLen, maxLen int) *rapid.Generator[[]T] {
return rapid.Map(rapid.IntRange(minLen, maxLen), func(n int) []T {
return make([]T, n)
})
}