pax_global_header00006660000000000000000000000064125313542430014514gustar00rootroot0000000000000052 comment=232e8563676cd15c3a36ba5e675ad4312ac4cb11 testify-1.0/000077500000000000000000000000001253135424300130435ustar00rootroot00000000000000testify-1.0/.gitignore000066400000000000000000000004071253135424300150340ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe .DS_Store testify-1.0/.travis.yml000066400000000000000000000001211253135424300151460ustar00rootroot00000000000000language: go go: - 1.1 - 1.2 - 1.3 - tip script: - go test -v ./... testify-1.0/LICENCE.txt000066400000000000000000000021631253135424300146500ustar00rootroot00000000000000Copyright (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.testify-1.0/README.md000066400000000000000000000255111253135424300143260ustar00rootroot00000000000000Testify - Thou Shalt Write Tests ================================ [![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) 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`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package ------------------------------------------------------------------------------------------- The `assert` package provides some helpful methods that allow you to write better test code in Go. * Prints friendly, easy to read failure descriptions * Allows for very readable code * Optionally annotate each assertion with a message See it in action: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) 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. if you assert many times, use the below: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert := assert.New(t) // assert equality assert.Equal(123, 123, "they should be equal") // assert inequality assert.NotEqual(123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(object) // assert for not nil (good when you expect something) if assert.NotNil(object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal("Something", object.Value) } } ``` `require` package ------------------------------------------------------------------------------------------- The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. [`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package --------------------------------------------------------------------------------------- The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http). We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead. [`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") 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: ```go 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.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.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). You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. [`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") 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: ```go // 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). `Suite` object has assertion methods: ```go // Basic imports import ( "testing" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including assertion methods. 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() { suite.Equal(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)) } ``` ------ Installation ============ To install Testify, use `go get`: * Latest version: go get github.com/stretchr/testify * Specific version: go get gopkg.in/stretchr/testify.v1 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: ```go 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 to the latest version, use `go get -u github.com/stretchr/testify`. ------ Version History =============== * 1.0 - New package versioning strategy adopted. ------ 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. testify-1.0/assert/000077500000000000000000000000001253135424300143445ustar00rootroot00000000000000testify-1.0/assert/assertions.go000066400000000000000000000541601253135424300170730ustar00rootroot00000000000000package assert import ( "bufio" "bytes" "fmt" "math" "reflect" "regexp" "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 } return false } // ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) expectedValue := reflect.ValueOf(expected) if expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { 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" && dir != "require") || 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 "" } // Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's // test printing (see inner comment for specifics) func indentMessageLines(message string, tabs int) string { outBuf := new(bytes.Buffer) for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { if i != 0 { outBuf.WriteRune('\n') } for ii := 0; ii < tabs; ii++ { outBuf.WriteRune('\t') // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter // by 1 prematurely. if ii == 0 && i > 0 { ii++ } } outBuf.WriteString(scanner.Text()) } return outBuf.String() } // 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:%s\n"+ "\r\tMessages:\t%s\n\r", getWhitespaceString(), CallerInfo(), indentMessageLines(failureMessage, 2), message) } else { t.Errorf("\r%s\r\tLocation:\t%s\n"+ "\r\tError:%s\n\r", getWhitespaceString(), CallerInfo(), indentMessageLines(failureMessage, 2)) } 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 (expected)\n"+ " != %#v (actual)", expected, actual), msgAndArgs...) } return true } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if !ObjectsAreEqualValues(expected, actual) { return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ " != %#v (actual)", 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 } // getLen try to get length of object. // return (false, 0) if impossible. func getLen(x interface{}) (ok bool, length int) { v := reflect.ValueOf(x) defer func() { if e := recover(); e != nil { ok = false } }() return true, v.Len() } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3, "The size of slice is not 3") // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { ok, l := getLen(object) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } // 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 } // containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found. func includeElement(list interface{}, element interface{}) (ok, found bool) { listValue := reflect.ValueOf(list) elementValue := reflect.ValueOf(element) defer func() { if e := recover(); e != nil { ok = false found = false } }() if reflect.TypeOf(list).Kind() == reflect.String { return true, strings.Contains(listValue.String(), elementValue.String()) } for i := 0; i < listValue.Len(); i++ { if ObjectsAreEqual(listValue.Index(i).Interface(), element) { return true, true } } return true, false } // Contains asserts that the specified string or list(array, slice...) contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") // 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 interface{}, msgAndArgs ...interface{}) bool { ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) } return true } // NotContains asserts that the specified string or list(array, slice...) does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") // 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 interface{}, msgAndArgs ...interface{}) bool { ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if found { 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, delta, dt), msgAndArgs...) } return true } func toFloat(x interface{}) (float64, bool) { var xf float64 xok := true switch xn := x.(type) { case uint8: xf = float64(xn) case uint16: xf = float64(xn) case uint32: xf = float64(xn) case uint64: xf = float64(xn) case int: xf = float64(xn) case int8: xf = float64(xn) case int16: xf = float64(xn) case int32: xf = float64(xn) case int64: xf = float64(xn) case float32: xf = float64(xn) case float64: xf = float64(xn) default: xok = false } return xf, xok } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { af, aok := toFloat(expected) bf, bok := toFloat(actual) if !aok || !bok { return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) } if math.IsNaN(af) { return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) } if math.IsNaN(bf) { return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) } dt := af - bf 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, delta, dt), msgAndArgs...) } return true } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) if !result { return result } } return true } // min(|expected|, |actual|) * epsilon func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 { af, aok := toFloat(expected) bf, bok := toFloat(actual) if !aok || !bok { // invalid input return 0 } if af < 0 { af = -af } if bf < 0 { bf = -bf } var delta float64 if af < bf { delta = af * epsilon } else { delta = bf * epsilon } return delta } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { delta := calcEpsilonDelta(expected, actual, epsilon) return InDelta(t, expected, actual, delta, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares two slices. func InEpsilonSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) if !result { return result } } 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) } // matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { match := matchRegexp(rx, str) if !match { Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) } return match } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { match := matchRegexp(rx, str) if match { Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) } return !match } testify-1.0/assert/assertions_test.go000066400000000000000000000471341253135424300201350ustar00rootroot00000000000000package assert import ( "errors" "math" "regexp" "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") } if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual('x', "x") { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual("x", 'x') { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0, 0.1) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0.1, 0) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(uint32(10), int32(10)) { t.Error("objectsAreEqual should return false") } if !ObjectsAreEqualValues(uint32(10), int32(10)) { t.Error("ObjectsAreEqualValues 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), int32(123)) { t.Error("Equal should return true") } if !Equal(mockT, uint64(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") } funcA := func() int { return 23 } funcB := func() int { return 42 } if !NotEqual(mockT, funcA, funcB) { t.Error("NotEqual should return true") } if NotEqual(mockT, "Hello World", "Hello World") { t.Error("NotEqual should return false") } if NotEqual(mockT, 123, 123) { t.Error("NotEqual should return false") } if NotEqual(mockT, 123.5, 123.5) { t.Error("NotEqual should return false") } if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { t.Error("NotEqual should return false") } if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("NotEqual should return false") } } type A struct { Name, Value string } func TestContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} complexList := []*A{ {"b", "c"}, {"d", "e"}, {"g", "h"}, {"j", "k"}, } 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\"") } if !Contains(mockT, list, "Bar") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") } if Contains(mockT, list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } if !Contains(mockT, complexList, &A{"g", "h"}) { t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") } if Contains(mockT, complexList, &A{"g", "e"}) { t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") } } func TestNotContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} 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\"") } if !NotContains(mockT, list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if NotContains(mockT, list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } } func Test_includeElement(t *testing.T) { list1 := []string{"Foo", "Bar"} list2 := []int{1, 2} ok, found := includeElement("Hello World", "World") True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo") True(t, ok) True(t, found) ok, found = includeElement(list1, "Bar") True(t, ok) True(t, found) ok, found = includeElement(list2, 1) True(t, ok) True(t, found) ok, found = includeElement(list2, 2) True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo!") True(t, ok) False(t, found) ok, found = includeElement(list2, 3) True(t, ok) False(t, found) ok, found = includeElement(list2, "1") True(t, ok) False(t, found) ok, found = includeElement(1433, "1") False(t, ok) False(t, found) } func TestCondition(t *testing.T) { mockT := new(testing.T) if !Condition(mockT, func() bool { return true }, "Truth") { t.Error("Condition should return true") } if Condition(mockT, func() bool { return false }, "Lie") { t.Error("Condition should return false") } } 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 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 Test_getLen(t *testing.T) { falseCases := []interface{}{ nil, 0, true, false, 'A', struct{}{}, } for _, v := range falseCases { ok, l := getLen(v) False(t, ok, "Expected getLen fail to get length of %#v", v) Equal(t, 0, l, "getLen should return 0 for %#v", v) } ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 trueCases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range trueCases { ok, l := getLen(c.v) True(t, ok, "Expected getLen success to get length of %#v", c.v) Equal(t, c.l, l) } } func TestLen(t *testing.T) { mockT := new(testing.T) False(t, Len(mockT, nil, 0), "nil does not have length") False(t, Len(mockT, 0, 0), "int does not have length") False(t, Len(mockT, true, 0), "true does not have length") False(t, Len(mockT, false, 0), "false does not have length") False(t, Len(mockT, 'A', 0), "Rune does not have length") False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } cases = []struct { v interface{} l int }{ {[]int{1, 2, 3}, 4}, {[...]int{1, 2, 3}, 2}, {"ABC", 2}, {map[int]int{1: 2, 2: 4, 3: 6}, 4}, {ch, 2}, {[]int{}, 1}, {map[int]int{}, 1}, {make(chan int), 1}, {[]int(nil), 1}, {map[int]int(nil), 1}, {(chan int)(nil), 1}, } for _, c := range cases { False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } } 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") } func TestInDelta(t *testing.T) { mockT := new(testing.T) True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInDeltaSlice(t *testing.T) { mockT := new(testing.T) True(t, InDeltaSlice(mockT, []float64{1.001, 0.999}, []float64{1, 1}, 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") True(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 1), "{1, 2} is element-wise close to {0, 3} in delta=1") False(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestInEpsilon(t *testing.T) { mockT := new(testing.T) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, } for _, tc := range cases { True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, } for _, tc := range cases { False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestInEpsilonSlice(t *testing.T) { mockT := new(testing.T) True(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") False(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestRegexp(t *testing.T) { mockT := new(testing.T) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, Regexp(mockT, tc.rx, tc.str)) True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) False(t, NotRegexp(mockT, tc.rx, tc.str)) False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) True(t, NotRegexp(mockT, tc.rx, tc.str)) True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } } testify-1.0/assert/doc.go000066400000000000000000000116101253135424300154370ustar00rootroot00000000000000// Package assert provides 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.") // // } // // if you assert many times, use the below: // // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // assert := assert.New(t) // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(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.EqualValues(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.Len(t, actualObject, expectedLength, [, message [, format-args]]) // // assert.Error(t, errorObject [, message [, format-args]]) // // assert.NoError(t, errorObject [, message [, format-args]]) // // assert.EqualError(t, theError, errString [, message [, format-args]]) // // assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) // // assert.IsType(t, expectedObject, actualObject [, message [, format-args]]) // // assert.Contains(t, stringOrSlice, substringOrElement [, message [, format-args]]) // // assert.NotContains(t, stringOrSlice, substringOrElement [, 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]]) // // assert.InDelta(t, numA, numB, delta, [, message [, format-args]]) // // assert.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) // // assert package contains Assertions object. it has assertion methods. // // Here is an overview of the assert functions: // assert.Equal(expected, actual [, message [, format-args]]) // // assert.EqualValues(expected, actual [, message [, format-args]]) // // assert.NotEqual(notExpected, actual [, message [, format-args]]) // // assert.True(actualBool [, message [, format-args]]) // // assert.False(actualBool [, message [, format-args]]) // // assert.Nil(actualObject [, message [, format-args]]) // // assert.NotNil(actualObject [, message [, format-args]]) // // assert.Empty(actualObject [, message [, format-args]]) // // assert.NotEmpty(actualObject [, message [, format-args]]) // // assert.Len(actualObject, expectedLength, [, message [, format-args]]) // // assert.Error(errorObject [, message [, format-args]]) // // assert.NoError(errorObject [, message [, format-args]]) // // assert.EqualError(theError, errString [, message [, format-args]]) // // assert.Implements((*MyInterface)(nil), new(MyObject) [,message [, format-args]]) // // assert.IsType(expectedObject, actualObject [, message [, format-args]]) // // assert.Contains(stringOrSlice, substringOrElement [, message [, format-args]]) // // assert.NotContains(stringOrSlice, substringOrElement [, message [, format-args]]) // // assert.Panics(func(){ // // // call code that should panic // // } [, message [, format-args]]) // // assert.NotPanics(func(){ // // // call code that should not panic // // } [, message [, format-args]]) // // assert.WithinDuration(timeA, timeB, deltaTime, [, message [, format-args]]) // // assert.InDelta(numA, numB, delta, [, message [, format-args]]) // // assert.InEpsilon(numA, numB, epsilon, [, message [, format-args]]) package assert testify-1.0/assert/errors.go000066400000000000000000000005061253135424300162100ustar00rootroot00000000000000package 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") testify-1.0/assert/forward_assertions.go000066400000000000000000000231711253135424300206150ustar00rootroot00000000000000package assert import "time" // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { return Fail(a.t, failureMessage, msgAndArgs...) } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject") func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { return Implements(a.t, interfaceObject, object, msgAndArgs...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { return IsType(a.t, expectedType, object, msgAndArgs...) } // Equal asserts that two objects are equal. // // assert.Equal(123, 123, "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool { return Equal(a.t, expected, actual, msgAndArgs...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool { return EqualValues(a.t, expected, actual, msgAndArgs...) } // Exactly asserts that two objects are equal is value and type. // // assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) bool { return Exactly(a.t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // assert.NotNil(err, "err should be something") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { return NotNil(a.t, object, msgAndArgs...) } // Nil asserts that the specified object is nil. // // assert.Nil(err, "err should be nothing") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { return Nil(a.t, object, msgAndArgs...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a // slice with len == 0. // // assert.Empty(obj) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { return Empty(a.t, object, msgAndArgs...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a // slice with len == 0. // // if assert.NotEmpty(obj) { // assert.Equal("two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { return NotEmpty(a.t, object, msgAndArgs...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(mySlice, 3, "The size of slice is not 3") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { return Len(a.t, object, length, msgAndArgs...) } // True asserts that the specified value is true. // // assert.True(myBool, "myBool should be true") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { return True(a.t, value, msgAndArgs...) } // False asserts that the specified value is true. // // assert.False(myBool, "myBool should be false") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { return False(a.t, value, msgAndArgs...) } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(obj1, obj2, "two objects shouldn't be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool { return NotEqual(a.t, expected, actual, msgAndArgs...) } // Contains asserts that the specified string contains the specified substring. // // assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) bool { return Contains(a.t, s, contains, msgAndArgs...) } // NotContains asserts that the specified string does NOT contain the specified substring. // // assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) bool { return NotContains(a.t, s, contains, msgAndArgs...) } // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { return Condition(a.t, comp, msgAndArgs...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return Panics(a.t, f, msgAndArgs...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return NotPanics(a.t, f, msgAndArgs...) } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(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 (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(err) { // assert.Equal(actualObj, expectedObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) bool { return NoError(a.t, theError, msgAndArgs...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(err, "An error was expected") { // assert.Equal(err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) bool { return Error(a.t, theError, msgAndArgs...) } // 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(err, "An error was expected") { // assert.Equal(err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { return EqualError(a.t, theError, errString, msgAndArgs...) } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return Regexp(a.t, rx, str, msgAndArgs...) } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return NotRegexp(a.t, rx, str, msgAndArgs...) } testify-1.0/assert/forward_assertions_test.go000066400000000000000000000331041253135424300216510ustar00rootroot00000000000000package assert import ( "errors" "regexp" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") } if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") } } func TestIsTypeWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") } if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") } } func TestEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Equal("Hello World", "Hello World") { t.Error("Equal should return true") } if !assert.Equal(123, 123) { t.Error("Equal should return true") } if !assert.Equal(123.5, 123.5) { t.Error("Equal should return true") } if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { t.Error("Equal should return true") } if !assert.Equal(nil, nil) { t.Error("Equal should return true") } } func TestEqualValuesWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.EqualValues(uint32(10), int32(10)) { t.Error("EqualValues should return true") } } func TestNotNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotNil(new(AssertionTesterConformingObject)) { t.Error("NotNil should return true: object is not nil") } if assert.NotNil(nil) { t.Error("NotNil should return false: object is nil") } } func TestNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Nil(nil) { t.Error("Nil should return true: object is nil") } if assert.Nil(new(AssertionTesterConformingObject)) { t.Error("Nil should return false: object is not nil") } } func TestTrueWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.True(true) { t.Error("True should return true") } if assert.True(false) { t.Error("True should return false") } } func TestFalseWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.False(false) { t.Error("False should return true") } if assert.False(true) { t.Error("False should return false") } } func TestExactlyWrapper(t *testing.T) { assert := New(new(testing.T)) a := float32(1) b := float64(1) c := float32(1) d := float32(2) if assert.Exactly(a, b) { t.Error("Exactly should return false") } if assert.Exactly(a, d) { t.Error("Exactly should return false") } if !assert.Exactly(a, c) { t.Error("Exactly should return true") } if assert.Exactly(nil, a) { t.Error("Exactly should return false") } if assert.Exactly(a, nil) { t.Error("Exactly should return false") } } func TestNotEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotEqual("Hello World", "Hello World!") { t.Error("NotEqual should return true") } if !assert.NotEqual(123, 1234) { t.Error("NotEqual should return true") } if !assert.NotEqual(123.5, 123.55) { t.Error("NotEqual should return true") } if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { t.Error("NotEqual should return true") } if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { t.Error("NotEqual should return true") } } func TestContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.Contains("Hello World", "Hello") { t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") } if assert.Contains("Hello World", "Salut") { t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") } if !assert.Contains(list, "Foo") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } if assert.Contains(list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } } func TestNotContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.NotContains("Hello World", "Hello!") { t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") } if assert.NotContains("Hello World", "Hello") { t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") } if !assert.NotContains(list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if assert.NotContains(list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } } func TestConditionWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Condition(func() bool { return true }, "Truth") { t.Error("Condition should return true") } if assert.Condition(func() bool { return false }, "Lie") { t.Error("Condition should return false") } } func TestDidPanicWrapper(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 TestPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Panics(func() { panic("Panic!") }) { t.Error("Panics should return true") } if assert.Panics(func() { }) { t.Error("Panics should return false") } } func TestNotPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotPanics(func() { }) { t.Error("NotPanics should return true") } if assert.NotPanics(func() { panic("Panic!") }) { t.Error("NotPanics should return false") } } func TestNoErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") // now set an error err = errors.New("Some error") assert.False(mockAssert.NoError(err), "NoError with error should return False") } func TestErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.Error(err), "Error should return False for nil arg") // now set an error err = errors.New("Some error") assert.True(mockAssert.Error(err), "Error with error should return True") } func TestEqualErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.EqualError(err, ""), "EqualError should return false for nil arg") // now set an error err = errors.New("some error") assert.False(mockAssert.EqualError(err, "Not some error"), "EqualError should return false for different error string") assert.True(mockAssert.EqualError(err, "some error"), "EqualError should return true") } func TestEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.Empty(""), "Empty string is empty") assert.True(mockAssert.Empty(nil), "Nil is empty") assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") assert.True(mockAssert.Empty(0), "Zero int value is empty") assert.True(mockAssert.Empty(false), "False value is empty") assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") assert.False(mockAssert.Empty(true), "True value is not empty") } func TestNotEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.NotEmpty(""), "Empty string is empty") assert.False(mockAssert.NotEmpty(nil), "Nil is empty") assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") assert.False(mockAssert.NotEmpty(false), "False value is empty") assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") assert.True(mockAssert.NotEmpty(true), "True value is not empty") } func TestLenWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.Len(nil, 0), "nil does not have length") assert.False(mockAssert.Len(0, 0), "int does not have length") assert.False(mockAssert.Len(true, 0), "true does not have length") assert.False(mockAssert.Len(false, 0), "false does not have length") assert.False(mockAssert.Len('A', 0), "Rune does not have length") assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDurationWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) a := time.Now() b := a.Add(10 * time.Second) assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDeltaWrapper(t *testing.T) { assert := New(new(testing.T)) True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInEpsilonWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, } for _, tc := range cases { True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, } for _, tc := range cases { False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestRegexpWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, assert.Regexp(tc.rx, tc.str)) True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) False(t, assert.NotRegexp(tc.rx, tc.str)) False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) True(t, assert.NotRegexp(tc.rx, tc.str)) True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } } testify-1.0/assert/http_assertions.go000066400000000000000000000131351253135424300201270ustar00rootroot00000000000000package assert import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" ) // httpCode is a helper that returns HTTP code of the response. It returns -1 // if building a new request fails. func httpCode(handler http.HandlerFunc, mode, url string, values url.Values) int { w := httptest.NewRecorder() req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) if err != nil { return -1 } handler(w, req) return w.Code } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusOK && code <= http.StatusPartialContent } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusBadRequest } // HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, mode, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { body := HTTPBody(handler, mode, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if !contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return contains } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { body := HTTPBody(handler, mode, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if contains { Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) } return !contains } // // Assertions Wrappers // // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPSuccess(a.t, handler, mode, url, values) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPRedirect(a.t, handler, mode, url, values) } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPError(a.t, handler, mode, url, values) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { return HTTPBodyContains(a.t, handler, mode, url, values, str) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContains(a.t, handler, mode, url, values, str) } testify-1.0/assert/http_assertions_test.go000066400000000000000000000070051253135424300211650ustar00rootroot00000000000000package assert import ( "fmt" "net/http" "net/url" "testing" ) func httpOK(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func httpRedirect(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTemporaryRedirect) } func httpError(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } func TestHTTPStatuses(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) } func TestHTTPStatusesWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) } func httpHelloName(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) } func TestHttpBody(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } func TestHttpBodyWrappers(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } testify-1.0/doc.go000066400000000000000000000016541253135424300141450ustar00rootroot00000000000000// Package testify is 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 // blank imports help docs. import ( // assert package _ "github.com/stretchr/testify/assert" // http package _ "github.com/stretchr/testify/http" // mock package _ "github.com/stretchr/testify/mock" ) testify-1.0/http/000077500000000000000000000000001253135424300140225ustar00rootroot00000000000000testify-1.0/http/doc.go000066400000000000000000000001421253135424300151130ustar00rootroot00000000000000// A set of tools to make testing http activity using the Go testing system easier. package http testify-1.0/http/test_response_writer.go000066400000000000000000000023631253135424300206460ustar00rootroot00000000000000package 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 } testify-1.0/http/test_round_tripper.go000066400000000000000000000004261253135424300203060ustar00rootroot00000000000000package 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) } testify-1.0/mock/000077500000000000000000000000001253135424300137745ustar00rootroot00000000000000testify-1.0/mock/doc.go000066400000000000000000000030551253135424300150730ustar00rootroot00000000000000// 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.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 testify-1.0/mock/mock.go000066400000000000000000000406431253135424300152630ustar00rootroot00000000000000package mock import ( "fmt" "github.com/stretchr/objx" "github.com/stretchr/testify/assert" "reflect" "runtime" "strings" "sync" "time" ) // 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 // Holds a channel that will be used to block the Return until it either // recieves a message or is closed. nil means it returns immediately. WaitFor <-chan time.Time // Holds a handler used to manipulate arguments content that are passed by // reference. It's useful when mocking methods such as unmarshalers or // decoders. Run func(Arguments) } // 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 mutex sync.Mutex } // 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 for _, arg := range arguments { if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) } } 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, nil, nil}) 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 } // WaitUntil sets the channel that will block the mock's return until its closed // or a message is received. // // Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) func (m *Mock) WaitUntil(w <-chan time.Time) *Mock { m.ExpectedCalls[len(m.ExpectedCalls)-1].WaitFor = w return m } // After sets how long to block until the call returns // // Mock.On("MyMethod", arg1, arg2).After(time.Second) func (m *Mock) After(d time.Duration) *Mock { return m.WaitUntil(time.After(d)) } // Run sets a handler to be called before returning. It can be used when // mocking a method such as unmarshalers that takes a pointer to a struct and // sets properties in such struct // // Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(function(args Arguments) { // arg := args.Get(0).(*map[string]interface{}) // arg["foo"] = "bar" // }) func (m *Mock) Run(fn func(Arguments)) *Mock { m.ExpectedCalls[len(m.ExpectedCalls)-1].Run = fn return m } /* 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) // If Call.WaitFor is set, blocks until the channel is closed or receives a message. func (m *Mock) Called(arguments ...interface{}) Arguments { defer m.mutex.Unlock() m.mutex.Lock() // 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, nil, nil}) // block if specified if call.WaitFor != nil { <-call.WaitFor } if call.Run != nil { call.Run(arguments) } 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("%v", 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("%v", 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: %v", 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: %v", 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: %v", index, args.Get(index))) } return s } testify-1.0/mock/mock_test.go000066400000000000000000000601761253135424300163250ustar00rootroot00000000000000package mock import ( "errors" "github.com/stretchr/testify/assert" "testing" "time" ) /* 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.Called(a, b, c) return args.Int(0), errors.New("Whoops") } func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { i.Called(yesorno) } type ExampleType struct { ran bool } func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { args := i.Called(et) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { args := i.Called(fn) return args.Error(0) } type ExampleFuncType func(string) error func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { args := i.Called(fn) 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.On("TheExampleMethod"), &mockedService.Mock) assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) } func Test_Mock_On_WithArgs(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.On("TheExampleMethod", 1, 2, 3), &mockedService.Mock) assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) assert.Equal(t, 1, mockedService.onMethodArguments[0]) assert.Equal(t, 2, mockedService.onMethodArguments[1]) assert.Equal(t, 3, mockedService.onMethodArguments[2]) } func Test_Mock_On_WithFuncArg(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.On("TheExampleMethodFunc", AnythingOfType("func(string) error")).Return(nil), &mockedService.Mock) assert.Equal(t, "TheExampleMethodFunc", mockedService.onMethodName) assert.Equal(t, AnythingOfType("func(string) error"), mockedService.onMethodArguments[0]) fn := func(string) error { return nil } mockedService.TheExampleMethodFunc(fn) } func Test_Mock_On_WithFuncPanics(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Panics(t, func() { mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) }) } func Test_Mock_On_WithFuncTypeArg(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).Return(nil), &mockedService.Mock) assert.Equal(t, "TheExampleMethodFuncType", mockedService.onMethodName) assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), mockedService.onMethodArguments[0]) fn := func(string) error { return nil } mockedService.TheExampleMethodFuncType(fn) } func Test_Mock_Return(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true), &mockedService.Mock) // ensure the call was created if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { call := mockedService.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) assert.Nil(t, call.WaitFor) } } func Test_Mock_Return_WaitUntil(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) ch := time.After(time.Second) assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).WaitUntil(ch), &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) assert.Equal(t, ch, call.WaitFor) } } func Test_Mock_Return_After(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).After(time.Second), &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) assert.NotEqual(t, nil, call.WaitFor) } } func Test_Mock_Return_Run(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.Mock.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Run(func(args Arguments) { arg := args.Get(0).(*ExampleType) arg.ran = 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, "TheExampleMethod3", call.Method) assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) assert.Equal(t, nil, call.ReturnArguments[0]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) assert.NotNil(t, call.Run) } et := ExampleType{} assert.Equal(t, false, et.ran) mockedService.TheExampleMethod3(&et) assert.Equal(t, true, et.ran) } func Test_Mock_Return_Once(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Once() // ensure the call was created if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { call := mockedService.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) assert.Nil(t, call.WaitFor) } } func Test_Mock_Return_Twice(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Twice() // ensure the call was created if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { call := mockedService.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) assert.Nil(t, call.WaitFor) } } func Test_Mock_Return_Times(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Times(5) // ensure the call was created if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { call := mockedService.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) assert.Nil(t, call.WaitFor) } } func Test_Mock_Return_Nothing(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(), &mockedService.Mock) // ensure the call was created if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { call := mockedService.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.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) returnArguments := mockedService.Called(1, 2, 3) if assert.Equal(t, 1, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.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 asyncCall(m *Mock, ch chan Arguments) { ch <- m.Called(1, 2, 3) } func Test_Mock_Called_blocks(t *testing.T) { var mockedService *TestExampleImplementation = new(TestExampleImplementation) mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) ch := make(chan Arguments) go asyncCall(&mockedService.Mock, ch) select { case <-ch: t.Fatal("should have waited") case <-time.After(1 * time.Millisecond): } returnArguments := <-ch if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { assert.Equal(t, "asyncCall", 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.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(5, "6", true).Once() mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(-1, "hi", false) returnArguments1 := mockedService.Called(1, 2, 3) returnArguments2 := mockedService.Called(1, 2, 3) if assert.Equal(t, 2, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) assert.Equal(t, 3, mockedService.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.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.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.On("Test_AssertExpectationsForObjects_Helper", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() mockedService3.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.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() mockedService3.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.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.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.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.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.Called(1, 2, 3) assert.False(t, mockedService.AssertExpectations(tt)) mockedService.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.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) args1 := mockedService.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.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.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) mockedService.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.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) mockedService.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.On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).Return() mockedService.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.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) mockedService.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.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() mockedService.Called(1, 2, 3) mockedService.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.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) mockedService.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)) } testify-1.0/package_test.go000066400000000000000000000002711253135424300160240ustar00rootroot00000000000000package 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.") } } testify-1.0/require/000077500000000000000000000000001253135424300145175ustar00rootroot00000000000000testify-1.0/require/doc.go000066400000000000000000000046411253135424300156200ustar00rootroot00000000000000// Alternative testing tools which stop test execution if test failed. // // Example Usage // // The following is a complete example using require in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/require" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // require.Equal(t, a, b, "The two words should be the same.") // // } // // Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. // // 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: // // require.Equal(t, expected, actual [, message [, format-args]) // // require.NotEqual(t, notExpected, actual [, message [, format-args]]) // // require.True(t, actualBool [, message [, format-args]]) // // require.False(t, actualBool [, message [, format-args]]) // // require.Nil(t, actualObject [, message [, format-args]]) // // require.NotNil(t, actualObject [, message [, format-args]]) // // require.Empty(t, actualObject [, message [, format-args]]) // // require.NotEmpty(t, actualObject [, message [, format-args]]) // // require.Error(t, errorObject [, message [, format-args]]) // // require.NoError(t, errorObject [, message [, format-args]]) // // require.EqualError(t, theError, errString [, message [, format-args]]) // // require.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) // // require.IsType(t, expectedObject, actualObject [, message [, format-args]]) // // require.Contains(t, string, substring [, message [, format-args]]) // // require.NotContains(t, string, substring [, message [, format-args]]) // // require.Panics(t, func(){ // // // call code that should panic // // } [, message [, format-args]]) // // require.NotPanics(t, func(){ // // // call code that should not panic // // } [, message [, format-args]]) // // require.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) // // require.InDelta(t, numA, numB, delta, [, message [, format-args]]) // // require.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) package require testify-1.0/require/forward_requirements.go000066400000000000000000000163051253135424300213220ustar00rootroot00000000000000package require import ( "time" "github.com/stretchr/testify/assert" ) type Assertions struct { t TestingT } func New(t TestingT) *Assertions { return &Assertions{ t: t, } } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { FailNow(a.t, failureMessage, msgAndArgs...) } // Implements asserts that an object is implemented by the specified interface. func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { Implements(a.t, interfaceObject, object, msgAndArgs...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { IsType(a.t, expectedType, object, msgAndArgs...) } // Equal asserts that two objects are equal. // // require.Equal(123, 123, "123 and 123 should be equal") func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) { Equal(a.t, expected, actual, msgAndArgs...) } // Exactly asserts that two objects are equal is value and type. // // require.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) { Exactly(a.t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // require.NotNil(err, "err should be something") func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { NotNil(a.t, object, msgAndArgs...) } // Nil asserts that the specified object is nil. // // require.Nil(err, "err should be nothing") func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { Nil(a.t, object, msgAndArgs...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a // slice with len == 0. // // require.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { Empty(a.t, object, msgAndArgs...) } // Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a // slice with len == 0. // // if require.NotEmpty(obj) { // require.Equal("two", obj[1]) // } func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { NotEmpty(a.t, object, msgAndArgs...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // require.Len(mySlice, 3, "The size of slice is not 3") func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { Len(a.t, object, length, msgAndArgs...) } // True asserts that the specified value is true. // // require.True(myBool, "myBool should be true") func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { True(a.t, value, msgAndArgs...) } // False asserts that the specified value is true. // // require.False(myBool, "myBool should be false") func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { False(a.t, value, msgAndArgs...) } // NotEqual asserts that the specified values are NOT equal. // // require.NotEqual(obj1, obj2, "two objects shouldn't be equal") func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) { NotEqual(a.t, expected, actual, msgAndArgs...) } // Contains asserts that the specified string contains the specified substring. // // require.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) { Contains(a.t, s, contains, msgAndArgs...) } // NotContains asserts that the specified string does NOT contain the specified substring. // // require.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) { NotContains(a.t, s, contains, msgAndArgs...) } // Uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { Condition(a.t, comp, msgAndArgs...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // require.Panics(func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { Panics(a.t, f, msgAndArgs...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // require.NotPanics(func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { NotPanics(a.t, f, msgAndArgs...) } // WithinDuration asserts that the two times are within duration delta of each other. // // require.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // InDelta asserts that the two numerals are within delta of each other. // // require.InDelta(t, math.Pi, (22 / 7.0), 0.01) func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if require.NoError(err) { // require.Equal(actualObj, expectedObj) // } func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) { NoError(a.t, theError, msgAndArgs...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if require.Error(err, "An error was expected") { // require.Equal(err, expectedError) // } func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) { Error(a.t, theError, msgAndArgs...) } // 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 require.Error(err, "An error was expected") { // require.Equal(err, expectedError) // } func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { EqualError(a.t, theError, errString, msgAndArgs...) } // Regexp asserts that a specified regexp matches a string. // // require.Regexp(t, regexp.MustCompile("start"), "it's starting") // require.Regexp(t, "start...$", "it's not starting") func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { Regexp(a.t, rx, str, msgAndArgs...) } // NotRegexp asserts that a specified regexp does not match a string. // // require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // require.NotRegexp(t, "^start", "it's not starting") func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { NotRegexp(a.t, rx, str, msgAndArgs...) } testify-1.0/require/forward_requirements_test.go000066400000000000000000000117531253135424300223630ustar00rootroot00000000000000package require import ( "errors" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { require := New(t) require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsTypeWrapper(t *testing.T) { require := New(t) require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualWrapper(t *testing.T) { require := New(t) require.Equal(1, 1) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Equal(1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqualWrapper(t *testing.T) { require := New(t) require.NotEqual(1, 2) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEqual(2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactlyWrapper(t *testing.T) { require := New(t) a := float32(1) b := float32(1) c := float64(1) require.Exactly(a, b) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Exactly(a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNilWrapper(t *testing.T) { require := New(t) require.NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotNil(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNilWrapper(t *testing.T) { require := New(t) require.Nil(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Nil(new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrueWrapper(t *testing.T) { require := New(t) require.True(true) mockT := new(MockT) mockRequire := New(mockT) mockRequire.True(false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalseWrapper(t *testing.T) { require := New(t) require.False(false) mockT := new(MockT) mockRequire := New(mockT) mockRequire.False(true) if !mockT.Failed { t.Error("Check should fail") } } func TestContainsWrapper(t *testing.T) { require := New(t) require.Contains("Hello World", "Hello") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Contains("Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContainsWrapper(t *testing.T) { require := New(t) require.NotContains("Hello World", "Hello!") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotContains("Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanicsWrapper(t *testing.T) { require := New(t) require.Panics(func() { panic("Panic!") }) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Panics(func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanicsWrapper(t *testing.T) { require := New(t) require.NotPanics(func() {}) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotPanics(func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoErrorWrapper(t *testing.T) { require := New(t) require.NoError(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NoError(errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestErrorWrapper(t *testing.T) { require := New(t) require.Error(errors.New("some error")) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Error(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualErrorWrapper(t *testing.T) { require := New(t) require.EqualError(errors.New("some error"), "some error") mockT := new(MockT) mockRequire := New(mockT) mockRequire.EqualError(errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmptyWrapper(t *testing.T) { require := New(t) require.Empty("") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Empty("x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmptyWrapper(t *testing.T) { require := New(t) require.NotEmpty("x") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEmpty("") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDurationWrapper(t *testing.T) { require := New(t) a := time.Now() b := a.Add(10 * time.Second) require.WithinDuration(a, b, 15*time.Second) mockT := new(MockT) mockRequire := New(mockT) mockRequire.WithinDuration(a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDeltaWrapper(t *testing.T) { require := New(t) require.InDelta(1.001, 1, 0.01) mockT := new(MockT) mockRequire := New(mockT) mockRequire.InDelta(1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } testify-1.0/require/requirements.go000066400000000000000000000205101253135424300175670ustar00rootroot00000000000000package require import ( "time" "github.com/stretchr/testify/assert" ) type TestingT interface { Errorf(format string, args ...interface{}) FailNow() } // Fail reports a failure through func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { assert.Fail(t, failureMessage, msgAndArgs...) t.FailNow() } // Implements asserts that an object is implemented by the specified interface. // // require.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // Equal asserts that two objects are equal. // // require.Equal(t, 123, 123, "123 and 123 should be equal") func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualValues asserts that two objects are equal or convertable to each other. // // require.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.EqualValues(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Exactly asserts that two objects are equal is value and type. // // require.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // require.NotNil(t, err, "err should be something") func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // require.Nil(t, err, "err should be nothing") func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // require.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // 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. // // require.NotEmpty(t, obj) // require.Equal(t, "one", obj[0]) func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // require.Len(t, mySlice, 3, "The size of slice is not 3") func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if !assert.Len(t, object, length, msgAndArgs...) { t.FailNow() } } // True asserts that the specified value is true. // // require.True(t, myBool, "myBool should be true") func True(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // False asserts that the specified value is true. // // require.False(t, myBool, "myBool should be false") func False(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // require.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Contains asserts that the specified string contains the specified substring. // // require.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { if !assert.Contains(t, s, contains, msgAndArgs...) { t.FailNow() } } // NotContains asserts that the specified string does NOT contain the specified substring. // // require.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { if !assert.NotContains(t, s, contains, msgAndArgs...) { t.FailNow() } } // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // require.Panics(t, func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // require.NotPanics(t, func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // require.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // require.InDelta(t, math.Pi, (22 / 7.0), 0.01) func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InEpsilon asserts that expected and actual have a relative error less than epsilon func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // Regexp asserts that a specified regexp matches a string. // // require.Regexp(t, regexp.MustCompile("start"), "it's starting") // require.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.Regexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // NotRegexp asserts that a specified regexp does not match a string. // // require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // require.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.NotRegexp(t, rx, str, msgAndArgs...) { t.FailNow() } } /* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // require.NoError(t, err) // require.Equal(t, actualObj, expectedObj) // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // require.Error(t, err, "An error was expected") // require.Equal(t, err, expectedError) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // require.Error(t, err, "An error was expected") // require.Equal(t, err, expectedError) // } func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if !assert.EqualError(t, theError, errString, msgAndArgs...) { t.FailNow() } } testify-1.0/require/requirements_test.go000066400000000000000000000107101253135424300206270ustar00rootroot00000000000000package require 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 { } type MockT struct { Failed bool } func (t *MockT) FailNow() { t.Failed = true } func (t *MockT) Errorf(format string, args ...interface{}) { _, _ = format, args } func TestImplements(t *testing.T) { Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsType(t *testing.T) { IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqual(t *testing.T) { Equal(t, 1, 1) mockT := new(MockT) Equal(mockT, 1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqual(t *testing.T) { NotEqual(t, 1, 2) mockT := new(MockT) NotEqual(mockT, 2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactly(t *testing.T) { a := float32(1) b := float32(1) c := float64(1) Exactly(t, a, b) mockT := new(MockT) Exactly(mockT, a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNil(t *testing.T) { NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) NotNil(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNil(t *testing.T) { Nil(t, nil) mockT := new(MockT) Nil(mockT, new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrue(t *testing.T) { True(t, true) mockT := new(MockT) True(mockT, false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalse(t *testing.T) { False(t, false) mockT := new(MockT) False(mockT, true) if !mockT.Failed { t.Error("Check should fail") } } func TestContains(t *testing.T) { Contains(t, "Hello World", "Hello") mockT := new(MockT) Contains(mockT, "Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContains(t *testing.T) { NotContains(t, "Hello World", "Hello!") mockT := new(MockT) NotContains(mockT, "Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanics(t *testing.T) { Panics(t, func() { panic("Panic!") }) mockT := new(MockT) Panics(mockT, func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanics(t *testing.T) { NotPanics(t, func() {}) mockT := new(MockT) NotPanics(mockT, func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoError(t *testing.T) { NoError(t, nil) mockT := new(MockT) NoError(mockT, errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestError(t *testing.T) { Error(t, errors.New("some error")) mockT := new(MockT) Error(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualError(t *testing.T) { EqualError(t, errors.New("some error"), "some error") mockT := new(MockT) EqualError(mockT, errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmpty(t *testing.T) { Empty(t, "") mockT := new(MockT) Empty(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmpty(t *testing.T) { NotEmpty(t, "x") mockT := new(MockT) NotEmpty(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDuration(t *testing.T) { a := time.Now() b := a.Add(10 * time.Second) WithinDuration(t, a, b, 15*time.Second) mockT := new(MockT) WithinDuration(mockT, a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDelta(t *testing.T) { InDelta(t, 1.001, 1, 0.01) mockT := new(MockT) InDelta(mockT, 1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } testify-1.0/suite/000077500000000000000000000000001253135424300141745ustar00rootroot00000000000000testify-1.0/suite/doc.go000066400000000000000000000051761253135424300153010ustar00rootroot00000000000000// 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". // Suite object has assertion methods. // // 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) // suite.Equal(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 testify-1.0/suite/interfaces.go000066400000000000000000000014361253135424300166520ustar00rootroot00000000000000package 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() } testify-1.0/suite/suite.go000066400000000000000000000055641253135424300156660ustar00rootroot00000000000000package suite import ( "flag" "fmt" "os" "reflect" "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) 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 { *assert.Assertions require *require.Assertions 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 suite.Assertions = assert.New(t) } // Require returns a require context for suite. func (suite *Suite) Require() *require.Assertions { if suite.require == nil { suite.require = require.New(suite.T()) } return suite.require } // Assert returns an assert context for suite. Normally, you can call // `suite.NoError(expected, actual)`, but for situations where the embedded // methods are overridden (for example, you might want to override // assert.Assertions with require.Assertions), this method is provided so you // can call `suite.Assert().NoError()`. func (suite *Suite) Assert() *assert.Assertions { if suite.Assertions == nil { suite.Assertions = assert.New(suite.T()) } return suite.Assertions } // 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() } defer func() { if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { tearDownAllSuite.TearDownSuite() } }() 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() } defer func() { if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { tearDownTestSuite.TearDownTest() } suite.SetT(parentT) }() method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) }, } tests = append(tests, test) } } if !testing.RunTests(func(_, _ string) (bool, error) { return true, nil }, tests) { t.Fail() } } // 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) } testify-1.0/suite/suite_test.go000066400000000000000000000135751253135424300167260ustar00rootroot00000000000000package suite import ( "errors" "io/ioutil" "os" "testing" "github.com/stretchr/testify/assert" ) // 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 } type SuiteSkipTester struct { // Include our basic suite logic. Suite // Keep counts of how many times each method is run. SetupSuiteRunCount int TearDownSuiteRunCount 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++ } func (suite *SuiteSkipTester) SetupSuite() { suite.SetupSuiteRunCount++ suite.T().Skip() } // 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++ } func (suite *SuiteSkipTester) 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) suite.Equal(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) suite.NotEqual(suite.TestTwoRunCount, beforeCount) } func (suite *SuiteTester) TestSkip() { suite.T().Skip() } // 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 three test methods (TestOne, TestTwo, and TestSkip), so // the SetupTest and TearDownTest methods (which should be run once for // each test) should have been run three times. assert.Equal(t, suiteTester.SetupTestRunCount, 3) assert.Equal(t, suiteTester.TearDownTestRunCount, 3) // 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) suiteSkipTester := new(SuiteSkipTester) Run(t, suiteSkipTester) // The suite was only run once, so the SetupSuite and TearDownSuite // methods should have each been run only once, even though SetupSuite // called Skip() assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) } func TestSuiteGetters(t *testing.T) { suite := new(SuiteTester) suite.SetT(t) assert.NotNil(t, suite.Assert()) assert.Equal(t, suite.Assertions, suite.Assert()) assert.NotNil(t, suite.Require()) assert.Equal(t, suite.require, suite.Require()) } 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!") // Failed tests' output is always printed assert.Contains(t, output, "TESTLOGFAIL") if testing.Verbose() { // In verbose mode, output from successful tests is also printed assert.Contains(t, output, "TESTLOGPASS") } else { assert.NotContains(t, output, "TESTLOGPASS") } }