package dbx import ( "context" "errors" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFetch_EmptyOnNoRows(t *testing.T) { stmt := mockStatement{ queryContextFn: func(_ context.Context, dest any) error { return ErrNoRows }, } result, err := Fetch[row](mockQueryable{}, stmt) require.NoError(t, err) assert.Empty(t, result) } func TestFetch_ReturnsRows(t *testing.T) { stmt := mockStatement{ queryContextFn: func(_ context.Context, dest any) error { ptr := dest.(*[]*row) *ptr = []*row{{ID: 1}, {ID: 2}} return nil }, } result, err := Fetch[row](mockQueryable{}, stmt) require.NoError(t, err) assert.Len(t, result, 2) } func TestMustFetch_NotFound(t *testing.T) { errNotFound := errors.New("not found") stmt := mockStatement{ queryContextFn: func(_ context.Context, _ any) error { return ErrNoRows }, } result, err := MustFetch[row](mockQueryable{}, stmt, errNotFound) assert.Nil(t, result) assert.ErrorIs(t, err, errNotFound) } func TestFetchContext_PropagatesContext(t *testing.T) { ctx := context.WithValue(context.Background(), testContextKey{}, "ok") var gotCtx context.Context stmt := mockStatement{ queryContextFn: func(c context.Context, dest any) error { gotCtx = c ptr := dest.(*[]*row) *ptr = []*row{{ID: 3}} return nil }, } _, err := FetchContext[row](ctx, mockQueryable{}, stmt) require.NoError(t, err) assert.Equal(t, ctx, gotCtx) } type testContextKey struct{} func TestFetchOne_NilWhenEmpty(t *testing.T) { stmt := mockStatement{ queryContextFn: func(_ context.Context, _ any) error { return ErrNoRows }, } result, err := FetchOne[row](mockQueryable{}, stmt) require.NoError(t, err) assert.Nil(t, result) } func TestMustFetchOne_NotFound(t *testing.T) { errNotFound := errors.New("not found") stmt := mockStatement{ queryContextFn: func(_ context.Context, _ any) error { return ErrNoRows }, } result, err := MustFetchOne[row](mockQueryable{}, stmt, errNotFound) assert.Nil(t, result) assert.ErrorIs(t, err, errNotFound) } func TestQuery_ScansDest(t *testing.T) { stmt := mockStatement{ queryContextFn: func(_ context.Context, dest any) error { ptr := dest.(*row) ptr.ID = 5 return nil }, } var result row err := Query(mockQueryable{}, stmt, &result) require.NoError(t, err) assert.Equal(t, 5, result.ID) } func TestMustQuery_NotFound(t *testing.T) { errNotFound := errors.New("not found") stmt := mockStatement{ queryContextFn: func(_ context.Context, _ any) error { return ErrNoRows }, } var result row err := MustQuery(mockQueryable{}, stmt, &result, errNotFound) assert.ErrorIs(t, err, errNotFound) } func TestMustQueryContext_PropagatesContext(t *testing.T) { ctx := context.WithValue(context.Background(), testContextKey{}, "ok") var gotCtx context.Context stmt := mockStatement{ queryContextFn: func(c context.Context, dest any) error { gotCtx = c return ErrNoRows }, } _ = MustQueryContext(ctx, mockQueryable{}, stmt, &row{}, errors.New("nf")) assert.Equal(t, ctx, gotCtx) }