test

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2024 License: MIT Imports: 10 Imported by: 0

README

test

License Go Reference Go Report Card GitHub CI codecov

A lightweight test helper package 🧪

Project Description

test is my take on a handy, lightweight Go test helper package. Inspired by matryer/is, carlmjohnson/be and others.

It provides a lightweight, but useful, extension to the std lib testing package with a friendlier and hopefully intuitive API. You definitely don't need it, but might find it useful anyway 🙂

Installation

go get github.com/FollowTheProcess/test@latest

Usage

test is as easy as...

func TestSomething(t *testing.T) {
    test.Equal(t, "hello", "hello") // Obviously fine
    test.Equal(t, "hello", "there") // Fails

    test.NotEqual(t, 42, 27) // Passes, these are not equal
    test.NotEqual(t, 42, 42) // Fails

    test.NearlyEqual(t, 3.0000000001, 3.0) // Look, floats handled easily!

    err := doSomething()
    test.Ok(t, err) // Fails if err != nil
    test.Err(t, err) // Fails if err == nil

    // Can even add context
    test.Ok(t, err, "doSomething went wrong")

    test.True(t, true) // Passes
    test.False(t, true) // Fails

    // Get $CWD/testdata easily
    test.Data(t) // /Users/you/project/package/testdata

    // Check against contents of a file (relative to $CWD/testdata)
    // including line ending normalisation
    test.File(t, "expected.txt", "hello\n")

    // Just like the good old reflect.DeepEqual, but with a nicer format
    test.DeepEqual(t, []string{"hello"}, []string{"world"}) // Fails
}
Non Comparable Types

test uses Go 1.18+ generics under the hood for most of the comparison, which is great, but what if your types don't satisfy comparable. We also provide test.EqualFunc and test.NotEqualFunc for those exact situations!

These allow you to pass in a custom comparator function for your type, if your comparator function returns true, the types are considered equal.

func TestNonComparableTypes(t *testing.T) {
    // Slices do not satisfy comparable
    a := []string{"hello", "there"}
    b := []string{"hello", "there"}
    c := []string{"general", "kenobi"}

    // Custom function, returns true if things should be considered equal
    sliceEqual := func(a, b, []string) { return true } // Cheating

    test.EqualFunc(t, a, b, sliceEqual) // Passes

    // Can also use e.g. the new slices package
    test.EqualFunc(t, a, b, slices.Equal[string]) // Also passes :)

    test.EqualFunc(t, a, c, slices.Equal[string]) // Fails
}

You can also use this same pattern for custom user defined types, structs etc.

Rich Comparison

Large structs or long slices can often be difficult to compare using reflect.DeepEqual, you have to scan for the difference yourself. test provides a test.Diff function that produces a rich text diff for you on failure:

func TestDiff(t *testing.T) {
    // Pretend these are very long, or are large structs
    a := []string{"hello", "world"}
    b := []string{"hello", "there"}

    test.Diff(t, a, b)
}

Will give you:

--- FAIL: TestDiff (0.00s)
    main_test.go:14: Mismatch (-want, +got):
          []string{
                "hello",
        -       "there",
        +       "world",
          }
Table Driven Tests

Table driven tests are great! But when you test errors too it can get a bit awkward, you have to do the if (err != nil) != tt.wantErr thing and I personally always have to do the boolean logic in my head to make sure I got that right. Enter test.WantErr:

func TestTableThings(t *testing.T) {
    tests := []struct {
        name    string
        want    int
        wantErr bool
    }{
        {
            name:    "no error",
            want:    4,
            wantErr: false,
        },
        {
            name:    "yes error",
            want:    4,
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := SomeFunction()
    
            test.WantErr(t, err, tt.wantErr)
            test.Equal(t, got, tt.want)
        })
    }
}

Which is basically semantically equivalent to:

func TestTableThings(t *testing.T) {
    tests := []struct {
        name    string
        want    int
        wantErr bool
    }{
        {
            name:    "no error",
            want:    4,
            wantErr: false,
        },
        {
            name:    "yes error",
            want:    4,
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := SomeFunction()
    
            if tt.wantErr {
                test.Err(t, err)
            } else {
                test.Ok(t, err)
            }
            test.Equal(t, got, tt.want)
        })
    }
}
Capturing Stdout and Stderr

We've all been there, trying to test a function that prints but doesn't accept an io.Writer as a destination 🙄.

That's where test.CaptureOutput comes in!

func TestOutput(t *testing.T) {
    // Function that prints to stdout and stderr, but imagine this is defined somewhere else
    // maybe a 3rd party library that you don't control, it just prints and you can't tell it where
    fn := func() error {
        fmt.Fprintln(os.Stdout, "hello stdout")
        fmt.Fprintln(os.Stderr, "hello stderr")

        return nil
    }

    // CaptureOutput to the rescue!
    stdout, stderr := test.CaptureOutput(t, fn)

    test.Equal(t, stdout, "hello stdout\n")
    test.Equal(t, stderr, "hello stderr\n")
}

Under the hood CaptureOutput temporarily captures both streams, copies the data to a buffer and returns the output back to you, before cleaning everything back up again.

Credits

This package was created with copier and the FollowTheProcess/go_copier project template.

Documentation

Overview

Package test provides a lightweight, but useful extension to the std lib's testing package with a friendlier and more intuitive API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureOutput added in v0.9.0

func CaptureOutput(t testing.TB, fn func() error) (stdout, stderr string)

CaptureOutput captures and returns data printed to stdout and stderr by the provided function fn, allowing you to test functions that write to those streams and do not have an option to pass in an io.Writer.

If the provided function returns a non nil error, the test is failed with the error logged as the reason.

If any error occurs capturing stdout or stderr, the test will also be failed with a descriptive log.

fn := func() error {
	fmt.Println("hello stdout")
	return nil
}

stdout, stderr := test.CaptureOutput(t, fn)
fmt.Print(stdout) // "hello stdout\n"
fmt.Print(stderr) // ""

func Data added in v0.6.0

func Data(t testing.TB) string

Data returns the filepath to the testdata directory for the current package.

When running tests, Go will change the cwd to the directory of the package under test. This means that reference data stored in $CWD/testdata can be easily retrieved in the same way for any package.

The $CWD/testdata directory is a Go idiom, common practice, and is completely ignored by the go tool.

Data makes no guarantee that $CWD/testdata exists, it simply returns it's path.

file := filepath.Join(test.Data(t), "test.txt")

func DeepEqual

func DeepEqual(t testing.TB, got, want any)

DeepEqual fails if reflect.DeepEqual(got, want) == false.

func Diff

func Diff(t testing.TB, got, want any)

Diff fails if got != want and provides a rich diff.

If got and want are structs, unexported fields will be included in the comparison.

func Equal

func Equal[T comparable](t testing.TB, got, want T)

Equal fails if got != want.

test.Equal(t, "apples", "apples") // Passes
test.Equal(t, "apples", "oranges") // Fails

func EqualFunc

func EqualFunc[T any](t testing.TB, got, want T, equal func(a, b T) bool)

EqualFunc is like Equal but allows the user to pass a custom comparator, useful when the items to be compared do not implement the comparable generic constraint

The comparator should return true if the two items should be considered equal.

func Err added in v0.2.0

func Err(t testing.TB, err error, context ...string)

Err fails if err == nil.

err := shouldReturnErr()
test.Err(t, err, "shouldReturnErr")

func False

func False(t testing.TB, v bool)

False fails if v is true.

test.False(t, false) // Passes
test.False(t, true) // Fails

func File added in v0.7.0

func File(t testing.TB, file, want string)

File fails if the contents of the given file do not match want.

It takes the name of a file (relative to $CWD/testdata) and the contents to compare.

If the contents differ, the test will fail with output equivalent to test.Diff.

Files with differing line endings (e.g windows CR LF \r\n vs unix LF \n) will be normalised to \n prior to comparison so this function will behave identically across multiple platforms.

test.File(t, "expected.txt", "hello\n")

func NearlyEqual added in v0.8.0

func NearlyEqual[T ~float32 | ~float64](t testing.TB, got, want T)

NearlyEqual is like Equal but for floating point numbers where typically equality often fails.

If the difference between got and want is sufficiently small, they are considered equal.

test.NearlyEqual(t, 3.0000000001, 3.0) // Passes, close enough to be considered equal
test.NearlyEqual(t, 3.0000001, 3.0) // Fails, too different

func NotEqual

func NotEqual[T comparable](t testing.TB, got, want T)

NotEqual fails if got == want.

test.NotEqual(t, "apples", "oranges") // Passes
test.NotEqual(t, "apples", "apples") // Fails

func NotEqualFunc

func NotEqualFunc[T any](t testing.TB, got, want T, equal func(a, b T) bool)

NotEqualFunc is like NotEqual but allows the user to pass a custom comparator, useful when the items to be compared do not implement the comparable generic constraint

The comparator should return true if the two items should be considered equal.

func Ok

func Ok(t testing.TB, err error, context ...string)

Ok fails if err != nil, optionally adding context to the output.

err := doSomething()
test.Ok(t, err, "Doing something")

func True

func True(t testing.TB, v bool)

True fails if v is false.

test.True(t, true) // Passes
test.True(t, false) // Fails

func WantErr added in v0.5.0

func WantErr(t testing.TB, err error, want bool)

WantErr fails if you got an error and didn't want it, or if you didn't get an error but wanted one.

It simplifies checking for errors in table driven tests where on any iteration err may or may not be nil.

test.WantErr(t, errors.New("uh oh"), true) // Passes, got error when we wanted one
test.WantErr(t, errors.New("uh oh"), false) // Fails, got error but didn't want one
test.WantErr(t, nil, true) // Fails, wanted an error but didn't get one
test.WantErr(t, nil, false) // Passes, didn't want an error and didn't get one

Types

This section is empty.

Jump to

Keyboard shortcuts

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