Skip to content

Commit

Permalink
Merge branch 'stretchr:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
thekidder authored Sep 6, 2023
2 parents d71365d + 882382d commit 028da16
Show file tree
Hide file tree
Showing 15 changed files with 115 additions and 91 deletions.
20 changes: 19 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
go_version: ["1.20", "1.19"]
go_version:
- "1.19"
- "1.20"
steps:
- uses: actions/checkout@v3
- name: Setup Go
Expand All @@ -17,3 +19,19 @@ jobs:
- run: ./.ci.gofmt.sh
- run: ./.ci.govet.sh
- run: go test -v -race ./...
test:
runs-on: ubuntu-latest
strategy:
matrix:
go_version:
- "1.17"
- "1.18"
- "1.19"
- "1.20"
steps:
- uses: actions/checkout@v3
- name: Setup Go
uses: actions/[email protected]
with:
go-version: ${{ matrix.go_version }}
- run: go test -v -race ./...
1 change: 0 additions & 1 deletion MAINTAINERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ pull requests.

* @glesica
* @boyan-soubachov
* @mvdkleijn

38 changes: 20 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ Features include:
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 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)
* For an introduction to writing test code in Go, see https://go.dev/doc/code#Testing
* Check out the API Documentation https://pkg.go.dev/github.com/stretchr/testify
* To make your testing life easier, check out our other project, [gorc](https://github.com/stretchr/gorc)
* A little about [Test-Driven Development (TDD)](https://en.wikipedia.org/wiki/Test-driven_development)



[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package
[`assert`](https://pkg.go.dev/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.
Expand Down Expand Up @@ -100,19 +100,21 @@ func TestSomething(t *testing.T) {
}
```

[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package
[`require`](https://pkg.go.dev/github.com/stretchr/testify/require "API documentation") package
---------------------------------------------------------------------------------------------

The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test.
These functions must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test.
Otherwise race conditions may occur.

See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details.
See [t.FailNow](https://pkg.go.dev/testing#T.FailNow) for details.

[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package
[`mock`](https://pkg.go.dev/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:
An example test function that tests a piece of code that relies on an external object `testObj`, can set up expectations (testify) and assert that they indeed happened:

```go
package yours
Expand Down Expand Up @@ -157,7 +159,7 @@ func TestSomething(t *testing.T) {
// create an instance of our test object
testObj := new(MyMockedObject)

// setup expectations
// set up expectations
testObj.On("DoSomething", 123).Return(true, nil)

// call the code we are testing
Expand All @@ -179,7 +181,7 @@ func TestSomethingWithPlaceholder(t *testing.T) {
// create an instance of our test object
testObj := new(MyMockedObject)

// setup expectations with a placeholder in the argument list
// set up expectations with a placeholder in the argument list
testObj.On("DoSomething", mock.Anything).Return(true, nil)

// call the code we are testing
Expand All @@ -198,7 +200,7 @@ func TestSomethingElse2(t *testing.T) {
// create an instance of our test object
testObj := new(MyMockedObject)

// setup expectations with a placeholder in the argument list
// set up expectations with a placeholder in the argument list
mockCall := testObj.On("DoSomething", mock.Anything).Return(true, nil)

// call the code we are testing
Expand All @@ -217,14 +219,14 @@ func TestSomethingElse2(t *testing.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).
For more information on how to write mock code, check out the [API documentation for the `mock` package](https://pkg.go.dev/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.
You can use the [mockery tool](https://vektra.github.io/mockery/latest/) 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
[`suite`](https://pkg.go.dev/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.
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:

Expand Down Expand Up @@ -265,7 +267,7 @@ func TestExampleTestSuite(t *testing.T) {

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).
For more information on writing suites, check out the [API documentation for the `suite` package](https://pkg.go.dev/github.com/stretchr/testify/suite).

`Suite` object has assertion methods:

Expand Down Expand Up @@ -359,7 +361,7 @@ 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.
Code generation is used. [Look for `Code generated with`](https://github.com/search?q=repo%3Astretchr%2Ftestify%20%22Code%20generated%20with%22&type=code) at the top of some files. Run `go generate ./...` to update generated files.

We also chat on the [Gophers Slack](https://gophers.slack.com) group in the `#testify` and `#testify-dev` channels.

Expand Down
6 changes: 2 additions & 4 deletions _codegen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,8 @@ func (f *testFunc) CommentWithoutT(receiver string) string {
return strings.Replace(f.Comment(), search, replace, -1)
}

var headerTemplate = `/*
* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
* THIS FILE MUST NOT BE EDITED BY HAND
*/
// Standard header https://go.dev/s/generatedcode.
var headerTemplate = `// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT.
package {{.Name}}
Expand Down
2 changes: 1 addition & 1 deletion assert/assertion_compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
break
}

// time.Time can compared!
// time.Time can be compared!
timeObj1, ok := obj1.(time.Time)
if !ok {
timeObj1 = obj1Value.Convert(timeType).Interface().(time.Time)
Expand Down
7 changes: 2 additions & 5 deletions assert/assertion_format.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions assert/assertion_forward.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 10 additions & 12 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (

"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
yaml "gopkg.in/yaml.v3"
"gopkg.in/yaml.v3"
)

//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
Expand Down Expand Up @@ -266,7 +266,7 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {

// Aligns the provided message so that all lines after the first line start at the same location as the first line.
// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
// The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the
// basis on which the alignment occurs).
func indentMessageLines(message string, longestLabelLen int) string {
outBuf := new(bytes.Buffer)
Expand Down Expand Up @@ -496,7 +496,7 @@ func samePointers(first, second interface{}) bool {
// representations appropriate to be presented to the user.
//
// If the values are not of like type, the returned strings will be prefixed
// with the type name, and the value will be enclosed in parenthesis similar
// with the type name, and the value will be enclosed in parentheses similar
// to a type conversion in the Go grammar.
func formatUnequalValues(expected, actual interface{}) (e string, a string) {
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
Expand All @@ -523,7 +523,7 @@ func truncatingFormat(data interface{}) string {
return value
}

// EqualValues asserts that two objects are equal or convertable to the same types
// EqualValues asserts that two objects are equal or convertible to the same types
// and equal.
//
// assert.EqualValues(t, uint32(123), int32(123))
Expand Down Expand Up @@ -731,16 +731,14 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {

}

// getLen try to get length of object.
// return (false, 0) if impossible.
func getLen(x interface{}) (ok bool, length int) {
// getLen tries to get the length of an object.
// It returns (0, false) if impossible.
func getLen(x interface{}) (length int, ok bool) {
v := reflect.ValueOf(x)
defer func() {
if e := recover(); e != nil {
ok = false
}
ok = recover() == nil
}()
return true, v.Len()
return v.Len(), true
}

// Len asserts that the specified object has specific length.
Expand All @@ -751,7 +749,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
if h, ok := t.(tHelper); ok {
h.Helper()
}
ok, l := getLen(object)
l, ok := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
}
Expand Down
26 changes: 16 additions & 10 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1428,7 +1428,7 @@ func TestError(t *testing.T) {
True(t, Error(mockT, err), "Error with error should return True")

// go vet check
True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True")
True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should return True")

// returning an empty error interface
err = func() error {
Expand Down Expand Up @@ -1582,7 +1582,7 @@ func Test_getLen(t *testing.T) {
struct{}{},
}
for _, v := range falseCases {
ok, l := getLen(v)
l, ok := 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)
}
Expand Down Expand Up @@ -1611,7 +1611,7 @@ func Test_getLen(t *testing.T) {
}

for _, c := range trueCases {
ok, l := getLen(c.v)
l, ok := getLen(c.v)
True(t, ok, "Expected getLen success to get length of %#v", c.v)
Equal(t, c.l, l)
}
Expand Down Expand Up @@ -1907,12 +1907,12 @@ func TestInEpsilonSlice(t *testing.T) {
True(t, InEpsilonSlice(mockT,
[]float64{2.2, math.NaN(), 2.0},
[]float64{2.1, math.NaN(), 2.1},
0.06), "{2.2, NaN, 2.0} is element-wise close to {2.1, NaN, 2.1} in espilon=0.06")
0.06), "{2.2, NaN, 2.0} is element-wise close to {2.1, NaN, 2.1} in epsilon=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")
0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in epsilon=0.04")

False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
}
Expand Down Expand Up @@ -2794,14 +2794,20 @@ func TestNeverFalse(t *testing.T) {
True(t, Never(t, condition, 100*time.Millisecond, 20*time.Millisecond))
}

// TestNeverTrue checks Never with a condition that returns true on second call.
func TestNeverTrue(t *testing.T) {
mockT := new(testing.T)
state := 0

// A list of values returned by condition.
// Channel protects against concurrent access.
returns := make(chan bool, 2)
returns <- false
returns <- true
defer close(returns)

// Will return true on second call.
condition := func() bool {
defer func() {
state = state + 1
}()
return state == 2
return <-returns
}

False(t, Never(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
Expand Down
5 changes: 4 additions & 1 deletion assert/http_assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, va
// empty string if building a new request fails.
func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string {
w := httptest.NewRecorder()
req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
if len(values) > 0 {
url += "?" + values.Encode()
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return ""
}
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
module github.com/stretchr/testify

go 1.20
// This should match the minimum supported version that is tested in
// .github/workflows/main.yml
go 1.17

require (
github.com/davecgh/go-spew v1.1.1
Expand Down
Loading

0 comments on commit 028da16

Please sign in to comment.