• Stars
    star
    103
  • Rank 333,046 (Top 7 %)
  • Language
    Go
  • License
    MIT License
  • Created over 2 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Go test helper for minimalists

Be Go Reference Go Report Card Coverage Status Mentioned in Awesome Go

Package be is the minimalist testing helper for Go.

Inspired by Mat Ryer and Alex Edwards.

Features

  • Simple and readable test assertions using generics
  • Built-in helpers for common cases like be.NilErr and be.In
  • Fail fast by default but easily switch to relaxed with be.Relaxed(t)
  • Helpers for testing against golden files with the testfile subpackage
  • No dependencies: just uses standard library

Example usage

Test for simple equality using generics:

// Test two unequal strings
be.Equal(t, "hello", "world")     // bad
// t.Fatal("want: hello; got: world")
// Test two equal strings
be.Equal(t, "goodbye", "goodbye") // good
// Test equal integers, etc.
be.Equal(t, 200, resp.StatusCode)
be.Equal(t, tc.wantPtr, gotPtr)

// Test for inequality
be.Unequal(t, "hello", "world")     // good
be.Unequal(t, "goodbye", "goodbye") // bad
// t.Fatal("got: goodbye")

Test for equality of slices:

s := []int{1, 2, 3}
be.AllEqual(t, []int{1, 2, 3}, s) // good
be.AllEqual(t, []int{3, 2, 1}, s) // bad
// t.Fatal("want: [3 2 1]; got: [1 2 3]")

Handle errors:

var err error
be.NilErr(t, err)   // good
be.Nonzero(t, err) // bad
// t.Fatal("got: <nil>")
err = errors.New("(O_o)")
be.NilErr(t, err)   // bad
// t.Fatal("got: (O_o)")
be.Nonzero(t, err) // good

Check substring containment:

be.In(t, "world", "hello, world") // good
be.In(t, "World", "hello, world") // bad
// t.Fatal("World" not in "hello, world")
be.NotIn(t, "\x01", []byte("\a\b\x00\r\t")) // good
be.NotIn(t, "\x00", []byte("\a\b\x00\r\t")) // bad
// t.Fatal("\x00" in "\a\b\x00\r\t")

Test anything else:

be.True(t, o.IsValid())
be.True(t, len(pages) >= 20)

Test using goldenfiles:

// Start a sub-test for each .txt file
testfile.Run(t, "testdata/*.txt", func(t *testing.T, path string) {
	// Read the file
	input := testfile.Read(t, path)

	// Do some conversion on it
	type myStruct struct{ Whatever string }
	got := myStruct{strings.ToUpper(input)}

	// See if the struct is equivalent to a .json file
	wantFile := strings.TrimSuffix(path, ".txt") + ".json"
	testfile.EqualJSON(t, wantFile, got)

	// If it's not equivalent,
	// the got struct will be dumped
	// to a file named testdata/-failed-test-name.json
})

Philosophy

Tests usually should not fail. When they do fail, the failure should be repeatable. Therefore, it doesn't make sense to spend a lot of time writing good test messages. (This is unlike error messages, which should happen fairly often, and in production, irrepeatably.) Package be is designed to simply fail a test quickly and quietly if a condition is not met with a reference to the line number of the failing test. If the reason for having the test is not immediately clear from context, you can write a comment, just like in normal code. If you do need more extensive reporting to figure out why a test is failing, use be.DebugLog or be.Debug to capture more information.

Most tests just need simple equality testing, which is handled by be.Equal (for comparable types), be.AllEqual (for slices of comparable types), and be.DeepEqual (which relies on reflect.DeepEqual). Another common test is that a string or byte slice should contain or not some substring, which is handled by be.In and be.NotIn. Rather than package be providing every possible test helper, you are encouraged to write your own advanced helpers for use with be.True, while package be takes away the drudgery of writing yet another simple func nilErr(t *testing.T, err) { ... }.

The testfile subpackage has functions that make it easy to write file-based tests that ensure that the output of some transformation matches a golden file. Subtests can automatically be run for all files matching a glob pattern, such as testfile.Run(t, "testdata/*/input.txt", ...). If the test fails, the failure output will be written to a file, such as "testdata/basic-test/-failed-output.txt", and then the output can be examined via diff testing with standard tools. Set the environmental variable TESTFILE_UPDATE to update the golden file.

Every tool in the be module requires a testing.TB as its first argument. There are various clever ways to get the testing.TB implicitly, but package be is designed to be simple and explicit, so it's easiest to just always pass in a testing.TB the boring way.

More Repositories

1

requests

HTTP requests for Gophers
Go
1,488
star
2

flowmatic

Structured concurrency made easy
Go
366
star
3

versioninfo

Importable package that parses version info from debug.ReadBuildInfo().
Go
248
star
4

heffalump

Heffalump is an endless honeypot
Go
199
star
5

pomodoro

Command line pomodoro timer
Go
173
star
6

go-cli

Template for creating Go CLIs
Go
57
star
7

new

A helper function to create a pointer to a new object in Go 1.18+
Go
55
star
8

workgroup

Structured concurrency manager for Go
Go
46
star
9

certinfo

Get information about the certificate used at a domain
Go
34
star
10

truthy

Package truthy provides truthy condition testing with Go generics
Go
33
star
11

exembed

Go Embed experiments
Go
30
star
12

get-headers

Tool that shows headers and stats from GET-ing a URL
Go
28
star
13

deque

Generic deque container
Go
27
star
14

netlify-go-function-demo

https://blog.carlmjohnson.net/post/2020/how-to-host-golang-on-netlify-for-free/
HTML
26
star
15

shitpic

Recompresses JPEGs to make shitpics
JavaScript
25
star
16

resperr

Go package to associate status codes and messages with errors
Go
23
star
17

csv

Go CSV reader like Python's DictReader
Go
21
star
18

scattered

Command line tool for asset hashing
Go
20
star
19

tumblr-importr

An importer that uses the Tumblr API to create a Hugo static site
Go
20
star
20

decoder-ring

CLI tool for decoding/encoding from common formats
Go
16
star
21

springerle

A cookiecutter tool written in Go
Go
16
star
22

errorx

Error helpers for Go
Go
16
star
23

syncx

Go sync utility functions using generics
Go
14
star
24

bytemap

Bytemap contains types for making maps from bytes to bool, integer, or float using a backing array
Go
12
star
25

pointer

Generic pointer helpers
Go
11
star
26

opensesame

Trivial password generator
Go
11
star
27

exitcode

Go package to convert errors to exit codes
Go
10
star
28

flagext

Implementations of the flag.Value interface to extend the flag package
Go
9
star
29

go-run

Shebang line equivalent for Go
Go
9
star
30

json-tidy

Pretty prints JSON from stdin, files, or URLs
Go
9
star
31

tsrproxy

Simple Tailscale reverse proxy
Go
7
star
32

flagx

Extensions to the Go flag package
Go
7
star
33

collections

Go
6
star
34

portfor

Deterministic hash from name to a port number
Go
6
star
35

sudoku

Sudoku solver in Go
Go
6
star
36

simple-reverse-proxy

A simple reverse proxy written in Go
Go
5
star
37

monterey-jack

A friend to zippers
Go
4
star
38

haystack

Pinboard search CLI
Go
4
star
39

crockford

Go implementation of Crockford base 32 encoding
Go
4
star
40

go-utils

Implementation of the Fisher–Yates shuffle (Knuth shuffle) in Go
Go
4
star
41

feed2json

Given an Atom or RSS feed, creates a comparable JSON feed
Go
3
star
42

whatsit

Looks at a file and guess its content type
Go
3
star
43

webarchive

Go
3
star
44

stringutil

Some Go string utilities
Go
3
star
45

gsize

Utility that tells how large a file will be after gzip compression
Go
3
star
46

kawatte

Recursive bulk find and replace
Go
3
star
47

bletchley

Simple command line application for basic public key crypto
Go
2
star
48

Watsuji-and-Aesthetics

Dissertation, Carl M. Johnson
HTML
2
star
49

errutil

Helpful tools for errors in Go
Go
2
star
50

randline

Chooses random line(s) from a file
Go
2
star
51

nfspampurge

Delete all spam from Netlify spam page
Go
2
star
52

richpaste

Paste as rich text in Mac OS
Go
2
star
53

walker

Walker, File Ranger
Go
2
star
54

slumber

Like Unix sleep but takes minutes, hours, etc.
Go
1
star
55

lich

A port of Wolf Rentzsch's Lich binary file format to Go (golang)
Go
1
star
56

rootdown

The internet demanded another Go router
Go
1
star
57

echo-request

Simple server that echoes requests back as text
Go
1
star
58

loggo

Logs requests to files for debugging webhooks
Go
1
star
59

luhn

Yet another Luhn algorithm implementation
Go
1
star
60

django-context-variables

Simple utility to help make declarative class-based views in Django
Python
1
star
61

junix

A re-implementation of common Unix commands with output as JSON instead of plain text
Go
1
star
62

rank-em

CLI tool for making ranking lists
Go
1
star
63

errors

Some Go error helpers
Go
1
star
64

jax

JavaScript for Automation scripts
AppleScript
1
star
65

python-defunct

Defunct. See https://github.com/carlmjohnson/python-tools instead.
Python
1
star
66

352-interactive-design-development

HTML
1
star
67

randpwd

Randomly generated passwords
HTML
1
star
68

slackhook

Simple client for Slack web hook URLs
Go
1
star
69

dotfiles-public

Public repo for configuration files (git, Sublime Text, etc.)
Python
1
star
70

gracefulserver

Boilerplate for starting an HTTP server in Go with graceful shutdown
Go
1
star
71

carljohnson-jour352

HTML
1
star
72

scooter

Scoot files into directories by date added
Go
1
star
73

carlana-redirect

1
star
74

jamtalk

Repo for SRCCON 2019 talk
HTML
1
star