errorspec

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: BSD-3-Clause Imports: 3 Imported by: 0

README

errorspec -- error specifications for table tests

Documentation

Overview

Package errorspec provides helpers for asserting error values in tests

var testCases = []struct {
	input   string
	output  string
	errspec errorspec.Assertion
}{
	{
		input:  "hello world",
		output: "OK",
		// default errspec equivalent to errorspec.NoError
	},
	{
		input: "hello, w",
		errspec: errorspec.Is(io.ErrUnexpectedEOF),
	},
	{
		input: "おはよう",
		errspec: errorspec.As(func(t testing.TB, err MyError) bool {
			return assert.Equal(t, "jp", err.LangCode)
		})
	},
}

for _, tc := range testCases {
	t.Run(tc.name, func(t *testing.T) {
		out, err := MyFunc(tc.input)
		assert.Equal(t, tc.output, out)
		errorspec.CheckError(t, tc.errspec, err)
	})
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckError

func CheckError(t testing.TB, assertion Assertion, err error) bool

CheckError applies the given assertion to err and returns the result. Table tests should use this function to evaluate the test case assertion against the error returned by the function under test.

for _, tc := range testCases {
    t.Run(tc.name, func(t *testing.T) {
        out, err := MyFunc(tc.input)
        assert.Equal(t, tc.output, out)
        errorspec.CheckError(t, tc.errspec, err)
    })
}

func Error

func Error(t testing.TB, err error) bool

Error asserts that err is non-nil.

func NoError

func NoError(t testing.TB, err error) bool

NoError asserts that err is nil.

Types

type Assertion

type Assertion = func(t testing.TB, err error) bool

Assertion describes an error value in a test. A nil assertion is treated the same as NoError. Table test structs will typically will include an Assertion field.

type testCase struct {
    name string
    input string
    output any
    errspec errorspec.Assertion
}

func AllOf

func AllOf(asserts ...Assertion) Assertion

AllOf returns an assertion that checks all of the given assertions until one fails. If all assertions pass, the returned assertion passes.

func As

func As[E error](fn func(testing.TB, E) bool) Assertion

As asserts an E type in the error chain. If fn is non-nil it is passed the extracted error for additional checks.

func Is

func Is(target error) Assertion

Is asserts the presence of target in the error chain.

func Require

func Require(assert Assertion) Assertion

Require wraps an assertion so the test fails immediately if the assertion fails.

Jump to

Keyboard shortcuts

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