ogletest

package
v0.0.0-...-82b3e0f Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2014 License: MIT, Apache-2.0 Imports: 13 Imported by: 0

README

ogletest is a unit testing framework for Go with the following features:

  • An extensive and extensible set of matchers for expressing expectations.
  • Automatic failure messages; no need to say t.Errorf("Expected %v, got %v"...).
  • Clean, readable output that tells you exactly what you need to know.
  • Built-in support for mocking through the oglemock package.
  • Style and semantics similar to Google Test and Google JS Test.

It integrates with Go's built-in testing package, so it works with the go test command, and even with other types of test within your package. Unlike the testing package which offers only basic capabilities for signalling failures, it offers ways to express expectations and get nice failure messages automatically.

Installation

First, make sure you have installed Go 1.0.2 or newer. See here for instructions.

Use the following command to install ogletest and its dependencies, and to keep them up to date:

go get -u github.com/smartystreets/goconvey/convey/assertions/ogletest

Documentation

See here for package documentation hosted on GoPkgDoc containing an exhaustive list of exported symbols. Alternatively, you can install the package and then use go doc:

go doc github.com/smartystreets/goconvey/convey/assertions/ogletest

An important part of ogletest is its use of matchers provided by the oglematchers package. See that package's documentation for information on the built-in matchers available, and check out the oglematchers.Matcher interface if you want to define your own.

Example

Let's say you have a function in your package people with the following signature:

// GetRandomPerson returns the name and phone number of Tony, Dennis, or Scott.
func GetRandomPerson() (name, phone string) {
  [...]
}

A silly function, but it will do for an example. You can write a couple of tests for it as follows:

package people

import (
  "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
  "github.com/smartystreets/goconvey/convey/assertions/ogletest"
  "testing"
)

// Give ogletest a chance to run your tests when invoked by 'go test'.
func TestOgletest(t *testing.T) { ogletest.RunTests(t) }

// Create a test suite, which groups together logically related test methods
// (defined below). You can share common setup and teardown code here; see the
// package docs for more info.
type PeopleTest struct {}
func init() { ogletest.RegisterTestSuite(&PeopleTest{}) }

func (t *PeopleTest) ReturnsCorrectNames() {
  // Call the function a few times, and make sure it never strays from the set
  // of expected names.
  for i := 0; i < 25; i++ {
    name, _ := GetRandomPerson()
    ogletest.ExpectThat(name, oglematchers.AnyOf("Tony", "Dennis", "Scott"))
  }
}

func (t *PeopleTest) FormatsPhoneNumbersCorrectly() {
  // Call the function a few times, and make sure it returns phone numbers in a
  // standard US format.
  for i := 0; i < 25; i++ {
    _, phone := GetRandomPerson()
    ogletest.ExpectThat(phone, oglematchers.MatchesRegexp(`^\(\d{3}\) \d{3}-\d{4}$`))
}

Note that test control functions (RunTests, ExpectThat, and so on) are part of the ogletest package, whereas built-in matchers (AnyOf, MatchesRegexp, and more) are part of the oglematchers library. You can of course use dot imports so that you don't need to prefix each function with its package name:

import (
  . "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
  . "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)

If you save the test in a file whose name ends in _test.go, you can run your tests by simply invoking the following in your package directory:

go test

Here's what the failure output of ogletest looks like, if your function's implementation is bad.

[----------] Running tests from PeopleTest
[ RUN      ] PeopleTest.FormatsPhoneNumbersCorrectly
people_test.go:32:
Expected: matches regexp "^\(\d{3}\) \d{3}-\d{4}$"
Actual:   +1 800 555 5555

[  FAILED  ] PeopleTest.FormatsPhoneNumbersCorrectly
[ RUN      ] PeopleTest.ReturnsCorrectNames
people_test.go:23:
Expected: or(Tony, Dennis, Scott)
Actual:   Bart

[  FAILED  ] PeopleTest.ReturnsCorrectNames
[----------] Finished with tests from PeopleTest

And if the test passes:

[----------] Running tests from PeopleTest
[ RUN      ] PeopleTest.FormatsPhoneNumbersCorrectly
[       OK ] PeopleTest.FormatsPhoneNumbersCorrectly
[ RUN      ] PeopleTest.ReturnsCorrectNames
[       OK ] PeopleTest.ReturnsCorrectNames
[----------] Finished with tests from PeopleTest

Documentation

Overview

Package ogletest provides a framework for writing expressive unit tests. It integrates with the builtin testing package, so it works with the gotest command. Unlike the testing package which offers only basic capabilities for signalling failures, it offers ways to express expectations and get nice failure messages automatically.

For example:

////////////////////////////////////////////////////////////////////////
// testing package test
////////////////////////////////////////////////////////////////////////

someStr, err := ComputeSomeString()
if err != nil {
  t.Errorf("ComputeSomeString: expected nil error, got %v", err)
}

!strings.Contains(someStr, "foo") {
  t.Errorf("ComputeSomeString: expected substring foo, got %v", someStr)
}

////////////////////////////////////////////////////////////////////////
// ogletest test
////////////////////////////////////////////////////////////////////////

someStr, err := ComputeSomeString()
ExpectEq(nil, err)
ExpectThat(someStr, HasSubstr("foo")

Failure messages require no work from the user, and look like the following:

foo_test.go:103:
Expected: has substring "foo"
Actual:   "bar baz"

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExpectCall

func ExpectCall(o oglemock.MockObject, method string) oglemock.PartialExpecation

ExpectCall expresses an expectation that the method of the given name should be called on the supplied mock object. It returns a function that should be called with the expected arguments, matchers for the arguments, or a mix of both.

For example:

mockWriter := [...]
ogletest.ExpectCall(mockWriter, "Write")(oglematchers.ElementsAre(0x1))
    .WillOnce(oglemock.Return(1, nil))

This is a shortcut for calling i.MockController.ExpectCall, where i is the TestInfo struct for the currently-running test. Unlike that direct approach, this function automatically sets the correct file name and line number for the expectation.

func RegisterTestSuite

func RegisterTestSuite(p interface{})

RegisterTestSuite tells ogletest about a test suite containing tests that it should run. Any exported method on the type pointed to by the supplied prototype value will be treated as test methods, with the exception of the following methods (which need not be present):

  • SetUpTestSuite() -- called exactly once, before the first test method is run. The receiver of this method will be a zero value of the test suite type, and is not shared with any other methods. Use this method to set up any necessary global state shared by all of the test methods.

  • TearDownTestSuite() -- called exactly once, after the last test method is run. The receiver of this method will be a zero value of the test suite type, and is not shared with any other methods. Use this method to clean up after any necessary global state shared by all of the test methods.

  • SetUp(testInfo) -- called before each test method is invoked, with the same receiver as that test method, and with a TestInfo arg. At the time this method is invoked, the receiver is a zero value for the test suite type. Use this method for common setup code that works on data not shared across tests.

  • TearDown() -- called after each test method is invoked, with the same receiver as that test method. Use this method for common cleanup code that works on data not shared across tests.

Each test method is invoked on a different receiver, which is initially a zero value of the test suite type.

Example:

// Some value that is needed by the tests but is expensive to compute.
var someExpensiveThing uint

type FooTest struct {
  // Path to a temporary file used by the tests. Each test gets a
  // different temporary file.
  tempFile string
}
func init() { ogletest.RegisterTestSuite(&FooTest{}) }

func (t *FooTest) SetUpTestSuite() {
  someExpensiveThing = ComputeSomeExpensiveThing()
}

func (t *FooTest) SetUp() {
  t.tempFile = CreateTempFile()
}

func (t *FooTest) TearDown() {
  DeleteTempFile(t.tempFile)
}

func (t *FooTest) FrobinicatorIsSuccessfullyTweaked() {
  res := DoSomethingWithExpensiveThing(someExpensiveThing, t.tempFile)
  ExpectThat(res, Equals(true))
}

func RunTests

func RunTests(t *testing.T)

RunTests runs the test suites registered with ogletest, communicating failures to the supplied testing.T object. This is the bridge between ogletest and the testing package (and gotest); you should ensure that it's called at least once by creating a gotest-compatible test function and calling it there.

For example:

import (
  "github.com/smartystreets/goconvey/convey/assertions/ogletest"
  "testing"
)

func TestOgletest(t *testing.T) {
  ogletest.RunTests(t)
}

Types

type ExpectationResult

type ExpectationResult interface {
	// SetCaller updates the file name and line number associated with the
	// expectation. This allows, for example, a utility function to express that
	// *its* caller should have its line number printed if the expectation fails,
	// instead of the line number of the ExpectThat call within the utility
	// function.
	SetCaller(fileName string, lineNumber int)

	// MatchResult returns the result returned by the expectation's matcher for
	// the supplied candidate.
	MatchResult() error
}

ExpectationResult is an interface returned by ExpectThat that allows callers to get information about the result of the expectation and set their own custom information. This is not useful to the average consumer, but may be helpful if you're writing widely used test utility functions.

func AssertEq

func AssertEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult

AssertEq(e, a) is equivalent to AssertThat(a, oglematchers.Equals(e)).

func AssertFalse

func AssertFalse(b interface{}, errorParts ...interface{}) ExpectationResult

AssertFalse(b) is equivalent to AssertThat(b, oglematchers.Equals(false)).

func AssertGe

func AssertGe(x, y interface{}, errorParts ...interface{}) ExpectationResult

AssertGe(x, y) is equivalent to AssertThat(x, oglematchers.GreaterOrEqual(y)).

func AssertGt

func AssertGt(x, y interface{}, errorParts ...interface{}) ExpectationResult

AssertGt(x, y) is equivalent to AssertThat(x, oglematchers.GreaterThan(y)).

func AssertLe

func AssertLe(x, y interface{}, errorParts ...interface{}) ExpectationResult

AssertLe(x, y) is equivalent to AssertThat(x, oglematchers.LessOrEqual(y)).

func AssertLt

func AssertLt(x, y interface{}, errorParts ...interface{}) ExpectationResult

AssertLt(x, y) is equivalent to AssertThat(x, oglematchers.LessThan(y)).

func AssertNe

func AssertNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult

AssertNe(e, a) is equivalent to AssertThat(a, oglematchers.Not(oglematchers.Equals(e))).

func AssertThat

func AssertThat(
	x interface{},
	m oglematchers.Matcher,
	errorParts ...interface{}) ExpectationResult

AssertThat is identical to ExpectThat, except that in the event of failure it halts the currently running test immediately. It is thus useful for things like bounds checking:

someSlice := [...]
AssertEq(1, len(someSlice))  // Protects next line from panicking.
ExpectEq("taco", someSlice[0])

func AssertTrue

func AssertTrue(b interface{}, errorParts ...interface{}) ExpectationResult

AssertTrue(b) is equivalent to AssertThat(b, oglematchers.Equals(true)).

func ExpectEq

func ExpectEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult

ExpectEq(e, a) is equivalent to ExpectThat(a, oglematchers.Equals(e)).

func ExpectFalse

func ExpectFalse(b interface{}, errorParts ...interface{}) ExpectationResult

ExpectFalse(b) is equivalent to ExpectThat(b, oglematchers.Equals(false)).

func ExpectGe

func ExpectGe(x, y interface{}, errorParts ...interface{}) ExpectationResult

ExpectGe(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterOrEqual(y)).

func ExpectGt

func ExpectGt(x, y interface{}, errorParts ...interface{}) ExpectationResult

ExpectGt(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterThan(y)).

func ExpectLe

func ExpectLe(x, y interface{}, errorParts ...interface{}) ExpectationResult

ExpectLe(x, y) is equivalent to ExpectThat(x, oglematchers.LessOrEqual(y)).

func ExpectLt

func ExpectLt(x, y interface{}, errorParts ...interface{}) ExpectationResult

ExpectLt(x, y) is equivalent to ExpectThat(x, oglematchers.LessThan(y)).

func ExpectNe

func ExpectNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult

ExpectNe(e, a) is equivalent to ExpectThat(a, oglematchers.Not(oglematchers.Equals(e))).

func ExpectThat

func ExpectThat(
	x interface{},
	m oglematchers.Matcher,
	errorParts ...interface{}) ExpectationResult

ExpectThat confirms that the supplied matcher matches the value x, adding a failure record to the currently running test if it does not. If additional parameters are supplied, the first will be used as a format string for the later ones, and the user-supplied error message will be added to the test output in the event of a failure.

For example:

ExpectThat(userName, Equals("jacobsa"))
ExpectThat(users[i], Equals("jacobsa"), "while processing user %d", i)

func ExpectTrue

func ExpectTrue(b interface{}, errorParts ...interface{}) ExpectationResult

ExpectTrue(b) is equivalent to ExpectThat(b, oglematchers.Equals(true)).

type TestInfo

type TestInfo struct {
	// A mock controller that is set up to report errors to the ogletest test
	// runner. This can be used for setting up mock expectations and handling
	// mock calls. The Finish method should not be run by the user; ogletest will
	// do that automatically after the test's TearDown method is run.
	//
	// Note that this feature is still experimental, and is subject to change.
	MockController oglemock.Controller
	// contains filtered or unexported fields
}

TestInfo represents information about a currently running or previously-run test.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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