assert

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 25 Imported by: 0

README

Assert

Fork of the very nice testza with some modifications. This version uses comparable from newer versions of golang and drops the Assert prefix from the functions. It also runs t.FailNow() for assert.NoError, and introduces json comparisons.

Latest Release Go Reference


Get The Module | Documentation



Screenshot of an example test message

Installation

# Execute this command inside your project
go get github.com/chalk-ai/assert


Description

assert is a full-featured testing framework for Go. It integrates with the default test runner, so you can use it with the standard go test tool. assert contains easy-to-use methods, like assertions, output capturing, fuzzing, and much more.

The main goal of assert is to provide an easy and fun experience writing tests and providing a nice, user-friendly output.

Features

Feature Description
Assertions Assertions allow you to quickly check objects for expected values.
Fuzzing Fuzzing allows you to check functions against sets of generated input parameters.
A couple lines of test code can run thousands of sanity tests.
Output Capture Capture and validate output written to the terminal.
Perfect for CLI tools.
Snapshots Snapshot objects between test runs, to ensure a consistent behaviour.
Clean Output Clean and colorful output provides you the needed details in an easy-to-understand format.
System Information assert prints information about the system on startup.
You can quickly figure out what's wrong, when a user submits an issue.
Well Documented Every function of assert is well documented and contains an example to make usage super easy.
Customizable assert features customizable settings, if you want to change something.
Test flags You can configure assert via flags too!
That makes it super simple to change test runs, or output, without touching code!

Getting Started

See the examples below for a quick introduction!

// --- Some Examples ---

// - Some assertions -
assert.AssertTrue(t, true) // -> Pass
assert.AssertNoError(t, err) // -> Pass
assert.AssertEqual(t, object, object) // -> Pass
// ...

// - Testing console output -
// Test the output of your CLI tool easily!
terminalOutput, _ := assert.CaptureStdout(func(w io.Writer) error {fmt.Println("Hello"); return nil})
asssert.AssertEqual(t, terminalOutput, "Hello\n") // -> Pass

// - Fuzzing -
// Testing a function that accepts email addresses as a parameter:

// Testset of many different email addresses
emailAddresses := assert.FuzzStringEmailAddresses()

// Run a test for every string in the test set
assert.FuzzStringRunTests(t, emailAddresses, func(t *testing.T, index int, str string) {
  user, domain, err := internal.ParseEmailAddress(str) // Use your function
  assert.AssertNoError(t, err) // Assert that your function does not return an error
  assert.AssertNotZero(t, user) // Assert that the user is returned
  assert.AssertNotZero(t, domain) // Assert that the domain is returned
})

// And that's just a few examples of what you can do with assert!

📚 Documentation

Module Methods
Settings
Click to expand
Assert
Click to expand
Capture
Click to expand
Fuzz Utils
Click to expand
Fuzz Booleans
Click to expand
Fuzz Strings
Click to expand
Fuzz Float64s
Click to expand
Fuzz Integers
Click to expand
Snapshot
Click to expand

Assert

AssertCompletesIn
func AssertCompletesIn(t testRunner, duration time.Duration, f func(), msg ...any)

AssertCompletesIn asserts that a function completes in a given time. Use this function to test that functions do not take too long to complete.

NOTE: Every system takes a different amount of time to complete a function. Do not set the duration too low, if you want consistent results.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertCompletesIn(t, 2 * time.Second, func() {
	// some code that should take less than 2 seconds...
}) // => PASS
AssertContains
func AssertContains(t testRunner, object, element any, msg ...any)

AssertContains asserts that a string/list/array/slice/map contains the specified element.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertContains(t, []int{1,2,3}, 2)
assert.AssertContains(t, []string{"Hello", "World"}, "World")
assert.AssertContains(t, "Hello, World!", "World")
AssertDecreasing
func AssertDecreasing(t testRunner, object any, msg ...any)

AssertDecreasing asserts that the values in a slice are decreasing. the test fails if the values are not in a slice or if the values are not comparable.

Valid input kinds are: []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []float32, []float64.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDecreasing(t, []int{1000, 137, 2, 1})
assert.AssertDecreasing(t, []float32{13.5, 7, 0.1, -10.3})
AssertDirEmpty
func AssertDirEmpty(t testRunner, dir string, msg ...any)

AssertDirEmpty asserts that a directory is empty. The test will pass when the directory is empty or does not exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirEmpty(t, "FolderName")
AssertDirExists
func AssertDirExists(t testRunner, dir string, msg ...any)

AssertDirExists asserts that a directory exists. The test will pass when the directory exists, and it's visible to the current user. The test will fail, if the path points to a file.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirExists(t, "FolderName")
AssertDirNotEmpty
func AssertDirNotEmpty(t testRunner, dir string, msg ...any)

AssertDirNotEmpty asserts that a directory is not empty The test will pass when the directory is not empty and will fail if the directory does not exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirNotEmpty(t, "FolderName")
AssertEqual
func AssertEqual(t testRunner, expected any, actual any, msg ...any)

AssertEqual asserts that two objects are equal.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertEqual(t, "Hello, World!", "Hello, World!")
assert.AssertEqual(t, true, true)
AssertEqualValues
func AssertEqualValues(t testRunner, expected any, actual any, msg ...any)

AssertEqualValues asserts that two objects have equal values. The order of the values is also validated.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertEqualValues(t, []string{"Hello", "World"}, []string{"Hello", "World"})
assert.AssertEqualValues(t, []int{1,2}, []int{1,2})
assert.AssertEqualValues(t, []int{1,2}, []int{2,1}) // FAILS (wrong order)

Comparing struct values:

person1 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

person2 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

assert.AssertEqualValues(t, person1, person2)
AssertErrorIs
func AssertErrorIs(t testRunner, err, target error, msg ...any)

AssertErrorIs asserts that target is inside the error chain of err.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

var testErr = errors.New("hello world")
var testErrWrapped = fmt.Errorf("test err: %w", testErr)
assert.AssertErrorIs(t, testErrWrapped ,testErr)
AssertFalse
func AssertFalse(t testRunner, value any, msg ...any)

AssertFalse asserts that an expression or object resolves to false.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertFalse(t, false)
assert.AssertFalse(t, 1 == 2)
assert.AssertFalse(t, 2 != 2)
assert.AssertFalse(t, 1 > 5 && 4 < 0)
AssertFileExists
func AssertFileExists(t testRunner, file string, msg ...any)

AssertFileExists asserts that a file exists.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertFileExists(t, "./test.txt")
assert.AssertFileExists(t, "./config.yaml", "the config file is missing")
AssertGreater
func AssertGreater(t testRunner, object1, object2 any, msg ...any)

AssertGreater asserts that the first object is greater than the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertGreater(t, 5, 1)
assert.AssertGreater(t, 10, -10)
AssertGreaterOrEqual
func AssertGreaterOrEqual(t testRunner, object1, object2 interface{}, msg ...interface{})

AssertGreaterOrEqual asserts that the first object is greater than or equal to the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertGreaterOrEqual(t, 5, 1)
assert.AssertGreaterOrEqual(t, 10, -10)

assert.AssertGreaterOrEqual(t, 10, 10)

AssertImplements
func AssertImplements(t testRunner, interfaceObject, object any, msg ...any)

AssertImplements asserts that an objects implements an interface.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertImplements(t, (*YourInterface)(nil), new(YourObject))
assert.AssertImplements(t, (*fmt.Stringer)(nil), new(types.Const)) => pass
AssertInRange
func AssertInRange[T number](t testRunner, value T, min T, max T, msg ...any)

AssertInRange asserts that the value is in the range.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertInRange(t, 5, 1, 10)
AssertIncreasing
func AssertIncreasing(t testRunner, object any, msg ...any)

AssertIncreasing asserts that the values in a slice are increasing. the test fails if the values are not in a slice or if the values are not comparable.

Valid input kinds are: []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []float32, []float64.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertIncreasing(t, []int{1, 2, 137, 1000})
assert.AssertIncreasing(t, []float32{-10.3, 0.1, 7, 13.5})
AssertKindOf
func AssertKindOf(t testRunner, expectedKind reflect.Kind, object any, msg ...any)

AssertKindOf asserts that the object is a type of kind exptectedKind.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertKindOf(t, reflect.Slice, []int{1,2,3})
assert.AssertKindOf(t, reflect.Slice, []string{"Hello", "World"})
assert.AssertKindOf(t, reflect.Int, 1337)
assert.AssertKindOf(t, reflect.Bool, true)
assert.AssertKindOf(t, reflect.Map, map[string]bool{})
AssertLen
func AssertLen(t testRunner, object any, length int, msg ...any)

AssertLen asserts that the length of an object is equal to the given length.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLen(t, "abc", 3)
assert.AssertLen(t, "Assert", 6)
assert.AssertLen(t, []int{1, 2, 1337, 25}, 4)
assert.AssertLen(t, map[string]int{"asd": 1, "test": 1337}, 2)
AssertLess
func AssertLess(t testRunner, object1, object2 any, msg ...any)

AssertLess asserts that the first object is less than the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLess(t, 1, 5)
assert.AssertLess(t, -10, 10)
AssertLessOrEqual
func AssertLessOrEqual(t testRunner, object1, object2 interface{}, msg ...interface{})

AssertLessOrEqual asserts that the first object is less than or equal to the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLessOrEqual(t, 1, 5)
assert.AssertLessOrEqual(t, -10, 10)
assert.AssertLessOrEqual(t, 1, 1)
AssertNil
func AssertNil(t testRunner, object any, msg ...any)

AssertNil asserts that an object is nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNil(t, nil)
AssertNoDirExists
func AssertNoDirExists(t testRunner, dir string, msg ...any)

AssertNoDirExists asserts that a directory does not exists. The test will pass, if the path points to a file, as a directory with the same name, cannot exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNoDirExists(t, "FolderName")
AssertNoError
func AssertNoError(t testRunner, err error, msg ...any)

AssertNoError asserts that an error is nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

err := nil
assert.AssertNoError(t, err)
AssertNoFileExists
func AssertNoFileExists(t testRunner, file string, msg ...any)
AssertNoSubset
func AssertNoSubset(t testRunner, list any, subset any, msg ...any)

AssertNoSubset asserts that the second parameter is not a subset of the list. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNoSubset(t, []int{1, 2, 3}, []int{1, 7})
assert.AssertNoSubset(t, []string{"Hello", "World", "Test"}, []string{"Test", "John"})
AssertNotCompletesIn
func AssertNotCompletesIn(t testRunner, duration time.Duration, f func(), msg ...any)

AssertNotCompletesIn asserts that a function does not complete in a given time. Use this function to test that functions do not complete to quickly. For example if your database connection completes in under a millisecond, there might be something wrong.

NOTE: Every system takes a different amount of time to complete a function. Do not set the duration too high, if you want consistent results.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotCompletesIn(t, 2 * time.Second, func() {
	// some code that should take more than 2 seconds...
	time.Sleep(3 * time.Second)
}) // => PASS
AssertNotContains
func AssertNotContains(t testRunner, object, element any, msg ...any)

AssertNotContains asserts that a string/list/array/slice/map does not contain the specified element.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotContains(t, []string{"Hello", "World"}, "Spaceship")
assert.AssertNotContains(t, "Hello, World!", "Spaceship")
AssertNotEqual
func AssertNotEqual(t testRunner, expected any, actual any, msg ...any)

AssertNotEqual asserts that two objects are not equal.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotEqual(t, true, false)
assert.AssertNotEqual(t, "Hello", "World")
AssertNotEqualValues
func AssertNotEqualValues(t testRunner, expected any, actual any, msg ...any)

AssertNotEqualValues asserts that two objects do not have equal values.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotEqualValues(t, []int{1,2}, []int{3,4})

Comparing struct values:

person1 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

person2 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "female", // <-- CHANGED
}

assert.AssertNotEqualValues(t, person1, person2)
AssertNotErrorIs
func AssertNotErrorIs(t testRunner, err, target error, msg ...any)

AssertNotErrorIs

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

var testErr = errors.New("hello world")
var test2Err = errors.New("hello world 2")
var testErrWrapped = fmt.Errorf("test err: %w", testErr)
assert.AssertNotErrorIs(t, testErrWrapped, test2Err)
AssertNotImplements
func AssertNotImplements(t testRunner, interfaceObject, object any, msg ...any)

AssertNotImplements asserts that an object does not implement an interface.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotImplements(t, (*YourInterface)(nil), new(YourObject))
assert.AssertNotImplements(t, (*fmt.Stringer)(nil), new(types.Const)) => fail, because types.Const does implement fmt.Stringer.
AssertNotInRange
func AssertNotInRange[T number](t testRunner, value T, min T, max T, msg ...any)

AssertNotInRange asserts that the value is not in the range.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotInRange(t, 5, 1, 10)
AssertNotKindOf
func AssertNotKindOf(t testRunner, kind reflect.Kind, object any, msg ...any)

AssertNotKindOf asserts that the object is not a type of kind kind.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotKindOf(t, reflect.Slice, "Hello, World")
assert.AssertNotKindOf(t, reflect.Slice, true)
assert.AssertNotKindOf(t, reflect.Int, 13.37)
assert.AssertNotKindOf(t, reflect.Bool, map[string]bool{})
assert.AssertNotKindOf(t, reflect.Map, false)
AssertNotNil
func AssertNotNil(t testRunner, object any, msg ...any)

AssertNotNil asserts that an object is not nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotNil(t, true)
assert.AssertNotNil(t, "Hello, World!")
assert.AssertNotNil(t, 0)
AssertNotNumeric
func AssertNotNumeric(t testRunner, object any, msg ...any)

AssertNotNumeric checks if the object is not a numeric type. Numeric types are: Int, Int8, Int16, Int32, Int64, Float32, Float64, Uint, Uint8, Uint16, Uint32, Uint64, Complex64 and Complex128.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotNumeric(t, true)
assert.AssertNotNumeric(t, "123")
AssertNotPanics
func AssertNotPanics(t testRunner, f func(), msg ...any)

AssertNotPanics asserts that a function does not panic.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotPanics(t, func() {
	// some code that does not call a panic...
}) // => PASS
AssertNotRegexp
func AssertNotRegexp(t testRunner, regex any, txt any, msg ...any)

AssertNotRegexp asserts that a string does not match a given regexp.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotRegexp(t, "ab.*", "Hello, World!")
AssertNotSameElements
func AssertNotSameElements(t testRunner, expected any, actual any, msg ...any)

AssertNotSameElements asserts that two slices contains same elements (including pointers). The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

 assert.AssertNotSameElements(t, []string{"Hello", "World"}, []string{"Hello", "World", "World"})
 assert.AssertNotSameElements(t, []int{1,2}, []int{1,2,3})

 type A struct {
	  a string
 }
 assert.AssertNotSameElements(t, []*A{{a: "A"}, {a: "B"}, {a: "C"}}, []*A{{a: "A"}, {a: "B"}, {a: "C"}, {a: "D"}})
AssertNotUnique
func AssertNotUnique[elementType comparable](t testRunner, list []elementType, msg ...any)

AssertNotUnique asserts that the elements in a list are not unique.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotUnique(t, []int{1, 2, 3, 3})
AssertNotZero
func AssertNotZero(t testRunner, value any, msg ...any)

AssertNotZero asserts that the value is not the zero value for it's type.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotZero(t, 1337)
assert.AssertNotZero(t, true)
assert.AssertNotZero(t, "Hello, World")
AssertNumeric
func AssertNumeric(t testRunner, object any, msg ...any)

AssertNumeric asserts that the object is a numeric type. Numeric types are: Int, Int8, Int16, Int32, Int64, Float32, Float64, Uint, Uint8, Uint16, Uint32, Uint64, Complex64 and Complex128.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNumeric(t, 123)
assert.AssertNumeric(t, 1.23)
assert.AssertNumeric(t, uint(123))
AssertPanics
func AssertPanics(t testRunner, f func(), msg ...any)

AssertPanics asserts that a function panics.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertPanics(t, func() {
	// ...
	panic("some panic")
}) // => PASS
AssertRegexp
func AssertRegexp(t testRunner, regex any, txt any, msg ...any)

AssertRegexp asserts that a string matches a given regexp.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertRegexp(t, "^a.*c$", "abc")
AssertSameElements
func AssertSameElements(t testRunner, expected any, actual any, msg ...any)

AssertSameElements asserts that two slices contains same elements (including pointers). The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

 assert.AssertSameElements(t, []string{"Hello", "World"}, []string{"Hello", "World"})
 assert.AssertSameElements(t, []int{1,2,3}, []int{1,2,3})
 assert.AssertSameElements(t, []int{1,2}, []int{2,1})

 type A struct {
	  a string
 }
 assert.AssertSameElements(t, []*A{{a: "A"}, {a: "B"}, {a: "C"}}, []*A{{a: "A"}, {a: "B"}, {a: "C"}})
AssertSubset
func AssertSubset(t testRunner, list any, subset any, msg ...any)

AssertSubset asserts that the second parameter is a subset of the list. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertSubset(t, []int{1, 2, 3}, []int{1, 2})
assert.AssertSubset(t, []string{"Hello", "World", "Test"}, []string{"Test", "World"})
AssertTestFails
func AssertTestFails(t testRunner, test func(t TestingPackageWithFailFunctions), msg ...any)

AssertTestFails asserts that a unit test fails. A unit test fails if one of the following methods is called in the test function: Error, Errorf, Fail, FailNow, Fatal, Fatalf

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertTestFails(t, func(t assert.TestingPackageWithFailFunctions) {
	assert.AssertTrue(t, false)
}) // => Pass

assert.AssertTestFails(t, func(t assert.TestingPackageWithFailFunctions) {
	// ...
	t.Fail() // Or any other failing method.
}) // => Pass
AssertTrue
func AssertTrue(t testRunner, value any, msg ...any)

AssertTrue asserts that an expression or object resolves to true.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertTrue(t, true)
assert.AssertTrue(t, 1 == 1)
assert.AssertTrue(t, 2 != 3)
assert.AssertTrue(t, 1 > 0 && 4 < 5)
AssertUnique
func AssertUnique[elementType comparable](t testRunner, list []elementType, msg ...any)

AssertUnique asserts that the list contains only unique elements. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertUnique(t, []int{1, 2, 3})
assert.AssertUnique(t, []string{"Hello", "World", "!"})
AssertZero
func AssertZero(t testRunner, value any, msg ...any)

AssertZero asserts that the value is the zero value for it's type.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertZero(t, 0)
assert.AssertZero(t, false)
assert.AssertZero(t, "")

Capture

CaptureStderr
func CaptureStderr(capture func(w io.Writer) error) (string, error)

CaptureStderr captures everything written to stderr from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stderr, err := assert.CaptureStderr(func(w io.Writer) error {
	_, err := fmt.Fprint(os.Stderr, "Hello, World!")
	assert.AssertNoError(t, err)
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello, World!", stderr)
CaptureStdout
func CaptureStdout(capture func(w io.Writer) error) (string, error)

CaptureStdout captures everything written to stdout from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stdout, err := assert.CaptureStdout(func(w io.Writer) error {
	fmt.Println("Hello, World!")
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello, World!", stdout)
CaptureStdoutAndStderr
func CaptureStdoutAndStderr(capture func(stdoutWriter, stderrWriter io.Writer) error) (stdout, stderr string, err error)

CaptureStdoutAndStderr captures everything written to stdout and stderr from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stdout, stderr, err := assert.CaptureStdoutAndStderr(func(stdoutWriter, stderrWriter io.Writer) error {
	fmt.Fprint(os.Stdout, "Hello")
	fmt.Fprint(os.Stderr, "World")
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello", stdout)
assert.AssertEqual(t, "World", stderr)

Fuzz Booleans

FuzzBoolFull
func FuzzBoolFull() []bool

FuzzBoolFull returns true and false in a boolean slice.

Fuzz Float64s

FuzzFloat64Full
func FuzzFloat64Full() (floats []float64)

FuzzFloat64Full returns a combination of every float64 testset and some random float64s (positive and negative).

FuzzFloat64GenerateRandomNegative
func FuzzFloat64GenerateRandomNegative(count int, min float64) (floats []float64)

FuzzFloat64GenerateRandomNegative generates random negative integers with a minimum of min. If the minimum is positive, it will be converted to a negative number. If it is set to 0, there is no limit.

FuzzFloat64GenerateRandomPositive
func FuzzFloat64GenerateRandomPositive(count int, max float64) (floats []float64)

FuzzFloat64GenerateRandomPositive generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

FuzzFloat64GenerateRandomRange
func FuzzFloat64GenerateRandomRange(count int, min, max float64) (floats []float64)

FuzzFloat64GenerateRandomRange generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

Fuzz Integers

FuzzIntFull
func FuzzIntFull() (ints []int)

FuzzIntFull returns a combination of every integer testset and some random integers (positive and negative).

FuzzIntGenerateRandomNegative
func FuzzIntGenerateRandomNegative(count, min int) (ints []int)

FuzzIntGenerateRandomNegative generates random negative integers with a minimum of min. If the minimum is 0, or above, the maximum will be set to math.MinInt64.

FuzzIntGenerateRandomPositive
func FuzzIntGenerateRandomPositive(count, max int) (ints []int)

FuzzIntGenerateRandomPositive generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

FuzzIntGenerateRandomRange
func FuzzIntGenerateRandomRange(count, min, max int) (ints []int)

FuzzIntGenerateRandomRange generates random integers with a range of min to max.

Fuzz Strings

FuzzStringEmailAddresses
func FuzzStringEmailAddresses() []string

FuzzStringEmailAddresses returns a test set with valid email addresses. The addresses may look like they are invalid, but they are all conform to RFC 2822 and could be used. You can use this test set to test your email validation process.

FuzzStringEmpty
func FuzzStringEmpty() []string

FuzzStringEmpty returns a test set with a single empty string.

FuzzStringFull
func FuzzStringFull() (ret []string)

FuzzStringFull contains all string test sets plus ten generated random strings. This test set is huge and should only be used if you want to make sure that no string, at all, can crash a process.

FuzzStringGenerateRandom
func FuzzStringGenerateRandom(count, length int) (result []string)

FuzzStringGenerateRandom returns random strings in a test set.

FuzzStringHtmlTags
func FuzzStringHtmlTags() []string

FuzzStringHtmlTags returns a test set with different html tags.

Example:

FuzzStringLong
func FuzzStringLong() (testSet []string)

FuzzStringLong returns a test set with long random strings. Returns: [0]: Random string (length: 25) [1]: Random string (length: 50) [2]: Random string (length: 100) [3]: Random string (length: 1,000) [4]: Random string (length: 100,000)

FuzzStringNumeric
func FuzzStringNumeric() []string

FuzzStringNumeric returns a test set with strings that are numeric. The highest number in here is "9223372036854775807", which is equal to the maxmim int64.

FuzzStringUsernames
func FuzzStringUsernames() []string

FuzzStringUsernames returns a test set with usernames.

Fuzz Utils

FuzzUtilDistinctSet
func FuzzUtilDistinctSet[setType comparable](testSet []setType) []setType

FuzzUtilDistinctSet returns a set with removed duplicates.

Example:

uniqueSet := assert.FuzzUtilDistinctSet([]string{"A", "C", "A", "B", "A", "B", "C"})
// uniqueSet => []string{"A", "C", "B"}
FuzzUtilLimitSet
func FuzzUtilLimitSet[setType any](testSet []setType, max int) []setType

FuzzUtilLimitSet returns a random sample of a test set with a maximal size.

Example:

limitedSet := assert.FuzzUtilLimitSet(assert.FuzzStringFull(), 10)
FuzzUtilMergeSets
func FuzzUtilMergeSets[setType any](sets ...[]setType) (merged []setType)

FuzzUtilMergeSets merges multiple test sets into one. All test sets must have the same type.

Example:

mergedSet := assert.FuzzUtilMergeSets(assert.FuzzIntGenerateRandomNegative(3, 0), assert.FuzzIntGenerateRandomPositive(2, 0))
FuzzUtilModifySet
func FuzzUtilModifySet[setType any](inputSet []setType, modifier func(index int, value setType) setType) (floats []setType)

FuzzUtilModifySet returns a modified version of a test set.

Example:

 modifiedSet := assert.FuzzUtilModifySet(assert.FuzzIntFull(), func(i int, value int) int {
		return i * 2 // double every value in the test set
	})
FuzzUtilRunTests
func FuzzUtilRunTests[setType any](t testRunner, testSet []setType, testFunc func(t *testing.T, index int, f setType))

FuzzUtilRunTests runs a test for every value in a test set. You can use the value as input parameter for your functions, to sanity test against many different cases. This ensures that your functions have a correct error handling and enables you to test against hundreds of cases easily.

Example:

assert.FuzzUtilRunTests(t, assert.FuzzStringEmailAddresses(), func(t *testing.T, index int, emailAddress string) {
	// Test logic
	// err := YourFunction(emailAddress)
	// assert.AssertNoError(t, err)
	// ...
})

GetColorsEnabled
func GetColorsEnabled() bool

GetColorsEnabled returns current value of ColorsEnabled setting. ColorsEnabled controls if assert should print colored output.

GetDiffContextLines
func GetDiffContextLines() int

GetDiffContextLines returns current value of DiffContextLines setting. DiffContextLines setting controls how many lines are shown around a changed diff line. If set to -1 it will show full diff.

GetLineNumbersEnabled
func GetLineNumbersEnabled() bool

GetLineNumbersEnabled returns current value of LineNumbersEnabled setting. LineNumbersEnabled controls if line numbers should be printed in failing tests.

GetRandomSeed
func GetRandomSeed() int64

GetRandomSeed returns current value of the random seed setting.

GetShowStartupMessage
func GetShowStartupMessage() bool

GetShowStartupMessage returns current value of showStartupMessage setting. showStartupMessage setting controls if the startup message should be printed.

Settings

SetColorsEnabled
func SetColorsEnabled(enabled bool)

SetColorsEnabled controls if assert should print colored output. You should use this in the init() method of the package, which contains your tests.

This setting can also be set by the command line flag --assert.disable-color.

Example:

init() {
  assert.SetColorsEnabled(false) // Disable colored output
  assert.SetColorsEnabled(true)  // Enable colored output
}
SetDiffContextLines
func SetDiffContextLines(lines int)

SetDiffContextLines controls how many lines are shown around a changed diff line. If set to -1 it will show full diff. You should use this in the init() method of the package, which contains your tests.

This setting can also be set by the command line flag --assert.diff-context-lines.

Example:

init() {
  assert.SetDiffContextLines(-1) // Show all diff lines
  assert.SetDiffContextLines(3)  // Show 3 lines around every changed line
}
SetLineNumbersEnabled
func SetLineNumbersEnabled(enabled bool)

SetLineNumbersEnabled controls if line numbers should be printed in failing tests. You should use this in the init() method of the package, which contains your tests.

This setting can also be set by the command line flag --assert.disable-line-numbers.

Example:

init() {
  assert.SetLineNumbersEnabled(false) // Disable line numbers
  assert.SetLineNumbersEnabled(true)  // Enable line numbers
}
SetRandomSeed
func SetRandomSeed(seed int64)

SetRandomSeed sets the seed for the random generator used in assert. Using the same seed will result in the same random sequences each time and guarantee a reproducible test run. Use this setting, if you want a 100% deterministic test. You should use this in the init() method of the package, which contains your tests.

This setting can also be set by the command line flag --assert.seed.

Example:

init() {
  assert.SetRandomSeed(1337) // Set the seed to 1337
  assert.SetRandomSeed(time.Now().UnixNano()) // Set the seed back to the current time (default | non-deterministic)
}
SetShowStartupMessage
func SetShowStartupMessage(show bool)

SetShowStartupMessage controls if the startup message should be printed. You should use this in the init() method of the package, which contains your tests.

This setting can also be set by the command line flag --assert.disable-startup-message.

Example:

init() {
  assert.SetShowStartupMessage(false) // Disable the startup message
  assert.SetShowStartupMessage(true)  // Enable the startup message
}

Snapshot

SnapshotCreate
func SnapshotCreate(name string, snapshotObject any) error

SnapshotCreate creates a snapshot of an object, which can be validated in future test runs. Using this function directly will override previous snapshots with the same name. You most likely want to use SnapshotCreateOrValidate.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotCreate(t.Name(), objectToBeSnapshotted)
SnapshotCreateOrValidate
func SnapshotCreateOrValidate(t testRunner, name string, object any, msg ...any) error

SnapshotCreateOrValidate creates a snapshot of an object which can be used in future test runs. It is good practice to name your snapshots the same as the test they are created in. You can do that automatically by using t.Name() as the second parameter, if you are using the inbuilt test system of Go. If a snapshot already exists, the function will not create a new one, but validate the exisiting one. To re-create a snapshot, you can delete the according file in /testdata/snapshots/.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotCreateOrValidate(t, t.Name(), object)
assert.SnapshotCreateOrValidate(t, t.Name(), object, "Optional Message")
SnapshotValidate
func SnapshotValidate(t testRunner, name string, actual any, msg ...any) error

SnapshotValidate validates an already exisiting snapshot of an object. You most likely want to use SnapshotCreateOrValidate.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotValidate(t, t.Name(), objectToBeValidated)
assert.SnapshotValidate(t, t.Name(), objectToBeValidated, "Optional message")

Made with ❤️ by @MarvinJWendt and contributors! | MarvinJWendt.com

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureStderr

func CaptureStderr(capture func(w io.Writer) error) (string, error)

CaptureStderr captures everything written to stderr from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stderr, err := assert.CaptureStderr(func(w io.Writer) error {
	_, err := fmt.Fprint(os.Stderr, "Hello, World!")
	assert.AssertNoError(t, err)
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello, World!", stderr)

func CaptureStdout

func CaptureStdout(capture func(w io.Writer) error) (string, error)

CaptureStdout captures everything written to stdout from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stdout, err := assert.CaptureStdout(func(w io.Writer) error {
	fmt.Println("Hello, World!")
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello, World!", stdout)

func CaptureStdoutAndStderr

func CaptureStdoutAndStderr(capture func(stdoutWriter, stderrWriter io.Writer) error) (stdout, stderr string, err error)

CaptureStdoutAndStderr captures everything written to stdout and stderr from a specific function. You can use this method in tests, to validate that your functions writes a string to the terminal.

Example:

stdout, stderr, err := assert.CaptureStdoutAndStderr(func(stdoutWriter, stderrWriter io.Writer) error {
	fmt.Fprint(os.Stdout, "Hello")
	fmt.Fprint(os.Stderr, "World")
	return nil
})

assert.AssertNoError(t, err)
assert.AssertEqual(t, "Hello", stdout)
assert.AssertEqual(t, "World", stderr)

func CompletesIn

func CompletesIn(t testRunner, duration time.Duration, f func(), msg ...any)

CompletesIn asserts that a function completes in a given time. Use this function to test that functions do not take too long to complete.

NOTE: Every system takes a different amount of time to complete a function. Do not set the duration too low, if you want consistent results.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertCompletesIn(t, 2 * time.Second, func() {
	// some code that should take less than 2 seconds...
}) // => PASS

func Contains

func Contains(t testRunner, object, element any, msg ...any)

Contains asserts that a string/list/array/slice/map contains the specified element.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertContains(t, []int{1,2,3}, 2)
assert.AssertContains(t, []string{"Hello", "World"}, "World")
assert.AssertContains(t, "Hello, World!", "World")

func Decreasing

func Decreasing(t testRunner, object any, msg ...any)

Decreasing asserts that the values in a slice are decreasing. the test fails if the values are not in a slice or if the values are not comparable.

Valid input kinds are: []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []float32, []float64.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDecreasing(t, []int{1000, 137, 2, 1})
assert.AssertDecreasing(t, []float32{13.5, 7, 0.1, -10.3})

func DirEmpty

func DirEmpty(t testRunner, dir string, msg ...any)

DirEmpty asserts that a directory is empty. The test will pass when the directory is empty or does not exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirEmpty(t, "FolderName")

func DirExists

func DirExists(t testRunner, dir string, msg ...any)

DirExists asserts that a directory exists. The test will pass when the directory exists, and it's visible to the current user. The test will fail, if the path points to a file.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirExists(t, "FolderName")

func DirNotEmpty

func DirNotEmpty(t testRunner, dir string, msg ...any)

DirNotEmpty asserts that a directory is not empty The test will pass when the directory is not empty and will fail if the directory does not exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertDirNotEmpty(t, "FolderName")

func Equal

func Equal(t testRunner, expected any, actual any, msg ...any)

Equal asserts that two objects are equal.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertEqual(t, "Hello, World!", "Hello, World!")
assert.AssertEqual(t, true, true)

func EqualAsString added in v0.0.5

func EqualAsString(t testRunner, expected any, actual any, msg ...any)

func EqualLength added in v0.0.6

func EqualLength[T any, U any](t testRunner, expected []T, actual []U, msg ...any)

func EqualValues

func EqualValues(t testRunner, expected any, actual any, msg ...any)

EqualValues asserts that two objects have equal values. The order of the values is also validated.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertEqualValues(t, []string{"Hello", "World"}, []string{"Hello", "World"})
assert.AssertEqualValues(t, []int{1,2}, []int{1,2})
assert.AssertEqualValues(t, []int{1,2}, []int{2,1}) // FAILS (wrong order)

Comparing struct values:

person1 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

person2 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

assert.AssertEqualValues(t, person1, person2)

func Error added in v0.0.2

func Error(t testRunner, err error, msg ...any)

Error asserts that an error is not nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

err := errors.New("hello world")
assert.AssertError(t, err)

func ErrorIs

func ErrorIs(t testRunner, err, target error, msg ...any)

ErrorIs asserts that target is inside the error chain of err.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

var testErr = errors.New("hello world")
var testErrWrapped = fmt.Errorf("test err: %w", testErr)
assert.AssertErrorIs(t, testErrWrapped ,testErr)

func FailNow added in v0.0.3

func FailNow(t testRunner, msg ...any)

func FakeFirstName added in v0.0.6

func FakeFirstName() string

func FakeLastName added in v0.0.6

func FakeLastName() string

func False

func False(t testRunner, value any, msg ...any)

False asserts that an expression or object resolves to false.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertFalse(t, false)
assert.AssertFalse(t, 1 == 2)
assert.AssertFalse(t, 2 != 2)
assert.AssertFalse(t, 1 > 5 && 4 < 0)

func FileExists

func FileExists(t testRunner, file string, msg ...any)

FileExists asserts that a file exists.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertFileExists(t, "./test.txt")
assert.AssertFileExists(t, "./config.yaml", "the config file is missing")

func FuzzBoolFull

func FuzzBoolFull() []bool

FuzzBoolFull returns true and false in a boolean slice.

func FuzzFloat64Full

func FuzzFloat64Full() (floats []float64)

FuzzFloat64Full returns a combination of every float64 testset and some random float64s (positive and negative).

func FuzzFloat64GenerateRandomNegative

func FuzzFloat64GenerateRandomNegative(count int, min float64) (floats []float64)

FuzzFloat64GenerateRandomNegative generates random negative integers with a minimum of min. If the minimum is positive, it will be converted to a negative number. If it is set to 0, there is no limit.

func FuzzFloat64GenerateRandomPositive

func FuzzFloat64GenerateRandomPositive(count int, max float64) (floats []float64)

FuzzFloat64GenerateRandomPositive generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

func FuzzFloat64GenerateRandomRange

func FuzzFloat64GenerateRandomRange(count int, min, max float64) []float64

FuzzFloat64GenerateRandomRange generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

func FuzzIntFull

func FuzzIntFull() (ints []int)

FuzzIntFull returns a combination of every integer testset and some random integers (positive and negative).

func FuzzIntGenerateRandomNegative

func FuzzIntGenerateRandomNegative(count, min int) (ints []int)

FuzzIntGenerateRandomNegative generates random negative integers with a minimum of min. If the minimum is 0, or above, the maximum will be set to math.MinInt64.

func FuzzIntGenerateRandomPositive

func FuzzIntGenerateRandomPositive(count, max int) (ints []int)

FuzzIntGenerateRandomPositive generates random positive integers with a maximum of max. If the maximum is 0, or below, the maximum will be set to math.MaxInt64.

func FuzzIntGenerateRandomRange

func FuzzIntGenerateRandomRange(count, min, max int) (ints []int)

FuzzIntGenerateRandomRange generates random integers with a range of min to max.

func FuzzStringEmailAddresses

func FuzzStringEmailAddresses() []string

FuzzStringEmailAddresses returns a test set with valid email addresses. The addresses may look like they are invalid, but they are all conform to RFC 2822 and could be used. You can use this test set to test your email validation process.

func FuzzStringEmpty

func FuzzStringEmpty() []string

FuzzStringEmpty returns a test set with a single empty string.

func FuzzStringFull

func FuzzStringFull() (ret []string)

FuzzStringFull contains all string test sets plus ten generated random strings. This test set is huge and should only be used if you want to make sure that no string, at all, can crash a process.

func FuzzStringGenerateRandom

func FuzzStringGenerateRandom(count, length int) (result []string)

FuzzStringGenerateRandom returns random strings in a test set.

func FuzzStringHtmlTags

func FuzzStringHtmlTags() []string

FuzzStringHtmlTags returns a test set with different html tags.

Example:

func FuzzStringLong

func FuzzStringLong() (testSet []string)

FuzzStringLong returns a test set with long random strings. Returns: [0]: Random string (length: 25) [1]: Random string (length: 50) [2]: Random string (length: 100) [3]: Random string (length: 1,000) [4]: Random string (length: 100,000)

func FuzzStringNumeric

func FuzzStringNumeric() []string

FuzzStringNumeric returns a test set with strings that are numeric. The highest number in here is "9223372036854775807", which is equal to the maxmim int64.

func FuzzStringUsernames

func FuzzStringUsernames() []string

FuzzStringUsernames returns a test set with usernames.

func FuzzUtilDistinctSet

func FuzzUtilDistinctSet[setType comparable](testSet []setType) []setType

FuzzUtilDistinctSet returns a set with removed duplicates.

Example:

uniqueSet := assert.FuzzUtilDistinctSet([]string{"A", "C", "A", "B", "A", "B", "C"})
// uniqueSet => []string{"A", "C", "B"}

func FuzzUtilLimitSet

func FuzzUtilLimitSet[setType any](testSet []setType, max int) []setType

FuzzUtilLimitSet returns a random sample of a test set with a maximal size.

Example:

limitedSet := assert.FuzzUtilLimitSet(assert.FuzzStringFull(), 10)

func FuzzUtilMergeSets

func FuzzUtilMergeSets[setType any](sets ...[]setType) (merged []setType)

FuzzUtilMergeSets merges multiple test sets into one. All test sets must have the same type.

Example:

mergedSet := assert.FuzzUtilMergeSets(assert.FuzzIntGenerateRandomNegative(3, 0), assert.FuzzIntGenerateRandomPositive(2, 0))

func FuzzUtilModifySet

func FuzzUtilModifySet[setType any](inputSet []setType, modifier func(index int, value setType) setType) (floats []setType)

FuzzUtilModifySet returns a modified version of a test set.

Example:

 modifiedSet := assert.FuzzUtilModifySet(assert.FuzzIntFull(), func(i int, value int) int {
		return i * 2 // double every value in the test set
	})

func FuzzUtilRunTests

func FuzzUtilRunTests[setType any](t testRunner, testSet []setType, testFunc func(t *testing.T, index int, f setType))

FuzzUtilRunTests runs a test for every value in a test set. You can use the value as input parameter for your functions, to sanity test against many different cases. This ensures that your functions have a correct error handling and enables you to test against hundreds of cases easily.

Example:

assert.FuzzUtilRunTests(t, assert.FuzzStringEmailAddresses(), func(t *testing.T, index int, emailAddress string) {
	// Test logic
	// err := YourFunction(emailAddress)
	// assert.AssertNoError(t, err)
	// ...
})

func GetColorsEnabled

func GetColorsEnabled() bool

GetColorsEnabled returns current value of ColorsEnabled setting. ColorsEnabled controls if assert should print colored output.

func GetDiffContextLines

func GetDiffContextLines() int

GetDiffContextLines returns current value of DiffContextLines setting. DiffContextLines setting controls how many lines are shown around a changed diff line. If set to -1 it will show full diff.

func GetLineNumbersEnabled

func GetLineNumbersEnabled() bool

GetLineNumbersEnabled returns current value of LineNumbersEnabled setting. LineNumbersEnabled controls if line numbers should be printed in failing tests.

func GetRandomSeed

func GetRandomSeed() int64

GetRandomSeed returns current value of the random seed setting.

func GetShowStartupMessage

func GetShowStartupMessage() bool

GetShowStartupMessage returns current value of showStartupMessage setting. showStartupMessage setting controls if the startup message should be printed.

func Greater

func Greater[T constraints.Ordered](t testRunner, object1, object2 T, msg ...any)

Greater asserts that the first object is greater than the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertGreater(t, 5, 1)
assert.AssertGreater(t, 10, -10)

func GreaterOrEqual

func GreaterOrEqual[T constraints.Ordered](t testRunner, object1, object2 T, msg ...interface{})

GreaterOrEqual asserts that the first object is greater than or equal to the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertGreaterOrEqual(t, 5, 1)
assert.AssertGreaterOrEqual(t, 10, -10)

assert.AssertGreaterOrEqual(t, 10, 10)

func HasPrefix added in v0.0.5

func HasPrefix(t testRunner, s string, prefix string, msg ...any)

func HasSuffix added in v0.0.5

func HasSuffix(t testRunner, s string, suffix string, msg ...any)

func Implements

func Implements(t testRunner, interfaceObject, object any, msg ...any)

Implements asserts that an objects implements an interface.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertImplements(t, (*YourInterface)(nil), new(YourObject))
assert.AssertImplements(t, (*fmt.Stringer)(nil), new(types.Const)) => pass

func InRange

func InRange[T constraints.Ordered](t testRunner, value T, min T, max T, msg ...any)

InRange asserts that the value is in the range.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertInRange(t, 5, 1, 10)

func Increasing

func Increasing(t testRunner, object any, msg ...any)

Increasing asserts that the values in a slice are increasing. the test fails if the values are not in a slice or if the values are not comparable.

Valid input kinds are: []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []float32, []float64.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertIncreasing(t, []int{1, 2, 137, 1000})
assert.AssertIncreasing(t, []float32{-10.3, 0.1, 7, 13.5})

func JSONEqual added in v0.0.4

func JSONEqual(t testRunner, expected string, actual string, msg ...any)

func KindOf

func KindOf(t testRunner, expectedKind reflect.Kind, object any, msg ...any)

KindOf asserts that the object is a type of kind exptectedKind.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertKindOf(t, reflect.Slice, []int{1,2,3})
assert.AssertKindOf(t, reflect.Slice, []string{"Hello", "World"})
assert.AssertKindOf(t, reflect.Int, 1337)
assert.AssertKindOf(t, reflect.Bool, true)
assert.AssertKindOf(t, reflect.Map, map[string]bool{})

func Len

func Len(t testRunner, object any, length int, msg ...any)

Len asserts that the length of an object is equal to the given length.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLen(t, "abc", 3)
assert.AssertLen(t, "Assert", 6)
assert.AssertLen(t, []int{1, 2, 1337, 25}, 4)
assert.AssertLen(t, map[string]int{"asd": 1, "test": 1337}, 2)

func Less

func Less[T constraints.Ordered](t testRunner, object1, object2 T, msg ...any)

Less asserts that the first object is less than the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLess(t, 1, 5)
assert.AssertLess(t, -10, 10)

func LessOrEqual

func LessOrEqual[T constraints.Ordered](t testRunner, v1, v2 T, msg ...interface{})

LessOrEqual asserts that the first object is less than or equal to the second.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertLessOrEqual(t, 1, 5)
assert.AssertLessOrEqual(t, -10, 10)
assert.AssertLessOrEqual(t, 1, 1)

func Nil

func Nil(t testRunner, object any, msg ...any)

Nil asserts that an object is nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNil(t, nil)

func NoDirExists

func NoDirExists(t testRunner, dir string, msg ...any)

NoDirExists asserts that a directory does not exists. The test will pass, if the path points to a file, as a directory with the same name, cannot exist.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNoDirExists(t, "FolderName")

func NoError

func NoError(t testRunner, err error, msg ...any)

NoError asserts that an error is nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

err := nil
assert.AssertNoError(t, err)

func NoFileExists

func NoFileExists(t testRunner, file string, msg ...any)

func NoSubset

func NoSubset[T comparable](t testRunner, list []T, subset []T, msg ...any)

NoSubset asserts that the second parameter is not a subset of the list. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNoSubset(t, []int{1, 2, 3}, []int{1, 7})
assert.AssertNoSubset(t, []string{"Hello", "World", "Test"}, []string{"Test", "John"})

func NotCompletesIn

func NotCompletesIn(t testRunner, duration time.Duration, f func(), msg ...any)

NotCompletesIn asserts that a function does not complete in a given time. Use this function to test that functions do not complete to quickly. For example if your database connection completes in under a millisecond, there might be something wrong.

NOTE: Every system takes a different amount of time to complete a function. Do not set the duration too high, if you want consistent results.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotCompletesIn(t, 2 * time.Second, func() {
	// some code that should take more than 2 seconds...
	time.Sleep(3 * time.Second)
}) // => PASS

func NotContains

func NotContains(t testRunner, object, element any, msg ...any)

NotContains asserts that a string/list/array/slice/map does not contain the specified element.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotContains(t, []string{"Hello", "World"}, "Spaceship")
assert.AssertNotContains(t, "Hello, World!", "Spaceship")

func NotEqual

func NotEqual(t testRunner, expected any, actual any, msg ...any)

NotEqual asserts that two objects are not equal.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotEqual(t, true, false)
assert.AssertNotEqual(t, "Hello", "World")

func NotEqualValues

func NotEqualValues(t testRunner, expected any, actual any, msg ...any)

NotEqualValues asserts that two objects do not have equal values.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotEqualValues(t, []int{1,2}, []int{3,4})

Comparing struct values:

person1 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "male",
}

person2 := Person{
  Name:   "Marvin Wendt",
  Age:    20,
  Gender: "female", // <-- CHANGED
}

assert.AssertNotEqualValues(t, person1, person2)

func NotErrorIs

func NotErrorIs(t testRunner, err, target error, msg ...any)

NotErrorIs

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

var testErr = errors.New("hello world")
var test2Err = errors.New("hello world 2")
var testErrWrapped = fmt.Errorf("test err: %w", testErr)
assert.AssertNotErrorIs(t, testErrWrapped, test2Err)

func NotImplements

func NotImplements(t testRunner, interfaceObject, object any, msg ...any)

NotImplements asserts that an object does not implement an interface.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotImplements(t, (*YourInterface)(nil), new(YourObject))
assert.AssertNotImplements(t, (*fmt.Stringer)(nil), new(types.Const)) => fail, because types.Const does implement fmt.Stringer.

func NotInRange

func NotInRange[T constraints.Ordered](t testRunner, value T, min T, max T, msg ...any)

NotInRange asserts that the value is not in the range.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotInRange(t, 5, 1, 10)

func NotKindOf

func NotKindOf(t testRunner, kind reflect.Kind, object any, msg ...any)

NotKindOf asserts that the object is not a type of kind `kind`.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotKindOf(t, reflect.Slice, "Hello, World")
assert.AssertNotKindOf(t, reflect.Slice, true)
assert.AssertNotKindOf(t, reflect.Int, 13.37)
assert.AssertNotKindOf(t, reflect.Bool, map[string]bool{})
assert.AssertNotKindOf(t, reflect.Map, false)

func NotNil

func NotNil(t testRunner, object any, msg ...any)

NotNil asserts that an object is not nil.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotNil(t, true)
assert.AssertNotNil(t, "Hello, World!")
assert.AssertNotNil(t, 0)

func NotNumeric

func NotNumeric(t testRunner, object any, msg ...any)

NotNumeric checks if the object is not a numeric type. Numeric types are: Int, Int8, Int16, Int32, Int64, Float32, Float64, Uint, Uint8, Uint16, Uint32, Uint64, Complex64 and Complex128.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotNumeric(t, true)
assert.AssertNotNumeric(t, "123")

func NotPanics

func NotPanics(t testRunner, f func(), msg ...any)

NotPanics asserts that a function does not panic.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotPanics(t, func() {
	// some code that does not call a panic...
}) // => PASS

func NotRegexp

func NotRegexp(t testRunner, regex any, txt any, msg ...any)

NotRegexp asserts that a string does not match a given regexp.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotRegexp(t, "ab.*", "Hello, World!")

func NotSameElements

func NotSameElements[T comparable](t testRunner, expected []T, actual []T, msg ...any)

NotSameElements asserts that two slices contains same elements (including pointers). The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

 assert.AssertNotSameElements(t, []string{"Hello", "World"}, []string{"Hello", "World", "World"})
 assert.AssertNotSameElements(t, []int{1,2}, []int{1,2,3})

 type A struct {
	  a string
 }
 assert.AssertNotSameElements(t, []*A{{a: "A"}, {a: "B"}, {a: "C"}}, []*A{{a: "A"}, {a: "B"}, {a: "C"}, {a: "D"}})

func NotUnique

func NotUnique[elementType comparable](t testRunner, list []elementType, msg ...any)

NotUnique asserts that the elements in a list are not unique.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotUnique(t, []int{1, 2, 3, 3})

func NotZero

func NotZero(t testRunner, value any, msg ...any)

NotZero asserts that the value is not the zero value for it's type.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNotZero(t, 1337)
assert.AssertNotZero(t, true)
assert.AssertNotZero(t, "Hello, World")

func Numeric

func Numeric(t testRunner, object any, msg ...any)

Numeric asserts that the object is a numeric type. Numeric types are: Int, Int8, Int16, Int32, Int64, Float32, Float64, Uint, Uint8, Uint16, Uint32, Uint64, Complex64 and Complex128.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertNumeric(t, 123)
assert.AssertNumeric(t, 1.23)
assert.AssertNumeric(t, uint(123))

func Panics

func Panics(t testRunner, f func(), msg ...any)

Panics asserts that a function panics.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertPanics(t, func() {
	// ...
	panic("some panic")
}) // => PASS

func Regexp

func Regexp(t testRunner, regex any, txt any, msg ...any)

Regexp asserts that a string matches a given regexp.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertRegexp(t, "^a.*c$", "abc")

func SameElements

func SameElements[T comparable](t testRunner, expected []T, actual []T, msg ...any)

SameElements asserts that two slices contains same elements (including pointers). The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

 assert.AssertSameElements(t, []string{"Hello", "World"}, []string{"Hello", "World"})
 assert.AssertSameElements(t, []int{1,2,3}, []int{1,2,3})
 assert.AssertSameElements(t, []int{1,2}, []int{2,1})

 type A struct {
	  a string
 }
 assert.AssertSameElements(t, []*A{{a: "A"}, {a: "B"}, {a: "C"}}, []*A{{a: "A"}, {a: "B"}, {a: "C"}})

func SetColorsEnabled

func SetColorsEnabled(enabled bool)

SetColorsEnabled controls if assert should print colored output. You should use this in the init() method of the package, which contains your tests.

> This setting can also be set by the command line flag --assert.disable-color.

Example:

init() {
  assert.SetColorsEnabled(false) // Disable colored output
  assert.SetColorsEnabled(true)  // Enable colored output
}

func SetDiffContextLines

func SetDiffContextLines(lines int)

SetDiffContextLines controls how many lines are shown around a changed diff line. If set to -1 it will show full diff. You should use this in the init() method of the package, which contains your tests.

> This setting can also be set by the command line flag --assert.diff-context-lines.

Example:

init() {
  assert.SetDiffContextLines(-1) // Show all diff lines
  assert.SetDiffContextLines(3)  // Show 3 lines around every changed line
}

func SetLineNumbersEnabled

func SetLineNumbersEnabled(enabled bool)

SetLineNumbersEnabled controls if line numbers should be printed in failing tests. You should use this in the init() method of the package, which contains your tests.

> This setting can also be set by the command line flag --assert.disable-line-numbers.

Example:

init() {
  assert.SetLineNumbersEnabled(false) // Disable line numbers
  assert.SetLineNumbersEnabled(true)  // Enable line numbers
}

func SetRandomSeed

func SetRandomSeed(seed int64)

SetRandomSeed sets the seed for the random generator used in assert. Using the same seed will result in the same random sequences each time and guarantee a reproducible test run. Use this setting, if you want a 100% deterministic test. You should use this in the init() method of the package, which contains your tests.

> This setting can also be set by the command line flag --assert.seed.

Example:

init() {
  assert.SetRandomSeed(1337) // Set the seed to 1337
  assert.SetRandomSeed(time.Now().UnixNano()) // Set the seed back to the current time (default | non-deterministic)
}

func SetShowStartupMessage

func SetShowStartupMessage(show bool)

SetShowStartupMessage controls if the startup message should be printed. You should use this in the init() method of the package, which contains your tests.

> This setting can also be set by the command line flag --assert.disable-startup-message.

Example:

init() {
  assert.SetShowStartupMessage(false) // Disable the startup message
  assert.SetShowStartupMessage(true)  // Enable the startup message
}

func SnapshotCreate

func SnapshotCreate(name string, snapshotObject any) error

SnapshotCreate creates a snapshot of an object, which can be validated in future test runs. Using this function directly will override previous snapshots with the same name. You most likely want to use SnapshotCreateOrValidate.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotCreate(t.Name(), objectToBeSnapshotted)

func SnapshotCreateOrValidate

func SnapshotCreateOrValidate(t testRunner, name string, object any, msg ...any) error

SnapshotCreateOrValidate creates a snapshot of an object which can be used in future test runs. It is good practice to name your snapshots the same as the test they are created in. You can do that automatically by using t.Name() as the second parameter, if you are using the inbuilt test system of Go. If a snapshot already exists, the function will not create a new one, but validate the exisiting one. To re-create a snapshot, you can delete the according file in /testdata/snapshots/.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotCreateOrValidate(t, t.Name(), object)
assert.SnapshotCreateOrValidate(t, t.Name(), object, "Optional Message")

func SnapshotValidate

func SnapshotValidate(t testRunner, name string, actual any, msg ...any) error

SnapshotValidate validates an already exisiting snapshot of an object. You most likely want to use SnapshotCreateOrValidate.

NOTICE: \r\n will be replaced with \n to make the files consistent between operating systems.

Example:

assert.SnapshotValidate(t, t.Name(), objectToBeValidated)
assert.SnapshotValidate(t, t.Name(), objectToBeValidated, "Optional message")

func Subset

func Subset[T comparable](t testRunner, list []T, subset []T, msg ...any)

Subset asserts that the second parameter is a subset of the list. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertSubset(t, []int{1, 2, 3}, []int{1, 2})
assert.AssertSubset(t, []string{"Hello", "World", "Test"}, []string{"Test", "World"})

func TestFails

func TestFails(t testRunner, test func(t TestingPackageWithFailFunctions), msg ...any)

TestFails asserts that a unit test fails. A unit test fails if one of the following methods is called in the test function: Error, Errorf, Fail, FailNow, Fatal, Fatalf

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertTestFails(t, func(t assert.TestingPackageWithFailFunctions) {
	assert.AssertTrue(t, false)
}) // => Pass

assert.AssertTestFails(t, func(t assert.TestingPackageWithFailFunctions) {
	// ...
	t.Fail() // Or any other failing method.
}) // => Pass

func True

func True(t testRunner, value any, msg ...any)

True asserts that an expression or object resolves to true.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertTrue(t, true)
assert.AssertTrue(t, 1 == 1)
assert.AssertTrue(t, 2 != 3)
assert.AssertTrue(t, 1 > 0 && 4 < 5)

func Unique

func Unique[T comparable](t testRunner, list []T, msg ...any)

Unique asserts that the list contains only unique elements. The order is irrelevant.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertUnique(t, []int{1, 2, 3})
assert.AssertUnique(t, []string{"Hello", "World", "!"})

func Zero

func Zero(t testRunner, value any, msg ...any)

Zero asserts that the value is the zero value for it's type.

When using a custom message, the same formatting as with fmt.Sprintf() is used.

Example:

assert.AssertZero(t, 0)
assert.AssertZero(t, false)
assert.AssertZero(t, "")

Types

type FakeProfile added in v0.0.6

type FakeProfile struct {
	FirstName string
	LastName  string
	FullName  string
	Email     string
}

func GetFakeProfile added in v0.0.6

func GetFakeProfile() *FakeProfile

type TestingPackageWithFailFunctions

type TestingPackageWithFailFunctions interface {
	Error(args ...any)
	Errorf(format string, args ...any)
	Fail()
	FailNow()
	Fatal(args ...any)
	Fatalf(format string, args ...any)
}

TestingPackageWithFailFunctions contains every function that fails a test in testing.T.

Directories

Path Synopsis
Custom CI-System for https://github.com/MarvinJWendt/testza.
Custom CI-System for https://github.com/MarvinJWendt/testza.

Jump to

Keyboard shortcuts

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