├── .gitignore ├── Godeps ├── _workspace │ ├── .gitignore │ └── src │ │ └── github.com │ │ └── stretchr │ │ └── testify │ │ └── assert │ │ ├── errors.go │ │ ├── doc.go │ │ ├── forward_assertions.go │ │ ├── forward_assertions_test.go │ │ ├── assertions_test.go │ │ └── assertions.go ├── Readme └── Godeps.json ├── controlci.yml ├── LICENSE ├── backoff_test.go ├── README.md └── backoff.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /Godeps/_workspace/.gitignore: -------------------------------------------------------------------------------- 1 | /pkg 2 | /bin 3 | -------------------------------------------------------------------------------- /Godeps/Readme: -------------------------------------------------------------------------------- 1 | This directory tree is generated automatically by godep. 2 | 3 | Please do not edit. 4 | 5 | See https://github.com/tools/godep for more information. 6 | -------------------------------------------------------------------------------- /Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/diggs/go-backoff", 3 | "GoVersion": "go1.4.2", 4 | "Deps": [ 5 | { 6 | "ImportPath": "github.com/stretchr/testify/assert", 7 | "Rev": "a2e5515d4d8f83969e9617a2efd2dfaef2d36800" 8 | } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /controlci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | unit: 3 | description: Runs unit tests 4 | docker_image: golang:1.7.5 5 | auto: true 6 | command: | 7 | SRC_DIR=$GOPATH/src/go-backoff 8 | ln -sf $(pwd) $SRC_DIR 9 | cd $SRC_DIR 10 | go get github.com/tools/godep 11 | godep go test -v ./... 12 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // AnError is an error instance useful for testing. If the code does not care 8 | // about error specifics, and only needs to return the error for example, this 9 | // error should be used to make the test code more readable. 10 | var AnError = errors.New("assert.AnError general error for testing") 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Tyler Power 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /backoff_test.go: -------------------------------------------------------------------------------- 1 | package backoff 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "math" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func TestExponentialBackoff(t *testing.T) { 11 | exp := NewExponential(time.Millisecond, 0) 12 | for i := 0; i < 5; i++ { 13 | assert.Equal(t, int64(float64(time.Millisecond)*math.Pow(2, float64(i))), exp.NextDuration) 14 | exp.Backoff() 15 | } 16 | } 17 | 18 | func TestExponentialLimit(t *testing.T) { 19 | exp := NewExponential(time.Millisecond, 4*time.Millisecond) 20 | for i := 0; i < 5; i++ { 21 | exp.Backoff() 22 | } 23 | assert.Equal(t, 5, exp.count) 24 | assert.Equal(t, 4*time.Millisecond, exp.NextDuration) 25 | } 26 | 27 | func TestLinearBackoff(t *testing.T) { 28 | lin := NewLinear(time.Millisecond, 0) 29 | for i := 0; i < 5; i++ { 30 | assert.Equal(t, int64(float64(time.Millisecond)*float64(i)), lin.NextDuration) 31 | lin.Backoff() 32 | } 33 | } 34 | 35 | func TestLinearLimit(t *testing.T) { 36 | lin := NewLinear(time.Millisecond, 4*time.Millisecond) 37 | for i := 0; i < 5; i++ { 38 | lin.Backoff() 39 | } 40 | assert.Equal(t, 5, lin.count) 41 | assert.Equal(t, 4*time.Millisecond, lin.NextDuration) 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## What is it? 2 | 3 | go-backoff implements linear, [exponential and exponential with full jitter](http://www.awsarchitectureblog.com/2015/03/backoff.html) back off algorithms. 4 | 5 | ## Usage 6 | 7 | Instantiate and use a Backoff instance for the lifetime of a go routine. Call backoff.Backoff() to put the routine to sleep for the desired amount of time. Use backoff.Reset() to reset counters back to 0. 8 | 9 | ```go 10 | // Back off linearly, starting at 250ms, capping at 16 seconds 11 | linear = backoff.NewLinear(250*time.Millisecond, 16*time.Second) 12 | // Back off exponentially, starting at 5 seconds, capping at 320 seconds 13 | exp = backoff.NewExponential(5*time.Second, 320*time.Second) 14 | // Back off exponentially, starting at 1 minute, with no cap 15 | expt = backoff.NewExponential(time.Minute, 0) 16 | // Back off between 0 and exponentially, starting at 30 seconds, capping at 10 minutes 17 | expj = backoff.NewExponentialFullJitter(30*time.Second, 10*time.Minute) 18 | 19 | ... 20 | 21 | for { 22 | err := tryDoThing() 23 | if err != nil { 24 | glog.Debugf("Backing off %d second(s)", exp.NextDuration/time.Second) 25 | exp.Backoff() 26 | } else { 27 | exp.Reset() 28 | return 29 | } 30 | } 31 | 32 | ``` 33 | 34 | ## Tests 35 | ```bash 36 | go get github.com/tools/godep 37 | godep restore 38 | go test 39 | 40 | PASS 41 | ok github.com/diggs/go-backoff 6.319s 42 | ``` -------------------------------------------------------------------------------- /backoff.go: -------------------------------------------------------------------------------- 1 | package backoff 2 | 3 | import ( 4 | "crypto/rand" 5 | "math" 6 | "math/big" 7 | "time" 8 | ) 9 | 10 | // BackoffStrategy can be implemented to provide different backoff algorithms. 11 | type BackoffStrategy interface { 12 | // GetBackoffDuration calculates the next time.Duration that the current thread will sleep for when backing off. 13 | // It receives the current backoff count, the initial backoff duration and the last back off duration. 14 | GetBackoffDuration(int, time.Duration, time.Duration) time.Duration 15 | } 16 | 17 | // Backoff tracks the generic state of the configured back off strategy. 18 | type Backoff struct { 19 | // LastDuration contains the duration that was previously waited, or 0 if no backoff has occurred yet. 20 | LastDuration time.Duration 21 | // NextDuration contains the duration that will be waited on the next call to Backoff(). 22 | NextDuration time.Duration 23 | start time.Duration 24 | limit time.Duration 25 | count int 26 | strategy BackoffStrategy 27 | } 28 | 29 | // NewBackoff creates a new Backoff using the specified BackoffStrategy, start duration and limit. 30 | func NewBackoff(strategy BackoffStrategy, start time.Duration, limit time.Duration) *Backoff { 31 | backoff := Backoff{strategy: strategy, start: start, limit: limit} 32 | backoff.Reset() 33 | return &backoff 34 | } 35 | 36 | // Reset sets the Backoff to its initial conditions ready to start over. 37 | func (b *Backoff) Reset() { 38 | b.count = 0 39 | b.LastDuration = 0 40 | b.NextDuration = b.getNextDuration() 41 | } 42 | 43 | // Backoff causes the current thread/routine to sleep for NextDuration. 44 | func (b *Backoff) Backoff() { 45 | time.Sleep(b.NextDuration) 46 | b.count++ 47 | b.LastDuration = b.NextDuration 48 | b.NextDuration = b.getNextDuration() 49 | } 50 | 51 | func (b *Backoff) getNextDuration() time.Duration { 52 | backoff := b.strategy.GetBackoffDuration(b.count, b.start, b.LastDuration) 53 | if b.limit > 0 && backoff > b.limit { 54 | backoff = b.limit 55 | } 56 | return backoff 57 | } 58 | 59 | type exponential struct{} 60 | 61 | func (exponential) GetBackoffDuration(backoffCount int, start time.Duration, lastBackoff time.Duration) time.Duration { 62 | period := int64(math.Pow(2, float64(backoffCount))) 63 | return time.Duration(period) * start 64 | } 65 | 66 | // NewExponential creates a new backoff using the exponential backoff algorithm. 67 | func NewExponential(start time.Duration, limit time.Duration) *Backoff { 68 | return NewBackoff(exponential{}, start, limit) 69 | } 70 | 71 | type exponentialFullJitter struct { 72 | limit time.Duration 73 | } 74 | 75 | func (b exponentialFullJitter) GetBackoffDuration(backoffCount int, start time.Duration, lastBackoff time.Duration) time.Duration { 76 | backoff := exponential{}.GetBackoffDuration(backoffCount, start, lastBackoff) 77 | if backoff <= 0 { 78 | return backoff 79 | } 80 | // apply limit here to ensure the jitter falls btween 0-min(limit,backoff) 81 | if b.limit > 0 && backoff > b.limit { 82 | backoff = b.limit 83 | } 84 | jitter, _ := rand.Int(rand.Reader, big.NewInt(int64(backoff))) 85 | return time.Duration(jitter.Int64()) 86 | } 87 | 88 | // NewExponentialFullJitter creates a new backoff using the exponential with full jitter backoff algorithm. 89 | func NewExponentialFullJitter(start time.Duration, limit time.Duration) *Backoff { 90 | return NewBackoff(exponentialFullJitter{limit: limit}, start, limit) 91 | } 92 | 93 | type linear struct{} 94 | 95 | func (linear) GetBackoffDuration(backoffCount int, start time.Duration, lastBackoff time.Duration) time.Duration { 96 | return time.Duration(backoffCount) * start 97 | } 98 | 99 | // NewLinear creates a new backoff using the linear backoff algorithm. 100 | func NewLinear(start time.Duration, limit time.Duration) *Backoff { 101 | return NewBackoff(linear{}, start, limit) 102 | } 103 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go: -------------------------------------------------------------------------------- 1 | // A set of comprehensive testing tools for use with the normal Go testing system. 2 | // 3 | // Example Usage 4 | // 5 | // The following is a complete example using assert in a standard test function: 6 | // import ( 7 | // "testing" 8 | // "github.com/stretchr/testify/assert" 9 | // ) 10 | // 11 | // func TestSomething(t *testing.T) { 12 | // 13 | // var a string = "Hello" 14 | // var b string = "Hello" 15 | // 16 | // assert.Equal(t, a, b, "The two words should be the same.") 17 | // 18 | // } 19 | // 20 | // if you assert many times, use the below: 21 | // 22 | // import ( 23 | // "testing" 24 | // "github.com/stretchr/testify/assert" 25 | // ) 26 | // 27 | // func TestSomething(t *testing.T) { 28 | // assert := assert.New(t) 29 | // 30 | // var a string = "Hello" 31 | // var b string = "Hello" 32 | // 33 | // assert.Equal(a, b, "The two words should be the same.") 34 | // } 35 | // 36 | // Assertions 37 | // 38 | // Assertions allow you to easily write test code, and are global funcs in the `assert` package. 39 | // All assertion functions take, as the first argument, the `*testing.T` object provided by the 40 | // testing framework. This allows the assertion funcs to write the failings and other details to 41 | // the correct place. 42 | // 43 | // Every assertion function also takes an optional string message as the final argument, 44 | // allowing custom error messages to be appended to the message the assertion method outputs. 45 | // 46 | // Here is an overview of the assert functions: 47 | // 48 | // assert.Equal(t, expected, actual [, message [, format-args]) 49 | // 50 | // assert.NotEqual(t, notExpected, actual [, message [, format-args]]) 51 | // 52 | // assert.True(t, actualBool [, message [, format-args]]) 53 | // 54 | // assert.False(t, actualBool [, message [, format-args]]) 55 | // 56 | // assert.Nil(t, actualObject [, message [, format-args]]) 57 | // 58 | // assert.NotNil(t, actualObject [, message [, format-args]]) 59 | // 60 | // assert.Empty(t, actualObject [, message [, format-args]]) 61 | // 62 | // assert.NotEmpty(t, actualObject [, message [, format-args]]) 63 | // 64 | // assert.Len(t, actualObject, expectedLength, [, message [, format-args]]) 65 | // 66 | // assert.Error(t, errorObject [, message [, format-args]]) 67 | // 68 | // assert.NoError(t, errorObject [, message [, format-args]]) 69 | // 70 | // assert.EqualError(t, theError, errString [, message [, format-args]]) 71 | // 72 | // assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) 73 | // 74 | // assert.IsType(t, expectedObject, actualObject [, message [, format-args]]) 75 | // 76 | // assert.Contains(t, stringOrSlice, substringOrElement [, message [, format-args]]) 77 | // 78 | // assert.NotContains(t, stringOrSlice, substringOrElement [, message [, format-args]]) 79 | // 80 | // assert.Panics(t, func(){ 81 | // 82 | // // call code that should panic 83 | // 84 | // } [, message [, format-args]]) 85 | // 86 | // assert.NotPanics(t, func(){ 87 | // 88 | // // call code that should not panic 89 | // 90 | // } [, message [, format-args]]) 91 | // 92 | // assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) 93 | // 94 | // assert.InDelta(t, numA, numB, delta, [, message [, format-args]]) 95 | // 96 | // assert.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) 97 | // 98 | // assert package contains Assertions object. it has assertion methods. 99 | // 100 | // Here is an overview of the assert functions: 101 | // assert.Equal(expected, actual [, message [, format-args]) 102 | // 103 | // assert.NotEqual(notExpected, actual [, message [, format-args]]) 104 | // 105 | // assert.True(actualBool [, message [, format-args]]) 106 | // 107 | // assert.False(actualBool [, message [, format-args]]) 108 | // 109 | // assert.Nil(actualObject [, message [, format-args]]) 110 | // 111 | // assert.NotNil(actualObject [, message [, format-args]]) 112 | // 113 | // assert.Empty(actualObject [, message [, format-args]]) 114 | // 115 | // assert.NotEmpty(actualObject [, message [, format-args]]) 116 | // 117 | // assert.Len(actualObject, expectedLength, [, message [, format-args]]) 118 | // 119 | // assert.Error(errorObject [, message [, format-args]]) 120 | // 121 | // assert.NoError(errorObject [, message [, format-args]]) 122 | // 123 | // assert.EqualError(theError, errString [, message [, format-args]]) 124 | // 125 | // assert.Implements((*MyInterface)(nil), new(MyObject) [,message [, format-args]]) 126 | // 127 | // assert.IsType(expectedObject, actualObject [, message [, format-args]]) 128 | // 129 | // assert.Contains(stringOrSlice, substringOrElement [, message [, format-args]]) 130 | // 131 | // assert.NotContains(stringOrSlice, substringOrElement [, message [, format-args]]) 132 | // 133 | // assert.Panics(func(){ 134 | // 135 | // // call code that should panic 136 | // 137 | // } [, message [, format-args]]) 138 | // 139 | // assert.NotPanics(func(){ 140 | // 141 | // // call code that should not panic 142 | // 143 | // } [, message [, format-args]]) 144 | // 145 | // assert.WithinDuration(timeA, timeB, deltaTime, [, message [, format-args]]) 146 | // 147 | // assert.InDelta(numA, numB, delta, [, message [, format-args]]) 148 | // 149 | // assert.InEpsilon(numA, numB, epsilon, [, message [, format-args]]) 150 | package assert 151 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import "time" 4 | 5 | type Assertions struct { 6 | t TestingT 7 | } 8 | 9 | func New(t TestingT) *Assertions { 10 | return &Assertions{ 11 | t: t, 12 | } 13 | } 14 | 15 | // Fail reports a failure through 16 | func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { 17 | return Fail(a.t, failureMessage, msgAndArgs...) 18 | } 19 | 20 | // Implements asserts that an object is implemented by the specified interface. 21 | // 22 | // assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject") 23 | func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { 24 | return Implements(a.t, interfaceObject, object, msgAndArgs...) 25 | } 26 | 27 | // IsType asserts that the specified objects are of the same type. 28 | func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { 29 | return IsType(a.t, expectedType, object, msgAndArgs...) 30 | } 31 | 32 | // Equal asserts that two objects are equal. 33 | // 34 | // assert.Equal(123, 123, "123 and 123 should be equal") 35 | // 36 | // Returns whether the assertion was successful (true) or not (false). 37 | func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool { 38 | return Equal(a.t, expected, actual, msgAndArgs...) 39 | } 40 | 41 | // Exactly asserts that two objects are equal is value and type. 42 | // 43 | // assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") 44 | // 45 | // Returns whether the assertion was successful (true) or not (false). 46 | func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) bool { 47 | return Exactly(a.t, expected, actual, msgAndArgs...) 48 | } 49 | 50 | // NotNil asserts that the specified object is not nil. 51 | // 52 | // assert.NotNil(err, "err should be something") 53 | // 54 | // Returns whether the assertion was successful (true) or not (false). 55 | func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { 56 | return NotNil(a.t, object, msgAndArgs...) 57 | } 58 | 59 | // Nil asserts that the specified object is nil. 60 | // 61 | // assert.Nil(err, "err should be nothing") 62 | // 63 | // Returns whether the assertion was successful (true) or not (false). 64 | func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { 65 | return Nil(a.t, object, msgAndArgs...) 66 | } 67 | 68 | // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a 69 | // slice with len == 0. 70 | // 71 | // assert.Empty(obj) 72 | // 73 | // Returns whether the assertion was successful (true) or not (false). 74 | func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { 75 | return Empty(a.t, object, msgAndArgs...) 76 | } 77 | 78 | // Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a 79 | // slice with len == 0. 80 | // 81 | // if assert.NotEmpty(obj) { 82 | // assert.Equal("two", obj[1]) 83 | // } 84 | // 85 | // Returns whether the assertion was successful (true) or not (false). 86 | func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { 87 | return NotEmpty(a.t, object, msgAndArgs...) 88 | } 89 | 90 | // Len asserts that the specified object has specific length. 91 | // Len also fails if the object has a type that len() not accept. 92 | // 93 | // assert.Len(mySlice, 3, "The size of slice is not 3") 94 | // 95 | // Returns whether the assertion was successful (true) or not (false). 96 | func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { 97 | return Len(a.t, object, length, msgAndArgs...) 98 | } 99 | 100 | // True asserts that the specified value is true. 101 | // 102 | // assert.True(myBool, "myBool should be true") 103 | // 104 | // Returns whether the assertion was successful (true) or not (false). 105 | func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { 106 | return True(a.t, value, msgAndArgs...) 107 | } 108 | 109 | // False asserts that the specified value is true. 110 | // 111 | // assert.False(myBool, "myBool should be false") 112 | // 113 | // Returns whether the assertion was successful (true) or not (false). 114 | func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { 115 | return False(a.t, value, msgAndArgs...) 116 | } 117 | 118 | // NotEqual asserts that the specified values are NOT equal. 119 | // 120 | // assert.NotEqual(obj1, obj2, "two objects shouldn't be equal") 121 | // 122 | // Returns whether the assertion was successful (true) or not (false). 123 | func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool { 124 | return NotEqual(a.t, expected, actual, msgAndArgs...) 125 | } 126 | 127 | // Contains asserts that the specified string contains the specified substring. 128 | // 129 | // assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") 130 | // 131 | // Returns whether the assertion was successful (true) or not (false). 132 | func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) bool { 133 | return Contains(a.t, s, contains, msgAndArgs...) 134 | } 135 | 136 | // NotContains asserts that the specified string does NOT contain the specified substring. 137 | // 138 | // assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") 139 | // 140 | // Returns whether the assertion was successful (true) or not (false). 141 | func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) bool { 142 | return NotContains(a.t, s, contains, msgAndArgs...) 143 | } 144 | 145 | // Uses a Comparison to assert a complex condition. 146 | func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { 147 | return Condition(a.t, comp, msgAndArgs...) 148 | } 149 | 150 | // Panics asserts that the code inside the specified PanicTestFunc panics. 151 | // 152 | // assert.Panics(func(){ 153 | // GoCrazy() 154 | // }, "Calling GoCrazy() should panic") 155 | // 156 | // Returns whether the assertion was successful (true) or not (false). 157 | func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { 158 | return Panics(a.t, f, msgAndArgs...) 159 | } 160 | 161 | // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. 162 | // 163 | // assert.NotPanics(func(){ 164 | // RemainCalm() 165 | // }, "Calling RemainCalm() should NOT panic") 166 | // 167 | // Returns whether the assertion was successful (true) or not (false). 168 | func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { 169 | return NotPanics(a.t, f, msgAndArgs...) 170 | } 171 | 172 | // WithinDuration asserts that the two times are within duration delta of each other. 173 | // 174 | // assert.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") 175 | // 176 | // Returns whether the assertion was successful (true) or not (false). 177 | func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { 178 | return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) 179 | } 180 | 181 | // InDelta asserts that the two numerals are within delta of each other. 182 | // 183 | // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) 184 | // 185 | // Returns whether the assertion was successful (true) or not (false). 186 | func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 187 | return InDelta(a.t, expected, actual, delta, msgAndArgs...) 188 | } 189 | 190 | // InEpsilon asserts that expected and actual have a relative error less than epsilon 191 | // 192 | // Returns whether the assertion was successful (true) or not (false). 193 | func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { 194 | return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) 195 | } 196 | 197 | // NoError asserts that a function returned no error (i.e. `nil`). 198 | // 199 | // actualObj, err := SomeFunction() 200 | // if assert.NoError(err) { 201 | // assert.Equal(actualObj, expectedObj) 202 | // } 203 | // 204 | // Returns whether the assertion was successful (true) or not (false). 205 | func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) bool { 206 | return NoError(a.t, theError, msgAndArgs...) 207 | } 208 | 209 | // Error asserts that a function returned an error (i.e. not `nil`). 210 | // 211 | // actualObj, err := SomeFunction() 212 | // if assert.Error(err, "An error was expected") { 213 | // assert.Equal(err, expectedError) 214 | // } 215 | // 216 | // Returns whether the assertion was successful (true) or not (false). 217 | func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) bool { 218 | return Error(a.t, theError, msgAndArgs...) 219 | } 220 | 221 | // EqualError asserts that a function returned an error (i.e. not `nil`) 222 | // and that it is equal to the provided error. 223 | // 224 | // actualObj, err := SomeFunction() 225 | // if assert.Error(err, "An error was expected") { 226 | // assert.Equal(err, expectedError) 227 | // } 228 | // 229 | // Returns whether the assertion was successful (true) or not (false). 230 | func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { 231 | return EqualError(a.t, theError, errString, msgAndArgs...) 232 | } 233 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestImplementsWrapper(t *testing.T) { 10 | assert := New(new(testing.T)) 11 | 12 | if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { 13 | t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") 14 | } 15 | if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { 16 | t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") 17 | } 18 | } 19 | 20 | func TestIsTypeWrapper(t *testing.T) { 21 | assert := New(new(testing.T)) 22 | 23 | if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { 24 | t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") 25 | } 26 | if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { 27 | t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") 28 | } 29 | 30 | } 31 | 32 | func TestEqualWrapper(t *testing.T) { 33 | assert := New(new(testing.T)) 34 | 35 | if !assert.Equal("Hello World", "Hello World") { 36 | t.Error("Equal should return true") 37 | } 38 | if !assert.Equal(123, 123) { 39 | t.Error("Equal should return true") 40 | } 41 | if !assert.Equal(123.5, 123.5) { 42 | t.Error("Equal should return true") 43 | } 44 | if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { 45 | t.Error("Equal should return true") 46 | } 47 | if !assert.Equal(nil, nil) { 48 | t.Error("Equal should return true") 49 | } 50 | } 51 | 52 | func TestNotNilWrapper(t *testing.T) { 53 | assert := New(new(testing.T)) 54 | 55 | if !assert.NotNil(new(AssertionTesterConformingObject)) { 56 | t.Error("NotNil should return true: object is not nil") 57 | } 58 | if assert.NotNil(nil) { 59 | t.Error("NotNil should return false: object is nil") 60 | } 61 | 62 | } 63 | 64 | func TestNilWrapper(t *testing.T) { 65 | assert := New(new(testing.T)) 66 | 67 | if !assert.Nil(nil) { 68 | t.Error("Nil should return true: object is nil") 69 | } 70 | if assert.Nil(new(AssertionTesterConformingObject)) { 71 | t.Error("Nil should return false: object is not nil") 72 | } 73 | 74 | } 75 | 76 | func TestTrueWrapper(t *testing.T) { 77 | assert := New(new(testing.T)) 78 | 79 | if !assert.True(true) { 80 | t.Error("True should return true") 81 | } 82 | if assert.True(false) { 83 | t.Error("True should return false") 84 | } 85 | 86 | } 87 | 88 | func TestFalseWrapper(t *testing.T) { 89 | assert := New(new(testing.T)) 90 | 91 | if !assert.False(false) { 92 | t.Error("False should return true") 93 | } 94 | if assert.False(true) { 95 | t.Error("False should return false") 96 | } 97 | 98 | } 99 | 100 | func TestExactlyWrapper(t *testing.T) { 101 | assert := New(new(testing.T)) 102 | 103 | a := float32(1) 104 | b := float64(1) 105 | c := float32(1) 106 | d := float32(2) 107 | 108 | if assert.Exactly(a, b) { 109 | t.Error("Exactly should return false") 110 | } 111 | if assert.Exactly(a, d) { 112 | t.Error("Exactly should return false") 113 | } 114 | if !assert.Exactly(a, c) { 115 | t.Error("Exactly should return true") 116 | } 117 | 118 | if assert.Exactly(nil, a) { 119 | t.Error("Exactly should return false") 120 | } 121 | if assert.Exactly(a, nil) { 122 | t.Error("Exactly should return false") 123 | } 124 | 125 | } 126 | 127 | func TestNotEqualWrapper(t *testing.T) { 128 | 129 | assert := New(new(testing.T)) 130 | 131 | if !assert.NotEqual("Hello World", "Hello World!") { 132 | t.Error("NotEqual should return true") 133 | } 134 | if !assert.NotEqual(123, 1234) { 135 | t.Error("NotEqual should return true") 136 | } 137 | if !assert.NotEqual(123.5, 123.55) { 138 | t.Error("NotEqual should return true") 139 | } 140 | if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { 141 | t.Error("NotEqual should return true") 142 | } 143 | if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { 144 | t.Error("NotEqual should return true") 145 | } 146 | } 147 | 148 | func TestContainsWrapper(t *testing.T) { 149 | 150 | assert := New(new(testing.T)) 151 | list := []string{"Foo", "Bar"} 152 | 153 | if !assert.Contains("Hello World", "Hello") { 154 | t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") 155 | } 156 | if assert.Contains("Hello World", "Salut") { 157 | t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") 158 | } 159 | 160 | if !assert.Contains(list, "Foo") { 161 | t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") 162 | } 163 | if assert.Contains(list, "Salut") { 164 | t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") 165 | } 166 | 167 | } 168 | 169 | func TestNotContainsWrapper(t *testing.T) { 170 | 171 | assert := New(new(testing.T)) 172 | list := []string{"Foo", "Bar"} 173 | 174 | if !assert.NotContains("Hello World", "Hello!") { 175 | t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") 176 | } 177 | if assert.NotContains("Hello World", "Hello") { 178 | t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") 179 | } 180 | 181 | if !assert.NotContains(list, "Foo!") { 182 | t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") 183 | } 184 | if assert.NotContains(list, "Foo") { 185 | t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") 186 | } 187 | 188 | } 189 | 190 | func TestConditionWrapper(t *testing.T) { 191 | 192 | assert := New(new(testing.T)) 193 | 194 | if !assert.Condition(func() bool { return true }, "Truth") { 195 | t.Error("Condition should return true") 196 | } 197 | 198 | if assert.Condition(func() bool { return false }, "Lie") { 199 | t.Error("Condition should return false") 200 | } 201 | 202 | } 203 | 204 | func TestDidPanicWrapper(t *testing.T) { 205 | 206 | if funcDidPanic, _ := didPanic(func() { 207 | panic("Panic!") 208 | }); !funcDidPanic { 209 | t.Error("didPanic should return true") 210 | } 211 | 212 | if funcDidPanic, _ := didPanic(func() { 213 | }); funcDidPanic { 214 | t.Error("didPanic should return false") 215 | } 216 | 217 | } 218 | 219 | func TestPanicsWrapper(t *testing.T) { 220 | 221 | assert := New(new(testing.T)) 222 | 223 | if !assert.Panics(func() { 224 | panic("Panic!") 225 | }) { 226 | t.Error("Panics should return true") 227 | } 228 | 229 | if assert.Panics(func() { 230 | }) { 231 | t.Error("Panics should return false") 232 | } 233 | 234 | } 235 | 236 | func TestNotPanicsWrapper(t *testing.T) { 237 | 238 | assert := New(new(testing.T)) 239 | 240 | if !assert.NotPanics(func() { 241 | }) { 242 | t.Error("NotPanics should return true") 243 | } 244 | 245 | if assert.NotPanics(func() { 246 | panic("Panic!") 247 | }) { 248 | t.Error("NotPanics should return false") 249 | } 250 | 251 | } 252 | 253 | func TestEqualWrapper_Funcs(t *testing.T) { 254 | 255 | assert := New(t) 256 | 257 | type f func() int 258 | var f1 f = func() int { return 1 } 259 | var f2 f = func() int { return 2 } 260 | 261 | var f1_copy f = f1 262 | 263 | assert.Equal(f1_copy, f1, "Funcs are the same and should be considered equal") 264 | assert.NotEqual(f1, f2, "f1 and f2 are different") 265 | 266 | } 267 | 268 | func TestNoErrorWrapper(t *testing.T) { 269 | assert := New(t) 270 | mockAssert := New(new(testing.T)) 271 | 272 | // start with a nil error 273 | var err error = nil 274 | 275 | assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") 276 | 277 | // now set an error 278 | err = errors.New("Some error") 279 | 280 | assert.False(mockAssert.NoError(err), "NoError with error should return False") 281 | 282 | } 283 | 284 | func TestErrorWrapper(t *testing.T) { 285 | assert := New(t) 286 | mockAssert := New(new(testing.T)) 287 | 288 | // start with a nil error 289 | var err error = nil 290 | 291 | assert.False(mockAssert.Error(err), "Error should return False for nil arg") 292 | 293 | // now set an error 294 | err = errors.New("Some error") 295 | 296 | assert.True(mockAssert.Error(err), "Error with error should return True") 297 | 298 | } 299 | 300 | func TestEqualErrorWrapper(t *testing.T) { 301 | assert := New(t) 302 | mockAssert := New(new(testing.T)) 303 | 304 | // start with a nil error 305 | var err error 306 | assert.False(mockAssert.EqualError(err, ""), 307 | "EqualError should return false for nil arg") 308 | 309 | // now set an error 310 | err = errors.New("some error") 311 | assert.False(mockAssert.EqualError(err, "Not some error"), 312 | "EqualError should return false for different error string") 313 | assert.True(mockAssert.EqualError(err, "some error"), 314 | "EqualError should return true") 315 | } 316 | 317 | func TestEmptyWrapper(t *testing.T) { 318 | assert := New(t) 319 | mockAssert := New(new(testing.T)) 320 | 321 | assert.True(mockAssert.Empty(""), "Empty string is empty") 322 | assert.True(mockAssert.Empty(nil), "Nil is empty") 323 | assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") 324 | assert.True(mockAssert.Empty(0), "Zero int value is empty") 325 | assert.True(mockAssert.Empty(false), "False value is empty") 326 | 327 | assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") 328 | assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") 329 | assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") 330 | assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") 331 | assert.False(mockAssert.Empty(true), "True value is not empty") 332 | 333 | } 334 | 335 | func TestNotEmptyWrapper(t *testing.T) { 336 | assert := New(t) 337 | mockAssert := New(new(testing.T)) 338 | 339 | assert.False(mockAssert.NotEmpty(""), "Empty string is empty") 340 | assert.False(mockAssert.NotEmpty(nil), "Nil is empty") 341 | assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") 342 | assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") 343 | assert.False(mockAssert.NotEmpty(false), "False value is empty") 344 | 345 | assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") 346 | assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") 347 | assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") 348 | assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") 349 | assert.True(mockAssert.NotEmpty(true), "True value is not empty") 350 | 351 | } 352 | 353 | func TestLenWrapper(t *testing.T) { 354 | assert := New(t) 355 | mockAssert := New(new(testing.T)) 356 | 357 | assert.False(mockAssert.Len(nil, 0), "nil does not have length") 358 | assert.False(mockAssert.Len(0, 0), "int does not have length") 359 | assert.False(mockAssert.Len(true, 0), "true does not have length") 360 | assert.False(mockAssert.Len(false, 0), "false does not have length") 361 | assert.False(mockAssert.Len('A', 0), "Rune does not have length") 362 | assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") 363 | 364 | ch := make(chan int, 5) 365 | ch <- 1 366 | ch <- 2 367 | ch <- 3 368 | 369 | cases := []struct { 370 | v interface{} 371 | l int 372 | }{ 373 | {[]int{1, 2, 3}, 3}, 374 | {[...]int{1, 2, 3}, 3}, 375 | {"ABC", 3}, 376 | {map[int]int{1: 2, 2: 4, 3: 6}, 3}, 377 | {ch, 3}, 378 | 379 | {[]int{}, 0}, 380 | {map[int]int{}, 0}, 381 | {make(chan int), 0}, 382 | 383 | {[]int(nil), 0}, 384 | {map[int]int(nil), 0}, 385 | {(chan int)(nil), 0}, 386 | } 387 | 388 | for _, c := range cases { 389 | assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) 390 | } 391 | } 392 | 393 | func TestWithinDurationWrapper(t *testing.T) { 394 | assert := New(t) 395 | mockAssert := New(new(testing.T)) 396 | a := time.Now() 397 | b := a.Add(10 * time.Second) 398 | 399 | assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") 400 | assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") 401 | 402 | assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") 403 | assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") 404 | 405 | assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") 406 | assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") 407 | 408 | assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") 409 | assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") 410 | } 411 | 412 | func TestInDeltaWrapper(t *testing.T) { 413 | assert := New(new(testing.T)) 414 | 415 | True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") 416 | True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") 417 | True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") 418 | False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") 419 | False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") 420 | False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") 421 | 422 | cases := []struct { 423 | a, b interface{} 424 | delta float64 425 | }{ 426 | {uint8(2), uint8(1), 1}, 427 | {uint16(2), uint16(1), 1}, 428 | {uint32(2), uint32(1), 1}, 429 | {uint64(2), uint64(1), 1}, 430 | 431 | {int(2), int(1), 1}, 432 | {int8(2), int8(1), 1}, 433 | {int16(2), int16(1), 1}, 434 | {int32(2), int32(1), 1}, 435 | {int64(2), int64(1), 1}, 436 | 437 | {float32(2), float32(1), 1}, 438 | {float64(2), float64(1), 1}, 439 | } 440 | 441 | for _, tc := range cases { 442 | True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) 443 | } 444 | } 445 | 446 | func TestInEpsilonWrapper(t *testing.T) { 447 | assert := New(new(testing.T)) 448 | 449 | cases := []struct { 450 | a, b interface{} 451 | epsilon float64 452 | }{ 453 | {uint8(2), uint16(2), .001}, 454 | {2.1, 2.2, 0.1}, 455 | {2.2, 2.1, 0.1}, 456 | {-2.1, -2.2, 0.1}, 457 | {-2.2, -2.1, 0.1}, 458 | {uint64(100), uint8(101), 0.01}, 459 | {0.1, -0.1, 2}, 460 | } 461 | 462 | for _, tc := range cases { 463 | 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)) 464 | } 465 | 466 | cases = []struct { 467 | a, b interface{} 468 | epsilon float64 469 | }{ 470 | {uint8(2), int16(-2), .001}, 471 | {uint64(100), uint8(102), 0.01}, 472 | {2.1, 2.2, 0.001}, 473 | {2.2, 2.1, 0.001}, 474 | {2.1, -2.2, 1}, 475 | {2.1, "bla-bla", 0}, 476 | {0.1, -0.1, 1.99}, 477 | } 478 | 479 | for _, tc := range cases { 480 | 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)) 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | // AssertionTesterInterface defines an interface to be used for testing assertion methods 10 | type AssertionTesterInterface interface { 11 | TestMethod() 12 | } 13 | 14 | // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface 15 | type AssertionTesterConformingObject struct { 16 | } 17 | 18 | func (a *AssertionTesterConformingObject) TestMethod() { 19 | } 20 | 21 | // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface 22 | type AssertionTesterNonConformingObject struct { 23 | } 24 | 25 | func TestObjectsAreEqual(t *testing.T) { 26 | 27 | if !ObjectsAreEqual("Hello World", "Hello World") { 28 | t.Error("objectsAreEqual should return true") 29 | } 30 | if !ObjectsAreEqual(123, 123) { 31 | t.Error("objectsAreEqual should return true") 32 | } 33 | if !ObjectsAreEqual(123.5, 123.5) { 34 | t.Error("objectsAreEqual should return true") 35 | } 36 | if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { 37 | t.Error("objectsAreEqual should return true") 38 | } 39 | if !ObjectsAreEqual(nil, nil) { 40 | t.Error("objectsAreEqual should return true") 41 | } 42 | 43 | } 44 | 45 | func TestImplements(t *testing.T) { 46 | 47 | mockT := new(testing.T) 48 | 49 | if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { 50 | t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") 51 | } 52 | if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { 53 | t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") 54 | } 55 | 56 | } 57 | 58 | func TestIsType(t *testing.T) { 59 | 60 | mockT := new(testing.T) 61 | 62 | if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { 63 | t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") 64 | } 65 | if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { 66 | t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") 67 | } 68 | 69 | } 70 | 71 | func TestEqual(t *testing.T) { 72 | 73 | mockT := new(testing.T) 74 | 75 | if !Equal(mockT, "Hello World", "Hello World") { 76 | t.Error("Equal should return true") 77 | } 78 | if !Equal(mockT, 123, 123) { 79 | t.Error("Equal should return true") 80 | } 81 | if !Equal(mockT, 123.5, 123.5) { 82 | t.Error("Equal should return true") 83 | } 84 | if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { 85 | t.Error("Equal should return true") 86 | } 87 | if !Equal(mockT, nil, nil) { 88 | t.Error("Equal should return true") 89 | } 90 | if !Equal(mockT, int32(123), int64(123)) { 91 | t.Error("Equal should return true") 92 | } 93 | if !Equal(mockT, int64(123), uint64(123)) { 94 | t.Error("Equal should return true") 95 | } 96 | 97 | } 98 | 99 | func TestNotNil(t *testing.T) { 100 | 101 | mockT := new(testing.T) 102 | 103 | if !NotNil(mockT, new(AssertionTesterConformingObject)) { 104 | t.Error("NotNil should return true: object is not nil") 105 | } 106 | if NotNil(mockT, nil) { 107 | t.Error("NotNil should return false: object is nil") 108 | } 109 | 110 | } 111 | 112 | func TestNil(t *testing.T) { 113 | 114 | mockT := new(testing.T) 115 | 116 | if !Nil(mockT, nil) { 117 | t.Error("Nil should return true: object is nil") 118 | } 119 | if Nil(mockT, new(AssertionTesterConformingObject)) { 120 | t.Error("Nil should return false: object is not nil") 121 | } 122 | 123 | } 124 | 125 | func TestTrue(t *testing.T) { 126 | 127 | mockT := new(testing.T) 128 | 129 | if !True(mockT, true) { 130 | t.Error("True should return true") 131 | } 132 | if True(mockT, false) { 133 | t.Error("True should return false") 134 | } 135 | 136 | } 137 | 138 | func TestFalse(t *testing.T) { 139 | 140 | mockT := new(testing.T) 141 | 142 | if !False(mockT, false) { 143 | t.Error("False should return true") 144 | } 145 | if False(mockT, true) { 146 | t.Error("False should return false") 147 | } 148 | 149 | } 150 | 151 | func TestExactly(t *testing.T) { 152 | 153 | mockT := new(testing.T) 154 | 155 | a := float32(1) 156 | b := float64(1) 157 | c := float32(1) 158 | d := float32(2) 159 | 160 | if Exactly(mockT, a, b) { 161 | t.Error("Exactly should return false") 162 | } 163 | if Exactly(mockT, a, d) { 164 | t.Error("Exactly should return false") 165 | } 166 | if !Exactly(mockT, a, c) { 167 | t.Error("Exactly should return true") 168 | } 169 | 170 | if Exactly(mockT, nil, a) { 171 | t.Error("Exactly should return false") 172 | } 173 | if Exactly(mockT, a, nil) { 174 | t.Error("Exactly should return false") 175 | } 176 | 177 | } 178 | 179 | func TestNotEqual(t *testing.T) { 180 | 181 | mockT := new(testing.T) 182 | 183 | if !NotEqual(mockT, "Hello World", "Hello World!") { 184 | t.Error("NotEqual should return true") 185 | } 186 | if !NotEqual(mockT, 123, 1234) { 187 | t.Error("NotEqual should return true") 188 | } 189 | if !NotEqual(mockT, 123.5, 123.55) { 190 | t.Error("NotEqual should return true") 191 | } 192 | if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { 193 | t.Error("NotEqual should return true") 194 | } 195 | if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { 196 | t.Error("NotEqual should return true") 197 | } 198 | 199 | if NotEqual(mockT, "Hello World", "Hello World") { 200 | t.Error("NotEqual should return false") 201 | } 202 | if NotEqual(mockT, 123, 123) { 203 | t.Error("NotEqual should return false") 204 | } 205 | if NotEqual(mockT, 123.5, 123.5) { 206 | t.Error("NotEqual should return false") 207 | } 208 | if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { 209 | t.Error("NotEqual should return false") 210 | } 211 | if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { 212 | t.Error("NotEqual should return false") 213 | } 214 | } 215 | 216 | func TestContains(t *testing.T) { 217 | 218 | mockT := new(testing.T) 219 | list := []string{"Foo", "Bar"} 220 | 221 | if !Contains(mockT, "Hello World", "Hello") { 222 | t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") 223 | } 224 | if Contains(mockT, "Hello World", "Salut") { 225 | t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") 226 | } 227 | 228 | if !Contains(mockT, list, "Bar") { 229 | t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") 230 | } 231 | if Contains(mockT, list, "Salut") { 232 | t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") 233 | } 234 | 235 | } 236 | 237 | func TestNotContains(t *testing.T) { 238 | 239 | mockT := new(testing.T) 240 | list := []string{"Foo", "Bar"} 241 | 242 | if !NotContains(mockT, "Hello World", "Hello!") { 243 | t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") 244 | } 245 | if NotContains(mockT, "Hello World", "Hello") { 246 | t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") 247 | } 248 | 249 | if !NotContains(mockT, list, "Foo!") { 250 | t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") 251 | } 252 | if NotContains(mockT, list, "Foo") { 253 | t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") 254 | } 255 | 256 | } 257 | 258 | func Test_includeElement(t *testing.T) { 259 | 260 | list1 := []string{"Foo", "Bar"} 261 | list2 := []int{1, 2} 262 | 263 | ok, found := includeElement("Hello World", "World") 264 | True(t, ok) 265 | True(t, found) 266 | 267 | ok, found = includeElement(list1, "Foo") 268 | True(t, ok) 269 | True(t, found) 270 | 271 | ok, found = includeElement(list1, "Bar") 272 | True(t, ok) 273 | True(t, found) 274 | 275 | ok, found = includeElement(list2, 1) 276 | True(t, ok) 277 | True(t, found) 278 | 279 | ok, found = includeElement(list2, 2) 280 | True(t, ok) 281 | True(t, found) 282 | 283 | ok, found = includeElement(list1, "Foo!") 284 | True(t, ok) 285 | False(t, found) 286 | 287 | ok, found = includeElement(list2, 3) 288 | True(t, ok) 289 | False(t, found) 290 | 291 | ok, found = includeElement(list2, "1") 292 | True(t, ok) 293 | False(t, found) 294 | 295 | ok, found = includeElement(1433, "1") 296 | False(t, ok) 297 | False(t, found) 298 | 299 | } 300 | 301 | func TestCondition(t *testing.T) { 302 | mockT := new(testing.T) 303 | 304 | if !Condition(mockT, func() bool { return true }, "Truth") { 305 | t.Error("Condition should return true") 306 | } 307 | 308 | if Condition(mockT, func() bool { return false }, "Lie") { 309 | t.Error("Condition should return false") 310 | } 311 | 312 | } 313 | 314 | func TestDidPanic(t *testing.T) { 315 | 316 | if funcDidPanic, _ := didPanic(func() { 317 | panic("Panic!") 318 | }); !funcDidPanic { 319 | t.Error("didPanic should return true") 320 | } 321 | 322 | if funcDidPanic, _ := didPanic(func() { 323 | }); funcDidPanic { 324 | t.Error("didPanic should return false") 325 | } 326 | 327 | } 328 | 329 | func TestPanics(t *testing.T) { 330 | 331 | mockT := new(testing.T) 332 | 333 | if !Panics(mockT, func() { 334 | panic("Panic!") 335 | }) { 336 | t.Error("Panics should return true") 337 | } 338 | 339 | if Panics(mockT, func() { 340 | }) { 341 | t.Error("Panics should return false") 342 | } 343 | 344 | } 345 | 346 | func TestNotPanics(t *testing.T) { 347 | 348 | mockT := new(testing.T) 349 | 350 | if !NotPanics(mockT, func() { 351 | }) { 352 | t.Error("NotPanics should return true") 353 | } 354 | 355 | if NotPanics(mockT, func() { 356 | panic("Panic!") 357 | }) { 358 | t.Error("NotPanics should return false") 359 | } 360 | 361 | } 362 | 363 | func TestEqual_Funcs(t *testing.T) { 364 | 365 | type f func() int 366 | f1 := func() int { return 1 } 367 | f2 := func() int { return 2 } 368 | 369 | f1Copy := f1 370 | 371 | Equal(t, f1Copy, f1, "Funcs are the same and should be considered equal") 372 | NotEqual(t, f1, f2, "f1 and f2 are different") 373 | 374 | } 375 | 376 | func TestNoError(t *testing.T) { 377 | 378 | mockT := new(testing.T) 379 | 380 | // start with a nil error 381 | var err error 382 | 383 | True(t, NoError(mockT, err), "NoError should return True for nil arg") 384 | 385 | // now set an error 386 | err = errors.New("some error") 387 | 388 | False(t, NoError(mockT, err), "NoError with error should return False") 389 | 390 | } 391 | 392 | func TestError(t *testing.T) { 393 | 394 | mockT := new(testing.T) 395 | 396 | // start with a nil error 397 | var err error 398 | 399 | False(t, Error(mockT, err), "Error should return False for nil arg") 400 | 401 | // now set an error 402 | err = errors.New("some error") 403 | 404 | True(t, Error(mockT, err), "Error with error should return True") 405 | 406 | } 407 | 408 | func TestEqualError(t *testing.T) { 409 | mockT := new(testing.T) 410 | 411 | // start with a nil error 412 | var err error 413 | False(t, EqualError(mockT, err, ""), 414 | "EqualError should return false for nil arg") 415 | 416 | // now set an error 417 | err = errors.New("some error") 418 | False(t, EqualError(mockT, err, "Not some error"), 419 | "EqualError should return false for different error string") 420 | True(t, EqualError(mockT, err, "some error"), 421 | "EqualError should return true") 422 | } 423 | 424 | func Test_isEmpty(t *testing.T) { 425 | 426 | chWithValue := make(chan struct{}, 1) 427 | chWithValue <- struct{}{} 428 | 429 | True(t, isEmpty("")) 430 | True(t, isEmpty(nil)) 431 | True(t, isEmpty([]string{})) 432 | True(t, isEmpty(0)) 433 | True(t, isEmpty(int32(0))) 434 | True(t, isEmpty(int64(0))) 435 | True(t, isEmpty(false)) 436 | True(t, isEmpty(map[string]string{})) 437 | True(t, isEmpty(new(time.Time))) 438 | True(t, isEmpty(make(chan struct{}))) 439 | False(t, isEmpty("something")) 440 | False(t, isEmpty(errors.New("something"))) 441 | False(t, isEmpty([]string{"something"})) 442 | False(t, isEmpty(1)) 443 | False(t, isEmpty(true)) 444 | False(t, isEmpty(map[string]string{"Hello": "World"})) 445 | False(t, isEmpty(chWithValue)) 446 | 447 | } 448 | 449 | func TestEmpty(t *testing.T) { 450 | 451 | mockT := new(testing.T) 452 | chWithValue := make(chan struct{}, 1) 453 | chWithValue <- struct{}{} 454 | 455 | True(t, Empty(mockT, ""), "Empty string is empty") 456 | True(t, Empty(mockT, nil), "Nil is empty") 457 | True(t, Empty(mockT, []string{}), "Empty string array is empty") 458 | True(t, Empty(mockT, 0), "Zero int value is empty") 459 | True(t, Empty(mockT, false), "False value is empty") 460 | True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") 461 | 462 | False(t, Empty(mockT, "something"), "Non Empty string is not empty") 463 | False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") 464 | False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") 465 | False(t, Empty(mockT, 1), "Non-zero int value is not empty") 466 | False(t, Empty(mockT, true), "True value is not empty") 467 | False(t, Empty(mockT, chWithValue), "Channel with values is not empty") 468 | } 469 | 470 | func TestNotEmpty(t *testing.T) { 471 | 472 | mockT := new(testing.T) 473 | chWithValue := make(chan struct{}, 1) 474 | chWithValue <- struct{}{} 475 | 476 | False(t, NotEmpty(mockT, ""), "Empty string is empty") 477 | False(t, NotEmpty(mockT, nil), "Nil is empty") 478 | False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") 479 | False(t, NotEmpty(mockT, 0), "Zero int value is empty") 480 | False(t, NotEmpty(mockT, false), "False value is empty") 481 | False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") 482 | 483 | True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") 484 | True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") 485 | True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") 486 | True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") 487 | True(t, NotEmpty(mockT, true), "True value is not empty") 488 | True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") 489 | } 490 | 491 | func Test_getLen(t *testing.T) { 492 | falseCases := []interface{}{ 493 | nil, 494 | 0, 495 | true, 496 | false, 497 | 'A', 498 | struct{}{}, 499 | } 500 | for _, v := range falseCases { 501 | ok, l := getLen(v) 502 | False(t, ok, "Expected getLen fail to get length of %#v", v) 503 | Equal(t, 0, l, "getLen should return 0 for %#v", v) 504 | } 505 | 506 | ch := make(chan int, 5) 507 | ch <- 1 508 | ch <- 2 509 | ch <- 3 510 | trueCases := []struct { 511 | v interface{} 512 | l int 513 | }{ 514 | {[]int{1, 2, 3}, 3}, 515 | {[...]int{1, 2, 3}, 3}, 516 | {"ABC", 3}, 517 | {map[int]int{1: 2, 2: 4, 3: 6}, 3}, 518 | {ch, 3}, 519 | 520 | {[]int{}, 0}, 521 | {map[int]int{}, 0}, 522 | {make(chan int), 0}, 523 | 524 | {[]int(nil), 0}, 525 | {map[int]int(nil), 0}, 526 | {(chan int)(nil), 0}, 527 | } 528 | 529 | for _, c := range trueCases { 530 | ok, l := getLen(c.v) 531 | True(t, ok, "Expected getLen success to get length of %#v", c.v) 532 | Equal(t, c.l, l) 533 | } 534 | } 535 | 536 | func TestLen(t *testing.T) { 537 | mockT := new(testing.T) 538 | 539 | False(t, Len(mockT, nil, 0), "nil does not have length") 540 | False(t, Len(mockT, 0, 0), "int does not have length") 541 | False(t, Len(mockT, true, 0), "true does not have length") 542 | False(t, Len(mockT, false, 0), "false does not have length") 543 | False(t, Len(mockT, 'A', 0), "Rune does not have length") 544 | False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") 545 | 546 | ch := make(chan int, 5) 547 | ch <- 1 548 | ch <- 2 549 | ch <- 3 550 | 551 | cases := []struct { 552 | v interface{} 553 | l int 554 | }{ 555 | {[]int{1, 2, 3}, 3}, 556 | {[...]int{1, 2, 3}, 3}, 557 | {"ABC", 3}, 558 | {map[int]int{1: 2, 2: 4, 3: 6}, 3}, 559 | {ch, 3}, 560 | 561 | {[]int{}, 0}, 562 | {map[int]int{}, 0}, 563 | {make(chan int), 0}, 564 | 565 | {[]int(nil), 0}, 566 | {map[int]int(nil), 0}, 567 | {(chan int)(nil), 0}, 568 | } 569 | 570 | for _, c := range cases { 571 | True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) 572 | } 573 | 574 | cases = []struct { 575 | v interface{} 576 | l int 577 | }{ 578 | {[]int{1, 2, 3}, 4}, 579 | {[...]int{1, 2, 3}, 2}, 580 | {"ABC", 2}, 581 | {map[int]int{1: 2, 2: 4, 3: 6}, 4}, 582 | {ch, 2}, 583 | 584 | {[]int{}, 1}, 585 | {map[int]int{}, 1}, 586 | {make(chan int), 1}, 587 | 588 | {[]int(nil), 1}, 589 | {map[int]int(nil), 1}, 590 | {(chan int)(nil), 1}, 591 | } 592 | 593 | for _, c := range cases { 594 | False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) 595 | } 596 | } 597 | 598 | func TestWithinDuration(t *testing.T) { 599 | 600 | mockT := new(testing.T) 601 | a := time.Now() 602 | b := a.Add(10 * time.Second) 603 | 604 | True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") 605 | True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") 606 | 607 | False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") 608 | False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") 609 | 610 | False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") 611 | False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") 612 | 613 | False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") 614 | False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") 615 | } 616 | 617 | func TestInDelta(t *testing.T) { 618 | mockT := new(testing.T) 619 | 620 | True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") 621 | True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") 622 | True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") 623 | False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") 624 | False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") 625 | False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") 626 | 627 | cases := []struct { 628 | a, b interface{} 629 | delta float64 630 | }{ 631 | {uint8(2), uint8(1), 1}, 632 | {uint16(2), uint16(1), 1}, 633 | {uint32(2), uint32(1), 1}, 634 | {uint64(2), uint64(1), 1}, 635 | 636 | {int(2), int(1), 1}, 637 | {int8(2), int8(1), 1}, 638 | {int16(2), int16(1), 1}, 639 | {int32(2), int32(1), 1}, 640 | {int64(2), int64(1), 1}, 641 | 642 | {float32(2), float32(1), 1}, 643 | {float64(2), float64(1), 1}, 644 | } 645 | 646 | for _, tc := range cases { 647 | True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) 648 | } 649 | } 650 | 651 | func TestInEpsilon(t *testing.T) { 652 | mockT := new(testing.T) 653 | 654 | cases := []struct { 655 | a, b interface{} 656 | epsilon float64 657 | }{ 658 | {uint8(2), uint16(2), .001}, 659 | {2.1, 2.2, 0.1}, 660 | {2.2, 2.1, 0.1}, 661 | {-2.1, -2.2, 0.1}, 662 | {-2.2, -2.1, 0.1}, 663 | {uint64(100), uint8(101), 0.01}, 664 | {0.1, -0.1, 2}, 665 | } 666 | 667 | for _, tc := range cases { 668 | 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)) 669 | } 670 | 671 | cases = []struct { 672 | a, b interface{} 673 | epsilon float64 674 | }{ 675 | {uint8(2), int16(-2), .001}, 676 | {uint64(100), uint8(102), 0.01}, 677 | {2.1, 2.2, 0.001}, 678 | {2.2, 2.1, 0.001}, 679 | {2.1, -2.2, 1}, 680 | {2.1, "bla-bla", 0}, 681 | {0.1, -0.1, 1.99}, 682 | } 683 | 684 | for _, tc := range cases { 685 | 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)) 686 | } 687 | 688 | } 689 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "reflect" 8 | "runtime" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | // TestingT is an interface wrapper around *testing.T 14 | type TestingT interface { 15 | Errorf(format string, args ...interface{}) 16 | } 17 | 18 | // Comparison a custom function that returns true on success and false on failure 19 | type Comparison func() (success bool) 20 | 21 | /* 22 | Helper functions 23 | */ 24 | 25 | // ObjectsAreEqual determines if two objects are considered equal. 26 | // 27 | // This function does no assertion of any kind. 28 | func ObjectsAreEqual(expected, actual interface{}) bool { 29 | 30 | if expected == nil || actual == nil { 31 | return expected == actual 32 | } 33 | 34 | if reflect.DeepEqual(expected, actual) { 35 | return true 36 | } 37 | 38 | expectedValue := reflect.ValueOf(expected) 39 | actualValue := reflect.ValueOf(actual) 40 | if expectedValue == actualValue { 41 | return true 42 | } 43 | 44 | // Attempt comparison after type conversion 45 | if actualValue.Type().ConvertibleTo(expectedValue.Type()) && expectedValue == actualValue.Convert(expectedValue.Type()) { 46 | return true 47 | } 48 | 49 | // Last ditch effort 50 | if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { 51 | return true 52 | } 53 | 54 | return false 55 | 56 | } 57 | 58 | /* CallerInfo is necessary because the assert functions use the testing object 59 | internally, causing it to print the file:line of the assert method, rather than where 60 | the problem actually occured in calling code.*/ 61 | 62 | // CallerInfo returns a string containing the file and line number of the assert call 63 | // that failed. 64 | func CallerInfo() string { 65 | 66 | file := "" 67 | line := 0 68 | ok := false 69 | 70 | for i := 0; ; i++ { 71 | _, file, line, ok = runtime.Caller(i) 72 | if !ok { 73 | return "" 74 | } 75 | parts := strings.Split(file, "/") 76 | dir := parts[len(parts)-2] 77 | file = parts[len(parts)-1] 78 | if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { 79 | break 80 | } 81 | } 82 | 83 | return fmt.Sprintf("%s:%d", file, line) 84 | } 85 | 86 | // getWhitespaceString returns a string that is long enough to overwrite the default 87 | // output from the go testing framework. 88 | func getWhitespaceString() string { 89 | 90 | _, file, line, ok := runtime.Caller(1) 91 | if !ok { 92 | return "" 93 | } 94 | parts := strings.Split(file, "/") 95 | file = parts[len(parts)-1] 96 | 97 | return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) 98 | 99 | } 100 | 101 | func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { 102 | if len(msgAndArgs) == 0 || msgAndArgs == nil { 103 | return "" 104 | } 105 | if len(msgAndArgs) == 1 { 106 | return msgAndArgs[0].(string) 107 | } 108 | if len(msgAndArgs) > 1 { 109 | return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) 110 | } 111 | return "" 112 | } 113 | 114 | // Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's 115 | // test printing (see inner comment for specifics) 116 | func indentMessageLines(message string, tabs int) string { 117 | outBuf := new(bytes.Buffer) 118 | 119 | for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { 120 | if i != 0 { 121 | outBuf.WriteRune('\n') 122 | } 123 | for ii := 0; ii < tabs; ii++ { 124 | outBuf.WriteRune('\t') 125 | // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter 126 | // by 1 prematurely. 127 | if ii == 0 && i > 0 { 128 | ii++ 129 | } 130 | } 131 | outBuf.WriteString(scanner.Text()) 132 | } 133 | 134 | return outBuf.String() 135 | } 136 | 137 | // Fail reports a failure through 138 | func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { 139 | 140 | message := messageFromMsgAndArgs(msgAndArgs...) 141 | 142 | if len(message) > 0 { 143 | t.Errorf("\r%s\r\tLocation:\t%s\n"+ 144 | "\r\tError:%s\n"+ 145 | "\r\tMessages:\t%s\n\r", 146 | getWhitespaceString(), 147 | CallerInfo(), 148 | indentMessageLines(failureMessage, 2), 149 | message) 150 | } else { 151 | t.Errorf("\r%s\r\tLocation:\t%s\n"+ 152 | "\r\tError:%s\n\r", 153 | getWhitespaceString(), 154 | CallerInfo(), 155 | indentMessageLines(failureMessage, 2)) 156 | } 157 | 158 | return false 159 | } 160 | 161 | // Implements asserts that an object is implemented by the specified interface. 162 | // 163 | // assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") 164 | func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { 165 | 166 | interfaceType := reflect.TypeOf(interfaceObject).Elem() 167 | 168 | if !reflect.TypeOf(object).Implements(interfaceType) { 169 | return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...) 170 | } 171 | 172 | return true 173 | 174 | } 175 | 176 | // IsType asserts that the specified objects are of the same type. 177 | func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { 178 | 179 | if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { 180 | return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) 181 | } 182 | 183 | return true 184 | } 185 | 186 | // Equal asserts that two objects are equal. 187 | // 188 | // assert.Equal(t, 123, 123, "123 and 123 should be equal") 189 | // 190 | // Returns whether the assertion was successful (true) or not (false). 191 | func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 192 | 193 | if !ObjectsAreEqual(expected, actual) { 194 | return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ 195 | " != %#v (actual)", expected, actual), msgAndArgs...) 196 | } 197 | 198 | return true 199 | 200 | } 201 | 202 | // Exactly asserts that two objects are equal is value and type. 203 | // 204 | // assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") 205 | // 206 | // Returns whether the assertion was successful (true) or not (false). 207 | func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 208 | 209 | aType := reflect.TypeOf(expected) 210 | bType := reflect.TypeOf(actual) 211 | 212 | if aType != bType { 213 | return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType) 214 | } 215 | 216 | return Equal(t, expected, actual, msgAndArgs...) 217 | 218 | } 219 | 220 | // NotNil asserts that the specified object is not nil. 221 | // 222 | // assert.NotNil(t, err, "err should be something") 223 | // 224 | // Returns whether the assertion was successful (true) or not (false). 225 | func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 226 | 227 | success := true 228 | 229 | if object == nil { 230 | success = false 231 | } else { 232 | value := reflect.ValueOf(object) 233 | kind := value.Kind() 234 | if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { 235 | success = false 236 | } 237 | } 238 | 239 | if !success { 240 | Fail(t, "Expected not to be nil.", msgAndArgs...) 241 | } 242 | 243 | return success 244 | } 245 | 246 | // isNil checks if a specified object is nil or not, without Failing. 247 | func isNil(object interface{}) bool { 248 | if object == nil { 249 | return true 250 | } 251 | 252 | value := reflect.ValueOf(object) 253 | kind := value.Kind() 254 | if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { 255 | return true 256 | } 257 | 258 | return false 259 | } 260 | 261 | // Nil asserts that the specified object is nil. 262 | // 263 | // assert.Nil(t, err, "err should be nothing") 264 | // 265 | // Returns whether the assertion was successful (true) or not (false). 266 | func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 267 | if isNil(object) { 268 | return true 269 | } 270 | return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) 271 | } 272 | 273 | var zeros = []interface{}{ 274 | int(0), 275 | int8(0), 276 | int16(0), 277 | int32(0), 278 | int64(0), 279 | uint(0), 280 | uint8(0), 281 | uint16(0), 282 | uint32(0), 283 | uint64(0), 284 | float32(0), 285 | float64(0), 286 | } 287 | 288 | // isEmpty gets whether the specified object is considered empty or not. 289 | func isEmpty(object interface{}) bool { 290 | 291 | if object == nil { 292 | return true 293 | } else if object == "" { 294 | return true 295 | } else if object == false { 296 | return true 297 | } 298 | 299 | for _, v := range zeros { 300 | if object == v { 301 | return true 302 | } 303 | } 304 | 305 | objValue := reflect.ValueOf(object) 306 | 307 | switch objValue.Kind() { 308 | case reflect.Map: 309 | fallthrough 310 | case reflect.Slice, reflect.Chan: 311 | { 312 | return (objValue.Len() == 0) 313 | } 314 | case reflect.Ptr: 315 | { 316 | switch object.(type) { 317 | case *time.Time: 318 | return object.(*time.Time).IsZero() 319 | default: 320 | return false 321 | } 322 | } 323 | } 324 | return false 325 | } 326 | 327 | // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either 328 | // a slice or a channel with len == 0. 329 | // 330 | // assert.Empty(t, obj) 331 | // 332 | // Returns whether the assertion was successful (true) or not (false). 333 | func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 334 | 335 | pass := isEmpty(object) 336 | if !pass { 337 | Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) 338 | } 339 | 340 | return pass 341 | 342 | } 343 | 344 | // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either 345 | // a slice or a channel with len == 0. 346 | // 347 | // if assert.NotEmpty(t, obj) { 348 | // assert.Equal(t, "two", obj[1]) 349 | // } 350 | // 351 | // Returns whether the assertion was successful (true) or not (false). 352 | func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 353 | 354 | pass := !isEmpty(object) 355 | if !pass { 356 | Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) 357 | } 358 | 359 | return pass 360 | 361 | } 362 | 363 | // getLen try to get length of object. 364 | // return (false, 0) if impossible. 365 | func getLen(x interface{}) (ok bool, length int) { 366 | v := reflect.ValueOf(x) 367 | defer func() { 368 | if e := recover(); e != nil { 369 | ok = false 370 | } 371 | }() 372 | return true, v.Len() 373 | } 374 | 375 | // Len asserts that the specified object has specific length. 376 | // Len also fails if the object has a type that len() not accept. 377 | // 378 | // assert.Len(t, mySlice, 3, "The size of slice is not 3") 379 | // 380 | // Returns whether the assertion was successful (true) or not (false). 381 | func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { 382 | ok, l := getLen(object) 383 | if !ok { 384 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) 385 | } 386 | 387 | if l != length { 388 | return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) 389 | } 390 | return true 391 | } 392 | 393 | // True asserts that the specified value is true. 394 | // 395 | // assert.True(t, myBool, "myBool should be true") 396 | // 397 | // Returns whether the assertion was successful (true) or not (false). 398 | func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { 399 | 400 | if value != true { 401 | return Fail(t, "Should be true", msgAndArgs...) 402 | } 403 | 404 | return true 405 | 406 | } 407 | 408 | // False asserts that the specified value is true. 409 | // 410 | // assert.False(t, myBool, "myBool should be false") 411 | // 412 | // Returns whether the assertion was successful (true) or not (false). 413 | func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { 414 | 415 | if value != false { 416 | return Fail(t, "Should be false", msgAndArgs...) 417 | } 418 | 419 | return true 420 | 421 | } 422 | 423 | // NotEqual asserts that the specified values are NOT equal. 424 | // 425 | // assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") 426 | // 427 | // Returns whether the assertion was successful (true) or not (false). 428 | func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 429 | 430 | if ObjectsAreEqual(expected, actual) { 431 | return Fail(t, "Should not be equal", msgAndArgs...) 432 | } 433 | 434 | return true 435 | 436 | } 437 | 438 | // containsElement try loop over the list check if the list includes the element. 439 | // return (false, false) if impossible. 440 | // return (true, false) if element was not found. 441 | // return (true, true) if element was found. 442 | func includeElement(list interface{}, element interface{}) (ok, found bool) { 443 | 444 | listValue := reflect.ValueOf(list) 445 | elementValue := reflect.ValueOf(element) 446 | defer func() { 447 | if e := recover(); e != nil { 448 | ok = false 449 | found = false 450 | } 451 | }() 452 | 453 | if reflect.TypeOf(list).Kind() == reflect.String { 454 | return true, strings.Contains(listValue.String(), elementValue.String()) 455 | } 456 | 457 | for i := 0; i < listValue.Len(); i++ { 458 | if listValue.Index(i).Interface() == element { 459 | return true, true 460 | } 461 | } 462 | return true, false 463 | 464 | } 465 | 466 | // Contains asserts that the specified string or list(array, slice...) contains the 467 | // specified substring or element. 468 | // 469 | // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") 470 | // assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") 471 | // 472 | // Returns whether the assertion was successful (true) or not (false). 473 | func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { 474 | 475 | ok, found := includeElement(s, contains) 476 | if !ok { 477 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) 478 | } 479 | if !found { 480 | return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) 481 | } 482 | 483 | return true 484 | 485 | } 486 | 487 | // NotContains asserts that the specified string or list(array, slice...) does NOT contain the 488 | // specified substring or element. 489 | // 490 | // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") 491 | // assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") 492 | // 493 | // Returns whether the assertion was successful (true) or not (false). 494 | func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { 495 | 496 | ok, found := includeElement(s, contains) 497 | if !ok { 498 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) 499 | } 500 | if found { 501 | return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) 502 | } 503 | 504 | return true 505 | 506 | } 507 | 508 | // Condition uses a Comparison to assert a complex condition. 509 | func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { 510 | result := comp() 511 | if !result { 512 | Fail(t, "Condition failed!", msgAndArgs...) 513 | } 514 | return result 515 | } 516 | 517 | // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics 518 | // methods, and represents a simple func that takes no arguments, and returns nothing. 519 | type PanicTestFunc func() 520 | 521 | // didPanic returns true if the function passed to it panics. Otherwise, it returns false. 522 | func didPanic(f PanicTestFunc) (bool, interface{}) { 523 | 524 | didPanic := false 525 | var message interface{} 526 | func() { 527 | 528 | defer func() { 529 | if message = recover(); message != nil { 530 | didPanic = true 531 | } 532 | }() 533 | 534 | // call the target function 535 | f() 536 | 537 | }() 538 | 539 | return didPanic, message 540 | 541 | } 542 | 543 | // Panics asserts that the code inside the specified PanicTestFunc panics. 544 | // 545 | // assert.Panics(t, func(){ 546 | // GoCrazy() 547 | // }, "Calling GoCrazy() should panic") 548 | // 549 | // Returns whether the assertion was successful (true) or not (false). 550 | func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { 551 | 552 | if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { 553 | return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) 554 | } 555 | 556 | return true 557 | } 558 | 559 | // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. 560 | // 561 | // assert.NotPanics(t, func(){ 562 | // RemainCalm() 563 | // }, "Calling RemainCalm() should NOT panic") 564 | // 565 | // Returns whether the assertion was successful (true) or not (false). 566 | func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { 567 | 568 | if funcDidPanic, panicValue := didPanic(f); funcDidPanic { 569 | return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) 570 | } 571 | 572 | return true 573 | } 574 | 575 | // WithinDuration asserts that the two times are within duration delta of each other. 576 | // 577 | // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") 578 | // 579 | // Returns whether the assertion was successful (true) or not (false). 580 | func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { 581 | 582 | dt := expected.Sub(actual) 583 | if dt < -delta || dt > delta { 584 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) 585 | } 586 | 587 | return true 588 | } 589 | 590 | func toFloat(x interface{}) (float64, bool) { 591 | var xf float64 592 | xok := true 593 | 594 | switch xn := x.(type) { 595 | case uint8: 596 | xf = float64(xn) 597 | case uint16: 598 | xf = float64(xn) 599 | case uint32: 600 | xf = float64(xn) 601 | case uint64: 602 | xf = float64(xn) 603 | case int: 604 | xf = float64(xn) 605 | case int8: 606 | xf = float64(xn) 607 | case int16: 608 | xf = float64(xn) 609 | case int32: 610 | xf = float64(xn) 611 | case int64: 612 | xf = float64(xn) 613 | case float32: 614 | xf = float64(xn) 615 | case float64: 616 | xf = float64(xn) 617 | default: 618 | xok = false 619 | } 620 | 621 | return xf, xok 622 | } 623 | 624 | // InDelta asserts that the two numerals are within delta of each other. 625 | // 626 | // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) 627 | // 628 | // Returns whether the assertion was successful (true) or not (false). 629 | func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 630 | 631 | af, aok := toFloat(expected) 632 | bf, bok := toFloat(actual) 633 | 634 | if !aok || !bok { 635 | return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) 636 | } 637 | 638 | dt := af - bf 639 | if dt < -delta || dt > delta { 640 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) 641 | } 642 | 643 | return true 644 | } 645 | 646 | // min(|expected|, |actual|) * epsilon 647 | func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 { 648 | af, aok := toFloat(expected) 649 | bf, bok := toFloat(actual) 650 | 651 | if !aok || !bok { 652 | // invalid input 653 | return 0 654 | } 655 | 656 | if af < 0 { 657 | af = -af 658 | } 659 | if bf < 0 { 660 | bf = -bf 661 | } 662 | var delta float64 663 | if af < bf { 664 | delta = af * epsilon 665 | } else { 666 | delta = bf * epsilon 667 | } 668 | return delta 669 | } 670 | 671 | // InEpsilon asserts that expected and actual have a relative error less than epsilon 672 | // 673 | // Returns whether the assertion was successful (true) or not (false). 674 | func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { 675 | delta := calcEpsilonDelta(expected, actual, epsilon) 676 | 677 | return InDelta(t, expected, actual, delta, msgAndArgs...) 678 | } 679 | 680 | /* 681 | Errors 682 | */ 683 | 684 | // NoError asserts that a function returned no error (i.e. `nil`). 685 | // 686 | // actualObj, err := SomeFunction() 687 | // if assert.NoError(t, err) { 688 | // assert.Equal(t, actualObj, expectedObj) 689 | // } 690 | // 691 | // Returns whether the assertion was successful (true) or not (false). 692 | func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { 693 | if isNil(err) { 694 | return true 695 | } 696 | 697 | return Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...) 698 | } 699 | 700 | // Error asserts that a function returned an error (i.e. not `nil`). 701 | // 702 | // actualObj, err := SomeFunction() 703 | // if assert.Error(t, err, "An error was expected") { 704 | // assert.Equal(t, err, expectedError) 705 | // } 706 | // 707 | // Returns whether the assertion was successful (true) or not (false). 708 | func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { 709 | 710 | message := messageFromMsgAndArgs(msgAndArgs...) 711 | return NotNil(t, err, "An error is expected but got nil. %s", message) 712 | 713 | } 714 | 715 | // EqualError asserts that a function returned an error (i.e. not `nil`) 716 | // and that it is equal to the provided error. 717 | // 718 | // actualObj, err := SomeFunction() 719 | // if assert.Error(t, err, "An error was expected") { 720 | // assert.Equal(t, err, expectedError) 721 | // } 722 | // 723 | // Returns whether the assertion was successful (true) or not (false). 724 | func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { 725 | 726 | message := messageFromMsgAndArgs(msgAndArgs...) 727 | if !NotNil(t, theError, "An error is expected but got nil. %s", message) { 728 | return false 729 | } 730 | s := "An error with value \"%s\" is expected but got \"%s\". %s" 731 | return Equal(t, theError.Error(), errString, 732 | s, errString, theError.Error(), message) 733 | } 734 | --------------------------------------------------------------------------------