check

package
v0.0.0-...-f5c3557 Latest Latest
Warning

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

Go to latest
Published: May 2, 2018 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package check provides dead-simple assertions and utilities for testing.

All tests created with check.New() run in parallel, so be warned.

Example (Check)
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/iheartradio/cog/check"
)

func main() {
	// Typically you would pass in your *testing.T or *testing.B here
	c := check.New(nil)

	// These are just a few of the provided functions. Check out the full
	// documentation for everything.

	c.Equal(1, 1, "the universe is falling apart")
	c.NotEqual(1, 2, "those can't be equal!")

	panics := func() {
		panic("i get nervous sometimes")
	}
	c.Panics(panics, "this should always panic")

	// Make absolute path relative for example output checking
	wd, _ := os.Getwd()
	rel, _ := filepath.Rel(wd, c.FS.Path("test_file"))

	// Assuming you're using check.Main() in a TestMain() function, the test
	// data directory is wiped out when all tests pass, so go ahead and make
	// things messy.
	fmt.Println("test-specific file:", rel)

}
Output:

test-specific file: test_data/Example_check/test_file
Example (Errorer)
package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"

	"github.com/iheartradio/cog/check"
)

type MockWriter struct {
	check.Errorer
	io.Writer
}

func (mw *MockWriter) Write(b []byte) (int, error) {
	if mw.Fail() {
		return 0, fmt.Errorf("errorer forced to fail")
	}

	return mw.Writer.Write(b)
}

func main() {
	buff := &bytes.Buffer{}
	w := MockWriter{Writer: buff}

	// Errors are returned based on the call stack: on the first call from a
	// given stack, Fail() returns true. On any successive calls, Fail() returns
	// false.
	//
	// By doing this, you can test all errors by repeatedly calling the same
	// function until it succeeds. This allows you to test all error pathways
	// and ensure that everything works right. The following code demonstrates
	// this idea.
	err := errors.New("")
	for err != nil {
		_, err = w.Write([]byte("important data"))
		fmt.Println("Error from write:", err)
	}

}
Output:

Error from write: errorer forced to fail
Error from write: <nil>

Index

Examples

Constants

View Source
const DataDir = "test_data"

DataDir is the name of the directory where test-specific files live; that is, files created specifically for a single test while running the test.

Variables

View Source
var (
	// FixtureDir is the directory that all of your fixtures live in. This
	// directory is located by walking up the tree, starting at the CWD until a
	// directory with the given name is found. Typically, this will be
	// "test_fixtures", but you may choose your own name.
	FixtureDir = "test_fixtures"
)

Functions

func Cleanup

func Cleanup()

Cleanup removes any and all testing state

This is typically only called from Main(), so you needn't worry about it unless you're implementing your own TestMain().

func Fixture

func Fixture(parts ...string) string

Fixture gets the path to the fixture described by `parts`. If the FixtureDir is not found, this panics.

The fixture directory is found by climbing the FS tree until a directory containing the directory defined by the constant FixtureDir is found. If found, the absolute path to that directory is joined with the given parts is returned.

func GetTestDetails

func GetTestDetails() (path, name string)

GetTestDetails gets the file path and name of the test.

func GetTestName

func GetTestName() string

GetTestName gets the name of the current test.

func Main

func Main(m *testing.M)

Main provides an alternative main for testing. This sets the testing environment up and also cleans it up on success; on failure, test files are left so that you can better inspect the failure.

If you want to use this functionality, add the following somewhere in your tests:

func TestMain(m *testing.M) {
	check.Main(m)
}

func Setup

func Setup()

Setup does basic pre-test checks to ensure the environment is ready to run. (It's just simple stuff, like make sure DataDir exists, and etc).

This is typically only called from Main(), so you needn't worry about it unless you're implementing your own TestMain().

Types

type C

type C struct {
	testing.TB

	// Access to the test's data directory
	FS FS
}

C is like *testing.T/*testing.B, but with more fun

func New

func New(tb testing.TB) *C

New creates a new C and marks this test as parallel

func (*C) B

func (c *C) B() *testing.B

B provides access to the underlying *testing.B. If C was not instantiated with a *testing.B, this panics.

func (*C) Contains

func (c *C) Contains(iter, v interface{}, msg ...interface{}) bool

Contains checks that iter contains v. Returns true if it does, false otherwise.

The following checks are done:

  1. If a map, checks if the map contains key v.
  2. If iter is a slice/array and v is a slice/array, checks to see if v is a subset of iter.
  3. If iter is a slice/array and v is not, checks if any element in iter equals v.
  4. If iter is a string, falls back to strings.Contains.

func (*C) Equal

func (c *C) Equal(e, g interface{}, msg ...interface{}) bool

Equal compares to things, ensuring that they are equal to each other. `e` is the expected value; `g` is the value you got somewhere else. Returns true if they not equal, false otherwise.

Equal takes special care of floating point numbers, ensuring that any precision loss doesn't affect their equality.

If `e` is nil, `g` will be checked for nil, and if it's an interface, its value will be checked for nil. Keep in mind that, for interfaces, this is _not_ a strict `g == nil` comparison.

func (*C) Error

func (c *C) Error(err error, msg ...interface{}) bool

Error ensures that an error is not nil. Returns true if an error was received, false otherwise.

func (*C) False

func (c *C) False(cond bool, msg ...interface{}) bool

False checks that the given bool is false. Returns the value opposite value of the bool.

func (*C) Is

func (c *C) Is(e, g interface{}, msg ...interface{}) bool

Is ensures that g is the same type as e. Returns true if they are the same type, false otherwise.

func (*C) IsNot

func (c *C) IsNot(e, g interface{}, msg ...interface{}) bool

IsNot ensures that g is not the same type as e. Returns true if they are not the same type, false otherwise.

func (*C) Len

func (c *C) Len(v interface{}, l int, msg ...interface{}) (eq bool)

Len checks that the length of the given v is l. Returns true if equal, false otherwise.

func (*C) LenNot

func (c *C) LenNot(v interface{}, l int, msg ...interface{}) (eq bool)

LenNot checks that the length of the given v is not l. Returns true if not equal, false otherwise.

func (*C) MustBe

func (c *C) MustBe(e, g interface{}, msg ...interface{})

MustBe is like Is, except it panics on failure.

func (*C) MustContain

func (c *C) MustContain(iter, v interface{}, msg ...interface{})

MustContain is like Contains, except it panics on failure.

func (*C) MustEqual

func (c *C) MustEqual(e, g interface{}, msg ...interface{})

MustEqual is like Equal, except it panics on failure.

func (*C) MustError

func (c *C) MustError(err error, msg ...interface{})

MustError is like Error, except it panics on failure.

func (*C) MustFalse

func (c *C) MustFalse(cond bool, msg ...interface{})

MustFalse is like False, except it panics on failure.

func (*C) MustLen

func (c *C) MustLen(v interface{}, l int, msg ...interface{})

MustLen is like Len, except it panics on failure.

func (*C) MustLenNot

func (c *C) MustLenNot(v interface{}, l int, msg ...interface{})

MustLenNot is like LenNot, except it panics on failure.

func (*C) MustNotBe

func (c *C) MustNotBe(e, g interface{}, msg ...interface{})

MustNotBe is like IsNot, except it panics on failure.

func (*C) MustNotContain

func (c *C) MustNotContain(iter, v interface{}, msg ...interface{})

MustNotContain is like NotContains, except it panics on failure.

func (*C) MustNotEqual

func (c *C) MustNotEqual(e, g interface{}, msg ...interface{})

MustNotEqual is like NotEqual, except it panics on failure.

func (*C) MustNotError

func (c *C) MustNotError(err error, msg ...interface{})

MustNotError is like NotError, except it panics on failure.

func (*C) MustNotPanic

func (c *C) MustNotPanic(fn func(), msg ...interface{})

MustNotPanic is like NotPanic, except it panics on failure.

func (*C) MustPanic

func (c *C) MustPanic(fn func(), msg ...interface{})

MustPanic is like Panic, except it panics on failure.

func (*C) MustTrue

func (c *C) MustTrue(cond bool, msg ...interface{})

MustTrue is like True, except it panics on failure.

func (*C) NotContains

func (c *C) NotContains(iter, v interface{}, msg ...interface{}) bool

NotContains checks that v does not contain c. Returns true if it does, false otherwise.

func (*C) NotEqual

func (c *C) NotEqual(e, g interface{}, msg ...interface{}) bool

NotEqual compares to things, ensuring that they do not equal each other. Returns true if they are not equal, false otherwise.

NotEqual takes special care of floating point numbers, ensuring that any precision loss doesn't affect their equality.

func (*C) NotError

func (c *C) NotError(err error, msg ...interface{}) bool

NotError ensures that an error is nil. Returns true if no error was found, false otherwise.

func (*C) NotPanic

func (c *C) NotPanic(fn func(), msg ...interface{}) (ok bool)

NotPanic ensures that the given function does not panic

func (*C) Panics

func (c *C) Panics(fn func(), msg ...interface{}) (ok bool)

Panics ensures that the given function panics

func (*C) T

func (c *C) T() *testing.T

T provides access to the underlying *testing.T. If C was not instantiated with a *testing.T, this panics.

func (*C) True

func (c *C) True(cond bool, msg ...interface{}) bool

True checks that the given bool is true. Returns the value of the bool.

func (*C) Until

func (c *C) Until(wait time.Duration, fn func() bool, msg ...interface{})

Until polls for the given function for the given amount of time. If in that time the function did not return true, the test fails immediately.

type Errorer

type Errorer struct {
	// If test functions should not be considered when comparing stack traces
	IgnoreTestFns bool

	// Only functions with these names should be considered for errors
	OnlyIn []string
	// contains filtered or unexported fields
}

Errorer is useful for mocking out things that return errors. It will return an error for every unique stack trace that it sees, but only on the first run. This allows you to run the same code many times in succession until it succeeds. By doing this, you can test that all your error pathways function correctly.

func (*Errorer) Err

func (er *Errorer) Err() (err error)

Err returns a generic error if this should fail, or nil

func (*Errorer) Fail

func (er *Errorer) Fail() bool

Fail determines if the operation should fail with an error. This also marks the current stack as hit, so any future calls will return falser.

type FS

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

FS provides access to a test's directory

func (*FS) CleanDataDir

func (fs *FS) CleanDataDir()

CleanDataDir wipes out this test's data directory

func (*FS) ContentsEqual

func (fs *FS) ContentsEqual(path string, b []byte)

ContentsEqual checks that the contents of the given file exactly equal the given byte slice.

func (*FS) DirExists

func (fs *FS) DirExists(path string)

DirExists checks that the given directory exists

func (*FS) DirNotExists

func (fs *FS) DirNotExists(path string)

DirNotExists checks that the given directory exists

func (*FS) DumpTree

func (fs *FS) DumpTree(path string)

DumpTree walks the tree at the given path and writes each file to the test log

func (*FS) FileExists

func (fs *FS) FileExists(path string)

FileExists checks that the given file exists

func (*FS) FileNotExists

func (fs *FS) FileNotExists(path string)

FileNotExists checks that the given file does not exist

func (*FS) GetDataDir

func (fs *FS) GetDataDir() string

GetDataDir gets the test's data directory. On the first call, this also clears out any data directory that existed previously, giving your test a clean space to run.

If the DataDir is not found, this panics.

func (*FS) Path

func (fs *FS) Path(parts ...string) string

Path gets the absolute path of the test's data dir joined with the parts. The parent dirs are created, assuming that the last part is the file.

func (*FS) ReadFile

func (fs *FS) ReadFile(path string) []byte

ReadFile reads the contents of the file at given path in the test's data dir.

func (*FS) SContentsEqual

func (fs *FS) SContentsEqual(path string, b string)

SContentsEqual is like ContentsEqual, but with strings.

func (*FS) SReadFile

func (fs *FS) SReadFile(path string) string

SReadFile is like ReadFile, but it works on strings.

func (*FS) SWriteFile

func (fs *FS) SWriteFile(path, contents string)

SWriteFile is like WriteFile, but it works on strings

func (*FS) WriteFile

func (fs *FS) WriteFile(path string, contents []byte)

WriteFile writes the given contents to the given path in the test's data dir, creating everything as necessary.

Directories

Path Synopsis
Package chlog provides clog-based logging for testing Usage is really simple: import "github.com/iheartradio/cog/check/chlog" func TestStuff(t *testing.T) { log := chlog.New(t) }
Package chlog provides clog-based logging for testing Usage is really simple: import "github.com/iheartradio/cog/check/chlog" func TestStuff(t *testing.T) { log := chlog.New(t) }

Jump to

Keyboard shortcuts

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