A toolkit with common assertions and mocks that plays nicely with the standard library

Overview

Testify - Thou Shalt Write Tests

ℹ️ We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify

Build Status Go Report Card PkgGoDev

Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.

Features include:

Get started:

assert 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:

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:

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 for details.

mock package

The mock package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.

An example test function that tests a piece of code that relies on an external object testObj, can setup expectations (testify) and assert that they indeed happened:

package yours

import (
  "testing"
  "github.com/stretchr/testify/mock"
)

/*
  Test objects
*/

// MyMockedObject is a mocked object that implements an interface
// that describes an object that the code I am testing relies on.
type MyMockedObject struct{
  mock.Mock
}

// DoSomething is a method on MyMockedObject that implements some interface
// and just records the activity, and returns what the Mock object tells it to.
//
// In the real object, this method would do something useful, but since this
// is a mocked object - we're just going to stub it out.
//
// NOTE: This method is not being tested here, code that uses this object is.
func (m *MyMockedObject) DoSomething(number int) (bool, error) {

  args := m.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)


}

// TestSomethingWithPlaceholder is a second example of how to use our test object to
// make assertions about some target code we are testing.
// This time using a placeholder. Placeholders might be used when the
// data being passed in is normally dynamically generated and cannot be
// predicted beforehand (eg. containing hashes that are time sensitive)
func TestSomethingWithPlaceholder(t *testing.T) {

  // create an instance of our test object
  testObj := new(MyMockedObject)

  // setup expectations with a placeholder in the argument list
  testObj.On("DoSomething", mock.Anything).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.

You can use the mockery tool to autogenerate the mock code against an interface as well, making using mocks much quicker.

suite package

The suite package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.

An example suite is shown below:

// Basic imports
import (
    "testing"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/suite"
)

// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context
type ExampleTestSuite struct {
    suite.Suite
    VariableThatShouldStartAtFive int
}

// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
    suite.VariableThatShouldStartAtFive = 5
}

// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
    assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
}

// 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

For more information on writing suites, check out the API documentation for the suite package.

Suite object has assertion methods:

// 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:

go get github.com/stretchr/testify

This will then make the following packages available to you:

github.com/stretchr/testify/assert
github.com/stretchr/testify/require
github.com/stretchr/testify/mock
github.com/stretchr/testify/suite
github.com/stretchr/testify/http (deprecated)

Import the testify/assert package into your code using this template:

package yours

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

func TestSomething(t *testing.T) {

  assert.True(t, true, "True is true!")

}

Staying up to date

To update Testify to the latest version, use go get -u github.com/stretchr/testify.


Supported go versions

We support the three major Go versions, which are 1.13, 1.14 and 1.15 at the moment.


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.

Code generation is used. Look for CODE GENERATED AUTOMATICALLY at the top of some files. Run go generate ./... to update generated files.

We also chat on the Gophers Slack group in the #testify and #testify-dev channels.


License

This project is licensed under the terms of the MIT license.

Issues
  • Add go.mod and go.modverify

    Add go.mod and go.modverify

    What

    Add go.mod and go.sum, using Go 1.11.

    Why

    Now that golang/go#24301 has been accepted, lets start using go.mod files alongside Godep, and keep the two in sync.

    Notes

    There are no changes required to testify to support go.mod. The files were generated by running go build and `go mod tidy.

    Merging

    This PR is intended to be merged after #659 which adds Go1.11 to the list of supported builds.

    opened by leighmcculloch 25
  • race condition on master in mock

    race condition on master in mock

    Upgraded to master and tests that previously ran without issues now fail the race detector:

    $ go test ./model/modelhelpers/ -race -run TestUpdateRefreshScheduleTimerSuccess
    ==================
    WARNING: DATA RACE
    Read at 0x00c4203a34e8 by goroutine 21:
      reflect.typedmemmove()
          /usr/local/Cellar/go/1.10.2/libexec/src/runtime/mbarrier.go:265 +0x0
      reflect.packEface()
          /usr/local/Cellar/go/1.10.2/libexec/src/reflect/value.go:119 +0x101
      reflect.valueInterface()
          /usr/local/Cellar/go/1.10.2/libexec/src/reflect/value.go:978 +0x16a
      reflect.Value.Interface()
          /usr/local/Cellar/go/1.10.2/libexec/src/reflect/value.go:948 +0x51
      fmt.(*pp).printValue()
          /usr/local/Cellar/go/1.10.2/libexec/src/fmt/print.go:699 +0x3700
      fmt.(*pp).printValue()
          /usr/local/Cellar/go/1.10.2/libexec/src/fmt/print.go:853 +0x2550
      fmt.(*pp).printArg()
          /usr/local/Cellar/go/1.10.2/libexec/src/fmt/print.go:689 +0x192
      fmt.(*pp).doPrintf()
          /usr/local/Cellar/go/1.10.2/libexec/src/fmt/print.go:1099 +0x912
      fmt.Sprintf()
          /usr/local/Cellar/go/1.10.2/libexec/src/fmt/print.go:203 +0x73
      some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock.Arguments.Diff()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock/mock.go:678 +0x1416
      some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock.(*Mock).findExpectedCall()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock/mock.go:267 +0x175
      some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock.(*Mock).MethodCalled()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock/mock.go:343 +0xb3
      some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock.(*Mock).Called()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock/mock.go:333 +0x18a
      some.company.com/some/go-repo/mocks.(*ProvidesTimers).Remove()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/mocks/provides_timers.go:40 +0x2a1
    
    Previous write at 0x00c4203a34e8 by goroutine 20:
      sync/atomic.CompareAndSwapInt32()
          /usr/local/Cellar/go/1.10.2/libexec/src/runtime/race_amd64.s:293 +0xb
      sync.(*Mutex).Lock()
          /usr/local/Cellar/go/1.10.2/libexec/src/sync/mutex.go:74 +0x4d
      some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock.(*Mock).AssertCalled()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/vendor/github.com/stretchr/testify/mock/mock.go:489 +0xc8
      some.company.com/some/go-repo/model/modelhelpers.TestUpdateRefreshScheduleTimerSuccess()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/model/modelhelpers/helpers_test.go:267 +0xafe
      testing.tRunner()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:777 +0x16d
    
    Goroutine 21 (running) created at:
      some.company.com/some/go-repo/model/modelhelpers.removeTimerAsync()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/model/modelhelpers/helpers.go:94 +0x10f
      some.company.com/some/go-repo/model/modelhelpers.UpdateRefreshScheduleTimer()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/model/modelhelpers/helpers.go:152 +0x2c2
      some.company.com/some/go-repo/model/modelhelpers.TestUpdateRefreshScheduleTimerSuccess()
          /Users/andrewdeandrade/go/src/some.company.com/some/go-repo/model/modelhelpers/helpers_test.go:241 +0x5e0
      testing.tRunner()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:777 +0x16d
    
    Goroutine 20 (running) created at:
      testing.(*T).Run()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:824 +0x564
      testing.runTests.func1()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:1063 +0xa4
      testing.tRunner()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:777 +0x16d
      testing.runTests()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:1061 +0x4e1
      testing.(*M).Run()
          /usr/local/Cellar/go/1.10.2/libexec/src/testing/testing.go:978 +0x2cd
      main.main()
          _testmain.go:52 +0x22a
    

    Has anyone else encountered this?

    opened by andrewdeandrade 24
  • assert dont fail when nil is expected

    assert dont fail when nil is expected

    Hey there,

    I've a strange behavior, I might miss something or do something wrong.

    I am currently using testify/assert and testify/suite

    with :

    type MyTestSuite struct {
    	suite.Suite
        // some custom field
        db
    }
    
    func TestMyTestSuite(t *testing.T) {
         // init db
         // blabla
    
        suite.Run(t, &MyTestSuite{
            db
        })
    }
    
    func (s *MyTestSuite) TearDownTest() {
    	s.db.Query(nil, "DELETE FROM table;")
    }
    
    func (s *MyTestSuite) TestMyFunc() {
    
        foo, err := MyFunc(bar)
    
        assert.NotNil(s.T(), err) // err is nil here but dont fail
        assert.Nil(s.T(), foo)
        assert.Equal(s.T(), err.Error(), "failed")  // thus SIGSEGV happend here
    
       // followed by a lot of test after and more assert
    }
    

    The problem is that I have a SIGSEGV on assert.Equal(s.T(), err.Error(), "failed")

    because err is nil but it should not happen since I check assert.NotNil(s.T(), err) right before.

    I dont know why it pass, did I miss something somewhere ?

    Thanks for your time, Tommy

    opened by Tommy-42 24
  • Much Simpler Testify

    Much Simpler Testify

    Greetings, everyone!

    I have been thinking for a while about creating a much simpler version of testify.

    My goals would be to:

    • Make the API much smaller
    • Make the output more compact - probably a single line like the standard testing framework
    • ~~Use a require approach for all functions - abort if a test fails~~
    • Maintain the assert approach, with a require method that allows for a one-off require and fail. This will avoid deep nesting of if statements.
      • is.Equal(a,b).Require() or similar
    • Must manually output failure messages in the style of the testing framework, then call t.FailNow()
      • This will allow us to avoid using \r and \b which is incompatible with various output consoles.
      • Basically we need to duplicate the decorate function to generate our own output.
    • Remain completely dependent on the Go testing framework - testify should be as easy (or easier) to use as it is now... no fanciness.
    • Testify must take a testing.TB to enable testify usage in benchmark tests.

    The reason this has been on my mind is because I usually use a very small subset of the available API in the current testify, and I feel that it may be getting a bit bloated. In addition, I feel that testify may be adding some overhead to the testing process, thus increasing the amount of time it takes to run tests. I really should get some data to back that up. In addition, testify was written a long time ago, when we were still young gophers. I feel it could be much cleaner. :)

    I am still not sure this is something I will move forward with. I am hoping to get some feedback from the community to see what you think. Most likely this will live in its own subfolder as a separate package so the current version of testify doesn't just break for people currently using it.

    I'd appreciate some feedback from all of you who use testify, if you would be so kind:

    • What functionality do you find yourself using the most?
    • What functionality could you simply not live without?
    • What is missing that you feel should be added?
    • What is in testify that you feel should be removed?
    • What is in testify that you feel could be improved?
    • Anything else?

    Thanks in advance, everyone!

    opened by tylerstillwater 22
  • Add .Unset method to mock

    Add .Unset method to mock

    Summary

    This adds the ability to remove handlers that were added with .On

    Changes

    • Add .Unset Method
    • Add Unset method docs
    • Add Off method tests

    Motivation

    Nice to have this in tests where test will share majority of same mock handlers expect you might want to remove just 1 handler in one test.

    Related issues

    https://github.com/stretchr/testify/issues/558

    opened by pdufour 21
  • Add support for subtests (go 1.7)

    Add support for subtests (go 1.7)

    Adds a .Run(..) method onto test suites, mimicking the semantics of testing.Run. This will make writing table-driven tests in test suites cleaner and simpler, by handling the management of *testing.T instances transparently so that sub-tests can use the same suite.Assert() and suite.Require() methods, and have all output and test logic properly fall under the correct subtest.

    The major benefits of managing the *testing.T instance are:

    • Subtest output will be properly printed under each subtest, rather than all grouped under the test method
    • Subtests can be correctly executed using go test -run MyTestSuite/MyTestMethod/MySubTest
    opened by itzamna314 19
  • Allows mock call expectations to be defined in arbitrary order

    Allows mock call expectations to be defined in arbitrary order

    Originally the expctations required that the return values be specified immediately after the method name and arguments, otherwise the call setup will either panic (best case) or silently modify the previous call specification (worst case).

    This change moves the Return(), Run(), Once(), etc methods onto the Call struct, and changes the chaining behaviour so that they modify the Call data directly rather than referencing the last item in the ExpectedCalls array.

    The major externally visible change is that the methods all now return a pointer to the Call they're operating on, rather than a pointer to the containing Mock instance. This would break any code that chains multiple call setups together, so I have added an On method to Call that passes the call setup through to the Mock.

    I've updated the tests to match, and added a few new ones to cover the new functionality.

    opened by tcsc 19
  • assert.Equal randomly fails testing maps

    assert.Equal randomly fails testing maps

    assert.Equal (and other functions) will randomly fail testing equality of maps with the same values but different type.

    For example:

    package main
    
    import (
        "fmt"
        "github.com/stretchr/testify/assert"
        "testing"
    )
    
    func TestExactly(t *testing.T) {
        map1 := map[string]interface{}{"foo": 1234, "bar": int16(4321)}
        map2 := map[string]interface{}{"foo": 1234, "bar": int32(4321)}
    
        for i := 0; i < 3; i++ {
            if assert.Equal(t, map1, map2) {
                fmt.Printf("Everything is ok\n")
            } else {
                fmt.Printf("Everything is NOT OK\n")
            }
        }
    }
    

    Results in:

    === RUN TestExactly
    Everything is NOT OK
    Everything is ok
    Everything is NOT OK
    --- FAIL: TestExactly (0.00s)
        Location:   main_test.go:14
        Error:      Not equal: map[string]interface {}{"foo":1234, "bar":4321} (expected)
                        != map[string]interface {}{"foo":1234, "bar":4321} (actual)
    
        Location:   main_test.go:14
        Error:      Not equal: map[string]interface {}{"foo":1234, "bar":4321} (expected)
                        != map[string]interface {}{"bar":4321, "foo":1234} (actual)
    
    FAIL
    exit status 1
    FAIL    _/tmp/test6 0.012s
    

    The issue is because the type on bar is different between the maps (int16 in one, int32 in the other). ObjectsAreEqual uses reflect.DeepEqual which properly detects this, but then it continues to check equality of a fmt.Sprintf("%#v",...) on the values, and this randomly fails depending on the order it prints the map values in.

    The solution seems simple: remove the fmt.Sprintf() check. But I wasn't sure why that was in there to begin with.

    opened by phemmer 19
  • impr: `CallerInfo` should print full paths to the terminal

    impr: `CallerInfo` should print full paths to the terminal

    I am proposing this simple change, which changes this output

    --- FAIL: TestABC (0.00s)
        --- FAIL: TestABC/C (0.00s)
            6_test.go:258:
                	Error Trace:	6_test.go:258
                	            				6_test.go:748
                	Error:      	Not equal:
    ...
    

    to this:

    --- FAIL: TestABC (0.00s)
        --- FAIL: TestABC/C (0.00s)
            /0/1/2/3/4/5/6_test.go:258:
                	Error Trace:	/0/1/2/3/4/5/6_test.go:258
                	            				/0/1/2/3/4/5/6_test.go:748
                	Error:      	Not equal:
    ...
    

    With the latter output, it is much more straightforward to find the file you are looking for, even though in the displayed case, the file is the same.

    However, for VSCodium, the case is a little more helpful, since VSCodium's terminal is smart enough to recognize the output, and make links out of that output.

    Signed-off-by: Stavros Ntentos [email protected]

    Summary

    Changes

    Motivation

    Related issues

    opened by stdedos 18
  • Add using 'Equal' method of structure to test equality

    Add using 'Equal' method of structure to test equality

    If struct implements Equal method it should be used instead of recursively compare fields, because in some cases recursively comparing fields returns false result. for example type decimal.Decimal can have different internal representation for the same values.

    opened by bgaifullin 18
  • Optimise runtime for passing tests

    Optimise runtime for passing tests

    Summary

    Move some calls to testing.Helper() to reduce overhead.

    Changes

    Move call to Helper() after the check in various straightforward assert cases.

    ~Short-circuit require.NoError() and require.NoErrorf() so they do not call Helper() when no error is found.~ - deferred till another time

    Motivation

    Helper() in the standard Go runtime fetches a stack trace from the runtime, so is slow for calls that are made many times. However, Helper() only makes a difference if the call throws an error, so we can avoid that overhead in many cases which are otherwise cheap.

    Related issues

    #766 (not a full fix)

    enhancement 
    opened by bboreham 16
  • Nil actual type made AnythingOfType matcher panic

    Nil actual type made AnythingOfType matcher panic

    Summary

    Passing an actual value of type nil via a Mock into the argument matcher for AnythingOfType in a Mock causes a panic.

    Changes

    • Handle nil types up front when checking actual types against mock.AnythingOfType before calling any methods on the reflect.Type, which will be nil if the value was a nil interface.
    • Change formatting of the expected type from Name() to String() because Name is emptystring for pointer and some other types.

    Motivation

    Someone may expect their mock to be called with a nil interface, we should not panic in this case.

    Related issues

    Closes #1209

    opened by brackendawson 0
  • Assert that list contains type (not exact element)

    Assert that list contains type (not exact element)

    assert.IsType can be used to check a type. But I would like to only ensure that a list contains a specific type without checking for value equality (assert.Contains).

    I would imagine something like this: assert.ContainsType(t,ConcreteType{},[]interfaceType{SomeType{},AnotherType{},ConcreteType{}})

    opened by elchead 0
  • consider using String() method on types that implement fmt.Stringer

    consider using String() method on types that implement fmt.Stringer

    First of all, thanks for this great library! We use it quite extensively in go-libp2p.

    We're running into the problem that the error output is unreadable for many types.

    For example, we have a type peer.ID that's just a string (type peer.ID string), but the error output is practically unreadable:

    Error:      	[]peer.ID{"\x12 \x92\xad \xd38\r\xadG\xf4\xd57\xee\xe5B\xa6\xffk\x80\xb2\xdda\xe5&\a\xc69\x80>D=\xfc}", "\x12 \f5;\xd7\xca\x12\xe6\x8cɷ\x00\xa71\x85\xb7|\x8brGO\xb2\xb0\xf9\xaa\"A\xee\xd3#eHH", "\x12 \xa8q3O\xd00\x16\x83JA\xa2L\x1e\xed2\x9a\xf87\x01~\xf8ڗ\x97\xdaT\xb1\xe2(\x89\xba\x15", "\x12 \xa3\xbb\xcb`\x8cV\[email protected]\xd8%\xb3|}K\x90\a\xa7\xb5\xdeg\u0600|ʿ籐7\x8e\xc8"} does not contain "\x12 \xfd\x97\xf2?\x85?&\xc22el;\xac\xa4m\x1cj\xa4\xe3c\xcf\x00\x85u\xdb}:~3\xbf\x81\xaa"
    

    Another example is a type that contains a byte slice, but has a nice string representation. But instead of using that one, require error message print the byte slice.

    I'd be happy to contribute a PR, if this is something you would consider accepting.

    opened by marten-seemann 0
  • [Feature] test discription

    [Feature] test discription

    testify is very useful testing library. But, testify can't support test description. test description is test code explanation. I think if I read code that was written 1 month ago, I spend a little time to understand the code.

    If testify support test description, I think testify is more useful testing library.

    opened by lkeix 0
  • Mock: nothing does match mock.Anything

    Mock: nothing does match mock.Anything

    Having more arguments in a mock expectation than the interface has does not fail if those expectations match the string (Missing). This is only really confusing if the matcher is fairly generic, like mock.Anything.

    Perhaps the value used here should be a private type?

    Testify: v1.7.4 Go: go version go1.18 darwin/amd64

    package kata
    
    import (
    	"testing"
    
    	"github.com/stretchr/testify/mock"
    )
    
    type MyMock struct {
    	mock.Mock
    }
    
    func (t *MyMock) Do() {
    	t.Called()
    }
    
    func TestFoo(t *testing.T) {
    	m := &MyMock{}
    	m.Test(t)
    	m.On("Do", mock.Anything, mock.AnythingOfType("string"), "(Missing)", mock.MatchedBy(func(s string) bool {
    		t.Errorf("%q", s)
    		return true
    	})).Return()
    	m.Do()
    	m.AssertExpectations(t)
    }
    
    Running tool: /usr/local/go/bin/go test -timeout 30s -coverprofile=/var/folders/06/jjq25lws0cbcxv37ns0hb_mm0000gn/T/vscode-gohOmAs5/go-code-cover github.com/brackendawson/kata -race
    
    --- FAIL: TestFoo (0.00s)
        /Users/alandaws/src/github.com/brackendawson/kata/kata_test.go:21: "(Missing)"
        /Users/alandaws/src/github.com/brackendawson/kata/kata_test.go:21: "(Missing)"
        /Users/alandaws/src/github.com/brackendawson/kata/kata_test.go:25: PASS:	Do(string,mock.AnythingOfTypeArgument,string,mock.argumentMatcher)
    FAIL
    coverage: 0.0% of statements
    FAIL	github.com/brackendawson/kata	0.195s
    FAIL
    
    opened by brackendawson 0
Releases(v1.7.0)
  • v1.7.0(Jan 13, 2021)

  • v1.6.1(Jun 5, 2020)

    A breaking change was accidentally released in v1.6.0 which breaks the API for the HTTPBodyContains and HTTPBodyNotContains, this release reverts that change.

    Source code(tar.gz)
    Source code(zip)
  • v1.6.0(May 29, 2020)

  • v1.5.1(Feb 19, 2020)

  • v1.5.0(Feb 18, 2020)

  • v1.4.0(Aug 15, 2019)

  • v1.3.0(Jan 5, 2019)

    Pull requests included in this release:

    • https://github.com/stretchr/testify/pull/678 - Fixed incorrect comment
    • https://github.com/stretchr/testify/pull/661 - Allow assert.Equal on string type alias without panicking on failure
    • https://github.com/stretchr/testify/pull/659 - Add Go1.11 to CI
    • https://github.com/stretchr/testify/pull/682 - update comment to match function name
    • https://github.com/stretchr/testify/pull/688 - Bump Go versions and use '.x' to always get latest minor versions
    • https://github.com/stretchr/testify/pull/648 - Update the LICENSE to match the 'standard' MIT license file
    • https://github.com/stretchr/testify/pull/699 - Support arbitrary objects as the sole element in msgAndArgs
    • https://github.com/stretchr/testify/pull/696 - Recover panic in suite
    • https://github.com/stretchr/testify/pull/655 - Add support for subtests (go 1.7)
    • https://github.com/stretchr/testify/pull/607 - Add go.mod and go.modverify
    • https://github.com/stretchr/testify/pull/670 - Fix typo ("PASS" -> "FAIL")
    • https://github.com/stretchr/testify/pull/712 - Preserve stack frame for mock parent method call
    • https://github.com/stretchr/testify/pull/707 - fix for comparing kinds
    • https://github.com/stretchr/testify/pull/697 - Update readme to deprecate http and include available packages
    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Jun 9, 2018)

    • f35b8ab - Restore type information to matched output message
    • e494407 - Use %v to print matched argument values
    • 38eb60e - http_assertions: regenerate
    • adc0360 - http_assertions: fix docs (missing methods)
    • 26d6fa0 - More concrete error in Panics and PanicsWithValue
    • 1c264b1 - Refactor ObjectsAreEqual()
    • 2a15e20 - support diff display for string variables
    • ef2d015 - Run generator
    • 89226b8 - Compact template
    • 6c9d18a - Optimise template
    • c679ae2 - add function aliases for common assert and requires function signatures to make table driven tests easier
    • 380174f - Add placeholder example to docs
    • 33951ec - Add T object and Test method to Mock
    • 20dae58 - mock_test: remove unecessary code
    • 4c1331b - Anything: remove unecessary type
    • 921da25 - Displaying mismatch information of arguments diff while panic for closest function call. closes #556
    • 6efb0c4 - Adding url.Values to request RawQuery, fixes 522
    • b89eecf - Improve errors from mock assertions
    • 0bfbef4 - Modify AssertCalled and AssertNotCalled to give better error messages
    • bfc7630 - Add note about supported go versions to readme
    • 662d1e6 - Bump go version to 1.10
    • be8372a - Adding logging when mock assertions fails
    • a726187 - Fix vim-go integration and other editors
    • 8824eb4 - Store CallerInfo when On() is called and print for missing calls during AssertExpectations.
    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Jan 31, 2018)

    • 12b6f73 - Docs: Remove superfluous parenthesis
    • 85c7900 - Correct typo in assert.InDeltaMapValues
    • 33e9130 - Prune vendor & update deps
    • 5f831d4 - Print missing FAIL during AssertExpectation
    • 87b1dfb - Remove returns info from assertion docs
    • bf45a85 - Skip vendored packages from tests
    • 2c9035a - Changed mock assertions text output to be non-unicode friendly
    • 05aa1d4 - Remove outdated info from README
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Dec 30, 2017)

    • b91bfb9 - Move from Godep to dep for dependency management
    • 9ede17e - Drop old Go versions from tests
    • 8de2544 - Fix HTTP assertions to be consistent with the rest
    • b57b6d1 - Add FileExists and DirExists assertions
    • b3596e9 - Fxinng After(time.Duration) to wait properly
    • cbf22d8 - Support nil arguments to Argument Matchers
    • 42baa3e - Nil check in Implements assertion
    • b3dfaa9 - fail: add test name for logged output
    • 6e494f9 - put closestCall.Arguments to the expected side of the diff
    • 51464da - Consider empty/nil arrays as matching elements
    • 6f306a6 - Reuse aLen and bLen variables
    • 76de30e - Actually fail tests
    • ae87ba6 - Ran go generate
    • 8bd27dd - Compress some newlines
    • bf57a5d - ElementsMatch array/slice assertion ignoring order
    • 0c49dd9 - Replace is with in
    • 9fb9de1 - Make NotSubset actually fail the test on nil subset
    • 8ccf48a - Allow a method call to be optional
    • aa8279e - travis: add go1.9
    • c0f1d44 - indent actual value for better comparison with expected value
    • 249123e - Implement delta comparison for map values
    • 88a414d - generalize Empty assertion
    • 2aa2c17 - Fix unprotected call fields access in MethodCalled()
    • 890a5c3 - Issue #469 fix
    • 05e8a0e - Fix the actuality of InEpsilon
    • 2f1cd6b - time.Duraions are numbers too
    • b1f9894 - Fix InDelta expected nan check message
    • 4b92304 - Fix actual float conversion error message under calcRelativeError
    • f6abca5 - Added assert.PanicsWithValue + tests
    • e964b17 - add MethodCalled to the mock
    • 46b3c82 - Simple validation of Equal/NotEqual assertion arguments
    • cc18973 - Fix gogenerate travis check
    • e179a18 - Travis check go generate has been run
    • 3458981 - Run go vet in travis
    • c7668ea - Fixes #339 - Add assertionf assertions like Errorf and Equalf
    • c33f336 - Fix vet warnings and go generate to update docs
    • 3104bf5 - Use Go 1.7 subtests so suites can properly nest
    • b8c9b4e - Merge pull request #447 from stretchr/issue-442
    • bd79c01 - Fix race condition on mock package's Called
    • 253219d - Merge pull request #396 from medzin/issue-379
    • edd8e19 - Run go generate to syn generated assertions
    • aa10ab5 - Merge pull request #382 from GlenDC/feat-test-subset
    • 78be756 - Fixed HTTP assertions messages formatting and removed wrong test message
    • 3a59a58 - add Subset and NotSubset assertions
    • e68c5c5 - Merge pull request #446 from stretchr/gofmt-in-travis
    • dd57c7b - Check code is formatted in travis
    • eb84487 - Merge pull request #441 from stretchr/revert-commits
    • f712be9 - Revert "add mock.MethodCalled(methodName, args...)"
    • 34687eb - Revert "diffArguments: remove unnecessary range-for (#417)"
    • 2b76a97 - Revert "Added goconvey style assertions to the mock package"
    • b6296e3 - fix(docs): correct Error usage examples
    • d2f3716 - Add msgAndArgs pass forward to InDelta from InDeltaSlice
    • 158f9d0 - Check that there is a directory before trying to access it.
    • 18cfa68 - Added extra unit test for function with mixed variadic arguments.
    • b1f1bcb - fix typo
    • 09f61d7 - assert: fix error reporting when error contains escape sequences
    • 5c861cc - diffArguments: remove unnecessary range-for (#417)
    • bc11a6e - Tighten language by increasing overall consistency in wording in texts and argument names: use 'actual' instead of 'received'
    • 115ab90 - Provide argument name args in function signature
    • faf0710 - Added goconvey style assertions to the mock package
    • 97c0e43 - compare bytes with bytes.Equal instead of reflect.DeepEqual
    • 17a0bd5 - add mock.MethodCalled(methodName, args...)
    • 9afdd65 - Check number of provided arguments vs mocked
    • c67cacc - Merge pull request #438 from josephholsten/test-old-go
    • 287336f - travis: rm broken go releases
    • 32d79c5 - travis: check if these platforms are broken
    • 5c9da49 - HTTP code status assertions now fail tests
    • 4d4bfba - Merge pull request #392 from stretchr/add-nil-unequal-check
    • 332ae0e - Add Equal test comparing nil with non-nil
    • 2402e8e - Merge pull request #364 from nmiyake/fixFailOutput
    • 598ab58 - Merge pull request #171 from ANPez/master
    • cd206b0 - Merge pull request #318 from esdrasbeleza/master
    • ae4c58e - Merge pull request #367 from packrat386/rm_numeric_check
    • 6ac1453 - Merge pull request #370 from nmiyake/fixTypos
    • 211175b - Merge pull request #377 from seppestas/typo-fixes
    • 59b4bc5 - Merge pull request #371 from nmiyake/addEqualityDocs
    • 434d5c1 - Fixed minor typo
    • 3928f57 - Add comments for Equal and NotEqual to clarify pointer comparison
    • 13b9dd4 - Fix typos in comments in _codegen/main.go
    • 6835870 - Remove isNumericType check
    • 18a02ba - Merge pull request #365 from atombender/remove_addresses_from_diff
    • cbd71e7 - When diffing with spew, use a format that doesn't include pointer addresses (which generate false negatives). This updates go-spew to 04cdfd42973bb9c8589fd6a731800cf222fde1a9.
    • ddb91ee - Ensure that assert.Fail properly align its output
    • 5e72f93 - Remove timestamp from callback
    • 976c720 - Format generated code
    • 4b9bfb8 - run go/format on generated code
    • 75f4cfe - Merge pull request #331 from ansel1/master
    • 4ccf54a - Clearer messages
    • bf7a93e - Add timestamp
    • fcedfe2 - Add callbacks to run before and after each test
    • 8879a01 - Unlock and relock not needed anymore. Addresses #167.
    • 384cc66 - Merge branch 'master' of https://github.com/stretchr/testify
    • 4a6e516 - Added test to avoid regresions of #167.
    • 547cd8e - Release lock before .WaitUntil, as it may cause a deadlock when testing parallel objects. Address #167: Unable to test concurrent objects
    Source code(tar.gz)
    Source code(zip)
Owner
Stretchr, Inc.
Tame your unstructured data - We <3 open-source.
Stretchr, Inc.
:exclamation:Basic Assertion Library used along side native go testing, with building blocks for custom assertions

Package assert Package assert is a Basic Assertion library used along side native go testing Installation Use go get. go get github.com/go-playground/

Go Playgound 39 Apr 17, 2022
A modern generic testing assertions library for Go

test test is a generics based testing assertions library for Go. There are two packages, test and must. test - assertions that mark the test for failu

Seth Hoenig 12 Jun 23, 2022
Test your code without writing mocks with ephemeral Docker containers 📦 Setup popular services with just a couple lines of code ⏱️ No bash, no yaml, only code 💻

Gnomock – tests without mocks ??️ Spin up entire dependency stack ?? Setup initial dependency state – easily! ?? Test against actual, close to product

Yury Fedorov 845 Jun 26, 2022
Go module to validate Apple app attestations and assertions.

AppAttest Since iOS 14, Apple offers a new way to attest the integrity of a device. This is based on the WebAuthn specification. This go module implem

Bas Doorn 7 Apr 12, 2022
Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕

testza ?? Testza is like pizza for Go - you could life without it, but why should you? Get The Module | Documentation | Contributing | Code of Conduct

Marvin Wendt 389 Jun 18, 2022
Assert to perform programming assertions

Cli EN README Assert para realizar las aserciones de programación. GoDoc godoc for github Menú Principal Se configura un menú con ese ejemplo como dis

null 0 Jan 13, 2022
A collection of packages to augment the go testing package and support common patterns.

gotest.tools A collection of packages to augment testing and support common patterns. Usage With Go modules enabled (go1.11+) $ go get gotest.tools/v3

null 323 Jul 2, 2022
ctrsploit: A penetration toolkit for container environment

ctrsploit: A penetration toolkit for container environment

Lei Wang 6 Feb 22, 2022
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.

Fortio Fortio (Φορτίο) started as, and is, Istio's load testing tool and now graduated to be its own project. Fortio is also used by, among others, Me

Fortio (Φορτίο) 2.6k Jun 24, 2022
Playwright for Go a browser automation library to control Chromium, Firefox and WebKit with a single API.

?? Playwright for API reference | Example recipes Playwright is a Go library to automate Chromium, Firefox and WebKit with a single API. Playwright is

Max Schmitt 845 Jul 1, 2022
HTTP load testing tool and library. It's over 9000!

Vegeta Vegeta is a versatile HTTP load testing tool built out of a need to drill HTTP services with a constant request rate. It can be used both as a

Tomás Senart 19.8k Jun 27, 2022
A library for generating fake data such as names, addresses, and phone numbers.

faker Faker is a library for generating fake data such as names, addresses, and phone numbers. It is a (mostly) API-compatible port of Ruby Faker gem

Dmitri Goutnik 296 Jun 26, 2022
A WebDriver client and acceptance testing library for Go

Agouti Agouti is a library for writing browser-based acceptance tests in Google Go. It provides Gomega matchers and plays nicely with Ginkgo or Spec.

Stephen Levine 801 Jun 23, 2022
A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Americanas Go 6 Dec 19, 2021
Library created for testing JSON against patterns.

Gomatch Library created for testing JSON against patterns. The goal was to be able to validate JSON focusing only on parts essential in given test cas

null 41 Dec 1, 2021
A BDD library for Go

gospecify This provides a BDD syntax for testing your Go code. It should be familiar to anybody who has used libraries such as rspec. Installation The

Samuel Tesla 52 Nov 22, 2021
A Go test assertion library for verifying that two representations of JSON are semantically equal

jsonassert is a Go test assertion library for verifying that two representations of JSON are semantically equal. Usage Create a new *jsonassert.Assert

Roger Guldbrandsen 85 Jun 14, 2022
A Go library help testing your RESTful API application

RESTit A Go micro-framework to help writing RESTful API integration test Package RESTit provides helps to those who want to write an integration test

RESTit 55 Nov 25, 2021
testcase is an opinionated behavior-driven-testing library

Table of Contents testcase Guide Official API Documentation Getting Started / Example Modules Summary DRY Modularization Stability Case Study About te

Adam Luzsi 95 Jun 20, 2022