mirror of https://github.com/k3s-io/k3s
testify
parent
c7eaa2095c
commit
b66a822166
|
@ -0,0 +1,9 @@
|
|||
Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
|
||||
|
||||
Please consider promoting this project if you find it useful.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,230 @@
|
|||
Testify - Thou Shalt Write Tests
|
||||
================================
|
||||
|
||||
Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.
|
||||
|
||||
Features include:
|
||||
|
||||
* [Easy assertions](#assert-package)
|
||||
* [Mocking](#mock-package)
|
||||
* [HTTP response trapping](#http-package)
|
||||
* [Testing suite interfaces and functions](#suite-package)
|
||||
|
||||
Get started:
|
||||
|
||||
* Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
|
||||
* For an introduction to writing test code in Go, see our [blog post article](http://blog.stretchr.com/2014/03/05/test-driven-development-specifically-in-golang/) or check out http://golang.org/doc/code.html#Testing
|
||||
* Check out the API Documentation http://godoc.org/github.com/stretchr/testify
|
||||
* To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc)
|
||||
* A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development)
|
||||
|
||||
|
||||
|
||||
`assert` package
|
||||
----------------
|
||||
|
||||
The `assert` package provides some helpful methods that allow you to write better test code in Go. Check out the [API documentation for the `assert` package](http://godoc.org/github.com/stretchr/testify/assert).
|
||||
|
||||
* Prints friendly, easy to read failure descriptions
|
||||
* Allows for very readable code
|
||||
* Optionally annotate each assertion with a message
|
||||
|
||||
See it in action:
|
||||
|
||||
func TestSomething(t *testing.T) {
|
||||
|
||||
// assert equality
|
||||
assert.Equal(t, 123, 123, "they should be equal")
|
||||
|
||||
// assert inequality
|
||||
assert.NotEqual(t, 123, 456, "they should not be equal")
|
||||
|
||||
// assert for nil (good for errors)
|
||||
assert.Nil(t, object)
|
||||
|
||||
// assert for not nil (good when you expect something)
|
||||
if assert.NotNil(t, object) {
|
||||
|
||||
// now we know that object isn't nil, we are safe to make
|
||||
// further assertions without causing any errors
|
||||
assert.Equal(t, "Something", object.Value)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
* Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities.
|
||||
* Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
|
||||
|
||||
`http` package
|
||||
--------------
|
||||
|
||||
The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http).
|
||||
|
||||
`mock` package
|
||||
--------------
|
||||
|
||||
The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
|
||||
|
||||
An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened:
|
||||
|
||||
package yours
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
/*
|
||||
Test objects
|
||||
*/
|
||||
|
||||
// MyMockedObject is a mocked object that implements an interface
|
||||
// that describes an object that the code I am testing relies on.
|
||||
type MyMockedObject struct{
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// DoSomething is a method on MyMockedObject that implements some interface
|
||||
// and just records the activity, and returns what the Mock object tells it to.
|
||||
//
|
||||
// In the real object, this method would do something useful, but since this
|
||||
// is a mocked object - we're just going to stub it out.
|
||||
//
|
||||
// NOTE: This method is not being tested here, code that uses this object is.
|
||||
func (m *MyMockedObject) DoSomething(number int) (bool, error) {
|
||||
|
||||
args := m.Mock.Called(number)
|
||||
return args.Bool(0), args.Error(1)
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
Actual test functions
|
||||
*/
|
||||
|
||||
// TestSomething is an example of how to use our test object to
|
||||
// make assertions about some target code we are testing.
|
||||
func TestSomething(t *testing.T) {
|
||||
|
||||
// create an instance of our test object
|
||||
testObj := new(MyMockedObject)
|
||||
|
||||
// setup expectations
|
||||
testObj.On("DoSomething", 123).Return(true, nil)
|
||||
|
||||
// call the code we are testing
|
||||
targetFuncThatDoesSomethingWithObj(testObj)
|
||||
|
||||
// assert that the expectations were met
|
||||
testObj.Mock.AssertExpectations(t)
|
||||
|
||||
}
|
||||
|
||||
For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock).
|
||||
|
||||
`suite` package
|
||||
---------------
|
||||
|
||||
The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
|
||||
|
||||
An example suite is shown below:
|
||||
|
||||
// Basic imports
|
||||
import (
|
||||
"testing"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
// Define the suite, and absorb the built-in basic suite
|
||||
// functionality from testify - including a T() method which
|
||||
// returns the current testing context
|
||||
type ExampleTestSuite struct {
|
||||
suite.Suite
|
||||
VariableThatShouldStartAtFive int
|
||||
}
|
||||
|
||||
// Make sure that VariableThatShouldStartAtFive is set to five
|
||||
// before each test
|
||||
func (suite *ExampleTestSuite) SetupTest() {
|
||||
suite.VariableThatShouldStartAtFive = 5
|
||||
}
|
||||
|
||||
// All methods that begin with "Test" are run as tests within a
|
||||
// suite.
|
||||
func (suite *ExampleTestSuite) TestExample() {
|
||||
assert.Equal(suite.T(), suite.VariableThatShouldStartAtFive, 5)
|
||||
}
|
||||
|
||||
// In order for 'go test' to run this suite, we need to create
|
||||
// a normal test function and pass our suite to suite.Run
|
||||
func TestExampleTestSuite(t *testing.T) {
|
||||
suite.Run(t, new(ExampleTestSuite))
|
||||
}
|
||||
|
||||
For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go)
|
||||
|
||||
For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
|
||||
|
||||
------
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
To install Testify, use `go get`:
|
||||
|
||||
go get github.com/stretchr/testify
|
||||
|
||||
This will then make the following packages available to you:
|
||||
|
||||
github.com/stretchr/testify/assert
|
||||
github.com/stretchr/testify/mock
|
||||
github.com/stretchr/testify/http
|
||||
|
||||
Import the `testify/assert` package into your code using this template:
|
||||
|
||||
package yours
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSomething(t *testing.T) {
|
||||
|
||||
assert.True(t, true, "True is true!")
|
||||
|
||||
}
|
||||
|
||||
------
|
||||
|
||||
Staying up to date
|
||||
==================
|
||||
|
||||
To update Testify, use `go get -u`:
|
||||
|
||||
go get -u github.com/stretchr/testify
|
||||
|
||||
------
|
||||
|
||||
Contributing
|
||||
============
|
||||
|
||||
Please feel free to submit issues, fork the repository and send pull requests!
|
||||
|
||||
When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.
|
||||
|
||||
------
|
||||
|
||||
Licence
|
||||
=======
|
||||
Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
|
||||
|
||||
Please consider promoting this project if you find it useful.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,537 @@
|
|||
package assert
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestingT is an interface wrapper around *testing.T
|
||||
type TestingT interface {
|
||||
Errorf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
// Comparison a custom function that returns true on success and false on failure
|
||||
type Comparison func() (success bool)
|
||||
|
||||
/*
|
||||
Helper functions
|
||||
*/
|
||||
|
||||
// ObjectsAreEqual determines if two objects are considered equal.
|
||||
//
|
||||
// This function does no assertion of any kind.
|
||||
func ObjectsAreEqual(expected, actual interface{}) bool {
|
||||
|
||||
if expected == nil || actual == nil {
|
||||
return expected == actual
|
||||
}
|
||||
|
||||
if reflect.DeepEqual(expected, actual) {
|
||||
return true
|
||||
}
|
||||
|
||||
expectedValue := reflect.ValueOf(expected)
|
||||
actualValue := reflect.ValueOf(actual)
|
||||
if expectedValue == actualValue {
|
||||
return true
|
||||
}
|
||||
|
||||
// Attempt comparison after type conversion
|
||||
if actualValue.Type().ConvertibleTo(expectedValue.Type()) && expectedValue == actualValue.Convert(expectedValue.Type()) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Last ditch effort
|
||||
if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
/* CallerInfo is necessary because the assert functions use the testing object
|
||||
internally, causing it to print the file:line of the assert method, rather than where
|
||||
the problem actually occured in calling code.*/
|
||||
|
||||
// CallerInfo returns a string containing the file and line number of the assert call
|
||||
// that failed.
|
||||
func CallerInfo() string {
|
||||
|
||||
file := ""
|
||||
line := 0
|
||||
ok := false
|
||||
|
||||
for i := 0; ; i++ {
|
||||
_, file, line, ok = runtime.Caller(i)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(file, "/")
|
||||
dir := parts[len(parts)-2]
|
||||
file = parts[len(parts)-1]
|
||||
if (dir != "assert" && dir != "mock") || file == "mock_test.go" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s:%d", file, line)
|
||||
}
|
||||
|
||||
// getWhitespaceString returns a string that is long enough to overwrite the default
|
||||
// output from the go testing framework.
|
||||
func getWhitespaceString() string {
|
||||
|
||||
_, file, line, ok := runtime.Caller(1)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(file, "/")
|
||||
file = parts[len(parts)-1]
|
||||
|
||||
return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line)))
|
||||
|
||||
}
|
||||
|
||||
func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
|
||||
if len(msgAndArgs) == 0 || msgAndArgs == nil {
|
||||
return ""
|
||||
}
|
||||
if len(msgAndArgs) == 1 {
|
||||
return msgAndArgs[0].(string)
|
||||
}
|
||||
if len(msgAndArgs) > 1 {
|
||||
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Fail reports a failure through
|
||||
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
|
||||
|
||||
message := messageFromMsgAndArgs(msgAndArgs...)
|
||||
|
||||
if len(message) > 0 {
|
||||
t.Errorf("\r%s\r\tLocation:\t%s\n\r\tError:\t\t%s\n\r\tMessages:\t%s\n\r", getWhitespaceString(), CallerInfo(), failureMessage, message)
|
||||
} else {
|
||||
t.Errorf("\r%s\r\tLocation:\t%s\n\r\tError:\t\t%s\n\r", getWhitespaceString(), CallerInfo(), failureMessage)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Implements asserts that an object is implemented by the specified interface.
|
||||
//
|
||||
// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
|
||||
func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
interfaceType := reflect.TypeOf(interfaceObject).Elem()
|
||||
|
||||
if !reflect.TypeOf(object).Implements(interfaceType) {
|
||||
return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// IsType asserts that the specified objects are of the same type.
|
||||
func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
|
||||
return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Equal asserts that two objects are equal.
|
||||
//
|
||||
// assert.Equal(t, 123, 123, "123 and 123 should be equal")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if !ObjectsAreEqual(expected, actual) {
|
||||
return Fail(t, fmt.Sprintf("Not equal: %#v != %#v", expected, actual), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// Exactly asserts that two objects are equal is value and type.
|
||||
//
|
||||
// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
aType := reflect.TypeOf(expected)
|
||||
bType := reflect.TypeOf(actual)
|
||||
|
||||
if aType != bType {
|
||||
return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType)
|
||||
}
|
||||
|
||||
return Equal(t, expected, actual, msgAndArgs...)
|
||||
|
||||
}
|
||||
|
||||
// NotNil asserts that the specified object is not nil.
|
||||
//
|
||||
// assert.NotNil(t, err, "err should be something")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
success := true
|
||||
|
||||
if object == nil {
|
||||
success = false
|
||||
} else {
|
||||
value := reflect.ValueOf(object)
|
||||
kind := value.Kind()
|
||||
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
|
||||
success = false
|
||||
}
|
||||
}
|
||||
|
||||
if !success {
|
||||
Fail(t, "Expected not to be nil.", msgAndArgs...)
|
||||
}
|
||||
|
||||
return success
|
||||
}
|
||||
|
||||
// isNil checks if a specified object is nil or not, without Failing.
|
||||
func isNil(object interface{}) bool {
|
||||
if object == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
value := reflect.ValueOf(object)
|
||||
kind := value.Kind()
|
||||
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Nil asserts that the specified object is nil.
|
||||
//
|
||||
// assert.Nil(t, err, "err should be nothing")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if isNil(object) {
|
||||
return true
|
||||
}
|
||||
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
|
||||
}
|
||||
|
||||
var zeros = []interface{}{
|
||||
int(0),
|
||||
int8(0),
|
||||
int16(0),
|
||||
int32(0),
|
||||
int64(0),
|
||||
uint(0),
|
||||
uint8(0),
|
||||
uint16(0),
|
||||
uint32(0),
|
||||
uint64(0),
|
||||
float32(0),
|
||||
float64(0),
|
||||
}
|
||||
|
||||
// isEmpty gets whether the specified object is considered empty or not.
|
||||
func isEmpty(object interface{}) bool {
|
||||
|
||||
if object == nil {
|
||||
return true
|
||||
} else if object == "" {
|
||||
return true
|
||||
} else if object == false {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, v := range zeros {
|
||||
if object == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
objValue := reflect.ValueOf(object)
|
||||
|
||||
switch objValue.Kind() {
|
||||
case reflect.Map:
|
||||
fallthrough
|
||||
case reflect.Slice, reflect.Chan:
|
||||
{
|
||||
return (objValue.Len() == 0)
|
||||
}
|
||||
case reflect.Ptr:
|
||||
{
|
||||
switch object.(type) {
|
||||
case *time.Time:
|
||||
return object.(*time.Time).IsZero()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
|
||||
// a slice or a channel with len == 0.
|
||||
//
|
||||
// assert.Empty(t, obj)
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
pass := isEmpty(object)
|
||||
if !pass {
|
||||
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
|
||||
}
|
||||
|
||||
return pass
|
||||
|
||||
}
|
||||
|
||||
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
|
||||
// a slice or a channel with len == 0.
|
||||
//
|
||||
// if assert.NotEmpty(t, obj) {
|
||||
// assert.Equal(t, "two", obj[1])
|
||||
// }
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
pass := !isEmpty(object)
|
||||
if !pass {
|
||||
Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
|
||||
}
|
||||
|
||||
return pass
|
||||
|
||||
}
|
||||
|
||||
// True asserts that the specified value is true.
|
||||
//
|
||||
// assert.True(t, myBool, "myBool should be true")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if value != true {
|
||||
return Fail(t, "Should be true", msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// False asserts that the specified value is true.
|
||||
//
|
||||
// assert.False(t, myBool, "myBool should be false")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if value != false {
|
||||
return Fail(t, "Should be false", msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// NotEqual asserts that the specified values are NOT equal.
|
||||
//
|
||||
// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if ObjectsAreEqual(expected, actual) {
|
||||
return Fail(t, "Should not be equal", msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// Contains asserts that the specified string contains the specified substring.
|
||||
//
|
||||
// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Contains(t TestingT, s, contains string, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if !strings.Contains(s, contains) {
|
||||
return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// NotContains asserts that the specified string does NOT contain the specified substring.
|
||||
//
|
||||
// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NotContains(t TestingT, s, contains string, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if strings.Contains(s, contains) {
|
||||
return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
// Condition uses a Comparison to assert a complex condition.
|
||||
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
|
||||
result := comp()
|
||||
if !result {
|
||||
Fail(t, "Condition failed!", msgAndArgs...)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
|
||||
// methods, and represents a simple func that takes no arguments, and returns nothing.
|
||||
type PanicTestFunc func()
|
||||
|
||||
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
|
||||
func didPanic(f PanicTestFunc) (bool, interface{}) {
|
||||
|
||||
didPanic := false
|
||||
var message interface{}
|
||||
func() {
|
||||
|
||||
defer func() {
|
||||
if message = recover(); message != nil {
|
||||
didPanic = true
|
||||
}
|
||||
}()
|
||||
|
||||
// call the target function
|
||||
f()
|
||||
|
||||
}()
|
||||
|
||||
return didPanic, message
|
||||
|
||||
}
|
||||
|
||||
// Panics asserts that the code inside the specified PanicTestFunc panics.
|
||||
//
|
||||
// assert.Panics(t, func(){
|
||||
// GoCrazy()
|
||||
// }, "Calling GoCrazy() should panic")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
|
||||
return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
|
||||
//
|
||||
// assert.NotPanics(t, func(){
|
||||
// RemainCalm()
|
||||
// }, "Calling RemainCalm() should NOT panic")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
|
||||
|
||||
if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
|
||||
return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// WithinDuration asserts that the two times are within duration delta of each other.
|
||||
//
|
||||
// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
|
||||
|
||||
dt := expected.Sub(actual)
|
||||
if dt < -delta || dt > delta {
|
||||
return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, dt, delta), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/*
|
||||
Errors
|
||||
*/
|
||||
|
||||
// NoError asserts that a function returned no error (i.e. `nil`).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if assert.NoError(t, err) {
|
||||
// assert.Equal(t, actualObj, expectedObj)
|
||||
// }
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
|
||||
if isNil(err) {
|
||||
return true
|
||||
}
|
||||
|
||||
return Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...)
|
||||
}
|
||||
|
||||
// Error asserts that a function returned an error (i.e. not `nil`).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if assert.Error(t, err, "An error was expected") {
|
||||
// assert.Equal(t, err, expectedError)
|
||||
// }
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
|
||||
|
||||
message := messageFromMsgAndArgs(msgAndArgs...)
|
||||
return NotNil(t, err, "An error is expected but got nil. %s", message)
|
||||
|
||||
}
|
||||
|
||||
// EqualError asserts that a function returned an error (i.e. not `nil`)
|
||||
// and that it is equal to the provided error.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if assert.Error(t, err, "An error was expected") {
|
||||
// assert.Equal(t, err, expectedError)
|
||||
// }
|
||||
//
|
||||
// Returns whether the assertion was successful (true) or not (false).
|
||||
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
|
||||
|
||||
message := messageFromMsgAndArgs(msgAndArgs...)
|
||||
if !NotNil(t, theError, "An error is expected but got nil. %s", message) {
|
||||
return false
|
||||
}
|
||||
s := "An error with value \"%s\" is expected but got \"%s\". %s"
|
||||
return Equal(t, theError.Error(), errString,
|
||||
s, errString, theError.Error(), message)
|
||||
}
|
|
@ -0,0 +1,420 @@
|
|||
package assert
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AssertionTesterInterface defines an interface to be used for testing assertion methods
|
||||
type AssertionTesterInterface interface {
|
||||
TestMethod()
|
||||
}
|
||||
|
||||
// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
|
||||
type AssertionTesterConformingObject struct {
|
||||
}
|
||||
|
||||
func (a *AssertionTesterConformingObject) TestMethod() {
|
||||
}
|
||||
|
||||
// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
|
||||
type AssertionTesterNonConformingObject struct {
|
||||
}
|
||||
|
||||
func TestObjectsAreEqual(t *testing.T) {
|
||||
|
||||
if !ObjectsAreEqual("Hello World", "Hello World") {
|
||||
t.Error("objectsAreEqual should return true")
|
||||
}
|
||||
if !ObjectsAreEqual(123, 123) {
|
||||
t.Error("objectsAreEqual should return true")
|
||||
}
|
||||
if !ObjectsAreEqual(123.5, 123.5) {
|
||||
t.Error("objectsAreEqual should return true")
|
||||
}
|
||||
if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
|
||||
t.Error("objectsAreEqual should return true")
|
||||
}
|
||||
if !ObjectsAreEqual(nil, nil) {
|
||||
t.Error("objectsAreEqual should return true")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestImplements(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
|
||||
t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
|
||||
}
|
||||
if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
|
||||
t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestIsType(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
|
||||
t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
|
||||
}
|
||||
if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
|
||||
t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestEqual(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !Equal(mockT, "Hello World", "Hello World") {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, 123, 123) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, 123.5, 123.5) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, nil, nil) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, int32(123), int64(123)) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
if !Equal(mockT, int64(123), uint64(123)) {
|
||||
t.Error("Equal should return true")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNotNil(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !NotNil(mockT, new(AssertionTesterConformingObject)) {
|
||||
t.Error("NotNil should return true: object is not nil")
|
||||
}
|
||||
if NotNil(mockT, nil) {
|
||||
t.Error("NotNil should return false: object is nil")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNil(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !Nil(mockT, nil) {
|
||||
t.Error("Nil should return true: object is nil")
|
||||
}
|
||||
if Nil(mockT, new(AssertionTesterConformingObject)) {
|
||||
t.Error("Nil should return false: object is not nil")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestTrue(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !True(mockT, true) {
|
||||
t.Error("True should return true")
|
||||
}
|
||||
if True(mockT, false) {
|
||||
t.Error("True should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestFalse(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !False(mockT, false) {
|
||||
t.Error("False should return true")
|
||||
}
|
||||
if False(mockT, true) {
|
||||
t.Error("False should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestExactly(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
a := float32(1)
|
||||
b := float64(1)
|
||||
c := float32(1)
|
||||
d := float32(2)
|
||||
|
||||
if Exactly(mockT, a, b) {
|
||||
t.Error("Exactly should return false")
|
||||
}
|
||||
if Exactly(mockT, a, d) {
|
||||
t.Error("Exactly should return false")
|
||||
}
|
||||
if !Exactly(mockT, a, c) {
|
||||
t.Error("Exactly should return true")
|
||||
}
|
||||
|
||||
if Exactly(mockT, nil, a) {
|
||||
t.Error("Exactly should return false")
|
||||
}
|
||||
if Exactly(mockT, a, nil) {
|
||||
t.Error("Exactly should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNotEqual(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !NotEqual(mockT, "Hello World", "Hello World!") {
|
||||
t.Error("NotEqual should return true")
|
||||
}
|
||||
if !NotEqual(mockT, 123, 1234) {
|
||||
t.Error("NotEqual should return true")
|
||||
}
|
||||
if !NotEqual(mockT, 123.5, 123.55) {
|
||||
t.Error("NotEqual should return true")
|
||||
}
|
||||
if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) {
|
||||
t.Error("NotEqual should return true")
|
||||
}
|
||||
if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) {
|
||||
t.Error("NotEqual should return true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContains(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !Contains(mockT, "Hello World", "Hello") {
|
||||
t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
|
||||
}
|
||||
if Contains(mockT, "Hello World", "Salut") {
|
||||
t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNotContains(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !NotContains(mockT, "Hello World", "Hello!") {
|
||||
t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
|
||||
}
|
||||
if NotContains(mockT, "Hello World", "Hello") {
|
||||
t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestDidPanic(t *testing.T) {
|
||||
|
||||
if funcDidPanic, _ := didPanic(func() {
|
||||
panic("Panic!")
|
||||
}); !funcDidPanic {
|
||||
t.Error("didPanic should return true")
|
||||
}
|
||||
|
||||
if funcDidPanic, _ := didPanic(func() {
|
||||
}); funcDidPanic {
|
||||
t.Error("didPanic should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPanics(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !Panics(mockT, func() {
|
||||
panic("Panic!")
|
||||
}) {
|
||||
t.Error("Panics should return true")
|
||||
}
|
||||
|
||||
if Panics(mockT, func() {
|
||||
}) {
|
||||
t.Error("Panics should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNotPanics(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
if !NotPanics(mockT, func() {
|
||||
}) {
|
||||
t.Error("NotPanics should return true")
|
||||
}
|
||||
|
||||
if NotPanics(mockT, func() {
|
||||
panic("Panic!")
|
||||
}) {
|
||||
t.Error("NotPanics should return false")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestEqual_Funcs(t *testing.T) {
|
||||
|
||||
type f func() int
|
||||
f1 := func() int { return 1 }
|
||||
f2 := func() int { return 2 }
|
||||
|
||||
f1Copy := f1
|
||||
|
||||
Equal(t, f1Copy, f1, "Funcs are the same and should be considered equal")
|
||||
NotEqual(t, f1, f2, "f1 and f2 are different")
|
||||
|
||||
}
|
||||
|
||||
func TestNoError(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
// start with a nil error
|
||||
var err error
|
||||
|
||||
True(t, NoError(mockT, err), "NoError should return True for nil arg")
|
||||
|
||||
// now set an error
|
||||
err = errors.New("some error")
|
||||
|
||||
False(t, NoError(mockT, err), "NoError with error should return False")
|
||||
|
||||
}
|
||||
|
||||
func TestError(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
// start with a nil error
|
||||
var err error
|
||||
|
||||
False(t, Error(mockT, err), "Error should return False for nil arg")
|
||||
|
||||
// now set an error
|
||||
err = errors.New("some error")
|
||||
|
||||
True(t, Error(mockT, err), "Error with error should return True")
|
||||
|
||||
}
|
||||
|
||||
func TestEqualError(t *testing.T) {
|
||||
mockT := new(testing.T)
|
||||
|
||||
// start with a nil error
|
||||
var err error
|
||||
False(t, EqualError(mockT, err, ""),
|
||||
"EqualError should return false for nil arg")
|
||||
|
||||
// now set an error
|
||||
err = errors.New("some error")
|
||||
False(t, EqualError(mockT, err, "Not some error"),
|
||||
"EqualError should return false for different error string")
|
||||
True(t, EqualError(mockT, err, "some error"),
|
||||
"EqualError should return true")
|
||||
}
|
||||
|
||||
func Test_isEmpty(t *testing.T) {
|
||||
|
||||
chWithValue := make(chan struct{}, 1)
|
||||
chWithValue <- struct{}{}
|
||||
|
||||
True(t, isEmpty(""))
|
||||
True(t, isEmpty(nil))
|
||||
True(t, isEmpty([]string{}))
|
||||
True(t, isEmpty(0))
|
||||
True(t, isEmpty(int32(0)))
|
||||
True(t, isEmpty(int64(0)))
|
||||
True(t, isEmpty(false))
|
||||
True(t, isEmpty(map[string]string{}))
|
||||
True(t, isEmpty(new(time.Time)))
|
||||
True(t, isEmpty(make(chan struct{})))
|
||||
False(t, isEmpty("something"))
|
||||
False(t, isEmpty(errors.New("something")))
|
||||
False(t, isEmpty([]string{"something"}))
|
||||
False(t, isEmpty(1))
|
||||
False(t, isEmpty(true))
|
||||
False(t, isEmpty(map[string]string{"Hello": "World"}))
|
||||
False(t, isEmpty(chWithValue))
|
||||
|
||||
}
|
||||
|
||||
func TestEmpty(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
chWithValue := make(chan struct{}, 1)
|
||||
chWithValue <- struct{}{}
|
||||
|
||||
True(t, Empty(mockT, ""), "Empty string is empty")
|
||||
True(t, Empty(mockT, nil), "Nil is empty")
|
||||
True(t, Empty(mockT, []string{}), "Empty string array is empty")
|
||||
True(t, Empty(mockT, 0), "Zero int value is empty")
|
||||
True(t, Empty(mockT, false), "False value is empty")
|
||||
True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
|
||||
|
||||
False(t, Empty(mockT, "something"), "Non Empty string is not empty")
|
||||
False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
|
||||
False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
|
||||
False(t, Empty(mockT, 1), "Non-zero int value is not empty")
|
||||
False(t, Empty(mockT, true), "True value is not empty")
|
||||
False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
|
||||
}
|
||||
|
||||
func TestNotEmpty(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
chWithValue := make(chan struct{}, 1)
|
||||
chWithValue <- struct{}{}
|
||||
|
||||
False(t, NotEmpty(mockT, ""), "Empty string is empty")
|
||||
False(t, NotEmpty(mockT, nil), "Nil is empty")
|
||||
False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
|
||||
False(t, NotEmpty(mockT, 0), "Zero int value is empty")
|
||||
False(t, NotEmpty(mockT, false), "False value is empty")
|
||||
False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
|
||||
|
||||
True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
|
||||
True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
|
||||
True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
|
||||
True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
|
||||
True(t, NotEmpty(mockT, true), "True value is not empty")
|
||||
True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
|
||||
}
|
||||
|
||||
func TestWithinDuration(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
a := time.Now()
|
||||
b := a.Add(10 * time.Second)
|
||||
|
||||
True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
|
||||
True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
|
||||
|
||||
False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
|
||||
False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
|
||||
False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
// A set of comprehensive testing tools for use with the normal Go testing system.
|
||||
//
|
||||
// Example Usage
|
||||
//
|
||||
// The following is a complete example using assert in a standard test function:
|
||||
// import (
|
||||
// "testing"
|
||||
// "github.com/stretchr/testify/assert"
|
||||
// )
|
||||
//
|
||||
// func TestSomething(t *testing.T) {
|
||||
//
|
||||
// var a string = "Hello"
|
||||
// var b string = "Hello"
|
||||
//
|
||||
// assert.Equal(t, a, b, "The two words should be the same.")
|
||||
//
|
||||
// }
|
||||
//
|
||||
// Assertions
|
||||
//
|
||||
// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
|
||||
// All assertion functions take, as the first argument, the `*testing.T` object provided by the
|
||||
// testing framework. This allows the assertion funcs to write the failings and other details to
|
||||
// the correct place.
|
||||
//
|
||||
// Every assertion function also takes an optional string message as the final argument,
|
||||
// allowing custom error messages to be appended to the message the assertion method outputs.
|
||||
//
|
||||
// Here is an overview of the assert functions:
|
||||
//
|
||||
// assert.Equal(t, expected, actual [, message [, format-args])
|
||||
//
|
||||
// assert.NotEqual(t, notExpected, actual [, message [, format-args]])
|
||||
//
|
||||
// assert.True(t, actualBool [, message [, format-args]])
|
||||
//
|
||||
// assert.False(t, actualBool [, message [, format-args]])
|
||||
//
|
||||
// assert.Nil(t, actualObject [, message [, format-args]])
|
||||
//
|
||||
// assert.NotNil(t, actualObject [, message [, format-args]])
|
||||
//
|
||||
// assert.Empty(t, actualObject [, message [, format-args]])
|
||||
//
|
||||
// assert.NotEmpty(t, actualObject [, message [, format-args]])
|
||||
//
|
||||
// assert.Error(t, errorObject [, message [, format-args]])
|
||||
//
|
||||
// assert.NoError(t, errorObject [, message [, format-args]])
|
||||
//
|
||||
// assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]])
|
||||
//
|
||||
// assert.IsType(t, expectedObject, actualObject [, message [, format-args]])
|
||||
//
|
||||
// assert.Contains(t, string, substring [, message [, format-args]])
|
||||
//
|
||||
// assert.NotContains(t, string, substring [, message [, format-args]])
|
||||
//
|
||||
// assert.Panics(t, func(){
|
||||
//
|
||||
// // call code that should panic
|
||||
//
|
||||
// } [, message [, format-args]])
|
||||
//
|
||||
// assert.NotPanics(t, func(){
|
||||
//
|
||||
// // call code that should not panic
|
||||
//
|
||||
// } [, message [, format-args]])
|
||||
//
|
||||
// assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]])
|
||||
|
||||
package assert
|
|
@ -0,0 +1,10 @@
|
|||
package assert
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AnError is an error instance useful for testing. If the code does not care
|
||||
// about error specifics, and only needs to return the error for example, this
|
||||
// error should be used to make the test code more readable.
|
||||
var AnError = errors.New("assert.AnError general error for testing")
|
|
@ -0,0 +1,18 @@
|
|||
// A set of packages that provide many tools for testifying that your code will behave as you intend.
|
||||
//
|
||||
// testify contains the following packages:
|
||||
//
|
||||
// The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system.
|
||||
//
|
||||
// The http package contains tools to make it easier to test http activity using the Go testing system.
|
||||
//
|
||||
// The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected.
|
||||
//
|
||||
// The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
|
||||
package testify
|
||||
|
||||
import (
|
||||
_ "github.com/stretchr/testify/assert"
|
||||
_ "github.com/stretchr/testify/http"
|
||||
_ "github.com/stretchr/testify/mock"
|
||||
)
|
|
@ -0,0 +1,2 @@
|
|||
// A set of tools to make testing http activity using the Go testing system easier.
|
||||
package http
|
|
@ -0,0 +1,52 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// TestResponseWriter is a http.ResponseWriter object that keeps track of all activity
|
||||
// allowing you to make assertions about how it was used.
|
||||
//
|
||||
// DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead.
|
||||
type TestResponseWriter struct {
|
||||
|
||||
// StatusCode is the last int written by the call to WriteHeader(int)
|
||||
StatusCode int
|
||||
|
||||
// Output is a string containing the written bytes using the Write([]byte) func.
|
||||
Output string
|
||||
|
||||
// header is the internal storage of the http.Header object
|
||||
header http.Header
|
||||
}
|
||||
|
||||
// Header gets the http.Header describing the headers that were set in this response.
|
||||
func (rw *TestResponseWriter) Header() http.Header {
|
||||
|
||||
if rw.header == nil {
|
||||
rw.header = make(http.Header)
|
||||
}
|
||||
|
||||
return rw.header
|
||||
}
|
||||
|
||||
// Write writes the specified bytes to Output.
|
||||
func (rw *TestResponseWriter) Write(bytes []byte) (int, error) {
|
||||
|
||||
// assume 200 success if no header has been set
|
||||
if rw.StatusCode == 0 {
|
||||
rw.WriteHeader(200)
|
||||
}
|
||||
|
||||
// add these bytes to the output string
|
||||
rw.Output = rw.Output + string(bytes)
|
||||
|
||||
// return normal values
|
||||
return 0, nil
|
||||
|
||||
}
|
||||
|
||||
// WriteHeader stores the HTTP status code in the StatusCode.
|
||||
func (rw *TestResponseWriter) WriteHeader(i int) {
|
||||
rw.StatusCode = i
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type TestRoundTripper struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
args := t.Called(req)
|
||||
return args.Get(0).(*http.Response), args.Error(1)
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
// Provides a system by which it is possible to mock your objects and verify calls are happening as expected.
|
||||
//
|
||||
// Example Usage
|
||||
//
|
||||
// The mock package provides an object, Mock, that tracks activity on another object. It is usually
|
||||
// embedded into a test object as shown below:
|
||||
//
|
||||
// type MyTestObject struct {
|
||||
// // add a Mock object instance
|
||||
// mock.Mock
|
||||
//
|
||||
// // other fields go here as normal
|
||||
// }
|
||||
//
|
||||
// When implementing the methods of an interface, you wire your functions up
|
||||
// to call the Mock.Called(args...) method, and return the appropriate values.
|
||||
//
|
||||
// For example, to mock a method that saves the name and age of a person and returns
|
||||
// the year of their birth or an error, you might write this:
|
||||
//
|
||||
// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) {
|
||||
// args := o.Mock.Called(firstname, lastname, age)
|
||||
// return args.Int(0), args.Error(1)
|
||||
// }
|
||||
//
|
||||
// The Int, Error and Bool methods are examples of strongly typed getters that take the argument
|
||||
// index position. Given this argument list:
|
||||
//
|
||||
// (12, true, "Something")
|
||||
//
|
||||
// You could read them out strongly typed like this:
|
||||
//
|
||||
// args.Int(0)
|
||||
// args.Bool(1)
|
||||
// args.String(2)
|
||||
//
|
||||
// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion:
|
||||
//
|
||||
// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine)
|
||||
//
|
||||
// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those
|
||||
// cases you should check for nil first.
|
||||
package mock
|
|
@ -0,0 +1,505 @@
|
|||
package mock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/objx"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// TestingT is an interface wrapper around *testing.T
|
||||
type TestingT interface {
|
||||
Logf(format string, args ...interface{})
|
||||
Errorf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
/*
|
||||
Call
|
||||
*/
|
||||
|
||||
// Call represents a method call and is used for setting expectations,
|
||||
// as well as recording activity.
|
||||
type Call struct {
|
||||
|
||||
// The name of the method that was or will be called.
|
||||
Method string
|
||||
|
||||
// Holds the arguments of the method.
|
||||
Arguments Arguments
|
||||
|
||||
// Holds the arguments that should be returned when
|
||||
// this method is called.
|
||||
ReturnArguments Arguments
|
||||
|
||||
// The number of times to return the return arguments when setting
|
||||
// expectations. 0 means to always return the value.
|
||||
Repeatability int
|
||||
}
|
||||
|
||||
// Mock is the workhorse used to track activity on another object.
|
||||
// For an example of its usage, refer to the "Example Usage" section at the top of this document.
|
||||
type Mock struct {
|
||||
|
||||
// The method name that is currently
|
||||
// being referred to by the On method.
|
||||
onMethodName string
|
||||
|
||||
// An array of the arguments that are
|
||||
// currently being referred to by the On method.
|
||||
onMethodArguments Arguments
|
||||
|
||||
// Represents the calls that are expected of
|
||||
// an object.
|
||||
ExpectedCalls []Call
|
||||
|
||||
// Holds the calls that were made to this mocked object.
|
||||
Calls []Call
|
||||
|
||||
// TestData holds any data that might be useful for testing. Testify ignores
|
||||
// this data completely allowing you to do whatever you like with it.
|
||||
testData objx.Map
|
||||
}
|
||||
|
||||
// TestData holds any data that might be useful for testing. Testify ignores
|
||||
// this data completely allowing you to do whatever you like with it.
|
||||
func (m *Mock) TestData() objx.Map {
|
||||
|
||||
if m.testData == nil {
|
||||
m.testData = make(objx.Map)
|
||||
}
|
||||
|
||||
return m.testData
|
||||
}
|
||||
|
||||
/*
|
||||
Setting expectations
|
||||
*/
|
||||
|
||||
// On starts a description of an expectation of the specified method
|
||||
// being called.
|
||||
//
|
||||
// Mock.On("MyMethod", arg1, arg2)
|
||||
func (m *Mock) On(methodName string, arguments ...interface{}) *Mock {
|
||||
m.onMethodName = methodName
|
||||
m.onMethodArguments = arguments
|
||||
return m
|
||||
}
|
||||
|
||||
// Return finishes a description of an expectation of the method (and arguments)
|
||||
// specified in the most recent On method call.
|
||||
//
|
||||
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2)
|
||||
func (m *Mock) Return(returnArguments ...interface{}) *Mock {
|
||||
m.ExpectedCalls = append(m.ExpectedCalls, Call{m.onMethodName, m.onMethodArguments, returnArguments, 0})
|
||||
return m
|
||||
}
|
||||
|
||||
// Once indicates that that the mock should only return the value once.
|
||||
//
|
||||
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once()
|
||||
func (m *Mock) Once() {
|
||||
m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 1
|
||||
}
|
||||
|
||||
// Twice indicates that that the mock should only return the value twice.
|
||||
//
|
||||
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice()
|
||||
func (m *Mock) Twice() {
|
||||
m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 2
|
||||
}
|
||||
|
||||
// Times indicates that that the mock should only return the indicated number
|
||||
// of times.
|
||||
//
|
||||
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5)
|
||||
func (m *Mock) Times(i int) {
|
||||
m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = i
|
||||
}
|
||||
|
||||
/*
|
||||
Recording and responding to activity
|
||||
*/
|
||||
|
||||
func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) {
|
||||
for i, call := range m.ExpectedCalls {
|
||||
if call.Method == method && call.Repeatability > -1 {
|
||||
|
||||
_, diffCount := call.Arguments.Diff(arguments)
|
||||
if diffCount == 0 {
|
||||
return i, &call
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return -1, nil
|
||||
}
|
||||
|
||||
func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) {
|
||||
|
||||
diffCount := 0
|
||||
var closestCall *Call = nil
|
||||
|
||||
for _, call := range m.ExpectedCalls {
|
||||
if call.Method == method {
|
||||
|
||||
_, tempDiffCount := call.Arguments.Diff(arguments)
|
||||
if tempDiffCount < diffCount || diffCount == 0 {
|
||||
diffCount = tempDiffCount
|
||||
closestCall = &call
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if closestCall == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return true, closestCall
|
||||
}
|
||||
|
||||
func callString(method string, arguments Arguments, includeArgumentValues bool) string {
|
||||
|
||||
var argValsString string = ""
|
||||
if includeArgumentValues {
|
||||
var argVals []string
|
||||
for argIndex, arg := range arguments {
|
||||
argVals = append(argVals, fmt.Sprintf("%d: %v", argIndex, arg))
|
||||
}
|
||||
argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t"))
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString)
|
||||
}
|
||||
|
||||
// Called tells the mock object that a method has been called, and gets an array
|
||||
// of arguments to return. Panics if the call is unexpected (i.e. not preceeded by
|
||||
// appropriate .On .Return() calls)
|
||||
func (m *Mock) Called(arguments ...interface{}) Arguments {
|
||||
|
||||
// get the calling function's name
|
||||
pc, _, _, ok := runtime.Caller(1)
|
||||
if !ok {
|
||||
panic("Couldn't get the caller information")
|
||||
}
|
||||
functionPath := runtime.FuncForPC(pc).Name()
|
||||
parts := strings.Split(functionPath, ".")
|
||||
functionName := parts[len(parts)-1]
|
||||
|
||||
found, call := m.findExpectedCall(functionName, arguments...)
|
||||
|
||||
switch {
|
||||
case found < 0:
|
||||
// we have to fail here - because we don't know what to do
|
||||
// as the return arguments. This is because:
|
||||
//
|
||||
// a) this is a totally unexpected call to this method,
|
||||
// b) the arguments are not what was expected, or
|
||||
// c) the developer has forgotten to add an accompanying On...Return pair.
|
||||
|
||||
closestFound, closestCall := m.findClosestCall(functionName, arguments...)
|
||||
|
||||
if closestFound {
|
||||
panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n", callString(functionName, arguments, true), callString(functionName, closestCall.Arguments, true)))
|
||||
} else {
|
||||
panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", functionName, functionName, callString(functionName, arguments, true), assert.CallerInfo()))
|
||||
}
|
||||
case call.Repeatability == 1:
|
||||
call.Repeatability = -1
|
||||
m.ExpectedCalls[found] = *call
|
||||
case call.Repeatability > 1:
|
||||
call.Repeatability -= 1
|
||||
m.ExpectedCalls[found] = *call
|
||||
}
|
||||
|
||||
// add the call
|
||||
m.Calls = append(m.Calls, Call{functionName, arguments, make([]interface{}, 0), 0})
|
||||
|
||||
return call.ReturnArguments
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
Assertions
|
||||
*/
|
||||
|
||||
// AssertExpectationsForObjects asserts that everything specified with On and Return
|
||||
// of the specified objects was in fact called as expected.
|
||||
//
|
||||
// Calls may have occurred in any order.
|
||||
func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool {
|
||||
var success bool = true
|
||||
for _, obj := range testObjects {
|
||||
mockObj := obj.(Mock)
|
||||
success = success && mockObj.AssertExpectations(t)
|
||||
}
|
||||
return success
|
||||
}
|
||||
|
||||
// AssertExpectations asserts that everything specified with On and Return was
|
||||
// in fact called as expected. Calls may have occurred in any order.
|
||||
func (m *Mock) AssertExpectations(t TestingT) bool {
|
||||
|
||||
var somethingMissing bool = false
|
||||
var failedExpectations int = 0
|
||||
|
||||
// iterate through each expectation
|
||||
for _, expectedCall := range m.ExpectedCalls {
|
||||
switch {
|
||||
case !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments):
|
||||
somethingMissing = true
|
||||
failedExpectations++
|
||||
t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
|
||||
case expectedCall.Repeatability > 0:
|
||||
somethingMissing = true
|
||||
failedExpectations++
|
||||
default:
|
||||
t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
|
||||
}
|
||||
}
|
||||
|
||||
if somethingMissing {
|
||||
t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(m.ExpectedCalls)-failedExpectations, len(m.ExpectedCalls), failedExpectations, assert.CallerInfo())
|
||||
}
|
||||
|
||||
return !somethingMissing
|
||||
}
|
||||
|
||||
// AssertNumberOfCalls asserts that the method was called expectedCalls times.
|
||||
func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool {
|
||||
var actualCalls int = 0
|
||||
for _, call := range m.Calls {
|
||||
if call.Method == methodName {
|
||||
actualCalls++
|
||||
}
|
||||
}
|
||||
return assert.Equal(t, actualCalls, expectedCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls))
|
||||
}
|
||||
|
||||
// AssertCalled asserts that the method was called.
|
||||
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool {
|
||||
if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) {
|
||||
t.Logf("%s", m.ExpectedCalls)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AssertNotCalled asserts that the method was not called.
|
||||
func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool {
|
||||
if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) {
|
||||
t.Logf("%s", m.ExpectedCalls)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool {
|
||||
for _, call := range m.Calls {
|
||||
if call.Method == methodName {
|
||||
|
||||
_, differences := Arguments(expected).Diff(call.Arguments)
|
||||
|
||||
if differences == 0 {
|
||||
// found the expected call
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
// we didn't find the expected call
|
||||
return false
|
||||
}
|
||||
|
||||
/*
|
||||
Arguments
|
||||
*/
|
||||
|
||||
// Arguments holds an array of method arguments or return values.
|
||||
type Arguments []interface{}
|
||||
|
||||
const (
|
||||
// The "any" argument. Used in Diff and Assert when
|
||||
// the argument being tested shouldn't be taken into consideration.
|
||||
Anything string = "mock.Anything"
|
||||
)
|
||||
|
||||
// AnythingOfTypeArgument is a string that contains the type of an argument
|
||||
// for use when type checking. Used in Diff and Assert.
|
||||
type AnythingOfTypeArgument string
|
||||
|
||||
// AnythingOfType returns an AnythingOfTypeArgument object containing the
|
||||
// name of the type to check for. Used in Diff and Assert.
|
||||
//
|
||||
// For example:
|
||||
// Assert(t, AnythingOfType("string"), AnythingOfType("int"))
|
||||
func AnythingOfType(t string) AnythingOfTypeArgument {
|
||||
return AnythingOfTypeArgument(t)
|
||||
}
|
||||
|
||||
// Get Returns the argument at the specified index.
|
||||
func (args Arguments) Get(index int) interface{} {
|
||||
if index+1 > len(args) {
|
||||
panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args)))
|
||||
}
|
||||
return args[index]
|
||||
}
|
||||
|
||||
// Is gets whether the objects match the arguments specified.
|
||||
func (args Arguments) Is(objects ...interface{}) bool {
|
||||
for i, obj := range args {
|
||||
if obj != objects[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Diff gets a string describing the differences between the arguments
|
||||
// and the specified objects.
|
||||
//
|
||||
// Returns the diff string and number of differences found.
|
||||
func (args Arguments) Diff(objects []interface{}) (string, int) {
|
||||
|
||||
var output string = "\n"
|
||||
var differences int
|
||||
|
||||
var maxArgCount int = len(args)
|
||||
if len(objects) > maxArgCount {
|
||||
maxArgCount = len(objects)
|
||||
}
|
||||
|
||||
for i := 0; i < maxArgCount; i++ {
|
||||
var actual, expected interface{}
|
||||
|
||||
if len(objects) <= i {
|
||||
actual = "(Missing)"
|
||||
} else {
|
||||
actual = objects[i]
|
||||
}
|
||||
|
||||
if len(args) <= i {
|
||||
expected = "(Missing)"
|
||||
} else {
|
||||
expected = args[i]
|
||||
}
|
||||
|
||||
if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() {
|
||||
|
||||
// type checking
|
||||
if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) {
|
||||
// not match
|
||||
differences++
|
||||
output = fmt.Sprintf("%s\t%d: \u274C type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual)
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
// normal checking
|
||||
|
||||
if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) {
|
||||
// match
|
||||
output = fmt.Sprintf("%s\t%d: \u2705 %s == %s\n", output, i, actual, expected)
|
||||
} else {
|
||||
// not match
|
||||
differences++
|
||||
output = fmt.Sprintf("%s\t%d: \u274C %s != %s\n", output, i, actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if differences == 0 {
|
||||
return "No differences.", differences
|
||||
}
|
||||
|
||||
return output, differences
|
||||
|
||||
}
|
||||
|
||||
// Assert compares the arguments with the specified objects and fails if
|
||||
// they do not exactly match.
|
||||
func (args Arguments) Assert(t TestingT, objects ...interface{}) bool {
|
||||
|
||||
// get the differences
|
||||
diff, diffCount := args.Diff(objects)
|
||||
|
||||
if diffCount == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
// there are differences... report them...
|
||||
t.Logf(diff)
|
||||
t.Errorf("%sArguments do not match.", assert.CallerInfo())
|
||||
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
// String gets the argument at the specified index. Panics if there is no argument, or
|
||||
// if the argument is of the wrong type.
|
||||
//
|
||||
// If no index is provided, String() returns a complete string representation
|
||||
// of the arguments.
|
||||
func (args Arguments) String(indexOrNil ...int) string {
|
||||
|
||||
if len(indexOrNil) == 0 {
|
||||
// normal String() method - return a string representation of the args
|
||||
var argsStr []string
|
||||
for _, arg := range args {
|
||||
argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg)))
|
||||
}
|
||||
return strings.Join(argsStr, ",")
|
||||
} else if len(indexOrNil) == 1 {
|
||||
// Index has been specified - get the argument at that index
|
||||
var index int = indexOrNil[0]
|
||||
var s string
|
||||
var ok bool
|
||||
if s, ok = args.Get(index).(string); !ok {
|
||||
panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index)))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil)))
|
||||
|
||||
}
|
||||
|
||||
// Int gets the argument at the specified index. Panics if there is no argument, or
|
||||
// if the argument is of the wrong type.
|
||||
func (args Arguments) Int(index int) int {
|
||||
var s int
|
||||
var ok bool
|
||||
if s, ok = args.Get(index).(int); !ok {
|
||||
panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %s", index, args.Get(index)))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Error gets the argument at the specified index. Panics if there is no argument, or
|
||||
// if the argument is of the wrong type.
|
||||
func (args Arguments) Error(index int) error {
|
||||
obj := args.Get(index)
|
||||
var s error
|
||||
var ok bool
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
if s, ok = obj.(error); !ok {
|
||||
panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %s", index, args.Get(index)))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Bool gets the argument at the specified index. Panics if there is no argument, or
|
||||
// if the argument is of the wrong type.
|
||||
func (args Arguments) Bool(index int) bool {
|
||||
var s bool
|
||||
var ok bool
|
||||
if s, ok = args.Get(index).(bool); !ok {
|
||||
panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %s", index, args.Get(index)))
|
||||
}
|
||||
return s
|
||||
}
|
|
@ -0,0 +1,669 @@
|
|||
package mock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/*
|
||||
Test objects
|
||||
*/
|
||||
|
||||
// ExampleInterface represents an example interface.
|
||||
type ExampleInterface interface {
|
||||
TheExampleMethod(a, b, c int) (int, error)
|
||||
}
|
||||
|
||||
// TestExampleImplementation is a test implementation of ExampleInterface
|
||||
type TestExampleImplementation struct {
|
||||
Mock
|
||||
}
|
||||
|
||||
func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) {
|
||||
args := i.Mock.Called(a, b, c)
|
||||
return args.Int(0), errors.New("Whoops")
|
||||
}
|
||||
|
||||
func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) {
|
||||
i.Mock.Called(yesorno)
|
||||
}
|
||||
|
||||
type ExampleType struct{}
|
||||
|
||||
func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error {
|
||||
args := i.Mock.Called(et)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
/*
|
||||
Mock
|
||||
*/
|
||||
|
||||
func Test_Mock_TestData(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
if assert.NotNil(t, mockedService.TestData()) {
|
||||
|
||||
mockedService.TestData().Set("something", 123)
|
||||
assert.Equal(t, 123, mockedService.TestData().Get("something").Data())
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_On(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
assert.Equal(t, mockedService.Mock.On("TheExampleMethod"), &mockedService.Mock)
|
||||
assert.Equal(t, "TheExampleMethod", mockedService.Mock.onMethodName)
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_On_WithArgs(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
assert.Equal(t, mockedService.Mock.On("TheExampleMethod", 1, 2, 3), &mockedService.Mock)
|
||||
assert.Equal(t, "TheExampleMethod", mockedService.Mock.onMethodName)
|
||||
assert.Equal(t, 1, mockedService.Mock.onMethodArguments[0])
|
||||
assert.Equal(t, 2, mockedService.Mock.onMethodArguments[1])
|
||||
assert.Equal(t, 3, mockedService.Mock.onMethodArguments[2])
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Return(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true), &mockedService.Mock)
|
||||
|
||||
// ensure the call was created
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
|
||||
call := mockedService.Mock.ExpectedCalls[0]
|
||||
|
||||
assert.Equal(t, "TheExampleMethod", call.Method)
|
||||
assert.Equal(t, "A", call.Arguments[0])
|
||||
assert.Equal(t, "B", call.Arguments[1])
|
||||
assert.Equal(t, true, call.Arguments[2])
|
||||
assert.Equal(t, 1, call.ReturnArguments[0])
|
||||
assert.Equal(t, "two", call.ReturnArguments[1])
|
||||
assert.Equal(t, true, call.ReturnArguments[2])
|
||||
assert.Equal(t, 0, call.Repeatability)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Return_Once(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Once()
|
||||
|
||||
// ensure the call was created
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
|
||||
call := mockedService.Mock.ExpectedCalls[0]
|
||||
|
||||
assert.Equal(t, "TheExampleMethod", call.Method)
|
||||
assert.Equal(t, "A", call.Arguments[0])
|
||||
assert.Equal(t, "B", call.Arguments[1])
|
||||
assert.Equal(t, true, call.Arguments[2])
|
||||
assert.Equal(t, 1, call.ReturnArguments[0])
|
||||
assert.Equal(t, "two", call.ReturnArguments[1])
|
||||
assert.Equal(t, true, call.ReturnArguments[2])
|
||||
assert.Equal(t, 1, call.Repeatability)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Return_Twice(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Twice()
|
||||
|
||||
// ensure the call was created
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
|
||||
call := mockedService.Mock.ExpectedCalls[0]
|
||||
|
||||
assert.Equal(t, "TheExampleMethod", call.Method)
|
||||
assert.Equal(t, "A", call.Arguments[0])
|
||||
assert.Equal(t, "B", call.Arguments[1])
|
||||
assert.Equal(t, true, call.Arguments[2])
|
||||
assert.Equal(t, 1, call.ReturnArguments[0])
|
||||
assert.Equal(t, "two", call.ReturnArguments[1])
|
||||
assert.Equal(t, true, call.ReturnArguments[2])
|
||||
assert.Equal(t, 2, call.Repeatability)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Return_Times(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Times(5)
|
||||
|
||||
// ensure the call was created
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
|
||||
call := mockedService.Mock.ExpectedCalls[0]
|
||||
|
||||
assert.Equal(t, "TheExampleMethod", call.Method)
|
||||
assert.Equal(t, "A", call.Arguments[0])
|
||||
assert.Equal(t, "B", call.Arguments[1])
|
||||
assert.Equal(t, true, call.Arguments[2])
|
||||
assert.Equal(t, 1, call.ReturnArguments[0])
|
||||
assert.Equal(t, "two", call.ReturnArguments[1])
|
||||
assert.Equal(t, true, call.ReturnArguments[2])
|
||||
assert.Equal(t, 5, call.Repeatability)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Return_Nothing(t *testing.T) {
|
||||
|
||||
// make a test impl object
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(), &mockedService.Mock)
|
||||
|
||||
// ensure the call was created
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
|
||||
call := mockedService.Mock.ExpectedCalls[0]
|
||||
|
||||
assert.Equal(t, "TheExampleMethod", call.Method)
|
||||
assert.Equal(t, "A", call.Arguments[0])
|
||||
assert.Equal(t, "B", call.Arguments[1])
|
||||
assert.Equal(t, true, call.Arguments[2])
|
||||
assert.Equal(t, 0, len(call.ReturnArguments))
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_findExpectedCall(t *testing.T) {
|
||||
|
||||
m := new(Mock)
|
||||
m.On("One", 1).Return("one")
|
||||
m.On("Two", 2).Return("two")
|
||||
m.On("Two", 3).Return("three")
|
||||
|
||||
f, c := m.findExpectedCall("Two", 3)
|
||||
|
||||
if assert.Equal(t, 2, f) {
|
||||
if assert.NotNil(t, c) {
|
||||
assert.Equal(t, "Two", c.Method)
|
||||
assert.Equal(t, 3, c.Arguments[0])
|
||||
assert.Equal(t, "three", c.ReturnArguments[0])
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) {
|
||||
|
||||
m := new(Mock)
|
||||
m.On("One", 1).Return("one")
|
||||
m.On("Two", 2).Return("two")
|
||||
m.On("Two", 3).Return("three")
|
||||
|
||||
f, _ := m.findExpectedCall("Two")
|
||||
|
||||
assert.Equal(t, -1, f)
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) {
|
||||
|
||||
m := new(Mock)
|
||||
m.On("One", 1).Return("one")
|
||||
m.On("Two", 2).Return("two").Once()
|
||||
m.On("Two", 3).Return("three").Twice()
|
||||
m.On("Two", 3).Return("three").Times(8)
|
||||
|
||||
f, c := m.findExpectedCall("Two", 3)
|
||||
|
||||
if assert.Equal(t, 2, f) {
|
||||
if assert.NotNil(t, c) {
|
||||
assert.Equal(t, "Two", c.Method)
|
||||
assert.Equal(t, 3, c.Arguments[0])
|
||||
assert.Equal(t, "three", c.ReturnArguments[0])
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_callString(t *testing.T) {
|
||||
|
||||
assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Called(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true)
|
||||
|
||||
returnArguments := mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
if assert.Equal(t, 1, len(mockedService.Mock.Calls)) {
|
||||
assert.Equal(t, "Test_Mock_Called", mockedService.Mock.Calls[0].Method)
|
||||
assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0])
|
||||
assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1])
|
||||
assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2])
|
||||
}
|
||||
|
||||
if assert.Equal(t, 3, len(returnArguments)) {
|
||||
assert.Equal(t, 5, returnArguments[0])
|
||||
assert.Equal(t, "6", returnArguments[1])
|
||||
assert.Equal(t, true, returnArguments[2])
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(5, "6", true).Once()
|
||||
mockedService.Mock.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(-1, "hi", false)
|
||||
|
||||
returnArguments1 := mockedService.Mock.Called(1, 2, 3)
|
||||
returnArguments2 := mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
if assert.Equal(t, 2, len(mockedService.Mock.Calls)) {
|
||||
assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Mock.Calls[0].Method)
|
||||
assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0])
|
||||
assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1])
|
||||
assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2])
|
||||
|
||||
assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Mock.Calls[1].Method)
|
||||
assert.Equal(t, 1, mockedService.Mock.Calls[1].Arguments[0])
|
||||
assert.Equal(t, 2, mockedService.Mock.Calls[1].Arguments[1])
|
||||
assert.Equal(t, 3, mockedService.Mock.Calls[1].Arguments[2])
|
||||
}
|
||||
|
||||
if assert.Equal(t, 3, len(returnArguments1)) {
|
||||
assert.Equal(t, 5, returnArguments1[0])
|
||||
assert.Equal(t, "6", returnArguments1[1])
|
||||
assert.Equal(t, true, returnArguments1[2])
|
||||
}
|
||||
|
||||
if assert.Equal(t, 3, len(returnArguments2)) {
|
||||
assert.Equal(t, -1, returnArguments2[0])
|
||||
assert.Equal(t, "hi", returnArguments2[1])
|
||||
assert.Equal(t, false, returnArguments2[2])
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4)
|
||||
|
||||
mockedService.TheExampleMethod(1, 2, 3)
|
||||
mockedService.TheExampleMethod(1, 2, 3)
|
||||
mockedService.TheExampleMethod(1, 2, 3)
|
||||
mockedService.TheExampleMethod(1, 2, 3)
|
||||
assert.Panics(t, func() {
|
||||
mockedService.TheExampleMethod(1, 2, 3)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_Called_Unexpected(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
// make sure it panics if no expectation was made
|
||||
assert.Panics(t, func() {
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
}, "Calling unexpected method should panic")
|
||||
|
||||
}
|
||||
|
||||
func Test_AssertExpectationsForObjects_Helper(t *testing.T) {
|
||||
|
||||
var mockedService1 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
var mockedService2 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
var mockedService3 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService1.Mock.On("Test_AssertExpectationsForObjects_Helper", 1).Return()
|
||||
mockedService2.Mock.On("Test_AssertExpectationsForObjects_Helper", 2).Return()
|
||||
mockedService3.Mock.On("Test_AssertExpectationsForObjects_Helper", 3).Return()
|
||||
|
||||
mockedService1.Called(1)
|
||||
mockedService2.Called(2)
|
||||
mockedService3.Called(3)
|
||||
|
||||
assert.True(t, AssertExpectationsForObjects(t, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock))
|
||||
|
||||
}
|
||||
|
||||
func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) {
|
||||
|
||||
var mockedService1 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
var mockedService2 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
var mockedService3 *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService1.Mock.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return()
|
||||
mockedService2.Mock.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return()
|
||||
mockedService3.Mock.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return()
|
||||
|
||||
mockedService1.Called(1)
|
||||
mockedService3.Called(3)
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.False(t, AssertExpectationsForObjects(tt, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertExpectations(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7)
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.False(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
// make the call now
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
// now assert expectations
|
||||
assert.True(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertExpectationsCustomType(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once()
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.False(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
// make the call now
|
||||
mockedService.TheExampleMethod3(&ExampleType{})
|
||||
|
||||
// now assert expectations
|
||||
assert.True(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice()
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.False(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
// make the call now
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
assert.False(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
// now assert expectations
|
||||
assert.True(t, mockedService.AssertExpectations(tt))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7)
|
||||
mockedService.Mock.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7)
|
||||
|
||||
args1 := mockedService.Mock.Called(1, 2, 3)
|
||||
assert.Equal(t, 5, args1.Int(0))
|
||||
assert.Equal(t, 6, args1.Int(1))
|
||||
assert.Equal(t, 7, args1.Int(2))
|
||||
|
||||
args2 := mockedService.Mock.Called(4, 5, 6)
|
||||
assert.Equal(t, 5, args2.Int(0))
|
||||
assert.Equal(t, 6, args2.Int(1))
|
||||
assert.Equal(t, 7, args2.Int(2))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertNumberOfCalls(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7)
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1))
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertCalled(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7)
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).Return()
|
||||
|
||||
mockedService.Mock.Called(1, "two", []uint8("three"))
|
||||
|
||||
assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8")))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertCalled_WithArguments(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7)
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3))
|
||||
assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once()
|
||||
mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once()
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
mockedService.Mock.Called(2, 3, 4)
|
||||
|
||||
tt := new(testing.T)
|
||||
assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3))
|
||||
assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4))
|
||||
assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5))
|
||||
|
||||
}
|
||||
|
||||
func Test_Mock_AssertNotCalled(t *testing.T) {
|
||||
|
||||
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
|
||||
|
||||
mockedService.Mock.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7)
|
||||
|
||||
mockedService.Mock.Called(1, 2, 3)
|
||||
|
||||
assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled"))
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
Arguments helper methods
|
||||
*/
|
||||
func Test_Arguments_Get(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
|
||||
assert.Equal(t, "string", args.Get(0).(string))
|
||||
assert.Equal(t, 123, args.Get(1).(int))
|
||||
assert.Equal(t, true, args.Get(2).(bool))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Is(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
|
||||
assert.True(t, args.Is("string", 123, true))
|
||||
assert.False(t, args.Is("wrong", 456, false))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"Hello World", 123, true}
|
||||
var diff string
|
||||
var count int
|
||||
diff, count = args.Diff([]interface{}{"Hello World", 456, "false"})
|
||||
|
||||
assert.Equal(t, 2, count)
|
||||
assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`)
|
||||
assert.Contains(t, diff, `false != %!s(bool=true)`)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
var diff string
|
||||
var count int
|
||||
diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"})
|
||||
|
||||
assert.Equal(t, 3, count)
|
||||
assert.Contains(t, diff, `extra != (Missing)`)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
var count int
|
||||
_, count = args.Diff([]interface{}{"string", Anything, true})
|
||||
|
||||
assert.Equal(t, 0, count)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", Anything, true}
|
||||
var count int
|
||||
_, count = args.Diff([]interface{}{"string", 123, true})
|
||||
|
||||
assert.Equal(t, 0, count)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", AnythingOfType("int"), true}
|
||||
var count int
|
||||
_, count = args.Diff([]interface{}{"string", 123, true})
|
||||
|
||||
assert.Equal(t, 0, count)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", AnythingOfType("string"), true}
|
||||
var count int
|
||||
var diff string
|
||||
diff, count = args.Diff([]interface{}{"string", 123, true})
|
||||
|
||||
assert.Equal(t, 1, count)
|
||||
assert.Contains(t, diff, `string != type int - %!s(int=123)`)
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Assert(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
|
||||
assert.True(t, args.Assert(t, "string", 123, true))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_String_Representation(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
assert.Equal(t, `string,int,bool`, args.String())
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_String(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
assert.Equal(t, "string", args.String(0))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Error(t *testing.T) {
|
||||
|
||||
var err error = errors.New("An Error")
|
||||
var args Arguments = []interface{}{"string", 123, true, err}
|
||||
assert.Equal(t, err, args.Error(3))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Error_Nil(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true, nil}
|
||||
assert.Equal(t, nil, args.Error(3))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Int(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
assert.Equal(t, 123, args.Int(1))
|
||||
|
||||
}
|
||||
|
||||
func Test_Arguments_Bool(t *testing.T) {
|
||||
|
||||
var args Arguments = []interface{}{"string", 123, true}
|
||||
assert.Equal(t, true, args.Bool(2))
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package testify
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImports(t *testing.T) {
|
||||
if assert.Equal(t, 1, 1) != true {
|
||||
t.Error("Something is wrong.")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
// The suite package contains logic for creating testing suite structs
|
||||
// and running the methods on those structs as tests. The most useful
|
||||
// piece of this package is that you can create setup/teardown methods
|
||||
// on your testing suites, which will run before/after the whole suite
|
||||
// or individual tests (depending on which interface(s) you
|
||||
// implement).
|
||||
//
|
||||
// A testing suite is usually built by first extending the built-in
|
||||
// suite functionality from suite.Suite in testify. Alternatively,
|
||||
// you could reproduce that logic on your own if you wanted (you
|
||||
// just need to implement the TestingSuite interface from
|
||||
// suite/interfaces.go).
|
||||
//
|
||||
// After that, you can implement any of the interfaces in
|
||||
// suite/interfaces.go to add setup/teardown functionality to your
|
||||
// suite, and add any methods that start with "Test" to add tests.
|
||||
// Methods that do not match any suite interfaces and do not begin
|
||||
// with "Test" will not be run by testify, and can safely be used as
|
||||
// helper methods.
|
||||
//
|
||||
// Once you've built your testing suite, you need to run the suite
|
||||
// (using suite.Run from testify) inside any function that matches the
|
||||
// identity that "go test" is already looking for (i.e.
|
||||
// func(*testing.T)).
|
||||
//
|
||||
// Regular expression to select test suites specified command-line
|
||||
// argument "-run". Regular expression to select the methods
|
||||
// of test suites specified command-line argument "-m".
|
||||
//
|
||||
// A crude example:
|
||||
// // Basic imports
|
||||
// import (
|
||||
// "testing"
|
||||
// "github.com/stretchr/testify/assert"
|
||||
// "github.com/stretchr/testify/suite"
|
||||
// )
|
||||
//
|
||||
// // Define the suite, and absorb the built-in basic suite
|
||||
// // functionality from testify - including a T() method which
|
||||
// // returns the current testing context
|
||||
// type ExampleTestSuite struct {
|
||||
// suite.Suite
|
||||
// VariableThatShouldStartAtFive int
|
||||
// }
|
||||
//
|
||||
// // Make sure that VariableThatShouldStartAtFive is set to five
|
||||
// // before each test
|
||||
// func (suite *ExampleTestSuite) SetupTest() {
|
||||
// suite.VariableThatShouldStartAtFive = 5
|
||||
// }
|
||||
//
|
||||
// // All methods that begin with "Test" are run as tests within a
|
||||
// // suite.
|
||||
// func (suite *ExampleTestSuite) TestExample() {
|
||||
// assert.Equal(suite.T(), suite.VariableThatShouldStartAtFive, 5)
|
||||
// }
|
||||
//
|
||||
// // In order for 'go test' to run this suite, we need to create
|
||||
// // a normal test function and pass our suite to suite.Run
|
||||
// func TestExampleTestSuite(t *testing.T) {
|
||||
// suite.Run(t, new(ExampleTestSuite))
|
||||
// }
|
||||
package suite
|
|
@ -0,0 +1,34 @@
|
|||
package suite
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestingSuite can store and return the current *testing.T context
|
||||
// generated by 'go test'.
|
||||
type TestingSuite interface {
|
||||
T() *testing.T
|
||||
SetT(*testing.T)
|
||||
}
|
||||
|
||||
// SetupAllSuite has a SetupSuite method, which will run before the
|
||||
// tests in the suite are run.
|
||||
type SetupAllSuite interface {
|
||||
SetupSuite()
|
||||
}
|
||||
|
||||
// SetupTestSuite has a SetupTest method, which will run before each
|
||||
// test in the suite.
|
||||
type SetupTestSuite interface {
|
||||
SetupTest()
|
||||
}
|
||||
|
||||
// TearDownAllSuite has a TearDownSuite method, which will run after
|
||||
// all the tests in the suite have been run.
|
||||
type TearDownAllSuite interface {
|
||||
TearDownSuite()
|
||||
}
|
||||
|
||||
// TearDownTestSuite has a TearDownTest method, which will run after
|
||||
// each test in the suite.
|
||||
type TearDownTestSuite interface {
|
||||
TearDownTest()
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package suite
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var matchMethod = flag.String("m", "", "regular expression to select tests of the suite to run")
|
||||
|
||||
// Suite is a basic testing suite with methods for storing and
|
||||
// retrieving the current *testing.T context.
|
||||
type Suite struct {
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
// T retrieves the current *testing.T context.
|
||||
func (suite *Suite) T() *testing.T {
|
||||
return suite.t
|
||||
}
|
||||
|
||||
// SetT sets the current *testing.T context.
|
||||
func (suite *Suite) SetT(t *testing.T) {
|
||||
suite.t = t
|
||||
}
|
||||
|
||||
// Run takes a testing suite and runs all of the tests attached
|
||||
// to it.
|
||||
func Run(t *testing.T, suite TestingSuite) {
|
||||
suite.SetT(t)
|
||||
|
||||
if setupAllSuite, ok := suite.(SetupAllSuite); ok {
|
||||
setupAllSuite.SetupSuite()
|
||||
}
|
||||
|
||||
methodFinder := reflect.TypeOf(suite)
|
||||
tests := []testing.InternalTest{}
|
||||
for index := 0; index < methodFinder.NumMethod(); index++ {
|
||||
method := methodFinder.Method(index)
|
||||
ok, err := methodFilter(method.Name)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if ok {
|
||||
test := testing.InternalTest{
|
||||
Name: method.Name,
|
||||
F: func(t *testing.T) {
|
||||
parentT := suite.T()
|
||||
suite.SetT(t)
|
||||
if setupTestSuite, ok := suite.(SetupTestSuite); ok {
|
||||
setupTestSuite.SetupTest()
|
||||
}
|
||||
method.Func.Call([]reflect.Value{reflect.ValueOf(suite)})
|
||||
if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok {
|
||||
tearDownTestSuite.TearDownTest()
|
||||
}
|
||||
suite.SetT(parentT)
|
||||
},
|
||||
}
|
||||
tests = append(tests, test)
|
||||
}
|
||||
}
|
||||
|
||||
if !testing.RunTests(func(_, _ string) (bool, error) { return true, nil },
|
||||
tests) {
|
||||
t.Fail()
|
||||
}
|
||||
|
||||
if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok {
|
||||
tearDownAllSuite.TearDownSuite()
|
||||
}
|
||||
}
|
||||
|
||||
// Filtering method according to set regular expression
|
||||
// specified command-line argument -m
|
||||
func methodFilter(name string) (bool, error) {
|
||||
if ok, _ := regexp.MatchString("^Test", name); !ok {
|
||||
return false, nil
|
||||
}
|
||||
return regexp.MatchString(*matchMethod, name)
|
||||
}
|
|
@ -0,0 +1,157 @@
|
|||
package suite
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// This suite is intended to store values to make sure that only
|
||||
// testing-suite-related methods are run. It's also a fully
|
||||
// functional example of a testing suite, using setup/teardown methods
|
||||
// and a helper method that is ignored by testify. To make this look
|
||||
// more like a real world example, all tests in the suite perform some
|
||||
// type of assertion.
|
||||
type SuiteTester struct {
|
||||
// Include our basic suite logic.
|
||||
Suite
|
||||
|
||||
// Keep counts of how many times each method is run.
|
||||
SetupSuiteRunCount int
|
||||
TearDownSuiteRunCount int
|
||||
SetupTestRunCount int
|
||||
TearDownTestRunCount int
|
||||
TestOneRunCount int
|
||||
TestTwoRunCount int
|
||||
NonTestMethodRunCount int
|
||||
}
|
||||
|
||||
// The SetupSuite method will be run by testify once, at the very
|
||||
// start of the testing suite, before any tests are run.
|
||||
func (suite *SuiteTester) SetupSuite() {
|
||||
suite.SetupSuiteRunCount++
|
||||
}
|
||||
|
||||
// The TearDownSuite method will be run by testify once, at the very
|
||||
// end of the testing suite, after all tests have been run.
|
||||
func (suite *SuiteTester) TearDownSuite() {
|
||||
suite.TearDownSuiteRunCount++
|
||||
}
|
||||
|
||||
// The SetupTest method will be run before every test in the suite.
|
||||
func (suite *SuiteTester) SetupTest() {
|
||||
suite.SetupTestRunCount++
|
||||
}
|
||||
|
||||
// The TearDownTest method will be run after every test in the suite.
|
||||
func (suite *SuiteTester) TearDownTest() {
|
||||
suite.TearDownTestRunCount++
|
||||
}
|
||||
|
||||
// Every method in a testing suite that begins with "Test" will be run
|
||||
// as a test. TestOne is an example of a test. For the purposes of
|
||||
// this example, we've included assertions in the tests, since most
|
||||
// tests will issue assertions.
|
||||
func (suite *SuiteTester) TestOne() {
|
||||
beforeCount := suite.TestOneRunCount
|
||||
suite.TestOneRunCount++
|
||||
assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount + 1)
|
||||
}
|
||||
|
||||
// TestTwo is another example of a test.
|
||||
func (suite *SuiteTester) TestTwo() {
|
||||
beforeCount := suite.TestTwoRunCount
|
||||
suite.TestTwoRunCount++
|
||||
assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount)
|
||||
}
|
||||
|
||||
// NonTestMethod does not begin with "Test", so it will not be run by
|
||||
// testify as a test in the suite. This is useful for creating helper
|
||||
// methods for your tests.
|
||||
func (suite *SuiteTester) NonTestMethod() {
|
||||
suite.NonTestMethodRunCount++
|
||||
}
|
||||
|
||||
// TestRunSuite will be run by the 'go test' command, so within it, we
|
||||
// can run our suite using the Run(*testing.T, TestingSuite) function.
|
||||
func TestRunSuite(t *testing.T) {
|
||||
suiteTester := new(SuiteTester)
|
||||
Run(t, suiteTester)
|
||||
|
||||
// Normally, the test would end here. The following are simply
|
||||
// some assertions to ensure that the Run function is working as
|
||||
// intended - they are not part of the example.
|
||||
|
||||
// The suite was only run once, so the SetupSuite and TearDownSuite
|
||||
// methods should have each been run only once.
|
||||
assert.Equal(t, suiteTester.SetupSuiteRunCount, 1)
|
||||
assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1)
|
||||
|
||||
// There are two test methods (TestOne and TestTwo), so the
|
||||
// SetupTest and TearDownTest methods (which should be run once for
|
||||
// each test) should have been run twice.
|
||||
assert.Equal(t, suiteTester.SetupTestRunCount, 2)
|
||||
assert.Equal(t, suiteTester.TearDownTestRunCount, 2)
|
||||
|
||||
// Each test should have been run once.
|
||||
assert.Equal(t, suiteTester.TestOneRunCount, 1)
|
||||
assert.Equal(t, suiteTester.TestTwoRunCount, 1)
|
||||
|
||||
// Methods that don't match the test method identifier shouldn't
|
||||
// have been run at all.
|
||||
assert.Equal(t, suiteTester.NonTestMethodRunCount, 0)
|
||||
}
|
||||
|
||||
type SuiteLoggingTester struct {
|
||||
Suite
|
||||
}
|
||||
|
||||
func (s *SuiteLoggingTester) TestLoggingPass() {
|
||||
s.T().Log("TESTLOGPASS")
|
||||
}
|
||||
|
||||
func (s *SuiteLoggingTester) TestLoggingFail() {
|
||||
s.T().Log("TESTLOGFAIL")
|
||||
assert.NotNil(s.T(), nil) //expected to fail
|
||||
}
|
||||
|
||||
type StdoutCapture struct {
|
||||
oldStdout *os.File
|
||||
readPipe *os.File
|
||||
}
|
||||
|
||||
func (sc *StdoutCapture) StartCapture() {
|
||||
sc.oldStdout = os.Stdout
|
||||
sc.readPipe, os.Stdout, _ = os.Pipe()
|
||||
}
|
||||
|
||||
func (sc *StdoutCapture) StopCapture() (string, error) {
|
||||
if sc.oldStdout == nil || sc.readPipe == nil {
|
||||
return "", errors.New("StartCapture not called before StopCapture")
|
||||
}
|
||||
os.Stdout.Close()
|
||||
os.Stdout = sc.oldStdout
|
||||
bytes, err := ioutil.ReadAll(sc.readPipe)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
func TestSuiteLogging(t *testing.T) {
|
||||
testT := testing.T{}
|
||||
|
||||
suiteLoggingTester := new(SuiteLoggingTester)
|
||||
|
||||
capture := StdoutCapture{}
|
||||
capture.StartCapture()
|
||||
Run(&testT, suiteLoggingTester)
|
||||
output, err := capture.StopCapture()
|
||||
|
||||
assert.Nil(t, err, "Got an error trying to capture stdout!")
|
||||
|
||||
assert.Contains(t, output, "TESTLOGFAIL")
|
||||
assert.NotContains(t, output, "TESTLOGPASS")
|
||||
}
|
Loading…
Reference in New Issue