gt

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

gt: Generics based Test library for Go

Go Reference test gosec lint

Type-safe test assertions for Go with IDE support and compile-time type checking.

color := "blue"
gt.Value(t, color).Equal("blue")   // Pass
gt.Value(t, color).Equal("orange") // Fail
// gt.Value(t, color).Equal(5)     // Compile error!

Installation

go get github.com/gaebalai/gt

Quick Start

import "github.com/gaebalai/gt"

func TestExample(t *testing.T) {
    // Value comparison
    gt.Value(t, user).Equal(expectedUser)

    // Array testing
    gt.Array(t, items).Length(3).Has(expectedItem)

    // Map testing
    gt.Map(t, config).HasKey("database").EqualAt("port", 5432)

    // String testing
    gt.String(t, email).Contains("@").HasSuffix(".com")

    // Number comparison
    gt.Number(t, count).Greater(0).LessOrEqual(100)

    // Error handling
    gt.NoError(t, err).Required()  // Fail fast if error
}

See examples/basic for a complete runnable example.

Available Types

Type Constructor Use for
Value gt.Value(t, v) Any value (structs, primitives)
Array gt.Array(t, arr) Slices and arrays
Map gt.Map(t, m) Maps
Number gt.Number(t, n) Numeric comparisons (>, <, etc.)
String gt.String(t, s) String operations
Bool gt.Bool(t, b) Boolean checks
Error gt.Error(t, err) Error validation
File gt.File(t, path) File system checks

Each type has a short alias: gt.V(), gt.A(), gt.M(), gt.N(), gt.S(), gt.B(), gt.F()

See GoDoc for all available methods.

Key Features

Method Chaining
gt.Array(t, users).
    Length(3).
    Has(admin).
    All(func(u User) bool { return u.Active })
Fail Fast with Required()
gt.NoError(t, err).Required()           // Stop immediately if error
gt.Value(t, config).Required().NotNil() // Stop if nil
Descriptive Error Messages
gt.Array(t, users).
    Describef("Users for tenant %s", tenantID).
    Length(5)

// Output:
// Users for tenant abc123
// array length is expected to be 5, but actual is 3
Function Return Values
// Handle (value, error) returns
result := gt.R1(parseJSON(input)).NoError(t)
gt.Value(t, result.Name).Equal("Alice")

// Test expected errors
gt.R1(parseJSON(badInput)).Error(t).Contains("invalid")

Best Practices

Use the specialized type that matches your data:

// Good - specialized types give better errors and methods
gt.Array(t, arr).Length(3)
gt.String(t, s).Contains("x")
gt.NoError(t, err)
gt.Number(t, n).Greater(5)

// Avoid - loses specialized functionality
gt.Value(t, len(arr)).Equal(3)
gt.Bool(t, strings.Contains(s, "x")).True()
gt.Value(t, err).Nil()
gt.Bool(t, n > 5).True()

Why gt?

Traditional test libraries like testify use interface{}/any:

// testify - no compile-time type checking
assert.Equal(t, "hello", 123)  // Compiles but fails at runtime

gt uses Go Generics (1.18+):

// gt - caught at compile time
gt.Value(t, "hello").Equal(123)  // Compile error!

Benefits:

  • Type mismatches caught before running tests
  • Full IDE autocompletion
  • Better error messages

For AI Coding Assistants

If you use Claude Code, copy examples/claude-rules/test-gt.md to your project's .claude/rules/ directory. This rule automatically applies when Claude works with test files and helps it use gt correctly.

See examples/claude-rules/README.md for setup instructions.

License

Apache License 2.0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var Diff = func(expect, actual any) string {
	switch reflect.ValueOf(actual).Kind() {
	case reflect.Pointer, reflect.UnsafePointer,
		reflect.Array, reflect.Slice,
		reflect.Struct, reflect.Map:
		return "diff:\n" + cmp.Diff(expect, actual, cmp.Exporter(func(t reflect.Type) bool { return true }))

	default:
		return strings.Join([]string{
			fmt.Sprintf("actual: %+v", actual),
			fmt.Sprintf("expect: %+v", expect),
		}, "\n")
	}
}
View Source
var DumpError = func(err error) string {
	return err.Error()
}
View Source
var EvalCompare = func(a, b any) bool {
	return reflect.DeepEqual(a, b)
}

EvalCompare is a function to check if actual value equals with expected value. A developer can replace EvalCompare with own evaluation function if needed.

EvalCompare(1, 2) == false
EvalCompare("abc", "axc") == false
EvalCompare([]int{1, 2, 3}, []int{1, 2, 3}) == true
View Source
var EvalFileExists = func(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

EvalFileExists is a function to check if file exists. A developer can replace EvalFileExists with own file existence check function if needed.

EvalFileExists("testdata/file.txt") == true
EvalFileExists("testdata/no-file.txt") == false
View Source
var EvalIsNil = func(v any) bool {
	value := reflect.ValueOf(v)

	switch value.Kind() {
	case reflect.Invalid:
		return true

	case reflect.Array, reflect.Slice:
		return value.Len() == 0

	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Uintptr, reflect.UnsafePointer:
		return value.IsNil()

	default:
		return false
	}
}

EvalIsNil is a function to check if actual value is nil. A developer can replace EvalIsNil with own nil check function if needed.

EvalIsNil(1) == false
EvalIsNil("abc") == false
EvalIsNil(nil) == true
EvalIsNil([]int{}) == true

Functions

func C

func C[T any](t testing.TB, v any) T

func Cast

func Cast[T any](t testing.TB, v any) T

Cast tries type assertion and will error and stop test if type assertion fails

var a any = "hello"
b := gt.Cast[string](a) // <- Pass and set "hello" to b
c := gt.Cast[int](a)    // <- Fail and stop test

func EQ

func EQ[T any](t testing.TB, actual T, expected T)

func Equal

func Equal[T any](t testing.TB, actual T, expected T)

func ErrorAs

func ErrorAs[T any](t testing.TB, actual error, callback func(expect *T))

ErrorAs checks error type by errors.As() function. If type check passed, callback will be invoked and given extracted error by errors.As.

func ExpectError

func ExpectError(t testing.TB, expected bool, err error)

ExpectError checks if an error occurrence matches the expectation. If expected is true, the test passes when err is not nil. If expected is false, the test passes when err is nil.

// Expect an error
err := someFailingFunction()
gt.ExpectError(t, true, err)  // Pass if err != nil

// Expect no error
err := someSuccessFunction()
gt.ExpectError(t, false, err) // Pass if err == nil

// Conditional error testing
shouldFail := true
err := conditionalFunction(shouldFail)
gt.ExpectError(t, shouldFail, err)

func NE

func NE[T any](t testing.TB, actual T, expected T)

func Nil

func Nil(t testing.TB, actual any)

Nil is a helper function to check if a value is nil. It handles nil pointers, interfaces, slices, maps, and channels.

gt.Nil(t, nil)
gt.Nil(t, (*int)(nil))
gt.Nil(t, []int(nil))
gt.Nil(t, map[string]int(nil))
gt.Nil(t, chan int(nil))

func NotEqual

func NotEqual[T any](t testing.TB, actual T, expected T)

func NotNil

func NotNil(t testing.TB, actual any)

NotNil is a helper function to check if a value is not nil. It handles nil pointers, interfaces, slices, maps, and channels.

gt.NotNil(t, 1)
gt.NotNil(t, "not nil")
gt.NotNil(t, []int{1, 2, 3})

Types

type ArrayTest

type ArrayTest[T any] struct {
	TestMeta
	// contains filtered or unexported fields
}

func A

func A[T any](t testing.TB, actual []T) ArrayTest[T]

A is sugar syntax of Array

func Array

func Array[T any](t testing.TB, actual []T) ArrayTest[T]

Array provides ArrayTest that has not only Value test methods but also array (slice) comparison methods

Example
t := newRecorder()

a := []int{2, 3, 4}
b := []int{2, 3, 5}

gt.Value(t, a).Equal(b)

fmt.Println(t.msgs[0])

func (ArrayTest[T]) All

func (x ArrayTest[T]) All(f func(v T) bool) ArrayTest[T]

All calls f with testing.TB and each elements in the array. If f returns false, All returns immediately and test will trigger error. If f returns true for all elements, All will pass.

v := []int{1, 2, 3, 5}
gt.Array(t, v).All(func(v int) bool {
    return v < 6
}) // Pass
gt.Array(t, v).All(func(v int) bool {
    return v < 4
}) // Fail

func (ArrayTest[T]) Any

func (x ArrayTest[T]) Any(f func(v T) bool) ArrayTest[T]

Any calls f with testing.TB and each elements in the array. If f returns true, Any returns immediately and test will pass. If f returns false for all elements, Any will trigger error.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Any(func(v int) bool {
    return v == 3
}) // Pass
gt.Array(t, v).Any(func(v int) bool {
    return v == 4
}) // Fail

func (ArrayTest[T]) At

func (x ArrayTest[T]) At(idx int, f func(t testing.TB, v T)) ArrayTest[T]

At calls f with testing.TB and idx th elements in the array. If idx is out of range, f is not called and test will trigger error.

v := []int{1, 2, 3, 5}
gt.Array(t, v).At(2, func(t testing.TB, v int) {
	gt.Value(t, v).Equal(3) // Pass
})

func (ArrayTest[T]) Contains

func (x ArrayTest[T]) Contains(expect []T) ArrayTest[T]

Contains check if actual has expect as sub sequence.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Contains([]int{1, 2, 3})) // Pass
gt.Array(t, v).Contains([]int{1, 2, 5})) // Fail

func (ArrayTest[T]) Describe

func (x ArrayTest[T]) Describe(description string) ArrayTest[T]

Describe sets a description for the test. The description will be displayed when the test fails.

gt.Array(t, items).Describe("Array should contain expected items").Equal(expected)

func (ArrayTest[T]) Describef

func (x ArrayTest[T]) Describef(format string, args ...any) ArrayTest[T]

Describef sets a formatted description for the test. The description will be displayed when the test fails.

gt.Array(t, items).Describef("Array should contain %d items for user %s", 5, "Alice").Length(5)

func (ArrayTest[T]) Distinct

func (x ArrayTest[T]) Distinct() ArrayTest[T]

Distinct checks if all elements in the array are distinct. If not, test will trigger error.

gt.Array(t, []int{1, 2, 3, 5}).Distinct() // Pass
gt.Array(t, []int{1, 2, 3, 2}).Distinct() // Fail

func (ArrayTest[T]) Equal

func (x ArrayTest[T]) Equal(expect []T) ArrayTest[T]

Equal check if actual does not equals with expect. Default evaluation function uses reflect.DeepEqual.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Equal([]int{1, 2, 3, 5}) // Pass
gt.Array(t, v).Equal([]int{1, 2, 3, 4}) // Fail

func (ArrayTest[T]) EqualAt

func (x ArrayTest[T]) EqualAt(idx int, expect T) ArrayTest[T]

EqualAt checks if actual[idx] equals expect. If idx is out of range, f is not called and test will trigger error.

v := []int{1, 2, 3, 5}
gt.Array(t, v).EqualAt(2, 3) // Pass
gt.Array(t, v).EqualAt(2, 1) // Fail
gt.Array(t, v).EqualAt(2, 5) // Fail by out of range

func (ArrayTest[T]) Has

func (x ArrayTest[T]) Has(expect T) ArrayTest[T]

Has check if actual has an expect element

v := []int{1, 2, 3, 5}
gt.Array(t, v).Has(5)) // Pass
gt.Array(t, v).Has(4)) // Fail

func (ArrayTest[T]) Length

func (x ArrayTest[T]) Length(expect int) ArrayTest[T]

Length checks if element number of actual array is expect.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Length(4) // Pass

func (ArrayTest[T]) Less

func (x ArrayTest[T]) Less(expect int) ArrayTest[T]

Less checks if array length is shorter than expect.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Less(5) // Pass
gt.Array(t, v).Less(4) // Fail

func (ArrayTest[T]) Longer

func (x ArrayTest[T]) Longer(expect int) ArrayTest[T]

Longer checks if array length is longer than expect.

v := []int{1, 2, 3, 5}
gt.Array(t, v).Longer(3) // Pass
gt.Array(t, v).Longer(4) // Fail

func (ArrayTest[T]) MatchThen

func (x ArrayTest[T]) MatchThen(match func(v T) bool, then func(t testing.TB, v T)) ArrayTest[T]

MatchThen calls then function with testing.TB and first element in the array that match with match. If no element matches, MatchThen will trigger error.

v := []struct{
    Name string
    Age int
}{
    {"Alice", 20},
    {"Bob", 21},
    {"Carol", 22},
}
gt.Array(t, v).MatchThen(func(v struct{Name string, Age int}) bool {
    return v.Name == "Bob"
}, func(t testing.TB, v struct{Name string, Age int}) {
    gt.Value(t, v.Age).Equal(21) // Pass
})

gt.Array(t, v).MatchThen(func(v struct{Name string, Age int}) bool {
    return v.Name == "Dave"
}, func(t testing.TB, v struct{Name string, Age int}) {
    gt.Value(t, v.Age).Equal(21) // Fail
})

func (ArrayTest[T]) NotContains

func (x ArrayTest[T]) NotContains(expect []T) ArrayTest[T]

NotContains check if actual does not have expect as sub sequence.

v := []int{1, 2, 3, 5}
gt.Array(t, v).NotContains([]int{1, 2, 3})) // Fail
gt.Array(t, v).NotContains([]int{1, 2, 5})) // Pass

func (ArrayTest[T]) NotEqual

func (x ArrayTest[T]) NotEqual(expect []T) ArrayTest[T]

NotEqual check if actual does not equals with expect. Default evaluation function uses reflect.DeepEqual.

v := []int{1, 2, 3, 5}
gt.Array(t, v).NotEqual([]int{1, 2, 3, 5}) // Fail
gt.Array(t, v).NotEqual([]int{1, 2, 3, 4}) // Pass

func (ArrayTest[T]) NotEqualAt

func (x ArrayTest[T]) NotEqualAt(idx int, expect T) ArrayTest[T]

NotEqualAt checks if actual[idx] equals expect. If idx is out of range, f is not called and test will trigger error.

v := []int{1, 2, 3, 5}
gt.Array(t, v).NotEqualAt(2, 1) // Pass
gt.Array(t, v).NotEqualAt(2, 3) // Fail
gt.Array(t, v).NotEqualAt(2, 5) // Fail by out of range

func (ArrayTest[T]) NotHas

func (x ArrayTest[T]) NotHas(expect T) ArrayTest[T]

NotHas check if actual does not have an expect element

v := []int{1, 2, 3, 5}
gt.Array(t, v).NotHas(5)) // Fail
gt.Array(t, v).NotHas(4)) // Pass

func (ArrayTest[T]) NotUnorderedEqual

func (x ArrayTest[T]) NotUnorderedEqual(expect []T) ArrayTest[T]

NotUnorderedEqual checks if actual and expect do not have the same elements regardless of order.

v := []int{1, 2, 3}
gt.Array(t, v).NotUnorderedEqual([]int{1, 2, 4}) // Pass
gt.Array(t, v).NotUnorderedEqual([]int{3, 1, 2}) // Fail

func (ArrayTest[T]) Required

func (x ArrayTest[T]) Required() ArrayTest[T]

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.FailNow().

func (ArrayTest[T]) UnorderedEqual

func (x ArrayTest[T]) UnorderedEqual(expect []T) ArrayTest[T]

UnorderedEqual checks if actual and expect have the same elements regardless of order. It considers duplicate elements (e.g., [1,1,2] matches [2,1,1] but not [1,2,2]).

v := []int{1, 2, 3}
gt.Array(t, v).UnorderedEqual([]int{3, 1, 2}) // Pass
gt.Array(t, v).UnorderedEqual([]int{1, 2, 4}) // Fail

type BoolTest

type BoolTest struct {
	TestMeta
	// contains filtered or unexported fields
}

func B

func B(t testing.TB, actual bool) BoolTest

func Bool

func Bool(t testing.TB, actual bool) BoolTest

func False

func False(t testing.TB, actual bool) BoolTest

func True

func True(t testing.TB, actual bool) BoolTest

func (BoolTest) Describe

func (x BoolTest) Describe(description string) BoolTest

Describe sets a description for the test. The description will be displayed when the test fails.

func (BoolTest) Describef

func (x BoolTest) Describef(format string, args ...any) BoolTest

Describef sets a formatted description for the test. The description will be displayed when the test fails.

func (BoolTest) False

func (x BoolTest) False() BoolTest

func (BoolTest) Required

func (x BoolTest) Required() BoolTest

func (BoolTest) True

func (x BoolTest) True() BoolTest

type ErrorTest

type ErrorTest struct {
	TestMeta
	// contains filtered or unexported fields
}

func Error

func Error(t testing.TB, actual error) ErrorTest

Value provides ErrorTest that is specialized for error testing

func (ErrorTest) Contains

func (x ErrorTest) Contains(substr string)

Contains checks if the error message contains the expected substring.

func (ErrorTest) Describe

func (x ErrorTest) Describe(description string) ErrorTest

Required checks if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.FailNow(). Describe sets a description for the test. The description will be displayed when the test fails.

func (ErrorTest) Describef

func (x ErrorTest) Describef(format string, args ...any) ErrorTest

Describef sets a formatted description for the test. The description will be displayed when the test fails.

func (ErrorTest) Is

func (x ErrorTest) Is(expected error)

Is checks error object equality by errors.Is() function.

func (ErrorTest) IsNot

func (x ErrorTest) IsNot(expected error)

IsNot checks error object not-equality by errors.Is() function.

func (ErrorTest) Required

func (x ErrorTest) Required() ErrorTest

type FileTest

type FileTest struct {
	TestMeta
	// contains filtered or unexported fields
}

func F

func F(t testing.TB, path string) FileTest

F is sugar syntax of File

func File

func File(t testing.TB, path string) FileTest

File provides FileTest that has basic comparison methods

func (FileTest) Describe

func (x FileTest) Describe(description string) FileTest

Describe sets a description for the test. The description will be displayed when the test fails.

func (FileTest) Describef

func (x FileTest) Describef(format string, args ...any) FileTest

Describef sets a formatted description for the test. The description will be displayed when the test fails.

func (FileTest) Exists

func (x FileTest) Exists() FileTest

Exists check if file exists

gt.File(t, "testdata/file.txt").Exists() // Pass
gt.File(t, "testdata/no-file.txt").Exists() // Fail

func (FileTest) NotExists

func (x FileTest) NotExists() FileTest

NotExists check if file does not exist

gt.File(t, "testdata/file.txt").NotExists() // Fail
gt.File(t, "testdata/no-file.txt").NotExists() // Pass

func (FileTest) Reader

func (x FileTest) Reader(f func(testing.TB, io.Reader)) FileTest

Reader calls f with file content

gt.File(t, "testdata/file.txt").Reader(func(t testing.TB, r io.Reader) {
   // Read file content from r
})

func (FileTest) Required

func (x FileTest) Required() FileTest

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.FailNow().

func (FileTest) String

func (x FileTest) String(f func(t testing.TB, s string)) FileTest

String calls f with file content

gt.File(t, "testdata/file.txt").String(func(t testing.TB, s string) {
   gt.Equal(t, s, "hello")
})

type MapTest

type MapTest[K comparable, V any] struct {
	TestMeta
	// contains filtered or unexported fields
}

func M

func M[K comparable, V any](t testing.TB, actual map[K]V) MapTest[K, V]

M is sugar syntax of Map

m := map[string]int{
	"blue": 5,
}
gt.M(t, m).HasKey("blue").HasValue(5)

func Map

func Map[K comparable, V any](t testing.TB, actual map[K]V) MapTest[K, V]

Map provides MapTest that has not only Value test methods but also key-value test

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).HasKey("blue").HasValue(5)
Example
t := newRecorder()

type user struct {
	ID   int
	Name string
}
a := &user{ID: 1, Name: "Alice"}
b := &user{ID: 2, Name: "Bob"}

gt.Value(t, a).Equal(b)

fmt.Println(t.msgs[0])
Example (Nil)
t := newRecorder()

type user struct {
	ID   int
	Name string
}
a := &user{ID: 1, Name: "Alice"}

gt.Value(t, a).Equal(nil)

fmt.Println(t.msgs[0])

func (MapTest[K, V]) At

func (x MapTest[K, V]) At(key K, f func(t testing.TB, v V)) MapTest[K, V]

At calls f with testing.TB and idx th elements in the array. If idx is out of range, f is not called and test will trigger error.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).At("blue", func(t testing.TB, v int) {
	gt.Value(t, v).Equal(5) // <- pass
})

func (MapTest[K, V]) Describe

func (x MapTest[K, V]) Describe(description string) MapTest[K, V]

Describe sets a description for the test. The description will be displayed when the test fails.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).Describe("Map should contain expected key-value pairs").HasKey("blue")

func (MapTest[K, V]) Describef

func (x MapTest[K, V]) Describef(format string, args ...any) MapTest[K, V]

Describef sets a formatted description for the test. The description will be displayed when the test fails.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).Describef("Map should contain key %s with value %d", "blue", 5).HasKeyValue("blue", 5)

func (MapTest[K, V]) Equal

func (x MapTest[K, V]) Equal(expect map[K]V) MapTest[K, V]

Equal checks if expect completely equals given actual map.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).Equal(map[string]int{"blue": 5}) // <- Pass
gt.Map(t, m).Equal(map[string]int{"blue": 0}) // <- Fail

func (MapTest[K, V]) EqualAt

func (x MapTest[K, V]) EqualAt(key K, expect V) MapTest[K, V]

EqualAt checks if actual[key] equals expect. If key is not found, test will fail.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).NotEqualAt("blue", 5)   // Pass
gt.Map(t, m).NotEqualAt("blue", 1)   // Fail
gt.Map(t, m).NotEqualAt("orange", 5) // Fail by key not found

func (MapTest[K, V]) HasKey

func (x MapTest[K, V]) HasKey(expect K) MapTest[K, V]

HasKey checks if the map has expect key.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).HasKey("blue")   // <- pass
gt.Map(t, m).HasKey("orange") // <- fail

func (MapTest[K, V]) HasKeyValue

func (x MapTest[K, V]) HasKeyValue(expectKey K, expectValue V) MapTest[K, V]

HasKeyValue checks if the map has expect a pair of key and value.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).HasKeyValue("blue", 5)   // <- pass
gt.Map(t, m).HasKeyValue("blue", 0)   // <- fail
gt.Map(t, m).HasKeyValue("orange", 5) // <- fail

func (MapTest[K, V]) HasValue

func (x MapTest[K, V]) HasValue(expect V) MapTest[K, V]

HasValue checks if the map has expect key.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).HasValue(5) // <- pass
gt.Map(t, m).HasValue(7) // <- fail

func (MapTest[K, V]) Length

func (x MapTest[K, V]) Length(expect int) MapTest[K, V]

Length checks number of a pair of keys.

m := map[string]int{
	"blue": 5,
	"orange: 0,
}
gt.Map(t, m).Length(2) // <- pass
gt.Map(t, m).Length(0) // <- pass

func (MapTest[K, V]) NotEqual

func (x MapTest[K, V]) NotEqual(expect map[K]V) MapTest[K, V]

NotEqual checks if expect does not equal given actual map.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).Equal(map[string]int{ // <- Pass
	"blue": 0,
})
gt.Map(t, m).Equal(map[string]int{ // <- Pass
	"blue": 5,
	"orange": 9,
})

func (MapTest[K, V]) NotEqualAt

func (x MapTest[K, V]) NotEqualAt(key K, expect V) MapTest[K, V]

NotEqualAt checks if actual[key] equals expect. If key is not found, test will fail.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).NotEqualAt("blue", 1)   // Pass
gt.Map(t, m).NotEqualAt("blue", 5)   // Fail
gt.Map(t, m).NotEqualAt("orange", 5) // Fail by key not found

func (MapTest[K, V]) NotHasKey

func (x MapTest[K, V]) NotHasKey(expect K) MapTest[K, V]

NotHasKey checks if the map does not have expect key.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).NotHasKey("orange") // <- pass
gt.Map(t, m).NotHasKey("blue")   // <- fail

func (MapTest[K, V]) NotHasKeyValue

func (x MapTest[K, V]) NotHasKeyValue(expectKey K, expectValue V) MapTest[K, V]

NotHasKeyValue checks if the map does not have expect a pair of key and value.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).NotHasKeyValue("blue", 5)   // <- fail
gt.Map(t, m).NotHasKeyValue("blue", 0)   // <- pass
gt.Map(t, m).NotHasKeyValue("orange", 5) // <- pass

func (MapTest[K, V]) NotHasValue

func (x MapTest[K, V]) NotHasValue(expect V) MapTest[K, V]

NotHasValue checks if the map has expect key.

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).NotHasValue(5) // <- fail
gt.Map(t, m).NotHasValue(7) // <- pass

func (MapTest[K, V]) Required

func (x MapTest[K, V]) Required() MapTest[K, V]

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.Failed().

m := map[string]int{
	"blue": 5,
}
gt.Map(t, m).Required().
	HasKey("blue", 0).      // <- fail
	HasKey("blue", 5).      // <- will not be tested
gt.Map(t, m).HasKey("blue") // <- will not be tested

type NoErrorTest

type NoErrorTest struct {
	// contains filtered or unexported fields
}

func NoError

func NoError(t testing.TB, actual error) NoErrorTest

NoError checks if error does not occur.

func (NoErrorTest) Required

func (x NoErrorTest) Required()

type NumberTest

type NumberTest[T number] struct {
	TestMeta
	// contains filtered or unexported fields
}

func N

func N[T number](t testing.TB, actual T) NumberTest[T]

N is sugar syntax of Number

func Number

func Number[T number](t testing.TB, actual T) NumberTest[T]

Number provides NumberTest that has not only Value test methods but also large-small comparison methods

func (NumberTest[T]) Describe

func (x NumberTest[T]) Describe(description string) NumberTest[T]

Describe sets a description for the test. The description will be displayed when the test fails.

n := 2
gt.Number(t, n).Describe("Number should match expected value").Equal(2)

func (NumberTest[T]) Describef

func (x NumberTest[T]) Describef(format string, args ...any) NumberTest[T]

Describef sets a formatted description for the test. The description will be displayed when the test fails.

n := 2
gt.Number(t, n).Describef("Number should be %d for calculation", 2).Equal(2)

func (NumberTest[T]) Equal

func (x NumberTest[T]) Equal(expect T) NumberTest[T]

Equal checks if expect equals given actual value.

n := 2
gt.Number(t, n).Equal(2)

func (NumberTest[T]) Greater

func (x NumberTest[T]) Greater(expect T) NumberTest[T]

Greater checks if actual value is greater than expect

n := 5
gt.Number(t, n).Greater(3) // Pass
gt.Number(t, n).Greater(5) // Fail

func (NumberTest[T]) GreaterOrEqual

func (x NumberTest[T]) GreaterOrEqual(expect T) NumberTest[T]

GreaterOrEqual checks if actual value is expect or greater

n := 5
gt.Number(t, n).GreaterOrEqual(3) // Pass
gt.Number(t, n).GreaterOrEqual(5) // Pass
gt.Number(t, n).GreaterOrEqual(6) // Fail

func (NumberTest[T]) Less

func (x NumberTest[T]) Less(expect T) NumberTest[T]

Less checks if actual value is less than expect

n := 5
gt.Number(t, n).Less(6) // Pass
gt.Number(t, n).Less(5) // Fail

func (NumberTest[T]) LessOrEqual

func (x NumberTest[T]) LessOrEqual(expect T) NumberTest[T]

LessOrEqual checks if actual value is expect or Less

n := 5
gt.Number(t, n).LessOrEqual(6) // Pass
gt.Number(t, n).LessOrEqual(5) // Pass
gt.Number(t, n).LessOrEqual(3) // Fail

func (NumberTest[T]) NotEqual

func (x NumberTest[T]) NotEqual(expect T) NumberTest[T]

NotEqual checks if expect does not equal given actual value.

n := 5
gt.Number(t, n).NotEqual(1) // Pass
gt.number(t, n).Equal(5)    // Fail

func (NumberTest[T]) Required

func (x NumberTest[T]) Required() NumberTest[T]

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.FailNow().

type Return1Test

type Return1Test[T1 any] struct {
	// contains filtered or unexported fields
}

func R1

func R1[T1 any](r1 T1, err error) Return1Test[T1]

func Return1

func Return1[T1 any](r1 T1, err error) Return1Test[T1]

Return1 creates a test for returned variables (one value and one error)

f := func() (string, error) {
	return "ok", nil
}
gt.Return1(f()).Error()               // Fail
gt.Return1(f()).NoError().Equal("ok") // Pass

func (Return1Test[T1]) Error

func (x Return1Test[T1]) Error(t testing.TB) ErrorTest

Error check if the function returned error. If error is nil, it will fail. If error is not nil, it provides ErrorTest

func (Return1Test[T1]) NoError

func (x Return1Test[T1]) NoError(t testing.TB) T1

NoError check if the function returned no error. If error is not nil, it will fail. If error is nil, it provides 1st returned value.

type Return2Test

type Return2Test[T1, T2 any] struct {
	// contains filtered or unexported fields
}

func R2

func R2[T1, T2 any](r1 T1, r2 T2, err error) Return2Test[T1, T2]

func Return2

func Return2[T1, T2 any](r1 T1, r2 T2, err error) Return2Test[T1, T2]

Return2 creates a test for returned variables (two values and one error)

f := func() (string, int, error) {
	return "ok", 1, nil
}
gt.Return2(f()).Error()           // Fail
s, i := gt.Return1(f()).NoError() // Pass

s.Equal("ok") // Pass
i.Equal(1)    // Pass

func (Return2Test[T1, T2]) Error

func (x Return2Test[T1, T2]) Error(t testing.TB) ErrorTest

Error check if the function returned error. If error is nil, it will fail. If error is not nil, it provides ErrorTest

func (Return2Test[T1, T2]) NoError

func (x Return2Test[T1, T2]) NoError(t testing.TB) (T1, T2)

NoError check if the function returned no error. If error is not nil, it will fail. If error is nil, it provides 1st and 2nd returned value.

type Return3Test

type Return3Test[T1, T2, T3 any] struct {
	// contains filtered or unexported fields
}

func R3

func R3[T1, T2, T3 any](r1 T1, r2 T2, r3 T3, err error) Return3Test[T1, T2, T3]

func Return3

func Return3[T1, T2, T3 any](r1 T1, r2 T2, r3 T3, err error) Return3Test[T1, T2, T3]

Return3 creates a test for returned variables (three values and one error)

f := func() (string, int, bool, error) {
	return "ok", 1, true, nil
}
gt.Return3(f()).Error()           // Fail
s, i, b := gt.Return1(f()).NoError() // Pass

s.Equal("ok") // Pass
i.Equal(1)    // Pass
b.Equal(true) // Pass

func (Return3Test[T1, T2, T3]) Error

func (x Return3Test[T1, T2, T3]) Error(t testing.TB) ErrorTest

Error check if the function returned error. If error is nil, it will fail. If error is not nil, it provides ErrorTest

func (Return3Test[T1, T2, T3]) NoError

func (x Return3Test[T1, T2, T3]) NoError(t testing.TB) (T1, T2, T3)

NoError check if the function returned no error. If error is not nil, it will fail. If error is nil, it provides 1st, 2nd and 3rd returned value.

type StringTest

type StringTest struct {
	TestMeta
	// contains filtered or unexported fields
}

func S

func S(t testing.TB, actual string) StringTest

S is sugar syntax of String

func String

func String(t testing.TB, actual string) StringTest

String provides StringTest that has basic comparison methods

func (StringTest) Contains

func (x StringTest) Contains(sub string) StringTest

Contains check if actual contains expected.

func (StringTest) ContainsAny

func (x StringTest) ContainsAny(substrs ...string) StringTest

ContainsAny checks if actual contains any of the expected substrings. The test passes if actual contains at least one of the provided substrings.

func (StringTest) ContainsNone

func (x StringTest) ContainsNone(substrs ...string) StringTest

ContainsNone checks if actual contains none of the expected substrings. The test passes if actual does not contain any of the provided substrings.

func (StringTest) Describe

func (x StringTest) Describe(description string) StringTest

Describe sets a description for the test. The description will be displayed when the test fails.

gt.String(t, actual).Describe("Username should match expected value").Equal(expected)

func (StringTest) Describef

func (x StringTest) Describef(format string, args ...any) StringTest

Describef sets a formatted description for the test. The description will be displayed when the test fails.

gt.String(t, actual).Describef("Username should match %s for user %s", expected, "Alice").Equal(expected)

func (StringTest) Equal

func (x StringTest) Equal(expect string) StringTest

Equal check if actual equals with expect. Default evaluation function uses reflect.DeepEqual.

func (StringTest) HasPrefix

func (x StringTest) HasPrefix(prefix string) StringTest

HasPrefix check if actual has prefix expected.

func (StringTest) HasSuffix

func (x StringTest) HasSuffix(suffix string) StringTest

HasSuffix check if actual has suffix expected.

func (StringTest) IsEmpty

func (x StringTest) IsEmpty() StringTest

IsEmpty check if actual is empty.

func (StringTest) IsNotEmpty

func (x StringTest) IsNotEmpty() StringTest

IsNotEmpty check if actual is not empty.

func (StringTest) Match

func (x StringTest) Match(pattern string) StringTest

Match check if actual matches with expected regular expression.

func (StringTest) NotContains

func (x StringTest) NotContains(sub string) StringTest

NotContains check if actual does not contain expected.

func (StringTest) NotEqual

func (x StringTest) NotEqual(expect string) StringTest

NotEqual check if actual does not equals with expect. Default evaluation function uses reflect.DeepEqual.

func (StringTest) NotHasPrefix

func (x StringTest) NotHasPrefix(prefix string) StringTest

NotHasPrefix check if actual does not have prefix expected.

func (StringTest) NotHasSuffix

func (x StringTest) NotHasSuffix(suffix string) StringTest

NotHasSuffix check if actual does not have suffix expected.

func (StringTest) NotMatch

func (x StringTest) NotMatch(pattern string) StringTest

NotMatch check if actual matches with expected regular expression.

func (StringTest) Required

func (x StringTest) Required() StringTest

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.FailNow().

type TestMeta

type TestMeta struct {
	// contains filtered or unexported fields
}

TestMeta holds common test metadata including the testing.TB instance and description. This struct is embedded in all test types to provide consistent description handling.

type ValueTest

type ValueTest[T any] struct {
	TestMeta
	// contains filtered or unexported fields
}

func V

func V[T any](t testing.TB, actual T) ValueTest[T]

V is sugar syntax of Value

func Value

func Value[T any](t testing.TB, actual T) ValueTest[T]

Value provides ValueTest that has basic comparison methods

Example (Nil)

nolint

t := newRecorder()

a := "test"

gt.Value(t, &a).Nil()

fmt.Println(t.msgs[0])

func (ValueTest[T]) Describe

func (x ValueTest[T]) Describe(description string) ValueTest[T]

Describe sets a description for the test. The description will be displayed when the test fails.

gt.Value(t, actual).Describe("User ID should match expected value").Equal(expected)

func (ValueTest[T]) Describef

func (x ValueTest[T]) Describef(format string, args ...any) ValueTest[T]

Describef sets a formatted description for the test. The description will be displayed when the test fails.

gt.Value(t, user.ID).Describef("User ID should be %d for user %s", 123, user.Name).Equal(123)

func (ValueTest[T]) Equal

func (x ValueTest[T]) Equal(expect T) ValueTest[T]

Equal check if actual equals with expect. Default evaluation function uses reflect.DeepEqual.

type user struct {
  Name string
}
u1 := user{Name: "blue"}
gt.Value(t, u1).Equal(user{Name: "blue"}) // Pass
gt.Value(t, u1).Equal(user{Name: "orange"}) // Fail

func (ValueTest[T]) In

func (x ValueTest[T]) In(expects ...T) ValueTest[T]

In checks actual is in expects. Default evaluation function uses reflect.DeepEqual.

func (ValueTest[T]) Nil

func (x ValueTest[T]) Nil() ValueTest[T]

Nil checks if actual is nil.

var u *User
gt.Value(t, u).Nil() // Pass
u = &User{}
gt.Value(t, u).Nil() // Fail

func (ValueTest[T]) NotEqual

func (x ValueTest[T]) NotEqual(expect T) ValueTest[T]

NotEqual check if actual does not equals with expect. Default evaluation function uses reflect.DeepEqual.

type user struct {
  Name string
}
u1 := user{Name: "blue"}
gt.Value(t, u1).NotEqual(user{Name: "blue"})   // Fail
gt.Value(t, u1).NotEqual(user{Name: "orange"}) // Pass

func (ValueTest[T]) NotNil

func (x ValueTest[T]) NotNil() ValueTest[T]

NotNil checks if actual is not nil.

var u *User
gt.Value(t, u).Nil() // Fail
u = &User{}
gt.Value(t, u).Nil() // Pass

func (ValueTest[T]) Required

func (x ValueTest[T]) Required() ValueTest[T]

Required check if error has occurred in previous test. If errors has been occurred in previous test, it immediately stop test by t.Failed().

name := "Alice"
gt.Value(t, name).Equal("Bob").Required() // Test will stop here

Directories

Path Synopsis
examples
describe command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL