Browse code

Update vendor

Signed-off-by: Daniel Nephin <dnephin@docker.com>

Daniel Nephin authored on 2017/12/23 06:33:58
Showing 51 changed files
... ...
@@ -2,7 +2,6 @@
2 2
 github.com/Azure/go-ansiterm d6e3b3328b783f23731bc4d058875b0371ff8109
3 3
 github.com/Microsoft/hcsshim v0.6.8
4 4
 github.com/Microsoft/go-winio v0.4.6
5
-github.com/davecgh/go-spew 346938d642f2ec3594ed81d874461961cd0faa76
6 5
 github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
7 6
 github.com/go-check/check 4ed411733c5785b40214c70bce814c3a3a689609 https://github.com/cpuguy83/check.git
8 7
 github.com/golang/gddo 9b12a26f3fbd7397dee4e20939ddca719d840d2a
... ...
@@ -19,10 +18,9 @@ golang.org/x/sys 37707fdb30a5b38865cfb95e5aab41707daec7fd
19 19
 github.com/docker/go-units 9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1
20 20
 github.com/docker/go-connections 7beb39f0b969b075d1325fecb092faf27fd357b6
21 21
 golang.org/x/text f72d8390a633d5dfb0cc84043294db9f6c935756
22
-github.com/stretchr/testify 4d4bfba8f1d1027c4fdbe371823030df51419987
23 22
 github.com/pmezard/go-difflib v1.0.0
24
-github.com/gotestyourself/gotestyourself 511344eed30e4384f010579a593dfb442033a692
25
-github.com/google/go-cmp v0.1.0
23
+github.com/gotestyourself/gotestyourself cf3a5ab914a2efa8bc838d09f5918c1d44d029
24
+github.com/google/go-cmp v0.2.0
26 25
 
27 26
 github.com/RackSec/srslog 456df3a81436d29ba874f3590eeeee25d666f8a5
28 27
 github.com/imdario/mergo 0.2.1
29 28
deleted file mode 100644
... ...
@@ -1,15 +0,0 @@
1
-ISC License
2
-
3
-Copyright (c) 2012-2016 Dave Collins <dave@davec.name>
4
-
5
-Permission to use, copy, modify, and distribute this software for any
6
-purpose with or without fee is hereby granted, provided that the above
7
-copyright notice and this permission notice appear in all copies.
8
-
9
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 1
deleted file mode 100644
... ...
@@ -1,205 +0,0 @@
1
-go-spew
2
-=======
3
-
4
-[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)]
5
-(https://travis-ci.org/davecgh/go-spew) [![ISC License]
6
-(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status]
7
-(https://img.shields.io/coveralls/davecgh/go-spew.svg)]
8
-(https://coveralls.io/r/davecgh/go-spew?branch=master)
9
-
10
-
11
-Go-spew implements a deep pretty printer for Go data structures to aid in
12
-debugging.  A comprehensive suite of tests with 100% test coverage is provided
13
-to ensure proper functionality.  See `test_coverage.txt` for the gocov coverage
14
-report.  Go-spew is licensed under the liberal ISC license, so it may be used in
15
-open source or commercial projects.
16
-
17
-If you're interested in reading about how this package came to life and some
18
-of the challenges involved in providing a deep pretty printer, there is a blog
19
-post about it
20
-[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/).
21
-
22
-## Documentation
23
-
24
-[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)]
25
-(http://godoc.org/github.com/davecgh/go-spew/spew)
26
-
27
-Full `go doc` style documentation for the project can be viewed online without
28
-installing this package by using the excellent GoDoc site here:
29
-http://godoc.org/github.com/davecgh/go-spew/spew
30
-
31
-You can also view the documentation locally once the package is installed with
32
-the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
33
-http://localhost:6060/pkg/github.com/davecgh/go-spew/spew
34
-
35
-## Installation
36
-
37
-```bash
38
-$ go get -u github.com/davecgh/go-spew/spew
39
-```
40
-
41
-## Quick Start
42
-
43
-Add this import line to the file you're working in:
44
-
45
-```Go
46
-import "github.com/davecgh/go-spew/spew"
47
-```
48
-
49
-To dump a variable with full newlines, indentation, type, and pointer
50
-information use Dump, Fdump, or Sdump:
51
-
52
-```Go
53
-spew.Dump(myVar1, myVar2, ...)
54
-spew.Fdump(someWriter, myVar1, myVar2, ...)
55
-str := spew.Sdump(myVar1, myVar2, ...)
56
-```
57
-
58
-Alternatively, if you would prefer to use format strings with a compacted inline
59
-printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most
60
-compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types
61
-and pointer addresses): 
62
-
63
-```Go
64
-spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
65
-spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
66
-spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
67
-spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
68
-```
69
-
70
-## Debugging a Web Application Example
71
-
72
-Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production.
73
-
74
-```Go
75
-package main
76
-
77
-import (
78
-    "fmt"
79
-    "html"
80
-    "net/http"
81
-
82
-    "github.com/davecgh/go-spew/spew"
83
-)
84
-
85
-func handler(w http.ResponseWriter, r *http.Request) {
86
-    w.Header().Set("Content-Type", "text/html")
87
-    fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
88
-    fmt.Fprintf(w, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")
89
-}
90
-
91
-func main() {
92
-    http.HandleFunc("/", handler)
93
-    http.ListenAndServe(":8080", nil)
94
-}
95
-```
96
-
97
-## Sample Dump Output
98
-
99
-```
100
-(main.Foo) {
101
- unexportedField: (*main.Bar)(0xf84002e210)({
102
-  flag: (main.Flag) flagTwo,
103
-  data: (uintptr) <nil>
104
- }),
105
- ExportedField: (map[interface {}]interface {}) {
106
-  (string) "one": (bool) true
107
- }
108
-}
109
-([]uint8) {
110
- 00000000  11 12 13 14 15 16 17 18  19 1a 1b 1c 1d 1e 1f 20  |............... |
111
- 00000010  21 22 23 24 25 26 27 28  29 2a 2b 2c 2d 2e 2f 30  |!"#$%&'()*+,-./0|
112
- 00000020  31 32                                             |12|
113
-}
114
-```
115
-
116
-## Sample Formatter Output
117
-
118
-Double pointer to a uint8:
119
-```
120
-	  %v: <**>5
121
-	 %+v: <**>(0xf8400420d0->0xf8400420c8)5
122
-	 %#v: (**uint8)5
123
-	%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
124
-```
125
-
126
-Pointer to circular struct with a uint8 field and a pointer to itself:
127
-```
128
-	  %v: <*>{1 <*><shown>}
129
-	 %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
130
-	 %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
131
-	%#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
132
-```
133
-
134
-## Configuration Options
135
-
136
-Configuration of spew is handled by fields in the ConfigState type. For
137
-convenience, all of the top-level functions use a global state available via the
138
-spew.Config global.
139
-
140
-It is also possible to create a ConfigState instance that provides methods
141
-equivalent to the top-level functions. This allows concurrent configuration
142
-options. See the ConfigState documentation for more details.
143
-
144
-```
145
-* Indent
146
-	String to use for each indentation level for Dump functions.
147
-	It is a single space by default.  A popular alternative is "\t".
148
-
149
-* MaxDepth
150
-	Maximum number of levels to descend into nested data structures.
151
-	There is no limit by default.
152
-
153
-* DisableMethods
154
-	Disables invocation of error and Stringer interface methods.
155
-	Method invocation is enabled by default.
156
-
157
-* DisablePointerMethods
158
-	Disables invocation of error and Stringer interface methods on types
159
-	which only accept pointer receivers from non-pointer variables.  This option
160
-	relies on access to the unsafe package, so it will not have any effect when
161
-	running in environments without access to the unsafe package such as Google
162
-	App Engine or with the "safe" build tag specified.
163
-	Pointer method invocation is enabled by default.
164
-
165
-* DisablePointerAddresses
166
-	DisablePointerAddresses specifies whether to disable the printing of
167
-	pointer addresses. This is useful when diffing data structures in tests.
168
-
169
-* DisableCapacities
170
-	DisableCapacities specifies whether to disable the printing of capacities
171
-	for arrays, slices, maps and channels. This is useful when diffing data
172
-	structures in tests.
173
-
174
-* ContinueOnMethod
175
-	Enables recursion into types after invoking error and Stringer interface
176
-	methods. Recursion after method invocation is disabled by default.
177
-
178
-* SortKeys
179
-	Specifies map keys should be sorted before being printed. Use
180
-	this to have a more deterministic, diffable output.  Note that
181
-	only native types (bool, int, uint, floats, uintptr and string)
182
-	and types which implement error or Stringer interfaces are supported,
183
-	with other types sorted according to the reflect.Value.String() output
184
-	which guarantees display stability.  Natural map order is used by
185
-	default.
186
-
187
-* SpewKeys
188
-	SpewKeys specifies that, as a last resort attempt, map keys should be
189
-	spewed to strings and sorted by those strings.  This is only considered
190
-	if SortKeys is true.
191
-
192
-```
193
-
194
-## Unsafe Package Dependency
195
-
196
-This package relies on the unsafe package to perform some of the more advanced
197
-features, however it also supports a "limited" mode which allows it to work in
198
-environments where the unsafe package is not available.  By default, it will
199
-operate in this mode on Google App Engine and when compiled with GopherJS.  The
200
-"safe" build tag may also be specified to force the package to build without
201
-using the unsafe package.
202
-
203
-## License
204
-
205
-Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
206 1
deleted file mode 100644
... ...
@@ -1,152 +0,0 @@
1
-// Copyright (c) 2015-2016 Dave Collins <dave@davec.name>
2
-//
3
-// Permission to use, copy, modify, and distribute this software for any
4
-// purpose with or without fee is hereby granted, provided that the above
5
-// copyright notice and this permission notice appear in all copies.
6
-//
7
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
-
15
-// NOTE: Due to the following build constraints, this file will only be compiled
16
-// when the code is not running on Google App Engine, compiled by GopherJS, and
17
-// "-tags safe" is not added to the go build command line.  The "disableunsafe"
18
-// tag is deprecated and thus should not be used.
19
-// +build !js,!appengine,!safe,!disableunsafe
20
-
21
-package spew
22
-
23
-import (
24
-	"reflect"
25
-	"unsafe"
26
-)
27
-
28
-const (
29
-	// UnsafeDisabled is a build-time constant which specifies whether or
30
-	// not access to the unsafe package is available.
31
-	UnsafeDisabled = false
32
-
33
-	// ptrSize is the size of a pointer on the current arch.
34
-	ptrSize = unsafe.Sizeof((*byte)(nil))
35
-)
36
-
37
-var (
38
-	// offsetPtr, offsetScalar, and offsetFlag are the offsets for the
39
-	// internal reflect.Value fields.  These values are valid before golang
40
-	// commit ecccf07e7f9d which changed the format.  The are also valid
41
-	// after commit 82f48826c6c7 which changed the format again to mirror
42
-	// the original format.  Code in the init function updates these offsets
43
-	// as necessary.
44
-	offsetPtr    = uintptr(ptrSize)
45
-	offsetScalar = uintptr(0)
46
-	offsetFlag   = uintptr(ptrSize * 2)
47
-
48
-	// flagKindWidth and flagKindShift indicate various bits that the
49
-	// reflect package uses internally to track kind information.
50
-	//
51
-	// flagRO indicates whether or not the value field of a reflect.Value is
52
-	// read-only.
53
-	//
54
-	// flagIndir indicates whether the value field of a reflect.Value is
55
-	// the actual data or a pointer to the data.
56
-	//
57
-	// These values are valid before golang commit 90a7c3c86944 which
58
-	// changed their positions.  Code in the init function updates these
59
-	// flags as necessary.
60
-	flagKindWidth = uintptr(5)
61
-	flagKindShift = uintptr(flagKindWidth - 1)
62
-	flagRO        = uintptr(1 << 0)
63
-	flagIndir     = uintptr(1 << 1)
64
-)
65
-
66
-func init() {
67
-	// Older versions of reflect.Value stored small integers directly in the
68
-	// ptr field (which is named val in the older versions).  Versions
69
-	// between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
70
-	// scalar for this purpose which unfortunately came before the flag
71
-	// field, so the offset of the flag field is different for those
72
-	// versions.
73
-	//
74
-	// This code constructs a new reflect.Value from a known small integer
75
-	// and checks if the size of the reflect.Value struct indicates it has
76
-	// the scalar field. When it does, the offsets are updated accordingly.
77
-	vv := reflect.ValueOf(0xf00)
78
-	if unsafe.Sizeof(vv) == (ptrSize * 4) {
79
-		offsetScalar = ptrSize * 2
80
-		offsetFlag = ptrSize * 3
81
-	}
82
-
83
-	// Commit 90a7c3c86944 changed the flag positions such that the low
84
-	// order bits are the kind.  This code extracts the kind from the flags
85
-	// field and ensures it's the correct type.  When it's not, the flag
86
-	// order has been changed to the newer format, so the flags are updated
87
-	// accordingly.
88
-	upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
89
-	upfv := *(*uintptr)(upf)
90
-	flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
91
-	if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
92
-		flagKindShift = 0
93
-		flagRO = 1 << 5
94
-		flagIndir = 1 << 6
95
-
96
-		// Commit adf9b30e5594 modified the flags to separate the
97
-		// flagRO flag into two bits which specifies whether or not the
98
-		// field is embedded.  This causes flagIndir to move over a bit
99
-		// and means that flagRO is the combination of either of the
100
-		// original flagRO bit and the new bit.
101
-		//
102
-		// This code detects the change by extracting what used to be
103
-		// the indirect bit to ensure it's set.  When it's not, the flag
104
-		// order has been changed to the newer format, so the flags are
105
-		// updated accordingly.
106
-		if upfv&flagIndir == 0 {
107
-			flagRO = 3 << 5
108
-			flagIndir = 1 << 7
109
-		}
110
-	}
111
-}
112
-
113
-// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
114
-// the typical safety restrictions preventing access to unaddressable and
115
-// unexported data.  It works by digging the raw pointer to the underlying
116
-// value out of the protected value and generating a new unprotected (unsafe)
117
-// reflect.Value to it.
118
-//
119
-// This allows us to check for implementations of the Stringer and error
120
-// interfaces to be used for pretty printing ordinarily unaddressable and
121
-// inaccessible values such as unexported struct fields.
122
-func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
123
-	indirects := 1
124
-	vt := v.Type()
125
-	upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
126
-	rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
127
-	if rvf&flagIndir != 0 {
128
-		vt = reflect.PtrTo(v.Type())
129
-		indirects++
130
-	} else if offsetScalar != 0 {
131
-		// The value is in the scalar field when it's not one of the
132
-		// reference types.
133
-		switch vt.Kind() {
134
-		case reflect.Uintptr:
135
-		case reflect.Chan:
136
-		case reflect.Func:
137
-		case reflect.Map:
138
-		case reflect.Ptr:
139
-		case reflect.UnsafePointer:
140
-		default:
141
-			upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
142
-				offsetScalar)
143
-		}
144
-	}
145
-
146
-	pv := reflect.NewAt(vt, upv)
147
-	rv = pv
148
-	for i := 0; i < indirects; i++ {
149
-		rv = rv.Elem()
150
-	}
151
-	return rv
152
-}
153 1
deleted file mode 100644
... ...
@@ -1,38 +0,0 @@
1
-// Copyright (c) 2015-2016 Dave Collins <dave@davec.name>
2
-//
3
-// Permission to use, copy, modify, and distribute this software for any
4
-// purpose with or without fee is hereby granted, provided that the above
5
-// copyright notice and this permission notice appear in all copies.
6
-//
7
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
-
15
-// NOTE: Due to the following build constraints, this file will only be compiled
16
-// when the code is running on Google App Engine, compiled by GopherJS, or
17
-// "-tags safe" is added to the go build command line.  The "disableunsafe"
18
-// tag is deprecated and thus should not be used.
19
-// +build js appengine safe disableunsafe
20
-
21
-package spew
22
-
23
-import "reflect"
24
-
25
-const (
26
-	// UnsafeDisabled is a build-time constant which specifies whether or
27
-	// not access to the unsafe package is available.
28
-	UnsafeDisabled = true
29
-)
30
-
31
-// unsafeReflectValue typically converts the passed reflect.Value into a one
32
-// that bypasses the typical safety restrictions preventing access to
33
-// unaddressable and unexported data.  However, doing this relies on access to
34
-// the unsafe package.  This is a stub version which simply returns the passed
35
-// reflect.Value when the unsafe package is not available.
36
-func unsafeReflectValue(v reflect.Value) reflect.Value {
37
-	return v
38
-}
39 1
deleted file mode 100644
... ...
@@ -1,341 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-package spew
18
-
19
-import (
20
-	"bytes"
21
-	"fmt"
22
-	"io"
23
-	"reflect"
24
-	"sort"
25
-	"strconv"
26
-)
27
-
28
-// Some constants in the form of bytes to avoid string overhead.  This mirrors
29
-// the technique used in the fmt package.
30
-var (
31
-	panicBytes            = []byte("(PANIC=")
32
-	plusBytes             = []byte("+")
33
-	iBytes                = []byte("i")
34
-	trueBytes             = []byte("true")
35
-	falseBytes            = []byte("false")
36
-	interfaceBytes        = []byte("(interface {})")
37
-	commaNewlineBytes     = []byte(",\n")
38
-	newlineBytes          = []byte("\n")
39
-	openBraceBytes        = []byte("{")
40
-	openBraceNewlineBytes = []byte("{\n")
41
-	closeBraceBytes       = []byte("}")
42
-	asteriskBytes         = []byte("*")
43
-	colonBytes            = []byte(":")
44
-	colonSpaceBytes       = []byte(": ")
45
-	openParenBytes        = []byte("(")
46
-	closeParenBytes       = []byte(")")
47
-	spaceBytes            = []byte(" ")
48
-	pointerChainBytes     = []byte("->")
49
-	nilAngleBytes         = []byte("<nil>")
50
-	maxNewlineBytes       = []byte("<max depth reached>\n")
51
-	maxShortBytes         = []byte("<max>")
52
-	circularBytes         = []byte("<already shown>")
53
-	circularShortBytes    = []byte("<shown>")
54
-	invalidAngleBytes     = []byte("<invalid>")
55
-	openBracketBytes      = []byte("[")
56
-	closeBracketBytes     = []byte("]")
57
-	percentBytes          = []byte("%")
58
-	precisionBytes        = []byte(".")
59
-	openAngleBytes        = []byte("<")
60
-	closeAngleBytes       = []byte(">")
61
-	openMapBytes          = []byte("map[")
62
-	closeMapBytes         = []byte("]")
63
-	lenEqualsBytes        = []byte("len=")
64
-	capEqualsBytes        = []byte("cap=")
65
-)
66
-
67
-// hexDigits is used to map a decimal value to a hex digit.
68
-var hexDigits = "0123456789abcdef"
69
-
70
-// catchPanic handles any panics that might occur during the handleMethods
71
-// calls.
72
-func catchPanic(w io.Writer, v reflect.Value) {
73
-	if err := recover(); err != nil {
74
-		w.Write(panicBytes)
75
-		fmt.Fprintf(w, "%v", err)
76
-		w.Write(closeParenBytes)
77
-	}
78
-}
79
-
80
-// handleMethods attempts to call the Error and String methods on the underlying
81
-// type the passed reflect.Value represents and outputes the result to Writer w.
82
-//
83
-// It handles panics in any called methods by catching and displaying the error
84
-// as the formatted value.
85
-func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
86
-	// We need an interface to check if the type implements the error or
87
-	// Stringer interface.  However, the reflect package won't give us an
88
-	// interface on certain things like unexported struct fields in order
89
-	// to enforce visibility rules.  We use unsafe, when it's available,
90
-	// to bypass these restrictions since this package does not mutate the
91
-	// values.
92
-	if !v.CanInterface() {
93
-		if UnsafeDisabled {
94
-			return false
95
-		}
96
-
97
-		v = unsafeReflectValue(v)
98
-	}
99
-
100
-	// Choose whether or not to do error and Stringer interface lookups against
101
-	// the base type or a pointer to the base type depending on settings.
102
-	// Technically calling one of these methods with a pointer receiver can
103
-	// mutate the value, however, types which choose to satisify an error or
104
-	// Stringer interface with a pointer receiver should not be mutating their
105
-	// state inside these interface methods.
106
-	if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
107
-		v = unsafeReflectValue(v)
108
-	}
109
-	if v.CanAddr() {
110
-		v = v.Addr()
111
-	}
112
-
113
-	// Is it an error or Stringer?
114
-	switch iface := v.Interface().(type) {
115
-	case error:
116
-		defer catchPanic(w, v)
117
-		if cs.ContinueOnMethod {
118
-			w.Write(openParenBytes)
119
-			w.Write([]byte(iface.Error()))
120
-			w.Write(closeParenBytes)
121
-			w.Write(spaceBytes)
122
-			return false
123
-		}
124
-
125
-		w.Write([]byte(iface.Error()))
126
-		return true
127
-
128
-	case fmt.Stringer:
129
-		defer catchPanic(w, v)
130
-		if cs.ContinueOnMethod {
131
-			w.Write(openParenBytes)
132
-			w.Write([]byte(iface.String()))
133
-			w.Write(closeParenBytes)
134
-			w.Write(spaceBytes)
135
-			return false
136
-		}
137
-		w.Write([]byte(iface.String()))
138
-		return true
139
-	}
140
-	return false
141
-}
142
-
143
-// printBool outputs a boolean value as true or false to Writer w.
144
-func printBool(w io.Writer, val bool) {
145
-	if val {
146
-		w.Write(trueBytes)
147
-	} else {
148
-		w.Write(falseBytes)
149
-	}
150
-}
151
-
152
-// printInt outputs a signed integer value to Writer w.
153
-func printInt(w io.Writer, val int64, base int) {
154
-	w.Write([]byte(strconv.FormatInt(val, base)))
155
-}
156
-
157
-// printUint outputs an unsigned integer value to Writer w.
158
-func printUint(w io.Writer, val uint64, base int) {
159
-	w.Write([]byte(strconv.FormatUint(val, base)))
160
-}
161
-
162
-// printFloat outputs a floating point value using the specified precision,
163
-// which is expected to be 32 or 64bit, to Writer w.
164
-func printFloat(w io.Writer, val float64, precision int) {
165
-	w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
166
-}
167
-
168
-// printComplex outputs a complex value using the specified float precision
169
-// for the real and imaginary parts to Writer w.
170
-func printComplex(w io.Writer, c complex128, floatPrecision int) {
171
-	r := real(c)
172
-	w.Write(openParenBytes)
173
-	w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
174
-	i := imag(c)
175
-	if i >= 0 {
176
-		w.Write(plusBytes)
177
-	}
178
-	w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
179
-	w.Write(iBytes)
180
-	w.Write(closeParenBytes)
181
-}
182
-
183
-// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
184
-// prefix to Writer w.
185
-func printHexPtr(w io.Writer, p uintptr) {
186
-	// Null pointer.
187
-	num := uint64(p)
188
-	if num == 0 {
189
-		w.Write(nilAngleBytes)
190
-		return
191
-	}
192
-
193
-	// Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
194
-	buf := make([]byte, 18)
195
-
196
-	// It's simpler to construct the hex string right to left.
197
-	base := uint64(16)
198
-	i := len(buf) - 1
199
-	for num >= base {
200
-		buf[i] = hexDigits[num%base]
201
-		num /= base
202
-		i--
203
-	}
204
-	buf[i] = hexDigits[num]
205
-
206
-	// Add '0x' prefix.
207
-	i--
208
-	buf[i] = 'x'
209
-	i--
210
-	buf[i] = '0'
211
-
212
-	// Strip unused leading bytes.
213
-	buf = buf[i:]
214
-	w.Write(buf)
215
-}
216
-
217
-// valuesSorter implements sort.Interface to allow a slice of reflect.Value
218
-// elements to be sorted.
219
-type valuesSorter struct {
220
-	values  []reflect.Value
221
-	strings []string // either nil or same len and values
222
-	cs      *ConfigState
223
-}
224
-
225
-// newValuesSorter initializes a valuesSorter instance, which holds a set of
226
-// surrogate keys on which the data should be sorted.  It uses flags in
227
-// ConfigState to decide if and how to populate those surrogate keys.
228
-func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface {
229
-	vs := &valuesSorter{values: values, cs: cs}
230
-	if canSortSimply(vs.values[0].Kind()) {
231
-		return vs
232
-	}
233
-	if !cs.DisableMethods {
234
-		vs.strings = make([]string, len(values))
235
-		for i := range vs.values {
236
-			b := bytes.Buffer{}
237
-			if !handleMethods(cs, &b, vs.values[i]) {
238
-				vs.strings = nil
239
-				break
240
-			}
241
-			vs.strings[i] = b.String()
242
-		}
243
-	}
244
-	if vs.strings == nil && cs.SpewKeys {
245
-		vs.strings = make([]string, len(values))
246
-		for i := range vs.values {
247
-			vs.strings[i] = Sprintf("%#v", vs.values[i].Interface())
248
-		}
249
-	}
250
-	return vs
251
-}
252
-
253
-// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted
254
-// directly, or whether it should be considered for sorting by surrogate keys
255
-// (if the ConfigState allows it).
256
-func canSortSimply(kind reflect.Kind) bool {
257
-	// This switch parallels valueSortLess, except for the default case.
258
-	switch kind {
259
-	case reflect.Bool:
260
-		return true
261
-	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
262
-		return true
263
-	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
264
-		return true
265
-	case reflect.Float32, reflect.Float64:
266
-		return true
267
-	case reflect.String:
268
-		return true
269
-	case reflect.Uintptr:
270
-		return true
271
-	case reflect.Array:
272
-		return true
273
-	}
274
-	return false
275
-}
276
-
277
-// Len returns the number of values in the slice.  It is part of the
278
-// sort.Interface implementation.
279
-func (s *valuesSorter) Len() int {
280
-	return len(s.values)
281
-}
282
-
283
-// Swap swaps the values at the passed indices.  It is part of the
284
-// sort.Interface implementation.
285
-func (s *valuesSorter) Swap(i, j int) {
286
-	s.values[i], s.values[j] = s.values[j], s.values[i]
287
-	if s.strings != nil {
288
-		s.strings[i], s.strings[j] = s.strings[j], s.strings[i]
289
-	}
290
-}
291
-
292
-// valueSortLess returns whether the first value should sort before the second
293
-// value.  It is used by valueSorter.Less as part of the sort.Interface
294
-// implementation.
295
-func valueSortLess(a, b reflect.Value) bool {
296
-	switch a.Kind() {
297
-	case reflect.Bool:
298
-		return !a.Bool() && b.Bool()
299
-	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
300
-		return a.Int() < b.Int()
301
-	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
302
-		return a.Uint() < b.Uint()
303
-	case reflect.Float32, reflect.Float64:
304
-		return a.Float() < b.Float()
305
-	case reflect.String:
306
-		return a.String() < b.String()
307
-	case reflect.Uintptr:
308
-		return a.Uint() < b.Uint()
309
-	case reflect.Array:
310
-		// Compare the contents of both arrays.
311
-		l := a.Len()
312
-		for i := 0; i < l; i++ {
313
-			av := a.Index(i)
314
-			bv := b.Index(i)
315
-			if av.Interface() == bv.Interface() {
316
-				continue
317
-			}
318
-			return valueSortLess(av, bv)
319
-		}
320
-	}
321
-	return a.String() < b.String()
322
-}
323
-
324
-// Less returns whether the value at index i should sort before the
325
-// value at index j.  It is part of the sort.Interface implementation.
326
-func (s *valuesSorter) Less(i, j int) bool {
327
-	if s.strings == nil {
328
-		return valueSortLess(s.values[i], s.values[j])
329
-	}
330
-	return s.strings[i] < s.strings[j]
331
-}
332
-
333
-// sortValues is a sort function that handles both native types and any type that
334
-// can be converted to error or Stringer.  Other inputs are sorted according to
335
-// their Value.String() value to ensure display stability.
336
-func sortValues(values []reflect.Value, cs *ConfigState) {
337
-	if len(values) == 0 {
338
-		return
339
-	}
340
-	sort.Sort(newValuesSorter(values, cs))
341
-}
342 1
deleted file mode 100644
... ...
@@ -1,306 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-package spew
18
-
19
-import (
20
-	"bytes"
21
-	"fmt"
22
-	"io"
23
-	"os"
24
-)
25
-
26
-// ConfigState houses the configuration options used by spew to format and
27
-// display values.  There is a global instance, Config, that is used to control
28
-// all top-level Formatter and Dump functionality.  Each ConfigState instance
29
-// provides methods equivalent to the top-level functions.
30
-//
31
-// The zero value for ConfigState provides no indentation.  You would typically
32
-// want to set it to a space or a tab.
33
-//
34
-// Alternatively, you can use NewDefaultConfig to get a ConfigState instance
35
-// with default settings.  See the documentation of NewDefaultConfig for default
36
-// values.
37
-type ConfigState struct {
38
-	// Indent specifies the string to use for each indentation level.  The
39
-	// global config instance that all top-level functions use set this to a
40
-	// single space by default.  If you would like more indentation, you might
41
-	// set this to a tab with "\t" or perhaps two spaces with "  ".
42
-	Indent string
43
-
44
-	// MaxDepth controls the maximum number of levels to descend into nested
45
-	// data structures.  The default, 0, means there is no limit.
46
-	//
47
-	// NOTE: Circular data structures are properly detected, so it is not
48
-	// necessary to set this value unless you specifically want to limit deeply
49
-	// nested data structures.
50
-	MaxDepth int
51
-
52
-	// DisableMethods specifies whether or not error and Stringer interfaces are
53
-	// invoked for types that implement them.
54
-	DisableMethods bool
55
-
56
-	// DisablePointerMethods specifies whether or not to check for and invoke
57
-	// error and Stringer interfaces on types which only accept a pointer
58
-	// receiver when the current type is not a pointer.
59
-	//
60
-	// NOTE: This might be an unsafe action since calling one of these methods
61
-	// with a pointer receiver could technically mutate the value, however,
62
-	// in practice, types which choose to satisify an error or Stringer
63
-	// interface with a pointer receiver should not be mutating their state
64
-	// inside these interface methods.  As a result, this option relies on
65
-	// access to the unsafe package, so it will not have any effect when
66
-	// running in environments without access to the unsafe package such as
67
-	// Google App Engine or with the "safe" build tag specified.
68
-	DisablePointerMethods bool
69
-
70
-	// DisablePointerAddresses specifies whether to disable the printing of
71
-	// pointer addresses. This is useful when diffing data structures in tests.
72
-	DisablePointerAddresses bool
73
-
74
-	// DisableCapacities specifies whether to disable the printing of capacities
75
-	// for arrays, slices, maps and channels. This is useful when diffing
76
-	// data structures in tests.
77
-	DisableCapacities bool
78
-
79
-	// ContinueOnMethod specifies whether or not recursion should continue once
80
-	// a custom error or Stringer interface is invoked.  The default, false,
81
-	// means it will print the results of invoking the custom error or Stringer
82
-	// interface and return immediately instead of continuing to recurse into
83
-	// the internals of the data type.
84
-	//
85
-	// NOTE: This flag does not have any effect if method invocation is disabled
86
-	// via the DisableMethods or DisablePointerMethods options.
87
-	ContinueOnMethod bool
88
-
89
-	// SortKeys specifies map keys should be sorted before being printed. Use
90
-	// this to have a more deterministic, diffable output.  Note that only
91
-	// native types (bool, int, uint, floats, uintptr and string) and types
92
-	// that support the error or Stringer interfaces (if methods are
93
-	// enabled) are supported, with other types sorted according to the
94
-	// reflect.Value.String() output which guarantees display stability.
95
-	SortKeys bool
96
-
97
-	// SpewKeys specifies that, as a last resort attempt, map keys should
98
-	// be spewed to strings and sorted by those strings.  This is only
99
-	// considered if SortKeys is true.
100
-	SpewKeys bool
101
-}
102
-
103
-// Config is the active configuration of the top-level functions.
104
-// The configuration can be changed by modifying the contents of spew.Config.
105
-var Config = ConfigState{Indent: " "}
106
-
107
-// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
108
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
109
-// the formatted string as a value that satisfies error.  See NewFormatter
110
-// for formatting details.
111
-//
112
-// This function is shorthand for the following syntax:
113
-//
114
-//	fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b))
115
-func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) {
116
-	return fmt.Errorf(format, c.convertArgs(a)...)
117
-}
118
-
119
-// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
120
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
121
-// the number of bytes written and any write error encountered.  See
122
-// NewFormatter for formatting details.
123
-//
124
-// This function is shorthand for the following syntax:
125
-//
126
-//	fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b))
127
-func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
128
-	return fmt.Fprint(w, c.convertArgs(a)...)
129
-}
130
-
131
-// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
132
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
133
-// the number of bytes written and any write error encountered.  See
134
-// NewFormatter for formatting details.
135
-//
136
-// This function is shorthand for the following syntax:
137
-//
138
-//	fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b))
139
-func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
140
-	return fmt.Fprintf(w, format, c.convertArgs(a)...)
141
-}
142
-
143
-// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
144
-// passed with a Formatter interface returned by c.NewFormatter.  See
145
-// NewFormatter for formatting details.
146
-//
147
-// This function is shorthand for the following syntax:
148
-//
149
-//	fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b))
150
-func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
151
-	return fmt.Fprintln(w, c.convertArgs(a)...)
152
-}
153
-
154
-// Print is a wrapper for fmt.Print that treats each argument as if it were
155
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
156
-// the number of bytes written and any write error encountered.  See
157
-// NewFormatter for formatting details.
158
-//
159
-// This function is shorthand for the following syntax:
160
-//
161
-//	fmt.Print(c.NewFormatter(a), c.NewFormatter(b))
162
-func (c *ConfigState) Print(a ...interface{}) (n int, err error) {
163
-	return fmt.Print(c.convertArgs(a)...)
164
-}
165
-
166
-// Printf is a wrapper for fmt.Printf that treats each argument as if it were
167
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
168
-// the number of bytes written and any write error encountered.  See
169
-// NewFormatter for formatting details.
170
-//
171
-// This function is shorthand for the following syntax:
172
-//
173
-//	fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b))
174
-func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) {
175
-	return fmt.Printf(format, c.convertArgs(a)...)
176
-}
177
-
178
-// Println is a wrapper for fmt.Println that treats each argument as if it were
179
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
180
-// the number of bytes written and any write error encountered.  See
181
-// NewFormatter for formatting details.
182
-//
183
-// This function is shorthand for the following syntax:
184
-//
185
-//	fmt.Println(c.NewFormatter(a), c.NewFormatter(b))
186
-func (c *ConfigState) Println(a ...interface{}) (n int, err error) {
187
-	return fmt.Println(c.convertArgs(a)...)
188
-}
189
-
190
-// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
191
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
192
-// the resulting string.  See NewFormatter for formatting details.
193
-//
194
-// This function is shorthand for the following syntax:
195
-//
196
-//	fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b))
197
-func (c *ConfigState) Sprint(a ...interface{}) string {
198
-	return fmt.Sprint(c.convertArgs(a)...)
199
-}
200
-
201
-// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
202
-// passed with a Formatter interface returned by c.NewFormatter.  It returns
203
-// the resulting string.  See NewFormatter for formatting details.
204
-//
205
-// This function is shorthand for the following syntax:
206
-//
207
-//	fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b))
208
-func (c *ConfigState) Sprintf(format string, a ...interface{}) string {
209
-	return fmt.Sprintf(format, c.convertArgs(a)...)
210
-}
211
-
212
-// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
213
-// were passed with a Formatter interface returned by c.NewFormatter.  It
214
-// returns the resulting string.  See NewFormatter for formatting details.
215
-//
216
-// This function is shorthand for the following syntax:
217
-//
218
-//	fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b))
219
-func (c *ConfigState) Sprintln(a ...interface{}) string {
220
-	return fmt.Sprintln(c.convertArgs(a)...)
221
-}
222
-
223
-/*
224
-NewFormatter returns a custom formatter that satisfies the fmt.Formatter
225
-interface.  As a result, it integrates cleanly with standard fmt package
226
-printing functions.  The formatter is useful for inline printing of smaller data
227
-types similar to the standard %v format specifier.
228
-
229
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
230
-addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb
231
-combinations.  Any other verbs such as %x and %q will be sent to the the
232
-standard fmt package for formatting.  In addition, the custom formatter ignores
233
-the width and precision arguments (however they will still work on the format
234
-specifiers not handled by the custom formatter).
235
-
236
-Typically this function shouldn't be called directly.  It is much easier to make
237
-use of the custom formatter by calling one of the convenience functions such as
238
-c.Printf, c.Println, or c.Printf.
239
-*/
240
-func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter {
241
-	return newFormatter(c, v)
242
-}
243
-
244
-// Fdump formats and displays the passed arguments to io.Writer w.  It formats
245
-// exactly the same as Dump.
246
-func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) {
247
-	fdump(c, w, a...)
248
-}
249
-
250
-/*
251
-Dump displays the passed parameters to standard out with newlines, customizable
252
-indentation, and additional debug information such as complete types and all
253
-pointer addresses used to indirect to the final value.  It provides the
254
-following features over the built-in printing facilities provided by the fmt
255
-package:
256
-
257
-	* Pointers are dereferenced and followed
258
-	* Circular data structures are detected and handled properly
259
-	* Custom Stringer/error interfaces are optionally invoked, including
260
-	  on unexported types
261
-	* Custom types which only implement the Stringer/error interfaces via
262
-	  a pointer receiver are optionally invoked when passing non-pointer
263
-	  variables
264
-	* Byte arrays and slices are dumped like the hexdump -C command which
265
-	  includes offsets, byte values in hex, and ASCII output
266
-
267
-The configuration options are controlled by modifying the public members
268
-of c.  See ConfigState for options documentation.
269
-
270
-See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
271
-get the formatted result as a string.
272
-*/
273
-func (c *ConfigState) Dump(a ...interface{}) {
274
-	fdump(c, os.Stdout, a...)
275
-}
276
-
277
-// Sdump returns a string with the passed arguments formatted exactly the same
278
-// as Dump.
279
-func (c *ConfigState) Sdump(a ...interface{}) string {
280
-	var buf bytes.Buffer
281
-	fdump(c, &buf, a...)
282
-	return buf.String()
283
-}
284
-
285
-// convertArgs accepts a slice of arguments and returns a slice of the same
286
-// length with each argument converted to a spew Formatter interface using
287
-// the ConfigState associated with s.
288
-func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) {
289
-	formatters = make([]interface{}, len(args))
290
-	for index, arg := range args {
291
-		formatters[index] = newFormatter(c, arg)
292
-	}
293
-	return formatters
294
-}
295
-
296
-// NewDefaultConfig returns a ConfigState with the following default settings.
297
-//
298
-// 	Indent: " "
299
-// 	MaxDepth: 0
300
-// 	DisableMethods: false
301
-// 	DisablePointerMethods: false
302
-// 	ContinueOnMethod: false
303
-// 	SortKeys: false
304
-func NewDefaultConfig() *ConfigState {
305
-	return &ConfigState{Indent: " "}
306
-}
307 1
deleted file mode 100644
... ...
@@ -1,211 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-/*
18
-Package spew implements a deep pretty printer for Go data structures to aid in
19
-debugging.
20
-
21
-A quick overview of the additional features spew provides over the built-in
22
-printing facilities for Go data types are as follows:
23
-
24
-	* Pointers are dereferenced and followed
25
-	* Circular data structures are detected and handled properly
26
-	* Custom Stringer/error interfaces are optionally invoked, including
27
-	  on unexported types
28
-	* Custom types which only implement the Stringer/error interfaces via
29
-	  a pointer receiver are optionally invoked when passing non-pointer
30
-	  variables
31
-	* Byte arrays and slices are dumped like the hexdump -C command which
32
-	  includes offsets, byte values in hex, and ASCII output (only when using
33
-	  Dump style)
34
-
35
-There are two different approaches spew allows for dumping Go data structures:
36
-
37
-	* Dump style which prints with newlines, customizable indentation,
38
-	  and additional debug information such as types and all pointer addresses
39
-	  used to indirect to the final value
40
-	* A custom Formatter interface that integrates cleanly with the standard fmt
41
-	  package and replaces %v, %+v, %#v, and %#+v to provide inline printing
42
-	  similar to the default %v while providing the additional functionality
43
-	  outlined above and passing unsupported format verbs such as %x and %q
44
-	  along to fmt
45
-
46
-Quick Start
47
-
48
-This section demonstrates how to quickly get started with spew.  See the
49
-sections below for further details on formatting and configuration options.
50
-
51
-To dump a variable with full newlines, indentation, type, and pointer
52
-information use Dump, Fdump, or Sdump:
53
-	spew.Dump(myVar1, myVar2, ...)
54
-	spew.Fdump(someWriter, myVar1, myVar2, ...)
55
-	str := spew.Sdump(myVar1, myVar2, ...)
56
-
57
-Alternatively, if you would prefer to use format strings with a compacted inline
58
-printing style, use the convenience wrappers Printf, Fprintf, etc with
59
-%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
60
-%#+v (adds types and pointer addresses):
61
-	spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
62
-	spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
63
-	spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
64
-	spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
65
-
66
-Configuration Options
67
-
68
-Configuration of spew is handled by fields in the ConfigState type.  For
69
-convenience, all of the top-level functions use a global state available
70
-via the spew.Config global.
71
-
72
-It is also possible to create a ConfigState instance that provides methods
73
-equivalent to the top-level functions.  This allows concurrent configuration
74
-options.  See the ConfigState documentation for more details.
75
-
76
-The following configuration options are available:
77
-	* Indent
78
-		String to use for each indentation level for Dump functions.
79
-		It is a single space by default.  A popular alternative is "\t".
80
-
81
-	* MaxDepth
82
-		Maximum number of levels to descend into nested data structures.
83
-		There is no limit by default.
84
-
85
-	* DisableMethods
86
-		Disables invocation of error and Stringer interface methods.
87
-		Method invocation is enabled by default.
88
-
89
-	* DisablePointerMethods
90
-		Disables invocation of error and Stringer interface methods on types
91
-		which only accept pointer receivers from non-pointer variables.
92
-		Pointer method invocation is enabled by default.
93
-
94
-	* DisablePointerAddresses
95
-		DisablePointerAddresses specifies whether to disable the printing of
96
-		pointer addresses. This is useful when diffing data structures in tests.
97
-
98
-	* DisableCapacities
99
-		DisableCapacities specifies whether to disable the printing of
100
-		capacities for arrays, slices, maps and channels. This is useful when
101
-		diffing data structures in tests.
102
-
103
-	* ContinueOnMethod
104
-		Enables recursion into types after invoking error and Stringer interface
105
-		methods. Recursion after method invocation is disabled by default.
106
-
107
-	* SortKeys
108
-		Specifies map keys should be sorted before being printed. Use
109
-		this to have a more deterministic, diffable output.  Note that
110
-		only native types (bool, int, uint, floats, uintptr and string)
111
-		and types which implement error or Stringer interfaces are
112
-		supported with other types sorted according to the
113
-		reflect.Value.String() output which guarantees display
114
-		stability.  Natural map order is used by default.
115
-
116
-	* SpewKeys
117
-		Specifies that, as a last resort attempt, map keys should be
118
-		spewed to strings and sorted by those strings.  This is only
119
-		considered if SortKeys is true.
120
-
121
-Dump Usage
122
-
123
-Simply call spew.Dump with a list of variables you want to dump:
124
-
125
-	spew.Dump(myVar1, myVar2, ...)
126
-
127
-You may also call spew.Fdump if you would prefer to output to an arbitrary
128
-io.Writer.  For example, to dump to standard error:
129
-
130
-	spew.Fdump(os.Stderr, myVar1, myVar2, ...)
131
-
132
-A third option is to call spew.Sdump to get the formatted output as a string:
133
-
134
-	str := spew.Sdump(myVar1, myVar2, ...)
135
-
136
-Sample Dump Output
137
-
138
-See the Dump example for details on the setup of the types and variables being
139
-shown here.
140
-
141
-	(main.Foo) {
142
-	 unexportedField: (*main.Bar)(0xf84002e210)({
143
-	  flag: (main.Flag) flagTwo,
144
-	  data: (uintptr) <nil>
145
-	 }),
146
-	 ExportedField: (map[interface {}]interface {}) (len=1) {
147
-	  (string) (len=3) "one": (bool) true
148
-	 }
149
-	}
150
-
151
-Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
152
-command as shown.
153
-	([]uint8) (len=32 cap=32) {
154
-	 00000000  11 12 13 14 15 16 17 18  19 1a 1b 1c 1d 1e 1f 20  |............... |
155
-	 00000010  21 22 23 24 25 26 27 28  29 2a 2b 2c 2d 2e 2f 30  |!"#$%&'()*+,-./0|
156
-	 00000020  31 32                                             |12|
157
-	}
158
-
159
-Custom Formatter
160
-
161
-Spew provides a custom formatter that implements the fmt.Formatter interface
162
-so that it integrates cleanly with standard fmt package printing functions. The
163
-formatter is useful for inline printing of smaller data types similar to the
164
-standard %v format specifier.
165
-
166
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
167
-addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
168
-combinations.  Any other verbs such as %x and %q will be sent to the the
169
-standard fmt package for formatting.  In addition, the custom formatter ignores
170
-the width and precision arguments (however they will still work on the format
171
-specifiers not handled by the custom formatter).
172
-
173
-Custom Formatter Usage
174
-
175
-The simplest way to make use of the spew custom formatter is to call one of the
176
-convenience functions such as spew.Printf, spew.Println, or spew.Printf.  The
177
-functions have syntax you are most likely already familiar with:
178
-
179
-	spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
180
-	spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
181
-	spew.Println(myVar, myVar2)
182
-	spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
183
-	spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
184
-
185
-See the Index for the full list convenience functions.
186
-
187
-Sample Formatter Output
188
-
189
-Double pointer to a uint8:
190
-	  %v: <**>5
191
-	 %+v: <**>(0xf8400420d0->0xf8400420c8)5
192
-	 %#v: (**uint8)5
193
-	%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
194
-
195
-Pointer to circular struct with a uint8 field and a pointer to itself:
196
-	  %v: <*>{1 <*><shown>}
197
-	 %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
198
-	 %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
199
-	%#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
200
-
201
-See the Printf example for details on the setup of variables being shown
202
-here.
203
-
204
-Errors
205
-
206
-Since it is possible for custom Stringer/error interfaces to panic, spew
207
-detects them and handles them internally by printing the panic information
208
-inline with the output.  Since spew is intended to provide deep pretty printing
209
-capabilities on structures, it intentionally does not return any errors.
210
-*/
211
-package spew
212 1
deleted file mode 100644
... ...
@@ -1,509 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-package spew
18
-
19
-import (
20
-	"bytes"
21
-	"encoding/hex"
22
-	"fmt"
23
-	"io"
24
-	"os"
25
-	"reflect"
26
-	"regexp"
27
-	"strconv"
28
-	"strings"
29
-)
30
-
31
-var (
32
-	// uint8Type is a reflect.Type representing a uint8.  It is used to
33
-	// convert cgo types to uint8 slices for hexdumping.
34
-	uint8Type = reflect.TypeOf(uint8(0))
35
-
36
-	// cCharRE is a regular expression that matches a cgo char.
37
-	// It is used to detect character arrays to hexdump them.
38
-	cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
39
-
40
-	// cUnsignedCharRE is a regular expression that matches a cgo unsigned
41
-	// char.  It is used to detect unsigned character arrays to hexdump
42
-	// them.
43
-	cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
44
-
45
-	// cUint8tCharRE is a regular expression that matches a cgo uint8_t.
46
-	// It is used to detect uint8_t arrays to hexdump them.
47
-	cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
48
-)
49
-
50
-// dumpState contains information about the state of a dump operation.
51
-type dumpState struct {
52
-	w                io.Writer
53
-	depth            int
54
-	pointers         map[uintptr]int
55
-	ignoreNextType   bool
56
-	ignoreNextIndent bool
57
-	cs               *ConfigState
58
-}
59
-
60
-// indent performs indentation according to the depth level and cs.Indent
61
-// option.
62
-func (d *dumpState) indent() {
63
-	if d.ignoreNextIndent {
64
-		d.ignoreNextIndent = false
65
-		return
66
-	}
67
-	d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
68
-}
69
-
70
-// unpackValue returns values inside of non-nil interfaces when possible.
71
-// This is useful for data types like structs, arrays, slices, and maps which
72
-// can contain varying types packed inside an interface.
73
-func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
74
-	if v.Kind() == reflect.Interface && !v.IsNil() {
75
-		v = v.Elem()
76
-	}
77
-	return v
78
-}
79
-
80
-// dumpPtr handles formatting of pointers by indirecting them as necessary.
81
-func (d *dumpState) dumpPtr(v reflect.Value) {
82
-	// Remove pointers at or below the current depth from map used to detect
83
-	// circular refs.
84
-	for k, depth := range d.pointers {
85
-		if depth >= d.depth {
86
-			delete(d.pointers, k)
87
-		}
88
-	}
89
-
90
-	// Keep list of all dereferenced pointers to show later.
91
-	pointerChain := make([]uintptr, 0)
92
-
93
-	// Figure out how many levels of indirection there are by dereferencing
94
-	// pointers and unpacking interfaces down the chain while detecting circular
95
-	// references.
96
-	nilFound := false
97
-	cycleFound := false
98
-	indirects := 0
99
-	ve := v
100
-	for ve.Kind() == reflect.Ptr {
101
-		if ve.IsNil() {
102
-			nilFound = true
103
-			break
104
-		}
105
-		indirects++
106
-		addr := ve.Pointer()
107
-		pointerChain = append(pointerChain, addr)
108
-		if pd, ok := d.pointers[addr]; ok && pd < d.depth {
109
-			cycleFound = true
110
-			indirects--
111
-			break
112
-		}
113
-		d.pointers[addr] = d.depth
114
-
115
-		ve = ve.Elem()
116
-		if ve.Kind() == reflect.Interface {
117
-			if ve.IsNil() {
118
-				nilFound = true
119
-				break
120
-			}
121
-			ve = ve.Elem()
122
-		}
123
-	}
124
-
125
-	// Display type information.
126
-	d.w.Write(openParenBytes)
127
-	d.w.Write(bytes.Repeat(asteriskBytes, indirects))
128
-	d.w.Write([]byte(ve.Type().String()))
129
-	d.w.Write(closeParenBytes)
130
-
131
-	// Display pointer information.
132
-	if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 {
133
-		d.w.Write(openParenBytes)
134
-		for i, addr := range pointerChain {
135
-			if i > 0 {
136
-				d.w.Write(pointerChainBytes)
137
-			}
138
-			printHexPtr(d.w, addr)
139
-		}
140
-		d.w.Write(closeParenBytes)
141
-	}
142
-
143
-	// Display dereferenced value.
144
-	d.w.Write(openParenBytes)
145
-	switch {
146
-	case nilFound == true:
147
-		d.w.Write(nilAngleBytes)
148
-
149
-	case cycleFound == true:
150
-		d.w.Write(circularBytes)
151
-
152
-	default:
153
-		d.ignoreNextType = true
154
-		d.dump(ve)
155
-	}
156
-	d.w.Write(closeParenBytes)
157
-}
158
-
159
-// dumpSlice handles formatting of arrays and slices.  Byte (uint8 under
160
-// reflection) arrays and slices are dumped in hexdump -C fashion.
161
-func (d *dumpState) dumpSlice(v reflect.Value) {
162
-	// Determine whether this type should be hex dumped or not.  Also,
163
-	// for types which should be hexdumped, try to use the underlying data
164
-	// first, then fall back to trying to convert them to a uint8 slice.
165
-	var buf []uint8
166
-	doConvert := false
167
-	doHexDump := false
168
-	numEntries := v.Len()
169
-	if numEntries > 0 {
170
-		vt := v.Index(0).Type()
171
-		vts := vt.String()
172
-		switch {
173
-		// C types that need to be converted.
174
-		case cCharRE.MatchString(vts):
175
-			fallthrough
176
-		case cUnsignedCharRE.MatchString(vts):
177
-			fallthrough
178
-		case cUint8tCharRE.MatchString(vts):
179
-			doConvert = true
180
-
181
-		// Try to use existing uint8 slices and fall back to converting
182
-		// and copying if that fails.
183
-		case vt.Kind() == reflect.Uint8:
184
-			// We need an addressable interface to convert the type
185
-			// to a byte slice.  However, the reflect package won't
186
-			// give us an interface on certain things like
187
-			// unexported struct fields in order to enforce
188
-			// visibility rules.  We use unsafe, when available, to
189
-			// bypass these restrictions since this package does not
190
-			// mutate the values.
191
-			vs := v
192
-			if !vs.CanInterface() || !vs.CanAddr() {
193
-				vs = unsafeReflectValue(vs)
194
-			}
195
-			if !UnsafeDisabled {
196
-				vs = vs.Slice(0, numEntries)
197
-
198
-				// Use the existing uint8 slice if it can be
199
-				// type asserted.
200
-				iface := vs.Interface()
201
-				if slice, ok := iface.([]uint8); ok {
202
-					buf = slice
203
-					doHexDump = true
204
-					break
205
-				}
206
-			}
207
-
208
-			// The underlying data needs to be converted if it can't
209
-			// be type asserted to a uint8 slice.
210
-			doConvert = true
211
-		}
212
-
213
-		// Copy and convert the underlying type if needed.
214
-		if doConvert && vt.ConvertibleTo(uint8Type) {
215
-			// Convert and copy each element into a uint8 byte
216
-			// slice.
217
-			buf = make([]uint8, numEntries)
218
-			for i := 0; i < numEntries; i++ {
219
-				vv := v.Index(i)
220
-				buf[i] = uint8(vv.Convert(uint8Type).Uint())
221
-			}
222
-			doHexDump = true
223
-		}
224
-	}
225
-
226
-	// Hexdump the entire slice as needed.
227
-	if doHexDump {
228
-		indent := strings.Repeat(d.cs.Indent, d.depth)
229
-		str := indent + hex.Dump(buf)
230
-		str = strings.Replace(str, "\n", "\n"+indent, -1)
231
-		str = strings.TrimRight(str, d.cs.Indent)
232
-		d.w.Write([]byte(str))
233
-		return
234
-	}
235
-
236
-	// Recursively call dump for each item.
237
-	for i := 0; i < numEntries; i++ {
238
-		d.dump(d.unpackValue(v.Index(i)))
239
-		if i < (numEntries - 1) {
240
-			d.w.Write(commaNewlineBytes)
241
-		} else {
242
-			d.w.Write(newlineBytes)
243
-		}
244
-	}
245
-}
246
-
247
-// dump is the main workhorse for dumping a value.  It uses the passed reflect
248
-// value to figure out what kind of object we are dealing with and formats it
249
-// appropriately.  It is a recursive function, however circular data structures
250
-// are detected and handled properly.
251
-func (d *dumpState) dump(v reflect.Value) {
252
-	// Handle invalid reflect values immediately.
253
-	kind := v.Kind()
254
-	if kind == reflect.Invalid {
255
-		d.w.Write(invalidAngleBytes)
256
-		return
257
-	}
258
-
259
-	// Handle pointers specially.
260
-	if kind == reflect.Ptr {
261
-		d.indent()
262
-		d.dumpPtr(v)
263
-		return
264
-	}
265
-
266
-	// Print type information unless already handled elsewhere.
267
-	if !d.ignoreNextType {
268
-		d.indent()
269
-		d.w.Write(openParenBytes)
270
-		d.w.Write([]byte(v.Type().String()))
271
-		d.w.Write(closeParenBytes)
272
-		d.w.Write(spaceBytes)
273
-	}
274
-	d.ignoreNextType = false
275
-
276
-	// Display length and capacity if the built-in len and cap functions
277
-	// work with the value's kind and the len/cap itself is non-zero.
278
-	valueLen, valueCap := 0, 0
279
-	switch v.Kind() {
280
-	case reflect.Array, reflect.Slice, reflect.Chan:
281
-		valueLen, valueCap = v.Len(), v.Cap()
282
-	case reflect.Map, reflect.String:
283
-		valueLen = v.Len()
284
-	}
285
-	if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 {
286
-		d.w.Write(openParenBytes)
287
-		if valueLen != 0 {
288
-			d.w.Write(lenEqualsBytes)
289
-			printInt(d.w, int64(valueLen), 10)
290
-		}
291
-		if !d.cs.DisableCapacities && valueCap != 0 {
292
-			if valueLen != 0 {
293
-				d.w.Write(spaceBytes)
294
-			}
295
-			d.w.Write(capEqualsBytes)
296
-			printInt(d.w, int64(valueCap), 10)
297
-		}
298
-		d.w.Write(closeParenBytes)
299
-		d.w.Write(spaceBytes)
300
-	}
301
-
302
-	// Call Stringer/error interfaces if they exist and the handle methods flag
303
-	// is enabled
304
-	if !d.cs.DisableMethods {
305
-		if (kind != reflect.Invalid) && (kind != reflect.Interface) {
306
-			if handled := handleMethods(d.cs, d.w, v); handled {
307
-				return
308
-			}
309
-		}
310
-	}
311
-
312
-	switch kind {
313
-	case reflect.Invalid:
314
-		// Do nothing.  We should never get here since invalid has already
315
-		// been handled above.
316
-
317
-	case reflect.Bool:
318
-		printBool(d.w, v.Bool())
319
-
320
-	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
321
-		printInt(d.w, v.Int(), 10)
322
-
323
-	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
324
-		printUint(d.w, v.Uint(), 10)
325
-
326
-	case reflect.Float32:
327
-		printFloat(d.w, v.Float(), 32)
328
-
329
-	case reflect.Float64:
330
-		printFloat(d.w, v.Float(), 64)
331
-
332
-	case reflect.Complex64:
333
-		printComplex(d.w, v.Complex(), 32)
334
-
335
-	case reflect.Complex128:
336
-		printComplex(d.w, v.Complex(), 64)
337
-
338
-	case reflect.Slice:
339
-		if v.IsNil() {
340
-			d.w.Write(nilAngleBytes)
341
-			break
342
-		}
343
-		fallthrough
344
-
345
-	case reflect.Array:
346
-		d.w.Write(openBraceNewlineBytes)
347
-		d.depth++
348
-		if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
349
-			d.indent()
350
-			d.w.Write(maxNewlineBytes)
351
-		} else {
352
-			d.dumpSlice(v)
353
-		}
354
-		d.depth--
355
-		d.indent()
356
-		d.w.Write(closeBraceBytes)
357
-
358
-	case reflect.String:
359
-		d.w.Write([]byte(strconv.Quote(v.String())))
360
-
361
-	case reflect.Interface:
362
-		// The only time we should get here is for nil interfaces due to
363
-		// unpackValue calls.
364
-		if v.IsNil() {
365
-			d.w.Write(nilAngleBytes)
366
-		}
367
-
368
-	case reflect.Ptr:
369
-		// Do nothing.  We should never get here since pointers have already
370
-		// been handled above.
371
-
372
-	case reflect.Map:
373
-		// nil maps should be indicated as different than empty maps
374
-		if v.IsNil() {
375
-			d.w.Write(nilAngleBytes)
376
-			break
377
-		}
378
-
379
-		d.w.Write(openBraceNewlineBytes)
380
-		d.depth++
381
-		if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
382
-			d.indent()
383
-			d.w.Write(maxNewlineBytes)
384
-		} else {
385
-			numEntries := v.Len()
386
-			keys := v.MapKeys()
387
-			if d.cs.SortKeys {
388
-				sortValues(keys, d.cs)
389
-			}
390
-			for i, key := range keys {
391
-				d.dump(d.unpackValue(key))
392
-				d.w.Write(colonSpaceBytes)
393
-				d.ignoreNextIndent = true
394
-				d.dump(d.unpackValue(v.MapIndex(key)))
395
-				if i < (numEntries - 1) {
396
-					d.w.Write(commaNewlineBytes)
397
-				} else {
398
-					d.w.Write(newlineBytes)
399
-				}
400
-			}
401
-		}
402
-		d.depth--
403
-		d.indent()
404
-		d.w.Write(closeBraceBytes)
405
-
406
-	case reflect.Struct:
407
-		d.w.Write(openBraceNewlineBytes)
408
-		d.depth++
409
-		if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
410
-			d.indent()
411
-			d.w.Write(maxNewlineBytes)
412
-		} else {
413
-			vt := v.Type()
414
-			numFields := v.NumField()
415
-			for i := 0; i < numFields; i++ {
416
-				d.indent()
417
-				vtf := vt.Field(i)
418
-				d.w.Write([]byte(vtf.Name))
419
-				d.w.Write(colonSpaceBytes)
420
-				d.ignoreNextIndent = true
421
-				d.dump(d.unpackValue(v.Field(i)))
422
-				if i < (numFields - 1) {
423
-					d.w.Write(commaNewlineBytes)
424
-				} else {
425
-					d.w.Write(newlineBytes)
426
-				}
427
-			}
428
-		}
429
-		d.depth--
430
-		d.indent()
431
-		d.w.Write(closeBraceBytes)
432
-
433
-	case reflect.Uintptr:
434
-		printHexPtr(d.w, uintptr(v.Uint()))
435
-
436
-	case reflect.UnsafePointer, reflect.Chan, reflect.Func:
437
-		printHexPtr(d.w, v.Pointer())
438
-
439
-	// There were not any other types at the time this code was written, but
440
-	// fall back to letting the default fmt package handle it in case any new
441
-	// types are added.
442
-	default:
443
-		if v.CanInterface() {
444
-			fmt.Fprintf(d.w, "%v", v.Interface())
445
-		} else {
446
-			fmt.Fprintf(d.w, "%v", v.String())
447
-		}
448
-	}
449
-}
450
-
451
-// fdump is a helper function to consolidate the logic from the various public
452
-// methods which take varying writers and config states.
453
-func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
454
-	for _, arg := range a {
455
-		if arg == nil {
456
-			w.Write(interfaceBytes)
457
-			w.Write(spaceBytes)
458
-			w.Write(nilAngleBytes)
459
-			w.Write(newlineBytes)
460
-			continue
461
-		}
462
-
463
-		d := dumpState{w: w, cs: cs}
464
-		d.pointers = make(map[uintptr]int)
465
-		d.dump(reflect.ValueOf(arg))
466
-		d.w.Write(newlineBytes)
467
-	}
468
-}
469
-
470
-// Fdump formats and displays the passed arguments to io.Writer w.  It formats
471
-// exactly the same as Dump.
472
-func Fdump(w io.Writer, a ...interface{}) {
473
-	fdump(&Config, w, a...)
474
-}
475
-
476
-// Sdump returns a string with the passed arguments formatted exactly the same
477
-// as Dump.
478
-func Sdump(a ...interface{}) string {
479
-	var buf bytes.Buffer
480
-	fdump(&Config, &buf, a...)
481
-	return buf.String()
482
-}
483
-
484
-/*
485
-Dump displays the passed parameters to standard out with newlines, customizable
486
-indentation, and additional debug information such as complete types and all
487
-pointer addresses used to indirect to the final value.  It provides the
488
-following features over the built-in printing facilities provided by the fmt
489
-package:
490
-
491
-	* Pointers are dereferenced and followed
492
-	* Circular data structures are detected and handled properly
493
-	* Custom Stringer/error interfaces are optionally invoked, including
494
-	  on unexported types
495
-	* Custom types which only implement the Stringer/error interfaces via
496
-	  a pointer receiver are optionally invoked when passing non-pointer
497
-	  variables
498
-	* Byte arrays and slices are dumped like the hexdump -C command which
499
-	  includes offsets, byte values in hex, and ASCII output
500
-
501
-The configuration options are controlled by an exported package global,
502
-spew.Config.  See ConfigState for options documentation.
503
-
504
-See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
505
-get the formatted result as a string.
506
-*/
507
-func Dump(a ...interface{}) {
508
-	fdump(&Config, os.Stdout, a...)
509
-}
510 1
deleted file mode 100644
... ...
@@ -1,419 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-package spew
18
-
19
-import (
20
-	"bytes"
21
-	"fmt"
22
-	"reflect"
23
-	"strconv"
24
-	"strings"
25
-)
26
-
27
-// supportedFlags is a list of all the character flags supported by fmt package.
28
-const supportedFlags = "0-+# "
29
-
30
-// formatState implements the fmt.Formatter interface and contains information
31
-// about the state of a formatting operation.  The NewFormatter function can
32
-// be used to get a new Formatter which can be used directly as arguments
33
-// in standard fmt package printing calls.
34
-type formatState struct {
35
-	value          interface{}
36
-	fs             fmt.State
37
-	depth          int
38
-	pointers       map[uintptr]int
39
-	ignoreNextType bool
40
-	cs             *ConfigState
41
-}
42
-
43
-// buildDefaultFormat recreates the original format string without precision
44
-// and width information to pass in to fmt.Sprintf in the case of an
45
-// unrecognized type.  Unless new types are added to the language, this
46
-// function won't ever be called.
47
-func (f *formatState) buildDefaultFormat() (format string) {
48
-	buf := bytes.NewBuffer(percentBytes)
49
-
50
-	for _, flag := range supportedFlags {
51
-		if f.fs.Flag(int(flag)) {
52
-			buf.WriteRune(flag)
53
-		}
54
-	}
55
-
56
-	buf.WriteRune('v')
57
-
58
-	format = buf.String()
59
-	return format
60
-}
61
-
62
-// constructOrigFormat recreates the original format string including precision
63
-// and width information to pass along to the standard fmt package.  This allows
64
-// automatic deferral of all format strings this package doesn't support.
65
-func (f *formatState) constructOrigFormat(verb rune) (format string) {
66
-	buf := bytes.NewBuffer(percentBytes)
67
-
68
-	for _, flag := range supportedFlags {
69
-		if f.fs.Flag(int(flag)) {
70
-			buf.WriteRune(flag)
71
-		}
72
-	}
73
-
74
-	if width, ok := f.fs.Width(); ok {
75
-		buf.WriteString(strconv.Itoa(width))
76
-	}
77
-
78
-	if precision, ok := f.fs.Precision(); ok {
79
-		buf.Write(precisionBytes)
80
-		buf.WriteString(strconv.Itoa(precision))
81
-	}
82
-
83
-	buf.WriteRune(verb)
84
-
85
-	format = buf.String()
86
-	return format
87
-}
88
-
89
-// unpackValue returns values inside of non-nil interfaces when possible and
90
-// ensures that types for values which have been unpacked from an interface
91
-// are displayed when the show types flag is also set.
92
-// This is useful for data types like structs, arrays, slices, and maps which
93
-// can contain varying types packed inside an interface.
94
-func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
95
-	if v.Kind() == reflect.Interface {
96
-		f.ignoreNextType = false
97
-		if !v.IsNil() {
98
-			v = v.Elem()
99
-		}
100
-	}
101
-	return v
102
-}
103
-
104
-// formatPtr handles formatting of pointers by indirecting them as necessary.
105
-func (f *formatState) formatPtr(v reflect.Value) {
106
-	// Display nil if top level pointer is nil.
107
-	showTypes := f.fs.Flag('#')
108
-	if v.IsNil() && (!showTypes || f.ignoreNextType) {
109
-		f.fs.Write(nilAngleBytes)
110
-		return
111
-	}
112
-
113
-	// Remove pointers at or below the current depth from map used to detect
114
-	// circular refs.
115
-	for k, depth := range f.pointers {
116
-		if depth >= f.depth {
117
-			delete(f.pointers, k)
118
-		}
119
-	}
120
-
121
-	// Keep list of all dereferenced pointers to possibly show later.
122
-	pointerChain := make([]uintptr, 0)
123
-
124
-	// Figure out how many levels of indirection there are by derferencing
125
-	// pointers and unpacking interfaces down the chain while detecting circular
126
-	// references.
127
-	nilFound := false
128
-	cycleFound := false
129
-	indirects := 0
130
-	ve := v
131
-	for ve.Kind() == reflect.Ptr {
132
-		if ve.IsNil() {
133
-			nilFound = true
134
-			break
135
-		}
136
-		indirects++
137
-		addr := ve.Pointer()
138
-		pointerChain = append(pointerChain, addr)
139
-		if pd, ok := f.pointers[addr]; ok && pd < f.depth {
140
-			cycleFound = true
141
-			indirects--
142
-			break
143
-		}
144
-		f.pointers[addr] = f.depth
145
-
146
-		ve = ve.Elem()
147
-		if ve.Kind() == reflect.Interface {
148
-			if ve.IsNil() {
149
-				nilFound = true
150
-				break
151
-			}
152
-			ve = ve.Elem()
153
-		}
154
-	}
155
-
156
-	// Display type or indirection level depending on flags.
157
-	if showTypes && !f.ignoreNextType {
158
-		f.fs.Write(openParenBytes)
159
-		f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
160
-		f.fs.Write([]byte(ve.Type().String()))
161
-		f.fs.Write(closeParenBytes)
162
-	} else {
163
-		if nilFound || cycleFound {
164
-			indirects += strings.Count(ve.Type().String(), "*")
165
-		}
166
-		f.fs.Write(openAngleBytes)
167
-		f.fs.Write([]byte(strings.Repeat("*", indirects)))
168
-		f.fs.Write(closeAngleBytes)
169
-	}
170
-
171
-	// Display pointer information depending on flags.
172
-	if f.fs.Flag('+') && (len(pointerChain) > 0) {
173
-		f.fs.Write(openParenBytes)
174
-		for i, addr := range pointerChain {
175
-			if i > 0 {
176
-				f.fs.Write(pointerChainBytes)
177
-			}
178
-			printHexPtr(f.fs, addr)
179
-		}
180
-		f.fs.Write(closeParenBytes)
181
-	}
182
-
183
-	// Display dereferenced value.
184
-	switch {
185
-	case nilFound == true:
186
-		f.fs.Write(nilAngleBytes)
187
-
188
-	case cycleFound == true:
189
-		f.fs.Write(circularShortBytes)
190
-
191
-	default:
192
-		f.ignoreNextType = true
193
-		f.format(ve)
194
-	}
195
-}
196
-
197
-// format is the main workhorse for providing the Formatter interface.  It
198
-// uses the passed reflect value to figure out what kind of object we are
199
-// dealing with and formats it appropriately.  It is a recursive function,
200
-// however circular data structures are detected and handled properly.
201
-func (f *formatState) format(v reflect.Value) {
202
-	// Handle invalid reflect values immediately.
203
-	kind := v.Kind()
204
-	if kind == reflect.Invalid {
205
-		f.fs.Write(invalidAngleBytes)
206
-		return
207
-	}
208
-
209
-	// Handle pointers specially.
210
-	if kind == reflect.Ptr {
211
-		f.formatPtr(v)
212
-		return
213
-	}
214
-
215
-	// Print type information unless already handled elsewhere.
216
-	if !f.ignoreNextType && f.fs.Flag('#') {
217
-		f.fs.Write(openParenBytes)
218
-		f.fs.Write([]byte(v.Type().String()))
219
-		f.fs.Write(closeParenBytes)
220
-	}
221
-	f.ignoreNextType = false
222
-
223
-	// Call Stringer/error interfaces if they exist and the handle methods
224
-	// flag is enabled.
225
-	if !f.cs.DisableMethods {
226
-		if (kind != reflect.Invalid) && (kind != reflect.Interface) {
227
-			if handled := handleMethods(f.cs, f.fs, v); handled {
228
-				return
229
-			}
230
-		}
231
-	}
232
-
233
-	switch kind {
234
-	case reflect.Invalid:
235
-		// Do nothing.  We should never get here since invalid has already
236
-		// been handled above.
237
-
238
-	case reflect.Bool:
239
-		printBool(f.fs, v.Bool())
240
-
241
-	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
242
-		printInt(f.fs, v.Int(), 10)
243
-
244
-	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
245
-		printUint(f.fs, v.Uint(), 10)
246
-
247
-	case reflect.Float32:
248
-		printFloat(f.fs, v.Float(), 32)
249
-
250
-	case reflect.Float64:
251
-		printFloat(f.fs, v.Float(), 64)
252
-
253
-	case reflect.Complex64:
254
-		printComplex(f.fs, v.Complex(), 32)
255
-
256
-	case reflect.Complex128:
257
-		printComplex(f.fs, v.Complex(), 64)
258
-
259
-	case reflect.Slice:
260
-		if v.IsNil() {
261
-			f.fs.Write(nilAngleBytes)
262
-			break
263
-		}
264
-		fallthrough
265
-
266
-	case reflect.Array:
267
-		f.fs.Write(openBracketBytes)
268
-		f.depth++
269
-		if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
270
-			f.fs.Write(maxShortBytes)
271
-		} else {
272
-			numEntries := v.Len()
273
-			for i := 0; i < numEntries; i++ {
274
-				if i > 0 {
275
-					f.fs.Write(spaceBytes)
276
-				}
277
-				f.ignoreNextType = true
278
-				f.format(f.unpackValue(v.Index(i)))
279
-			}
280
-		}
281
-		f.depth--
282
-		f.fs.Write(closeBracketBytes)
283
-
284
-	case reflect.String:
285
-		f.fs.Write([]byte(v.String()))
286
-
287
-	case reflect.Interface:
288
-		// The only time we should get here is for nil interfaces due to
289
-		// unpackValue calls.
290
-		if v.IsNil() {
291
-			f.fs.Write(nilAngleBytes)
292
-		}
293
-
294
-	case reflect.Ptr:
295
-		// Do nothing.  We should never get here since pointers have already
296
-		// been handled above.
297
-
298
-	case reflect.Map:
299
-		// nil maps should be indicated as different than empty maps
300
-		if v.IsNil() {
301
-			f.fs.Write(nilAngleBytes)
302
-			break
303
-		}
304
-
305
-		f.fs.Write(openMapBytes)
306
-		f.depth++
307
-		if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
308
-			f.fs.Write(maxShortBytes)
309
-		} else {
310
-			keys := v.MapKeys()
311
-			if f.cs.SortKeys {
312
-				sortValues(keys, f.cs)
313
-			}
314
-			for i, key := range keys {
315
-				if i > 0 {
316
-					f.fs.Write(spaceBytes)
317
-				}
318
-				f.ignoreNextType = true
319
-				f.format(f.unpackValue(key))
320
-				f.fs.Write(colonBytes)
321
-				f.ignoreNextType = true
322
-				f.format(f.unpackValue(v.MapIndex(key)))
323
-			}
324
-		}
325
-		f.depth--
326
-		f.fs.Write(closeMapBytes)
327
-
328
-	case reflect.Struct:
329
-		numFields := v.NumField()
330
-		f.fs.Write(openBraceBytes)
331
-		f.depth++
332
-		if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
333
-			f.fs.Write(maxShortBytes)
334
-		} else {
335
-			vt := v.Type()
336
-			for i := 0; i < numFields; i++ {
337
-				if i > 0 {
338
-					f.fs.Write(spaceBytes)
339
-				}
340
-				vtf := vt.Field(i)
341
-				if f.fs.Flag('+') || f.fs.Flag('#') {
342
-					f.fs.Write([]byte(vtf.Name))
343
-					f.fs.Write(colonBytes)
344
-				}
345
-				f.format(f.unpackValue(v.Field(i)))
346
-			}
347
-		}
348
-		f.depth--
349
-		f.fs.Write(closeBraceBytes)
350
-
351
-	case reflect.Uintptr:
352
-		printHexPtr(f.fs, uintptr(v.Uint()))
353
-
354
-	case reflect.UnsafePointer, reflect.Chan, reflect.Func:
355
-		printHexPtr(f.fs, v.Pointer())
356
-
357
-	// There were not any other types at the time this code was written, but
358
-	// fall back to letting the default fmt package handle it if any get added.
359
-	default:
360
-		format := f.buildDefaultFormat()
361
-		if v.CanInterface() {
362
-			fmt.Fprintf(f.fs, format, v.Interface())
363
-		} else {
364
-			fmt.Fprintf(f.fs, format, v.String())
365
-		}
366
-	}
367
-}
368
-
369
-// Format satisfies the fmt.Formatter interface. See NewFormatter for usage
370
-// details.
371
-func (f *formatState) Format(fs fmt.State, verb rune) {
372
-	f.fs = fs
373
-
374
-	// Use standard formatting for verbs that are not v.
375
-	if verb != 'v' {
376
-		format := f.constructOrigFormat(verb)
377
-		fmt.Fprintf(fs, format, f.value)
378
-		return
379
-	}
380
-
381
-	if f.value == nil {
382
-		if fs.Flag('#') {
383
-			fs.Write(interfaceBytes)
384
-		}
385
-		fs.Write(nilAngleBytes)
386
-		return
387
-	}
388
-
389
-	f.format(reflect.ValueOf(f.value))
390
-}
391
-
392
-// newFormatter is a helper function to consolidate the logic from the various
393
-// public methods which take varying config states.
394
-func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
395
-	fs := &formatState{value: v, cs: cs}
396
-	fs.pointers = make(map[uintptr]int)
397
-	return fs
398
-}
399
-
400
-/*
401
-NewFormatter returns a custom formatter that satisfies the fmt.Formatter
402
-interface.  As a result, it integrates cleanly with standard fmt package
403
-printing functions.  The formatter is useful for inline printing of smaller data
404
-types similar to the standard %v format specifier.
405
-
406
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
407
-addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
408
-combinations.  Any other verbs such as %x and %q will be sent to the the
409
-standard fmt package for formatting.  In addition, the custom formatter ignores
410
-the width and precision arguments (however they will still work on the format
411
-specifiers not handled by the custom formatter).
412
-
413
-Typically this function shouldn't be called directly.  It is much easier to make
414
-use of the custom formatter by calling one of the convenience functions such as
415
-Printf, Println, or Fprintf.
416
-*/
417
-func NewFormatter(v interface{}) fmt.Formatter {
418
-	return newFormatter(&Config, v)
419
-}
420 1
deleted file mode 100644
... ...
@@ -1,148 +0,0 @@
1
-/*
2
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3
- *
4
- * Permission to use, copy, modify, and distribute this software for any
5
- * purpose with or without fee is hereby granted, provided that the above
6
- * copyright notice and this permission notice appear in all copies.
7
- *
8
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
- */
16
-
17
-package spew
18
-
19
-import (
20
-	"fmt"
21
-	"io"
22
-)
23
-
24
-// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
25
-// passed with a default Formatter interface returned by NewFormatter.  It
26
-// returns the formatted string as a value that satisfies error.  See
27
-// NewFormatter for formatting details.
28
-//
29
-// This function is shorthand for the following syntax:
30
-//
31
-//	fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b))
32
-func Errorf(format string, a ...interface{}) (err error) {
33
-	return fmt.Errorf(format, convertArgs(a)...)
34
-}
35
-
36
-// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
37
-// passed with a default Formatter interface returned by NewFormatter.  It
38
-// returns the number of bytes written and any write error encountered.  See
39
-// NewFormatter for formatting details.
40
-//
41
-// This function is shorthand for the following syntax:
42
-//
43
-//	fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b))
44
-func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
45
-	return fmt.Fprint(w, convertArgs(a)...)
46
-}
47
-
48
-// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
49
-// passed with a default Formatter interface returned by NewFormatter.  It
50
-// returns the number of bytes written and any write error encountered.  See
51
-// NewFormatter for formatting details.
52
-//
53
-// This function is shorthand for the following syntax:
54
-//
55
-//	fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b))
56
-func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
57
-	return fmt.Fprintf(w, format, convertArgs(a)...)
58
-}
59
-
60
-// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
61
-// passed with a default Formatter interface returned by NewFormatter.  See
62
-// NewFormatter for formatting details.
63
-//
64
-// This function is shorthand for the following syntax:
65
-//
66
-//	fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b))
67
-func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
68
-	return fmt.Fprintln(w, convertArgs(a)...)
69
-}
70
-
71
-// Print is a wrapper for fmt.Print that treats each argument as if it were
72
-// passed with a default Formatter interface returned by NewFormatter.  It
73
-// returns the number of bytes written and any write error encountered.  See
74
-// NewFormatter for formatting details.
75
-//
76
-// This function is shorthand for the following syntax:
77
-//
78
-//	fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b))
79
-func Print(a ...interface{}) (n int, err error) {
80
-	return fmt.Print(convertArgs(a)...)
81
-}
82
-
83
-// Printf is a wrapper for fmt.Printf that treats each argument as if it were
84
-// passed with a default Formatter interface returned by NewFormatter.  It
85
-// returns the number of bytes written and any write error encountered.  See
86
-// NewFormatter for formatting details.
87
-//
88
-// This function is shorthand for the following syntax:
89
-//
90
-//	fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b))
91
-func Printf(format string, a ...interface{}) (n int, err error) {
92
-	return fmt.Printf(format, convertArgs(a)...)
93
-}
94
-
95
-// Println is a wrapper for fmt.Println that treats each argument as if it were
96
-// passed with a default Formatter interface returned by NewFormatter.  It
97
-// returns the number of bytes written and any write error encountered.  See
98
-// NewFormatter for formatting details.
99
-//
100
-// This function is shorthand for the following syntax:
101
-//
102
-//	fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b))
103
-func Println(a ...interface{}) (n int, err error) {
104
-	return fmt.Println(convertArgs(a)...)
105
-}
106
-
107
-// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
108
-// passed with a default Formatter interface returned by NewFormatter.  It
109
-// returns the resulting string.  See NewFormatter for formatting details.
110
-//
111
-// This function is shorthand for the following syntax:
112
-//
113
-//	fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b))
114
-func Sprint(a ...interface{}) string {
115
-	return fmt.Sprint(convertArgs(a)...)
116
-}
117
-
118
-// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
119
-// passed with a default Formatter interface returned by NewFormatter.  It
120
-// returns the resulting string.  See NewFormatter for formatting details.
121
-//
122
-// This function is shorthand for the following syntax:
123
-//
124
-//	fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b))
125
-func Sprintf(format string, a ...interface{}) string {
126
-	return fmt.Sprintf(format, convertArgs(a)...)
127
-}
128
-
129
-// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
130
-// were passed with a default Formatter interface returned by NewFormatter.  It
131
-// returns the resulting string.  See NewFormatter for formatting details.
132
-//
133
-// This function is shorthand for the following syntax:
134
-//
135
-//	fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b))
136
-func Sprintln(a ...interface{}) string {
137
-	return fmt.Sprintln(convertArgs(a)...)
138
-}
139
-
140
-// convertArgs accepts a slice of arguments and returns a slice of the same
141
-// length with each argument converted to a default spew Formatter interface.
142
-func convertArgs(args []interface{}) (formatters []interface{}) {
143
-	formatters = make([]interface{}, len(args))
144
-	for index, arg := range args {
145
-		formatters[index] = NewFormatter(arg)
146
-	}
147
-	return formatters
148
-}
... ...
@@ -21,7 +21,7 @@ The primary features of `cmp` are:
21 21
   equality is determined by recursively comparing the primitive kinds on both
22 22
   values, much like `reflect.DeepEqual`. Unlike `reflect.DeepEqual`, unexported
23 23
   fields are not compared by default; they result in panics unless suppressed
24
-  by using an `Ignore` option (see `cmpopts.IgnoreUnexported`) or explictly
24
+  by using an `Ignore` option (see `cmpopts.IgnoreUnexported`) or explicitly
25 25
   compared using the `AllowUnexported` option.
26 26
 
27 27
 See the [GoDoc documentation][godoc] for more information.
28 28
new file mode 100644
... ...
@@ -0,0 +1,89 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+// Package cmpopts provides common options for the cmp package.
5
+package cmpopts
6
+
7
+import (
8
+	"math"
9
+	"reflect"
10
+
11
+	"github.com/google/go-cmp/cmp"
12
+)
13
+
14
+func equateAlways(_, _ interface{}) bool { return true }
15
+
16
+// EquateEmpty returns a Comparer option that determines all maps and slices
17
+// with a length of zero to be equal, regardless of whether they are nil.
18
+//
19
+// EquateEmpty can be used in conjunction with SortSlices and SortMaps.
20
+func EquateEmpty() cmp.Option {
21
+	return cmp.FilterValues(isEmpty, cmp.Comparer(equateAlways))
22
+}
23
+
24
+func isEmpty(x, y interface{}) bool {
25
+	vx, vy := reflect.ValueOf(x), reflect.ValueOf(y)
26
+	return (x != nil && y != nil && vx.Type() == vy.Type()) &&
27
+		(vx.Kind() == reflect.Slice || vx.Kind() == reflect.Map) &&
28
+		(vx.Len() == 0 && vy.Len() == 0)
29
+}
30
+
31
+// EquateApprox returns a Comparer option that determines float32 or float64
32
+// values to be equal if they are within a relative fraction or absolute margin.
33
+// This option is not used when either x or y is NaN or infinite.
34
+//
35
+// The fraction determines that the difference of two values must be within the
36
+// smaller fraction of the two values, while the margin determines that the two
37
+// values must be within some absolute margin.
38
+// To express only a fraction or only a margin, use 0 for the other parameter.
39
+// The fraction and margin must be non-negative.
40
+//
41
+// The mathematical expression used is equivalent to:
42
+//	|x-y| ≤ max(fraction*min(|x|, |y|), margin)
43
+//
44
+// EquateApprox can be used in conjunction with EquateNaNs.
45
+func EquateApprox(fraction, margin float64) cmp.Option {
46
+	if margin < 0 || fraction < 0 || math.IsNaN(margin) || math.IsNaN(fraction) {
47
+		panic("margin or fraction must be a non-negative number")
48
+	}
49
+	a := approximator{fraction, margin}
50
+	return cmp.Options{
51
+		cmp.FilterValues(areRealF64s, cmp.Comparer(a.compareF64)),
52
+		cmp.FilterValues(areRealF32s, cmp.Comparer(a.compareF32)),
53
+	}
54
+}
55
+
56
+type approximator struct{ frac, marg float64 }
57
+
58
+func areRealF64s(x, y float64) bool {
59
+	return !math.IsNaN(x) && !math.IsNaN(y) && !math.IsInf(x, 0) && !math.IsInf(y, 0)
60
+}
61
+func areRealF32s(x, y float32) bool {
62
+	return areRealF64s(float64(x), float64(y))
63
+}
64
+func (a approximator) compareF64(x, y float64) bool {
65
+	relMarg := a.frac * math.Min(math.Abs(x), math.Abs(y))
66
+	return math.Abs(x-y) <= math.Max(a.marg, relMarg)
67
+}
68
+func (a approximator) compareF32(x, y float32) bool {
69
+	return a.compareF64(float64(x), float64(y))
70
+}
71
+
72
+// EquateNaNs returns a Comparer option that determines float32 and float64
73
+// NaN values to be equal.
74
+//
75
+// EquateNaNs can be used in conjunction with EquateApprox.
76
+func EquateNaNs() cmp.Option {
77
+	return cmp.Options{
78
+		cmp.FilterValues(areNaNsF64s, cmp.Comparer(equateAlways)),
79
+		cmp.FilterValues(areNaNsF32s, cmp.Comparer(equateAlways)),
80
+	}
81
+}
82
+
83
+func areNaNsF64s(x, y float64) bool {
84
+	return math.IsNaN(x) && math.IsNaN(y)
85
+}
86
+func areNaNsF32s(x, y float32) bool {
87
+	return areNaNsF64s(float64(x), float64(y))
88
+}
0 89
new file mode 100644
... ...
@@ -0,0 +1,145 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+package cmpopts
5
+
6
+import (
7
+	"fmt"
8
+	"reflect"
9
+	"unicode"
10
+	"unicode/utf8"
11
+
12
+	"github.com/google/go-cmp/cmp"
13
+)
14
+
15
+// IgnoreFields returns an Option that ignores exported fields of the
16
+// given names on a single struct type.
17
+// The struct type is specified by passing in a value of that type.
18
+//
19
+// The name may be a dot-delimited string (e.g., "Foo.Bar") to ignore a
20
+// specific sub-field that is embedded or nested within the parent struct.
21
+//
22
+// This does not handle unexported fields; use IgnoreUnexported instead.
23
+func IgnoreFields(typ interface{}, names ...string) cmp.Option {
24
+	sf := newStructFilter(typ, names...)
25
+	return cmp.FilterPath(sf.filter, cmp.Ignore())
26
+}
27
+
28
+// IgnoreTypes returns an Option that ignores all values assignable to
29
+// certain types, which are specified by passing in a value of each type.
30
+func IgnoreTypes(typs ...interface{}) cmp.Option {
31
+	tf := newTypeFilter(typs...)
32
+	return cmp.FilterPath(tf.filter, cmp.Ignore())
33
+}
34
+
35
+type typeFilter []reflect.Type
36
+
37
+func newTypeFilter(typs ...interface{}) (tf typeFilter) {
38
+	for _, typ := range typs {
39
+		t := reflect.TypeOf(typ)
40
+		if t == nil {
41
+			// This occurs if someone tries to pass in sync.Locker(nil)
42
+			panic("cannot determine type; consider using IgnoreInterfaces")
43
+		}
44
+		tf = append(tf, t)
45
+	}
46
+	return tf
47
+}
48
+func (tf typeFilter) filter(p cmp.Path) bool {
49
+	if len(p) < 1 {
50
+		return false
51
+	}
52
+	t := p.Last().Type()
53
+	for _, ti := range tf {
54
+		if t.AssignableTo(ti) {
55
+			return true
56
+		}
57
+	}
58
+	return false
59
+}
60
+
61
+// IgnoreInterfaces returns an Option that ignores all values or references of
62
+// values assignable to certain interface types. These interfaces are specified
63
+// by passing in an anonymous struct with the interface types embedded in it.
64
+// For example, to ignore sync.Locker, pass in struct{sync.Locker}{}.
65
+func IgnoreInterfaces(ifaces interface{}) cmp.Option {
66
+	tf := newIfaceFilter(ifaces)
67
+	return cmp.FilterPath(tf.filter, cmp.Ignore())
68
+}
69
+
70
+type ifaceFilter []reflect.Type
71
+
72
+func newIfaceFilter(ifaces interface{}) (tf ifaceFilter) {
73
+	t := reflect.TypeOf(ifaces)
74
+	if ifaces == nil || t.Name() != "" || t.Kind() != reflect.Struct {
75
+		panic("input must be an anonymous struct")
76
+	}
77
+	for i := 0; i < t.NumField(); i++ {
78
+		fi := t.Field(i)
79
+		switch {
80
+		case !fi.Anonymous:
81
+			panic("struct cannot have named fields")
82
+		case fi.Type.Kind() != reflect.Interface:
83
+			panic("embedded field must be an interface type")
84
+		case fi.Type.NumMethod() == 0:
85
+			// This matches everything; why would you ever want this?
86
+			panic("cannot ignore empty interface")
87
+		default:
88
+			tf = append(tf, fi.Type)
89
+		}
90
+	}
91
+	return tf
92
+}
93
+func (tf ifaceFilter) filter(p cmp.Path) bool {
94
+	if len(p) < 1 {
95
+		return false
96
+	}
97
+	t := p.Last().Type()
98
+	for _, ti := range tf {
99
+		if t.AssignableTo(ti) {
100
+			return true
101
+		}
102
+		if t.Kind() != reflect.Ptr && reflect.PtrTo(t).AssignableTo(ti) {
103
+			return true
104
+		}
105
+	}
106
+	return false
107
+}
108
+
109
+// IgnoreUnexported returns an Option that only ignores the immediate unexported
110
+// fields of a struct, including anonymous fields of unexported types.
111
+// In particular, unexported fields within the struct's exported fields
112
+// of struct types, including anonymous fields, will not be ignored unless the
113
+// type of the field itself is also passed to IgnoreUnexported.
114
+func IgnoreUnexported(typs ...interface{}) cmp.Option {
115
+	ux := newUnexportedFilter(typs...)
116
+	return cmp.FilterPath(ux.filter, cmp.Ignore())
117
+}
118
+
119
+type unexportedFilter struct{ m map[reflect.Type]bool }
120
+
121
+func newUnexportedFilter(typs ...interface{}) unexportedFilter {
122
+	ux := unexportedFilter{m: make(map[reflect.Type]bool)}
123
+	for _, typ := range typs {
124
+		t := reflect.TypeOf(typ)
125
+		if t == nil || t.Kind() != reflect.Struct {
126
+			panic(fmt.Sprintf("invalid struct type: %T", typ))
127
+		}
128
+		ux.m[t] = true
129
+	}
130
+	return ux
131
+}
132
+func (xf unexportedFilter) filter(p cmp.Path) bool {
133
+	sf, ok := p.Index(-1).(cmp.StructField)
134
+	if !ok {
135
+		return false
136
+	}
137
+	return xf.m[p.Index(-2).Type()] && !isExported(sf.Name())
138
+}
139
+
140
+// isExported reports whether the identifier is exported.
141
+func isExported(id string) bool {
142
+	r, _ := utf8.DecodeRuneInString(id)
143
+	return unicode.IsUpper(r)
144
+}
0 145
new file mode 100644
... ...
@@ -0,0 +1,146 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+package cmpopts
5
+
6
+import (
7
+	"fmt"
8
+	"reflect"
9
+
10
+	"github.com/google/go-cmp/cmp"
11
+	"github.com/google/go-cmp/cmp/internal/function"
12
+)
13
+
14
+// SortSlices returns a Transformer option that sorts all []V.
15
+// The less function must be of the form "func(T, T) bool" which is used to
16
+// sort any slice with element type V that is assignable to T.
17
+//
18
+// The less function must be:
19
+//	• Deterministic: less(x, y) == less(x, y)
20
+//	• Irreflexive: !less(x, x)
21
+//	• Transitive: if !less(x, y) and !less(y, z), then !less(x, z)
22
+//
23
+// The less function does not have to be "total". That is, if !less(x, y) and
24
+// !less(y, x) for two elements x and y, their relative order is maintained.
25
+//
26
+// SortSlices can be used in conjunction with EquateEmpty.
27
+func SortSlices(less interface{}) cmp.Option {
28
+	vf := reflect.ValueOf(less)
29
+	if !function.IsType(vf.Type(), function.Less) || vf.IsNil() {
30
+		panic(fmt.Sprintf("invalid less function: %T", less))
31
+	}
32
+	ss := sliceSorter{vf.Type().In(0), vf}
33
+	return cmp.FilterValues(ss.filter, cmp.Transformer("Sort", ss.sort))
34
+}
35
+
36
+type sliceSorter struct {
37
+	in  reflect.Type  // T
38
+	fnc reflect.Value // func(T, T) bool
39
+}
40
+
41
+func (ss sliceSorter) filter(x, y interface{}) bool {
42
+	vx, vy := reflect.ValueOf(x), reflect.ValueOf(y)
43
+	if !(x != nil && y != nil && vx.Type() == vy.Type()) ||
44
+		!(vx.Kind() == reflect.Slice && vx.Type().Elem().AssignableTo(ss.in)) ||
45
+		(vx.Len() <= 1 && vy.Len() <= 1) {
46
+		return false
47
+	}
48
+	// Check whether the slices are already sorted to avoid an infinite
49
+	// recursion cycle applying the same transform to itself.
50
+	ok1 := sliceIsSorted(x, func(i, j int) bool { return ss.less(vx, i, j) })
51
+	ok2 := sliceIsSorted(y, func(i, j int) bool { return ss.less(vy, i, j) })
52
+	return !ok1 || !ok2
53
+}
54
+func (ss sliceSorter) sort(x interface{}) interface{} {
55
+	src := reflect.ValueOf(x)
56
+	dst := reflect.MakeSlice(src.Type(), src.Len(), src.Len())
57
+	for i := 0; i < src.Len(); i++ {
58
+		dst.Index(i).Set(src.Index(i))
59
+	}
60
+	sortSliceStable(dst.Interface(), func(i, j int) bool { return ss.less(dst, i, j) })
61
+	ss.checkSort(dst)
62
+	return dst.Interface()
63
+}
64
+func (ss sliceSorter) checkSort(v reflect.Value) {
65
+	start := -1 // Start of a sequence of equal elements.
66
+	for i := 1; i < v.Len(); i++ {
67
+		if ss.less(v, i-1, i) {
68
+			// Check that first and last elements in v[start:i] are equal.
69
+			if start >= 0 && (ss.less(v, start, i-1) || ss.less(v, i-1, start)) {
70
+				panic(fmt.Sprintf("incomparable values detected: want equal elements: %v", v.Slice(start, i)))
71
+			}
72
+			start = -1
73
+		} else if start == -1 {
74
+			start = i
75
+		}
76
+	}
77
+}
78
+func (ss sliceSorter) less(v reflect.Value, i, j int) bool {
79
+	vx, vy := v.Index(i), v.Index(j)
80
+	return ss.fnc.Call([]reflect.Value{vx, vy})[0].Bool()
81
+}
82
+
83
+// SortMaps returns a Transformer option that flattens map[K]V types to be a
84
+// sorted []struct{K, V}. The less function must be of the form
85
+// "func(T, T) bool" which is used to sort any map with key K that is
86
+// assignable to T.
87
+//
88
+// Flattening the map into a slice has the property that cmp.Equal is able to
89
+// use Comparers on K or the K.Equal method if it exists.
90
+//
91
+// The less function must be:
92
+//	• Deterministic: less(x, y) == less(x, y)
93
+//	• Irreflexive: !less(x, x)
94
+//	• Transitive: if !less(x, y) and !less(y, z), then !less(x, z)
95
+//	• Total: if x != y, then either less(x, y) or less(y, x)
96
+//
97
+// SortMaps can be used in conjunction with EquateEmpty.
98
+func SortMaps(less interface{}) cmp.Option {
99
+	vf := reflect.ValueOf(less)
100
+	if !function.IsType(vf.Type(), function.Less) || vf.IsNil() {
101
+		panic(fmt.Sprintf("invalid less function: %T", less))
102
+	}
103
+	ms := mapSorter{vf.Type().In(0), vf}
104
+	return cmp.FilterValues(ms.filter, cmp.Transformer("Sort", ms.sort))
105
+}
106
+
107
+type mapSorter struct {
108
+	in  reflect.Type  // T
109
+	fnc reflect.Value // func(T, T) bool
110
+}
111
+
112
+func (ms mapSorter) filter(x, y interface{}) bool {
113
+	vx, vy := reflect.ValueOf(x), reflect.ValueOf(y)
114
+	return (x != nil && y != nil && vx.Type() == vy.Type()) &&
115
+		(vx.Kind() == reflect.Map && vx.Type().Key().AssignableTo(ms.in)) &&
116
+		(vx.Len() != 0 || vy.Len() != 0)
117
+}
118
+func (ms mapSorter) sort(x interface{}) interface{} {
119
+	src := reflect.ValueOf(x)
120
+	outType := mapEntryType(src.Type())
121
+	dst := reflect.MakeSlice(reflect.SliceOf(outType), src.Len(), src.Len())
122
+	for i, k := range src.MapKeys() {
123
+		v := reflect.New(outType).Elem()
124
+		v.Field(0).Set(k)
125
+		v.Field(1).Set(src.MapIndex(k))
126
+		dst.Index(i).Set(v)
127
+	}
128
+	sortSlice(dst.Interface(), func(i, j int) bool { return ms.less(dst, i, j) })
129
+	ms.checkSort(dst)
130
+	return dst.Interface()
131
+}
132
+func (ms mapSorter) checkSort(v reflect.Value) {
133
+	for i := 1; i < v.Len(); i++ {
134
+		if !ms.less(v, i-1, i) {
135
+			panic(fmt.Sprintf("partial order detected: want %v < %v", v.Index(i-1), v.Index(i)))
136
+		}
137
+	}
138
+}
139
+func (ms mapSorter) less(v reflect.Value, i, j int) bool {
140
+	vx, vy := v.Index(i).Field(0), v.Index(j).Field(0)
141
+	if !hasReflectStructOf {
142
+		vx, vy = vx.Elem(), vy.Elem()
143
+	}
144
+	return ms.fnc.Call([]reflect.Value{vx, vy})[0].Bool()
145
+}
0 146
new file mode 100644
... ...
@@ -0,0 +1,46 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+// +build !go1.8
5
+
6
+package cmpopts
7
+
8
+import (
9
+	"reflect"
10
+	"sort"
11
+)
12
+
13
+const hasReflectStructOf = false
14
+
15
+func mapEntryType(reflect.Type) reflect.Type {
16
+	return reflect.TypeOf(struct{ K, V interface{} }{})
17
+}
18
+
19
+func sliceIsSorted(slice interface{}, less func(i, j int) bool) bool {
20
+	return sort.IsSorted(reflectSliceSorter{reflect.ValueOf(slice), less})
21
+}
22
+func sortSlice(slice interface{}, less func(i, j int) bool) {
23
+	sort.Sort(reflectSliceSorter{reflect.ValueOf(slice), less})
24
+}
25
+func sortSliceStable(slice interface{}, less func(i, j int) bool) {
26
+	sort.Stable(reflectSliceSorter{reflect.ValueOf(slice), less})
27
+}
28
+
29
+type reflectSliceSorter struct {
30
+	slice reflect.Value
31
+	less  func(i, j int) bool
32
+}
33
+
34
+func (ss reflectSliceSorter) Len() int {
35
+	return ss.slice.Len()
36
+}
37
+func (ss reflectSliceSorter) Less(i, j int) bool {
38
+	return ss.less(i, j)
39
+}
40
+func (ss reflectSliceSorter) Swap(i, j int) {
41
+	vi := ss.slice.Index(i).Interface()
42
+	vj := ss.slice.Index(j).Interface()
43
+	ss.slice.Index(i).Set(reflect.ValueOf(vj))
44
+	ss.slice.Index(j).Set(reflect.ValueOf(vi))
45
+}
0 46
new file mode 100644
... ...
@@ -0,0 +1,31 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+// +build go1.8
5
+
6
+package cmpopts
7
+
8
+import (
9
+	"reflect"
10
+	"sort"
11
+)
12
+
13
+const hasReflectStructOf = true
14
+
15
+func mapEntryType(t reflect.Type) reflect.Type {
16
+	return reflect.StructOf([]reflect.StructField{
17
+		{Name: "K", Type: t.Key()},
18
+		{Name: "V", Type: t.Elem()},
19
+	})
20
+}
21
+
22
+func sliceIsSorted(slice interface{}, less func(i, j int) bool) bool {
23
+	return sort.SliceIsSorted(slice, less)
24
+}
25
+func sortSlice(slice interface{}, less func(i, j int) bool) {
26
+	sort.Slice(slice, less)
27
+}
28
+func sortSliceStable(slice interface{}, less func(i, j int) bool) {
29
+	sort.SliceStable(slice, less)
30
+}
0 31
new file mode 100644
... ...
@@ -0,0 +1,182 @@
0
+// Copyright 2017, The Go Authors. All rights reserved.
1
+// Use of this source code is governed by a BSD-style
2
+// license that can be found in the LICENSE.md file.
3
+
4
+package cmpopts
5
+
6
+import (
7
+	"fmt"
8
+	"reflect"
9
+	"strings"
10
+
11
+	"github.com/google/go-cmp/cmp"
12
+)
13
+
14
+// filterField returns a new Option where opt is only evaluated on paths that
15
+// include a specific exported field on a single struct type.
16
+// The struct type is specified by passing in a value of that type.
17
+//
18
+// The name may be a dot-delimited string (e.g., "Foo.Bar") to select a
19
+// specific sub-field that is embedded or nested within the parent struct.
20
+func filterField(typ interface{}, name string, opt cmp.Option) cmp.Option {
21
+	// TODO: This is currently unexported over concerns of how helper filters
22
+	// can be composed together easily.
23
+	// TODO: Add tests for FilterField.
24
+
25
+	sf := newStructFilter(typ, name)
26
+	return cmp.FilterPath(sf.filter, opt)
27
+}
28
+
29
+type structFilter struct {
30
+	t  reflect.Type // The root struct type to match on
31
+	ft fieldTree    // Tree of fields to match on
32
+}
33
+
34
+func newStructFilter(typ interface{}, names ...string) structFilter {
35
+	// TODO: Perhaps allow * as a special identifier to allow ignoring any
36
+	// number of path steps until the next field match?
37
+	// This could be useful when a concrete struct gets transformed into
38
+	// an anonymous struct where it is not possible to specify that by type,
39
+	// but the transformer happens to provide guarantees about the names of
40
+	// the transformed fields.
41
+
42
+	t := reflect.TypeOf(typ)
43
+	if t == nil || t.Kind() != reflect.Struct {
44
+		panic(fmt.Sprintf("%T must be a struct", typ))
45
+	}
46
+	var ft fieldTree
47
+	for _, name := range names {
48
+		cname, err := canonicalName(t, name)
49
+		if err != nil {
50
+			panic(fmt.Sprintf("%s: %v", strings.Join(cname, "."), err))
51
+		}
52
+		ft.insert(cname)
53
+	}
54
+	return structFilter{t, ft}
55
+}
56
+
57
+func (sf structFilter) filter(p cmp.Path) bool {
58
+	for i, ps := range p {
59
+		if ps.Type().AssignableTo(sf.t) && sf.ft.matchPrefix(p[i+1:]) {
60
+			return true
61
+		}
62
+	}
63
+	return false
64
+}
65
+
66
+// fieldTree represents a set of dot-separated identifiers.
67
+//
68
+// For example, inserting the following selectors:
69
+//	Foo
70
+//	Foo.Bar.Baz
71
+//	Foo.Buzz
72
+//	Nuka.Cola.Quantum
73
+//
74
+// Results in a tree of the form:
75
+//	{sub: {
76
+//		"Foo": {ok: true, sub: {
77
+//			"Bar": {sub: {
78
+//				"Baz": {ok: true},
79
+//			}},
80
+//			"Buzz": {ok: true},
81
+//		}},
82
+//		"Nuka": {sub: {
83
+//			"Cola": {sub: {
84
+//				"Quantum": {ok: true},
85
+//			}},
86
+//		}},
87
+//	}}
88
+type fieldTree struct {
89
+	ok  bool                 // Whether this is a specified node
90
+	sub map[string]fieldTree // The sub-tree of fields under this node
91
+}
92
+
93
+// insert inserts a sequence of field accesses into the tree.
94
+func (ft *fieldTree) insert(cname []string) {
95
+	if ft.sub == nil {
96
+		ft.sub = make(map[string]fieldTree)
97
+	}
98
+	if len(cname) == 0 {
99
+		ft.ok = true
100
+		return
101
+	}
102
+	sub := ft.sub[cname[0]]
103
+	sub.insert(cname[1:])
104
+	ft.sub[cname[0]] = sub
105
+}
106
+
107
+// matchPrefix reports whether any selector in the fieldTree matches
108
+// the start of path p.
109
+func (ft fieldTree) matchPrefix(p cmp.Path) bool {
110
+	for _, ps := range p {
111
+		switch ps := ps.(type) {
112
+		case cmp.StructField:
113
+			ft = ft.sub[ps.Name()]
114
+			if ft.ok {
115
+				return true
116
+			}
117
+			if len(ft.sub) == 0 {
118
+				return false
119
+			}
120
+		case cmp.Indirect:
121
+		default:
122
+			return false
123
+		}
124
+	}
125
+	return false
126
+}
127
+
128
+// canonicalName returns a list of identifiers where any struct field access
129
+// through an embedded field is expanded to include the names of the embedded
130
+// types themselves.
131
+//
132
+// For example, suppose field "Foo" is not directly in the parent struct,
133
+// but actually from an embedded struct of type "Bar". Then, the canonical name
134
+// of "Foo" is actually "Bar.Foo".
135
+//
136
+// Suppose field "Foo" is not directly in the parent struct, but actually
137
+// a field in two different embedded structs of types "Bar" and "Baz".
138
+// Then the selector "Foo" causes a panic since it is ambiguous which one it
139
+// refers to. The user must specify either "Bar.Foo" or "Baz.Foo".
140
+func canonicalName(t reflect.Type, sel string) ([]string, error) {
141
+	var name string
142
+	sel = strings.TrimPrefix(sel, ".")
143
+	if sel == "" {
144
+		return nil, fmt.Errorf("name must not be empty")
145
+	}
146
+	if i := strings.IndexByte(sel, '.'); i < 0 {
147
+		name, sel = sel, ""
148
+	} else {
149
+		name, sel = sel[:i], sel[i:]
150
+	}
151
+
152
+	// Type must be a struct or pointer to struct.
153
+	if t.Kind() == reflect.Ptr {
154
+		t = t.Elem()
155
+	}
156
+	if t.Kind() != reflect.Struct {
157
+		return nil, fmt.Errorf("%v must be a struct", t)
158
+	}
159
+
160
+	// Find the canonical name for this current field name.
161
+	// If the field exists in an embedded struct, then it will be expanded.
162
+	if !isExported(name) {
163
+		// Disallow unexported fields:
164
+		//	* To discourage people from actually touching unexported fields
165
+		//	* FieldByName is buggy (https://golang.org/issue/4876)
166
+		return []string{name}, fmt.Errorf("name must be exported")
167
+	}
168
+	sf, ok := t.FieldByName(name)
169
+	if !ok {
170
+		return []string{name}, fmt.Errorf("does not exist")
171
+	}
172
+	var ss []string
173
+	for i := range sf.Index {
174
+		ss = append(ss, t.FieldByIndex(sf.Index[:i+1]).Name)
175
+	}
176
+	if sel == "" {
177
+		return ss, nil
178
+	}
179
+	ssPost, err := canonicalName(sf.Type, sel)
180
+	return append(ss, ssPost...), err
181
+}
... ...
@@ -22,7 +22,7 @@
22 22
 // equality is determined by recursively comparing the primitive kinds on both
23 23
 // values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported
24 24
 // fields are not compared by default; they result in panics unless suppressed
25
-// by using an Ignore option (see cmpopts.IgnoreUnexported) or explictly compared
25
+// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared
26 26
 // using the AllowUnexported option.
27 27
 package cmp
28 28
 
... ...
@@ -35,7 +35,7 @@ import (
35 35
 	"github.com/google/go-cmp/cmp/internal/value"
36 36
 )
37 37
 
38
-// BUG: Maps with keys containing NaN values cannot be properly compared due to
38
+// BUG(dsnet): Maps with keys containing NaN values cannot be properly compared due to
39 39
 // the reflection package's inability to retrieve such entries. Equal will panic
40 40
 // anytime it comes across a NaN key, but this behavior may change.
41 41
 //
... ...
@@ -61,8 +61,8 @@ var nothing = reflect.Value{}
61 61
 //
62 62
 // • If the values have an Equal method of the form "(T) Equal(T) bool" or
63 63
 // "(T) Equal(I) bool" where T is assignable to I, then use the result of
64
-// x.Equal(y). Otherwise, no such method exists and evaluation proceeds to
65
-// the next rule.
64
+// x.Equal(y) even if x or y is nil.
65
+// Otherwise, no such method exists and evaluation proceeds to the next rule.
66 66
 //
67 67
 // • Lastly, try to compare x and y based on their basic kinds.
68 68
 // Simple kinds like booleans, integers, floats, complex numbers, strings, and
... ...
@@ -304,7 +304,8 @@ func (s *state) tryOptions(vx, vy reflect.Value, t reflect.Type) bool {
304 304
 
305 305
 	// Evaluate all filters and apply the remaining options.
306 306
 	if opt := opts.filter(s, vx, vy, t); opt != nil {
307
-		return opt.apply(s, vx, vy)
307
+		opt.apply(s, vx, vy)
308
+		return true
308 309
 	}
309 310
 	return false
310 311
 }
... ...
@@ -322,6 +323,7 @@ func (s *state) tryMethod(vx, vy reflect.Value, t reflect.Type) bool {
322 322
 }
323 323
 
324 324
 func (s *state) callTRFunc(f, v reflect.Value) reflect.Value {
325
+	v = sanitizeValue(v, f.Type().In(0))
325 326
 	if !s.dynChecker.Next() {
326 327
 		return f.Call([]reflect.Value{v})[0]
327 328
 	}
... ...
@@ -345,6 +347,8 @@ func (s *state) callTRFunc(f, v reflect.Value) reflect.Value {
345 345
 }
346 346
 
347 347
 func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
348
+	x = sanitizeValue(x, f.Type().In(0))
349
+	y = sanitizeValue(y, f.Type().In(1))
348 350
 	if !s.dynChecker.Next() {
349 351
 		return f.Call([]reflect.Value{x, y})[0].Bool()
350 352
 	}
... ...
@@ -372,20 +376,40 @@ func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
372 372
 	ret = f.Call(vs)[0]
373 373
 }
374 374
 
375
+// sanitizeValue converts nil interfaces of type T to those of type R,
376
+// assuming that T is assignable to R.
377
+// Otherwise, it returns the input value as is.
378
+func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
379
+	// TODO(dsnet): Remove this hacky workaround.
380
+	// See https://golang.org/issue/22143
381
+	if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
382
+		return reflect.New(t).Elem()
383
+	}
384
+	return v
385
+}
386
+
375 387
 func (s *state) compareArray(vx, vy reflect.Value, t reflect.Type) {
376 388
 	step := &sliceIndex{pathStep{t.Elem()}, 0, 0}
377 389
 	s.curPath.push(step)
378 390
 
379 391
 	// Compute an edit-script for slices vx and vy.
380
-	eq, es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result {
392
+	es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result {
381 393
 		step.xkey, step.ykey = ix, iy
382 394
 		return s.statelessCompare(vx.Index(ix), vy.Index(iy))
383 395
 	})
384 396
 
385
-	// Equal or no edit-script, so report entire slices as is.
386
-	if eq || es == nil {
397
+	// Report the entire slice as is if the arrays are of primitive kind,
398
+	// and the arrays are different enough.
399
+	isPrimitive := false
400
+	switch t.Elem().Kind() {
401
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
402
+		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
403
+		reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
404
+		isPrimitive = true
405
+	}
406
+	if isPrimitive && es.Dist() > (vx.Len()+vy.Len())/4 {
387 407
 		s.curPath.pop() // Pop first since we are reporting the whole slice
388
-		s.report(eq, vx, vy)
408
+		s.report(false, vx, vy)
389 409
 		return
390 410
 	}
391 411
 
... ...
@@ -50,7 +50,7 @@ import (
50 50
 //
51 51
 // The series of '.', 'X', 'Y', and 'M' characters at the bottom represents
52 52
 // the currently established path from the forward and reverse searches,
53
-// seperated by a '|' character.
53
+// separated by a '|' character.
54 54
 
55 55
 const (
56 56
 	updateDelay  = 100 * time.Millisecond
... ...
@@ -106,9 +106,9 @@ func (r Result) Similar() bool {
106 106
 // Difference reports whether two lists of lengths nx and ny are equal
107 107
 // given the definition of equality provided as f.
108 108
 //
109
-// This function may return a edit-script, which is a sequence of operations
110
-// needed to convert one list into the other. If non-nil, the following
111
-// invariants for the edit-script are maintained:
109
+// This function returns an edit-script, which is a sequence of operations
110
+// needed to convert one list into the other. The following invariants for
111
+// the edit-script are maintained:
112 112
 //	• eq == (es.Dist()==0)
113 113
 //	• nx == es.LenX()
114 114
 //	• ny == es.LenY()
... ...
@@ -117,17 +117,7 @@ func (r Result) Similar() bool {
117 117
 // produces an edit-script with a minimal Levenshtein distance). This algorithm
118 118
 // favors performance over optimality. The exact output is not guaranteed to
119 119
 // be stable and may change over time.
120
-func Difference(nx, ny int, f EqualFunc) (eq bool, es EditScript) {
121
-	es = searchGraph(nx, ny, f)
122
-	st := es.stats()
123
-	eq = len(es) == st.NI
124
-	if !eq && st.NI < (nx+ny)/4 {
125
-		return eq, nil // Edit-script more distracting than helpful
126
-	}
127
-	return eq, es
128
-}
129
-
130
-func searchGraph(nx, ny int, f EqualFunc) EditScript {
120
+func Difference(nx, ny int, f EqualFunc) (es EditScript) {
131 121
 	// This algorithm is based on traversing what is known as an "edit-graph".
132 122
 	// See Figure 1 from "An O(ND) Difference Algorithm and Its Variations"
133 123
 	// by Eugene W. Myers. Since D can be as large as N itself, this is
... ...
@@ -8,15 +8,11 @@ package value
8 8
 import (
9 9
 	"fmt"
10 10
 	"reflect"
11
+	"strconv"
11 12
 	"strings"
12 13
 	"unicode"
13
-	"unicode/utf8"
14 14
 )
15 15
 
16
-// formatFakePointers controls whether to substitute pointer addresses with nil.
17
-// This is used for deterministic testing.
18
-var formatFakePointers = false
19
-
20 16
 var stringerIface = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
21 17
 
22 18
 // Format formats the value v as a string.
... ...
@@ -26,28 +22,35 @@ var stringerIface = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
26 26
 //	* Avoids printing struct fields that are zero
27 27
 //	* Prints a nil-slice as being nil, not empty
28 28
 //	* Prints map entries in deterministic order
29
-func Format(v reflect.Value, useStringer bool) string {
30
-	return formatAny(v, formatConfig{useStringer, true, true, !formatFakePointers}, nil)
29
+func Format(v reflect.Value, conf FormatConfig) string {
30
+	conf.printType = true
31
+	conf.followPointers = true
32
+	conf.realPointers = true
33
+	return formatAny(v, conf, nil)
31 34
 }
32 35
 
33
-type formatConfig struct {
34
-	useStringer    bool // Should the String method be used if available?
35
-	printType      bool // Should we print the type before the value?
36
-	followPointers bool // Should we recursively follow pointers?
37
-	realPointers   bool // Should we print the real address of pointers?
36
+type FormatConfig struct {
37
+	UseStringer        bool // Should the String method be used if available?
38
+	printType          bool // Should we print the type before the value?
39
+	PrintPrimitiveType bool // Should we print the type of primitives?
40
+	followPointers     bool // Should we recursively follow pointers?
41
+	realPointers       bool // Should we print the real address of pointers?
38 42
 }
39 43
 
40
-func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) string {
44
+func formatAny(v reflect.Value, conf FormatConfig, visited map[uintptr]bool) string {
41 45
 	// TODO: Should this be a multi-line printout in certain situations?
42 46
 
43 47
 	if !v.IsValid() {
44 48
 		return "<non-existent>"
45 49
 	}
46
-	if conf.useStringer && v.Type().Implements(stringerIface) && v.CanInterface() {
50
+	if conf.UseStringer && v.Type().Implements(stringerIface) && v.CanInterface() {
47 51
 		if (v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) && v.IsNil() {
48 52
 			return "<nil>"
49 53
 		}
50
-		return fmt.Sprintf("%q", v.Interface().(fmt.Stringer).String())
54
+
55
+		const stringerPrefix = "s" // Indicates that the String method was used
56
+		s := v.Interface().(fmt.Stringer).String()
57
+		return stringerPrefix + formatString(s)
51 58
 	}
52 59
 
53 60
 	switch v.Kind() {
... ...
@@ -66,7 +69,7 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
66 66
 	case reflect.Complex64, reflect.Complex128:
67 67
 		return formatPrimitive(v.Type(), v.Complex(), conf)
68 68
 	case reflect.String:
69
-		return formatPrimitive(v.Type(), fmt.Sprintf("%q", v), conf)
69
+		return formatPrimitive(v.Type(), formatString(v.String()), conf)
70 70
 	case reflect.UnsafePointer, reflect.Chan, reflect.Func:
71 71
 		return formatPointer(v, conf)
72 72
 	case reflect.Ptr:
... ...
@@ -127,11 +130,13 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
127 127
 		visited = insertPointer(visited, v.Pointer())
128 128
 
129 129
 		var ss []string
130
-		subConf := conf
131
-		subConf.printType = v.Type().Elem().Kind() == reflect.Interface
130
+		keyConf, valConf := conf, conf
131
+		keyConf.printType = v.Type().Key().Kind() == reflect.Interface
132
+		keyConf.followPointers = false
133
+		valConf.printType = v.Type().Elem().Kind() == reflect.Interface
132 134
 		for _, k := range SortKeys(v.MapKeys()) {
133
-			sk := formatAny(k, formatConfig{realPointers: conf.realPointers}, visited)
134
-			sv := formatAny(v.MapIndex(k), subConf, visited)
135
+			sk := formatAny(k, keyConf, visited)
136
+			sv := formatAny(v.MapIndex(k), valConf, visited)
135 137
 			ss = append(ss, fmt.Sprintf("%s: %s", sk, sv))
136 138
 		}
137 139
 		s := fmt.Sprintf("{%s}", strings.Join(ss, ", "))
... ...
@@ -149,7 +154,7 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
149 149
 				continue // Elide zero value fields
150 150
 			}
151 151
 			name := v.Type().Field(i).Name
152
-			subConf.useStringer = conf.useStringer && isExported(name)
152
+			subConf.UseStringer = conf.UseStringer
153 153
 			s := formatAny(vv, subConf, visited)
154 154
 			ss = append(ss, fmt.Sprintf("%s: %s", name, s))
155 155
 		}
... ...
@@ -163,14 +168,33 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
163 163
 	}
164 164
 }
165 165
 
166
-func formatPrimitive(t reflect.Type, v interface{}, conf formatConfig) string {
167
-	if conf.printType && t.PkgPath() != "" {
166
+func formatString(s string) string {
167
+	// Use quoted string if it the same length as a raw string literal.
168
+	// Otherwise, attempt to use the raw string form.
169
+	qs := strconv.Quote(s)
170
+	if len(qs) == 1+len(s)+1 {
171
+		return qs
172
+	}
173
+
174
+	// Disallow newlines to ensure output is a single line.
175
+	// Only allow printable runes for readability purposes.
176
+	rawInvalid := func(r rune) bool {
177
+		return r == '`' || r == '\n' || !unicode.IsPrint(r)
178
+	}
179
+	if strings.IndexFunc(s, rawInvalid) < 0 {
180
+		return "`" + s + "`"
181
+	}
182
+	return qs
183
+}
184
+
185
+func formatPrimitive(t reflect.Type, v interface{}, conf FormatConfig) string {
186
+	if conf.printType && (conf.PrintPrimitiveType || t.PkgPath() != "") {
168 187
 		return fmt.Sprintf("%v(%v)", t, v)
169 188
 	}
170 189
 	return fmt.Sprintf("%v", v)
171 190
 }
172 191
 
173
-func formatPointer(v reflect.Value, conf formatConfig) string {
192
+func formatPointer(v reflect.Value, conf FormatConfig) string {
174 193
 	p := v.Pointer()
175 194
 	if !conf.realPointers {
176 195
 		p = 0 // For deterministic printing purposes
... ...
@@ -251,9 +275,3 @@ func isZero(v reflect.Value) bool {
251 251
 	}
252 252
 	return false
253 253
 }
254
-
255
-// isExported reports whether the identifier is exported.
256
-func isExported(id string) bool {
257
-	r, _ := utf8.DecodeRuneInString(id)
258
-	return unicode.IsUpper(r)
259
-}
... ...
@@ -24,7 +24,7 @@ func SortKeys(vs []reflect.Value) []reflect.Value {
24 24
 	// Deduplicate keys (fails for NaNs).
25 25
 	vs2 := vs[:1]
26 26
 	for _, v := range vs[1:] {
27
-		if v.Interface() != vs2[len(vs2)-1].Interface() {
27
+		if isLess(vs2[len(vs2)-1], v) {
28 28
 			vs2 = append(vs2, v)
29 29
 		}
30 30
 	}
... ...
@@ -38,9 +38,8 @@ type Option interface {
38 38
 type applicableOption interface {
39 39
 	Option
40 40
 
41
-	// apply executes the option and reports whether the option was applied.
42
-	// Each option may mutate s.
43
-	apply(s *state, vx, vy reflect.Value) bool
41
+	// apply executes the option, which may mutate s or panic.
42
+	apply(s *state, vx, vy reflect.Value)
44 43
 }
45 44
 
46 45
 // coreOption represents the following types:
... ...
@@ -85,7 +84,7 @@ func (opts Options) filter(s *state, vx, vy reflect.Value, t reflect.Type) (out
85 85
 	return out
86 86
 }
87 87
 
88
-func (opts Options) apply(s *state, _, _ reflect.Value) bool {
88
+func (opts Options) apply(s *state, _, _ reflect.Value) {
89 89
 	const warning = "ambiguous set of applicable options"
90 90
 	const help = "consider using filters to ensure at most one Comparer or Transformer may apply"
91 91
 	var ss []string
... ...
@@ -196,7 +195,7 @@ type ignore struct{ core }
196 196
 
197 197
 func (ignore) isFiltered() bool                                                     { return false }
198 198
 func (ignore) filter(_ *state, _, _ reflect.Value, _ reflect.Type) applicableOption { return ignore{} }
199
-func (ignore) apply(_ *state, _, _ reflect.Value) bool                              { return true }
199
+func (ignore) apply(_ *state, _, _ reflect.Value)                                   { return }
200 200
 func (ignore) String() string                                                       { return "Ignore()" }
201 201
 
202 202
 // invalid is a sentinel Option type to indicate that some options could not
... ...
@@ -204,7 +203,7 @@ func (ignore) String() string
204 204
 type invalid struct{ core }
205 205
 
206 206
 func (invalid) filter(_ *state, _, _ reflect.Value, _ reflect.Type) applicableOption { return invalid{} }
207
-func (invalid) apply(s *state, _, _ reflect.Value) bool {
207
+func (invalid) apply(s *state, _, _ reflect.Value) {
208 208
 	const help = "consider using AllowUnexported or cmpopts.IgnoreUnexported"
209 209
 	panic(fmt.Sprintf("cannot handle unexported field: %#v\n%s", s.curPath, help))
210 210
 }
... ...
@@ -215,9 +214,12 @@ func (invalid) apply(s *state, _, _ reflect.Value) bool {
215 215
 // The transformer f must be a function "func(T) R" that converts values of
216 216
 // type T to those of type R and is implicitly filtered to input values
217 217
 // assignable to T. The transformer must not mutate T in any way.
218
-// If T and R are the same type, an additional filter must be applied to
219
-// act as the base case to prevent an infinite recursion applying the same
220
-// transform to itself (see the SortedSlice example).
218
+//
219
+// To help prevent some cases of infinite recursive cycles applying the
220
+// same transform to the output of itself (e.g., in the case where the
221
+// input and output types are the same), an implicit filter is added such that
222
+// a transformer is applicable only if that exact transformer is not already
223
+// in the tail of the Path since the last non-Transform step.
221 224
 //
222 225
 // The name is a user provided label that is used as the Transform.Name in the
223 226
 // transformation PathStep. If empty, an arbitrary name is used.
... ...
@@ -248,14 +250,21 @@ type transformer struct {
248 248
 
249 249
 func (tr *transformer) isFiltered() bool { return tr.typ != nil }
250 250
 
251
-func (tr *transformer) filter(_ *state, _, _ reflect.Value, t reflect.Type) applicableOption {
251
+func (tr *transformer) filter(s *state, _, _ reflect.Value, t reflect.Type) applicableOption {
252
+	for i := len(s.curPath) - 1; i >= 0; i-- {
253
+		if t, ok := s.curPath[i].(*transform); !ok {
254
+			break // Hit most recent non-Transform step
255
+		} else if tr == t.trans {
256
+			return nil // Cannot directly use same Transform
257
+		}
258
+	}
252 259
 	if tr.typ == nil || t.AssignableTo(tr.typ) {
253 260
 		return tr
254 261
 	}
255 262
 	return nil
256 263
 }
257 264
 
258
-func (tr *transformer) apply(s *state, vx, vy reflect.Value) bool {
265
+func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
259 266
 	// Update path before calling the Transformer so that dynamic checks
260 267
 	// will use the updated path.
261 268
 	s.curPath.push(&transform{pathStep{tr.fnc.Type().Out(0)}, tr})
... ...
@@ -264,7 +273,6 @@ func (tr *transformer) apply(s *state, vx, vy reflect.Value) bool {
264 264
 	vx = s.callTRFunc(tr.fnc, vx)
265 265
 	vy = s.callTRFunc(tr.fnc, vy)
266 266
 	s.compareAny(vx, vy)
267
-	return true
268 267
 }
269 268
 
270 269
 func (tr transformer) String() string {
... ...
@@ -310,10 +318,9 @@ func (cm *comparer) filter(_ *state, _, _ reflect.Value, t reflect.Type) applica
310 310
 	return nil
311 311
 }
312 312
 
313
-func (cm *comparer) apply(s *state, vx, vy reflect.Value) bool {
313
+func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
314 314
 	eq := s.callTTBFunc(cm.fnc, vx, vy)
315 315
 	s.report(eq, vx, vy)
316
-	return true
317 316
 }
318 317
 
319 318
 func (cm comparer) String() string {
... ...
@@ -348,7 +355,7 @@ func (cm comparer) String() string {
348 348
 // all unexported fields on specified struct types.
349 349
 func AllowUnexported(types ...interface{}) Option {
350 350
 	if !supportAllowUnexported {
351
-		panic("AllowUnexported is not supported on App Engine Classic or GopherJS")
351
+		panic("AllowUnexported is not supported on purego builds, Google App Engine Standard, or GopherJS")
352 352
 	}
353 353
 	m := make(map[reflect.Type]bool)
354 354
 	for _, typ := range types {
... ...
@@ -79,6 +79,11 @@ type (
79 79
 		PathStep
80 80
 		Name() string
81 81
 		Func() reflect.Value
82
+
83
+		// Option returns the originally constructed Transformer option.
84
+		// The == operator can be used to detect the exact option used.
85
+		Option() Option
86
+
82 87
 		isTransform()
83 88
 	}
84 89
 )
... ...
@@ -94,10 +99,21 @@ func (pa *Path) pop() {
94 94
 // Last returns the last PathStep in the Path.
95 95
 // If the path is empty, this returns a non-nil PathStep that reports a nil Type.
96 96
 func (pa Path) Last() PathStep {
97
-	if len(pa) > 0 {
98
-		return pa[len(pa)-1]
97
+	return pa.Index(-1)
98
+}
99
+
100
+// Index returns the ith step in the Path and supports negative indexing.
101
+// A negative index starts counting from the tail of the Path such that -1
102
+// refers to the last step, -2 refers to the second-to-last step, and so on.
103
+// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
104
+func (pa Path) Index(i int) PathStep {
105
+	if i < 0 {
106
+		i = len(pa) + i
107
+	}
108
+	if i < 0 || i >= len(pa) {
109
+		return pathStep{}
99 110
 	}
100
-	return pathStep{}
111
+	return pa[i]
101 112
 }
102 113
 
103 114
 // String returns the simplified path to a node.
... ...
@@ -150,13 +166,12 @@ func (pa Path) GoString() string {
150 150
 			ssPost = append(ssPost, ")")
151 151
 			continue
152 152
 		case *typeAssertion:
153
-			// Elide type assertions immediately following a transform to
154
-			// prevent overly verbose path printouts.
155
-			// Some transforms return interface{} because of Go's lack of
156
-			// generics, but typically take in and return the exact same
157
-			// concrete type. Other times, the transform creates an anonymous
158
-			// struct, which will be very verbose to print.
159
-			if _, ok := nextStep.(*transform); ok {
153
+			// As a special-case, elide type assertions on anonymous types
154
+			// since they are typically generated dynamically and can be very
155
+			// verbose. For example, some transforms return interface{} because
156
+			// of Go's lack of generics, but typically take in and return the
157
+			// exact same concrete type.
158
+			if s.Type().PkgPath() == "" {
160 159
 				continue
161 160
 			}
162 161
 		}
... ...
@@ -250,6 +265,7 @@ func (sf structField) Name() string         { return sf.name }
250 250
 func (sf structField) Index() int           { return sf.idx }
251 251
 func (tf transform) Name() string           { return tf.trans.name }
252 252
 func (tf transform) Func() reflect.Value    { return tf.trans.fnc }
253
+func (tf transform) Option() Option         { return tf.trans }
253 254
 
254 255
 func (pathStep) isPathStep()           {}
255 256
 func (sliceIndex) isSliceIndex()       {}
... ...
@@ -30,12 +30,12 @@ func (r *defaultReporter) Report(x, y reflect.Value, eq bool, p Path) {
30 30
 	const maxLines = 256
31 31
 	r.ndiffs++
32 32
 	if r.nbytes < maxBytes && r.nlines < maxLines {
33
-		sx := value.Format(x, true)
34
-		sy := value.Format(y, true)
33
+		sx := value.Format(x, value.FormatConfig{UseStringer: true})
34
+		sy := value.Format(y, value.FormatConfig{UseStringer: true})
35 35
 		if sx == sy {
36
-			// Stringer is not helpful, so rely on more exact formatting.
37
-			sx = value.Format(x, false)
38
-			sy = value.Format(y, false)
36
+			// Unhelpful output, so use more exact formatting.
37
+			sx = value.Format(x, value.FormatConfig{PrintPrimitiveType: true})
38
+			sy = value.Format(y, value.FormatConfig{PrintPrimitiveType: true})
39 39
 		}
40 40
 		s := fmt.Sprintf("%#v:\n\t-: %s\n\t+: %s\n", p, sx, sy)
41 41
 		r.diffs = append(r.diffs, s)
... ...
@@ -49,5 +49,5 @@ func (r *defaultReporter) String() string {
49 49
 	if r.ndiffs == len(r.diffs) {
50 50
 		return s
51 51
 	}
52
-	return fmt.Sprintf("%s... %d more differences ...", s, len(r.diffs)-r.ndiffs)
52
+	return fmt.Sprintf("%s... %d more differences ...", s, r.ndiffs-len(r.diffs))
53 53
 }
... ...
@@ -2,7 +2,7 @@
2 2
 // Use of this source code is governed by a BSD-style
3 3
 // license that can be found in the LICENSE.md file.
4 4
 
5
-// +build appengine js
5
+// +build purego appengine js
6 6
 
7 7
 package cmp
8 8
 
... ...
@@ -2,7 +2,7 @@
2 2
 // Use of this source code is governed by a BSD-style
3 3
 // license that can be found in the LICENSE.md file.
4 4
 
5
-// +build !appengine,!js
5
+// +build !purego,!appengine,!js
6 6
 
7 7
 package cmp
8 8
 
... ...
@@ -30,3 +30,4 @@ patterns.
30 30
 ## Related
31 31
 
32 32
 * [maxbrunsfeld/counterfeiter](https://github.com/maxbrunsfeld/counterfeiter) - generate fakes for interfaces
33
+* [jonboulle/clockwork](https://github.com/jonboulle/clockwork) - a fake clock for testing code that uses `time`
... ...
@@ -1,6 +1,5 @@
1
-/*Package assert provides assertions and checks for comparing expected values to
2
-actual values. When an assertion or check fails a helpful error message is
3
-printed.
1
+/*Package assert provides assertions for comparing expected values to actual
2
+values. When an assertion fails a helpful error message is printed.
4 3
 
5 4
 Assert and Check
6 5
 
... ...
@@ -23,7 +22,7 @@ The example below shows assert used with some common types.
23 23
 
24 24
 	func TestEverything(t *testing.T) {
25 25
 	    // booleans
26
-	    assert.Assert(t, isOk)
26
+	    assert.Assert(t, ok)
27 27
 	    assert.Assert(t, !missing)
28 28
 
29 29
 	    // primitives
... ...
@@ -33,14 +32,15 @@ The example below shows assert used with some common types.
33 33
 
34 34
 	    // errors
35 35
 	    assert.NilError(t, closer.Close())
36
-	    assert.Assert(t, is.Error(err, "the exact error message"))
37
-	    assert.Assert(t, is.ErrorContains(err, "includes this"))
36
+	    assert.Error(t, err, "the exact error message")
37
+	    assert.ErrorContains(t, err, "includes this")
38
+	    assert.ErrorType(t, err, os.IsNotExist)
38 39
 
39 40
 	    // complex types
41
+	    assert.DeepEqual(t, result, myStruct{Name: "title"})
40 42
 	    assert.Assert(t, is.Len(items, 3))
41 43
 	    assert.Assert(t, len(sequence) != 0) // NotEmpty
42 44
 	    assert.Assert(t, is.Contains(mapping, "key"))
43
-	    assert.Assert(t, is.Compare(result, myStruct{Name: "title"}))
44 45
 
45 46
 	    // pointers and interface
46 47
 	    assert.Assert(t, is.Nil(ref))
... ...
@@ -51,40 +51,25 @@ Comparisons
51 51
 
52 52
 https://godoc.org/github.com/gotestyourself/gotestyourself/assert/cmp provides
53 53
 many common comparisons. Additional comparisons can be written to compare
54
-values in other ways.
55
-
56
-Below is an example of a custom comparison using a regex pattern:
57
-
58
-	func RegexP(value string, pattern string) func() (bool, string) {
59
-	    return func() (bool, string) {
60
-	        re := regexp.MustCompile(pattern)
61
-	        msg := fmt.Sprintf("%q did not match pattern %q", value, pattern)
62
-	        return re.MatchString(value), msg
63
-	    }
64
-	}
54
+values in other ways. See the example Assert (CustomComparison).
65 55
 
66 56
 */
67 57
 package assert
68 58
 
69 59
 import (
70 60
 	"fmt"
61
+	"go/ast"
62
+	"go/token"
71 63
 
64
+	gocmp "github.com/google/go-cmp/cmp"
72 65
 	"github.com/gotestyourself/gotestyourself/assert/cmp"
73 66
 	"github.com/gotestyourself/gotestyourself/internal/format"
74 67
 	"github.com/gotestyourself/gotestyourself/internal/source"
75 68
 )
76 69
 
77
-// BoolOrComparison can be a bool, or Comparison. Other types will panic.
70
+// BoolOrComparison can be a bool, or cmp.Comparison. See Assert() for usage.
78 71
 type BoolOrComparison interface{}
79 72
 
80
-// Comparison is a function which compares values and returns true if the actual
81
-// value matches the expected value. If the values do not match it returns a message
82
-// with details about why it failed.
83
-//
84
-// https://godoc.org/github.com/gotestyourself/gotestyourself/assert/cmp
85
-// provides many general purpose Comparisons.
86
-type Comparison func() (success bool, message string)
87
-
88 73
 // TestingT is the subset of testing.T used by the assert package.
89 74
 type TestingT interface {
90 75
 	FailNow()
... ...
@@ -96,84 +81,156 @@ type helperT interface {
96 96
 	Helper()
97 97
 }
98 98
 
99
-// stackIndex = Assert()/Check(), assert()
100
-const stackIndex = 2
101
-const comparisonArgPos = 1
102
-
103 99
 const failureMessage = "assertion failed: "
104 100
 
101
+// nolint: gocyclo
105 102
 func assert(
106 103
 	t TestingT,
107 104
 	failer func(),
105
+	argSelector argSelector,
108 106
 	comparison BoolOrComparison,
109 107
 	msgAndArgs ...interface{},
110 108
 ) bool {
111 109
 	if ht, ok := t.(helperT); ok {
112 110
 		ht.Helper()
113 111
 	}
112
+	var success bool
114 113
 	switch check := comparison.(type) {
115 114
 	case bool:
116 115
 		if check {
117 116
 			return true
118 117
 		}
119
-		source, err := source.GetCondition(stackIndex, comparisonArgPos)
120
-		if err != nil {
121
-			t.Log(err.Error())
122
-		}
118
+		logFailureFromBool(t, msgAndArgs...)
123 119
 
124
-		msg := " is false"
125
-		t.Log(format.WithCustomMessage(failureMessage+source+msg, msgAndArgs...))
126
-		failer()
127
-		return false
120
+	// Undocumented legacy comparison without Result type
121
+	case func() (success bool, message string):
122
+		success = runCompareFunc(t, check, msgAndArgs...)
128 123
 
129
-	case Comparison:
130
-		return runCompareFunc(failer, t, check, msgAndArgs...)
124
+	case nil:
125
+		return true
131 126
 
132
-	case func() (success bool, message string):
133
-		return runCompareFunc(failer, t, check, msgAndArgs...)
127
+	case error:
128
+		msg := "error is not nil: "
129
+		t.Log(format.WithCustomMessage(failureMessage+msg+check.Error(), msgAndArgs...))
130
+
131
+	case cmp.Comparison:
132
+		success = runComparison(t, argSelector, check, msgAndArgs...)
133
+
134
+	case func() cmp.Result:
135
+		success = runComparison(t, argSelector, check, msgAndArgs...)
134 136
 
135 137
 	default:
136
-		panic(fmt.Sprintf("comparison arg must be bool or Comparison, not %T", comparison))
138
+		t.Log(fmt.Sprintf("invalid Comparison: %v (%T)", check, check))
139
+	}
140
+
141
+	if success {
142
+		return true
137 143
 	}
144
+	failer()
145
+	return false
138 146
 }
139 147
 
140
-func runCompareFunc(failer func(), t TestingT, f Comparison, msgAndArgs ...interface{}) bool {
148
+func runCompareFunc(
149
+	t TestingT,
150
+	f func() (success bool, message string),
151
+	msgAndArgs ...interface{},
152
+) bool {
141 153
 	if ht, ok := t.(helperT); ok {
142 154
 		ht.Helper()
143 155
 	}
144 156
 	if success, message := f(); !success {
145 157
 		t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
146
-		failer()
147 158
 		return false
148 159
 	}
149 160
 	return true
150 161
 }
151 162
 
152
-// Assert performs a comparison, marks the test as having failed if the comparison
153
-// returns false, and stops execution immediately.
163
+func logFailureFromBool(t TestingT, msgAndArgs ...interface{}) {
164
+	if ht, ok := t.(helperT); ok {
165
+		ht.Helper()
166
+	}
167
+	const stackIndex = 3 // Assert()/Check(), assert(), formatFailureFromBool()
168
+	const comparisonArgPos = 1
169
+	args, err := source.CallExprArgs(stackIndex)
170
+	if err != nil {
171
+		t.Log(err.Error())
172
+		return
173
+	}
174
+
175
+	msg, err := boolFailureMessage(args[comparisonArgPos])
176
+	if err != nil {
177
+		t.Log(err.Error())
178
+		msg = "expression is false"
179
+	}
180
+
181
+	t.Log(format.WithCustomMessage(failureMessage+msg, msgAndArgs...))
182
+}
183
+
184
+func boolFailureMessage(expr ast.Expr) (string, error) {
185
+	if binaryExpr, ok := expr.(*ast.BinaryExpr); ok && binaryExpr.Op == token.NEQ {
186
+		x, err := source.FormatNode(binaryExpr.X)
187
+		if err != nil {
188
+			return "", err
189
+		}
190
+		y, err := source.FormatNode(binaryExpr.Y)
191
+		if err != nil {
192
+			return "", err
193
+		}
194
+		return x + " is " + y, nil
195
+	}
196
+
197
+	if unaryExpr, ok := expr.(*ast.UnaryExpr); ok && unaryExpr.Op == token.NOT {
198
+		x, err := source.FormatNode(unaryExpr.X)
199
+		if err != nil {
200
+			return "", err
201
+		}
202
+		return x + " is true", nil
203
+	}
204
+
205
+	formatted, err := source.FormatNode(expr)
206
+	if err != nil {
207
+		return "", err
208
+	}
209
+	return "expression is false: " + formatted, nil
210
+}
211
+
212
+// Assert performs a comparison. If the comparison fails the test is marked as
213
+// failed, a failure message is logged, and execution is stopped immediately.
214
+//
215
+// The comparison argument may be one of three types: bool, cmp.Comparison or
216
+// error.
217
+// When called with a bool the failure message will contain the literal source
218
+// code of the expression.
219
+// When called with a cmp.Comparison the comparison is responsible for producing
220
+// a helpful failure message.
221
+// When called with an error a nil value is considered success. A non-nil error
222
+// is a failure, and Error() is used as the failure message.
154 223
 func Assert(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) {
155 224
 	if ht, ok := t.(helperT); ok {
156 225
 		ht.Helper()
157 226
 	}
158
-	assert(t, t.FailNow, comparison, msgAndArgs...)
227
+	assert(t, t.FailNow, argsFromComparisonCall, comparison, msgAndArgs...)
159 228
 }
160 229
 
161
-// Check performs a comparison and marks the test as having failed if the comparison
162
-// returns false. Returns the result of the comparison.
230
+// Check performs a comparison. If the comparison fails the test is marked as
231
+// failed, a failure message is logged, and Check returns false. Otherwise returns
232
+// true.
233
+//
234
+// See Assert for details about the comparison arg and failure messages.
163 235
 func Check(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) bool {
164 236
 	if ht, ok := t.(helperT); ok {
165 237
 		ht.Helper()
166 238
 	}
167
-	return assert(t, t.Fail, comparison, msgAndArgs...)
239
+	return assert(t, t.Fail, argsFromComparisonCall, comparison, msgAndArgs...)
168 240
 }
169 241
 
170
-// NilError fails the test immediately if the last arg is a non-nil error.
171
-// This is equivalent to Assert(t, cmp.NilError(err)).
242
+// NilError fails the test immediately if err is not nil.
243
+// This is equivalent to Assert(t, err)
172 244
 func NilError(t TestingT, err error, msgAndArgs ...interface{}) {
173 245
 	if ht, ok := t.(helperT); ok {
174 246
 		ht.Helper()
175 247
 	}
176
-	assert(t, t.FailNow, cmp.NilError(err), msgAndArgs...)
248
+	assert(t, t.FailNow, argsAfterT, err, msgAndArgs...)
177 249
 }
178 250
 
179 251
 // Equal uses the == operator to assert two values are equal and fails the test
... ...
@@ -182,5 +239,51 @@ func Equal(t TestingT, x, y interface{}, msgAndArgs ...interface{}) {
182 182
 	if ht, ok := t.(helperT); ok {
183 183
 		ht.Helper()
184 184
 	}
185
-	assert(t, t.FailNow, cmp.Equal(x, y), msgAndArgs...)
185
+	assert(t, t.FailNow, argsAfterT, cmp.Equal(x, y), msgAndArgs...)
186
+}
187
+
188
+// DeepEqual uses https://github.com/google/go-cmp/cmp to assert two values
189
+// are equal and fails the test if they are not equal.
190
+// This is equivalent to Assert(t, cmp.DeepEqual(x, y)).
191
+func DeepEqual(t TestingT, x, y interface{}, opts ...gocmp.Option) {
192
+	if ht, ok := t.(helperT); ok {
193
+		ht.Helper()
194
+	}
195
+	assert(t, t.FailNow, argsAfterT, cmp.DeepEqual(x, y, opts...))
196
+}
197
+
198
+// Error fails the test if err is nil, or the error message is not the expected
199
+// message.
200
+// Equivalent to Assert(t, cmp.Error(err, message)).
201
+func Error(t TestingT, err error, message string, msgAndArgs ...interface{}) {
202
+	if ht, ok := t.(helperT); ok {
203
+		ht.Helper()
204
+	}
205
+	assert(t, t.FailNow, argsAfterT, cmp.Error(err, message), msgAndArgs...)
206
+}
207
+
208
+// ErrorContains fails the test if err is nil, or the error message does not
209
+// contain the expected substring.
210
+// Equivalent to Assert(t, cmp.ErrorContains(err, substring)).
211
+func ErrorContains(t TestingT, err error, substring string, msgAndArgs ...interface{}) {
212
+	if ht, ok := t.(helperT); ok {
213
+		ht.Helper()
214
+	}
215
+	assert(t, t.FailNow, argsAfterT, cmp.ErrorContains(err, substring), msgAndArgs...)
216
+}
217
+
218
+// ErrorType fails the test if err is nil, or err is not the expected type.
219
+//
220
+// Expected can be one of:
221
+// a func(error) bool which returns true if the error is the expected type,
222
+// an instance of a struct of the expected type,
223
+// a pointer to an interface the error is expected to implement,
224
+// a reflect.Type of the expected struct or interface.
225
+//
226
+// Equivalent to Assert(t, cmp.ErrorType(err, expected)).
227
+func ErrorType(t TestingT, err error, expected interface{}, msgAndArgs ...interface{}) {
228
+	if ht, ok := t.(helperT); ok {
229
+		ht.Helper()
230
+	}
231
+	assert(t, t.FailNow, argsAfterT, cmp.ErrorType(err, expected), msgAndArgs...)
186 232
 }
... ...
@@ -10,53 +10,113 @@ import (
10 10
 	"github.com/pmezard/go-difflib/difflib"
11 11
 )
12 12
 
13
-// Compare two complex values using https://godoc.org/github.com/google/go-cmp/cmp
13
+// Comparison is a function which compares values and returns ResultSuccess if
14
+// the actual value matches the expected value. If the values do not match the
15
+// Result will contain a message about why it failed.
16
+type Comparison func() Result
17
+
18
+// DeepEqual compares two values using https://godoc.org/github.com/google/go-cmp/cmp
14 19
 // and succeeds if the values are equal.
15 20
 //
16 21
 // The comparison can be customized using comparison Options.
17
-func Compare(x, y interface{}, opts ...cmp.Option) func() (bool, string) {
18
-	return func() (bool, string) {
22
+func DeepEqual(x, y interface{}, opts ...cmp.Option) Comparison {
23
+	return func() (result Result) {
24
+		defer func() {
25
+			if panicmsg, handled := handleCmpPanic(recover()); handled {
26
+				result = ResultFailure(panicmsg)
27
+			}
28
+		}()
19 29
 		diff := cmp.Diff(x, y, opts...)
20
-		return diff == "", "\n" + diff
30
+		return toResult(diff == "", "\n"+diff)
31
+	}
32
+}
33
+
34
+func handleCmpPanic(r interface{}) (string, bool) {
35
+	if r == nil {
36
+		return "", false
21 37
 	}
38
+	panicmsg, ok := r.(string)
39
+	if !ok {
40
+		panic(r)
41
+	}
42
+	switch {
43
+	case strings.HasPrefix(panicmsg, "cannot handle unexported field"):
44
+		return panicmsg, true
45
+	}
46
+	panic(r)
47
+}
48
+
49
+func toResult(success bool, msg string) Result {
50
+	if success {
51
+		return ResultSuccess
52
+	}
53
+	return ResultFailure(msg)
22 54
 }
23 55
 
24 56
 // Equal succeeds if x == y.
25
-func Equal(x, y interface{}) func() (success bool, message string) {
26
-	return func() (bool, string) {
27
-		return x == y, fmt.Sprintf("%v (%T) != %v (%T)", x, x, y, y)
57
+func Equal(x, y interface{}) Comparison {
58
+	return func() Result {
59
+		switch {
60
+		case x == y:
61
+			return ResultSuccess
62
+		case isMultiLineStringCompare(x, y):
63
+			return multiLineStringDiffResult(x.(string), y.(string))
64
+		}
65
+		return ResultFailureTemplate(`
66
+			{{- .Data.x}} (
67
+				{{- with callArg 0 }}{{ formatNode . }} {{end -}}
68
+				{{- printf "%T" .Data.x -}}
69
+			) != {{ .Data.y}} (
70
+				{{- with callArg 1 }}{{ formatNode . }} {{end -}}
71
+				{{- printf "%T" .Data.y -}}
72
+			)`,
73
+			map[string]interface{}{"x": x, "y": y})
28 74
 	}
29 75
 }
30 76
 
77
+func isMultiLineStringCompare(x, y interface{}) bool {
78
+	strX, ok := x.(string)
79
+	if !ok {
80
+		return false
81
+	}
82
+	strY, ok := y.(string)
83
+	if !ok {
84
+		return false
85
+	}
86
+	return strings.Contains(strX, "\n") || strings.Contains(strY, "\n")
87
+}
88
+
89
+func multiLineStringDiffResult(x, y string) Result {
90
+	diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
91
+		A:       difflib.SplitLines(x),
92
+		B:       difflib.SplitLines(y),
93
+		Context: 3,
94
+	})
95
+	if err != nil {
96
+		return ResultFailure(fmt.Sprintf("failed to diff: %s", err))
97
+	}
98
+	return ResultFailureTemplate(`
99
+--- {{ with callArg 0 }}{{ formatNode . }}{{else}}←{{end}}
100
+{{ .Data.diff }}`,
101
+		map[string]interface{}{"diff": diff})
102
+}
103
+
31 104
 // Len succeeds if the sequence has the expected length.
32
-func Len(seq interface{}, expected int) func() (bool, string) {
33
-	return func() (success bool, message string) {
105
+func Len(seq interface{}, expected int) Comparison {
106
+	return func() (result Result) {
34 107
 		defer func() {
35 108
 			if e := recover(); e != nil {
36
-				success = false
37
-				message = fmt.Sprintf("type %T does not have a length", seq)
109
+				result = ResultFailure(fmt.Sprintf("type %T does not have a length", seq))
38 110
 			}
39 111
 		}()
40 112
 		value := reflect.ValueOf(seq)
41 113
 		length := value.Len()
42 114
 		if length == expected {
43
-			return true, ""
115
+			return ResultSuccess
44 116
 		}
45 117
 		msg := fmt.Sprintf("expected %s (length %d) to have length %d", seq, length, expected)
46
-		return false, msg
47
-	}
48
-}
49
-
50
-// NilError succeeds if the last argument is a nil error.
51
-func NilError(arg interface{}, args ...interface{}) func() (bool, string) {
52
-	return func() (bool, string) {
53
-		msgFunc := func(value reflect.Value) string {
54
-			return fmt.Sprintf("error is not nil: %s", value.Interface().(error).Error())
55
-		}
56
-		if len(args) == 0 {
57
-			return isNil(arg, msgFunc)()
58
-		}
59
-		return isNil(args[len(args)-1], msgFunc)()
118
+		return ResultFailure(msg)
60 119
 	}
61 120
 }
62 121
 
... ...
@@ -68,11 +128,11 @@ func NilError(arg interface{}, args ...interface{}) func() (bool, string) {
68 68
 // If collection is a Map, contains will succeed if item is a key in the map.
69 69
 // If collection is a slice or array, item is compared to each item in the
70 70
 // sequence using reflect.DeepEqual().
71
-func Contains(collection interface{}, item interface{}) func() (bool, string) {
72
-	return func() (bool, string) {
71
+func Contains(collection interface{}, item interface{}) Comparison {
72
+	return func() Result {
73 73
 		colValue := reflect.ValueOf(collection)
74 74
 		if !colValue.IsValid() {
75
-			return false, fmt.Sprintf("nil does not contain items")
75
+			return ResultFailure(fmt.Sprintf("nil does not contain items"))
76 76
 		}
77 77
 		msg := fmt.Sprintf("%v does not contain %v", collection, item)
78 78
 
... ...
@@ -80,94 +140,72 @@ func Contains(collection interface{}, item interface{}) func() (bool, string) {
80 80
 		switch colValue.Type().Kind() {
81 81
 		case reflect.String:
82 82
 			if itemValue.Type().Kind() != reflect.String {
83
-				return false, "string may only contain strings"
83
+				return ResultFailure("string may only contain strings")
84 84
 			}
85
-			success := strings.Contains(colValue.String(), itemValue.String())
86
-			return success, fmt.Sprintf("string %q does not contain %q", collection, item)
85
+			return toResult(
86
+				strings.Contains(colValue.String(), itemValue.String()),
87
+				fmt.Sprintf("string %q does not contain %q", collection, item))
87 88
 
88 89
 		case reflect.Map:
89 90
 			if itemValue.Type() != colValue.Type().Key() {
90
-				return false, fmt.Sprintf(
91
-					"%v can not contain a %v key", colValue.Type(), itemValue.Type())
91
+				return ResultFailure(fmt.Sprintf(
92
+					"%v can not contain a %v key", colValue.Type(), itemValue.Type()))
92 93
 			}
93
-			index := colValue.MapIndex(itemValue)
94
-			return index.IsValid(), msg
94
+			return toResult(colValue.MapIndex(itemValue).IsValid(), msg)
95 95
 
96 96
 		case reflect.Slice, reflect.Array:
97 97
 			for i := 0; i < colValue.Len(); i++ {
98 98
 				if reflect.DeepEqual(colValue.Index(i).Interface(), item) {
99
-					return true, ""
99
+					return ResultSuccess
100 100
 				}
101 101
 			}
102
-			return false, msg
102
+			return ResultFailure(msg)
103 103
 		default:
104
-			return false, fmt.Sprintf("type %T does not contain items", collection)
104
+			return ResultFailure(fmt.Sprintf("type %T does not contain items", collection))
105 105
 		}
106 106
 	}
107 107
 }
108 108
 
109 109
 // Panics succeeds if f() panics.
110
-func Panics(f func()) func() (bool, string) {
111
-	return func() (success bool, message string) {
110
+func Panics(f func()) Comparison {
111
+	return func() (result Result) {
112 112
 		defer func() {
113 113
 			if err := recover(); err != nil {
114
-				success = true
114
+				result = ResultSuccess
115 115
 			}
116 116
 		}()
117 117
 		f()
118
-		return false, "did not panic"
119
-	}
120
-}
121
-
122
-// EqualMultiLine succeeds if the two strings are equal. If they are not equal
123
-// the failure message will be the difference between the two strings.
124
-func EqualMultiLine(x, y string) func() (bool, string) {
125
-	return func() (bool, string) {
126
-		if x == y {
127
-			return true, ""
128
-		}
129
-
130
-		diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
131
-			A:        difflib.SplitLines(x),
132
-			B:        difflib.SplitLines(y),
133
-			FromFile: "left",
134
-			ToFile:   "right",
135
-			Context:  3,
136
-		})
137
-		if err != nil {
138
-			return false, fmt.Sprintf("failed to produce diff: %s", err)
139
-		}
140
-		return false, "\n" + diff
118
+		return ResultFailure("did not panic")
141 119
 	}
142 120
 }
143 121
 
144 122
 // Error succeeds if err is a non-nil error, and the error message equals the
145 123
 // expected message.
146
-func Error(err error, message string) func() (bool, string) {
147
-	return func() (bool, string) {
124
+func Error(err error, message string) Comparison {
125
+	return func() Result {
148 126
 		switch {
149 127
 		case err == nil:
150
-			return false, "expected an error, got nil"
128
+			return ResultFailure("expected an error, got nil")
151 129
 		case err.Error() != message:
152
-			return false, fmt.Sprintf(
153
-				"expected error message %q, got %q", message, err.Error())
130
+			return ResultFailure(fmt.Sprintf(
131
+				"expected error %q, got %+v", message, err))
154 132
 		}
155
-		return true, ""
133
+		return ResultSuccess
156 134
 	}
157 135
 }
158 136
 
159 137
 // ErrorContains succeeds if err is a non-nil error, and the error message contains
160 138
 // the expected substring.
161
-func ErrorContains(err error, substring string) func() (bool, string) {
162
-	return func() (bool, string) {
139
+func ErrorContains(err error, substring string) Comparison {
140
+	return func() Result {
163 141
 		switch {
164 142
 		case err == nil:
165
-			return false, "expected an error, got nil"
143
+			return ResultFailure("expected an error, got nil")
166 144
 		case !strings.Contains(err.Error(), substring):
167
-			return false, fmt.Sprintf(
168
-				"expected error message to contain %q, got %q", substring, err.Error())
145
+			return ResultFailure(fmt.Sprintf(
146
+				"expected error to contain %q, got %+v", substring, err))
169 147
 		}
170
-		return true, ""
148
+		return ResultSuccess
171 149
 	}
172 150
 }
173 151
 
... ...
@@ -175,27 +213,98 @@ func ErrorContains(err error, substring string) func() (bool, string) {
175 175
 //
176 176
 // Use NilError() for comparing errors. Use Len(obj, 0) for comparing slices,
177 177
 // maps, and channels.
178
-func Nil(obj interface{}) func() (bool, string) {
178
+func Nil(obj interface{}) Comparison {
179 179
 	msgFunc := func(value reflect.Value) string {
180 180
 		return fmt.Sprintf("%v (type %s) is not nil", reflect.Indirect(value), value.Type())
181 181
 	}
182 182
 	return isNil(obj, msgFunc)
183 183
 }
184 184
 
185
-func isNil(obj interface{}, msgFunc func(reflect.Value) string) func() (bool, string) {
186
-	return func() (bool, string) {
185
+func isNil(obj interface{}, msgFunc func(reflect.Value) string) Comparison {
186
+	return func() Result {
187 187
 		if obj == nil {
188
-			return true, ""
188
+			return ResultSuccess
189 189
 		}
190 190
 		value := reflect.ValueOf(obj)
191 191
 		kind := value.Type().Kind()
192 192
 		if kind >= reflect.Chan && kind <= reflect.Slice {
193 193
 			if value.IsNil() {
194
-				return true, ""
194
+				return ResultSuccess
195
+			}
196
+			return ResultFailure(msgFunc(value))
197
+		}
198
+
199
+		return ResultFailure(fmt.Sprintf("%v (type %s) can not be nil", value, value.Type()))
200
+	}
201
+}
202
+
203
+// ErrorType succeeds if err is not nil and is of the expected type.
204
+//
205
+// Expected can be one of:
206
+// a func(error) bool which returns true if the error is the expected type,
207
+// an instance of a struct of the expected type,
208
+// a pointer to an interface the error is expected to implement,
209
+// a reflect.Type of the expected struct or interface.
210
+func ErrorType(err error, expected interface{}) Comparison {
211
+	return func() Result {
212
+		switch expectedType := expected.(type) {
213
+		case func(error) bool:
214
+			return cmpErrorTypeFunc(err, expectedType)
215
+		case reflect.Type:
216
+			if expectedType.Kind() == reflect.Interface {
217
+				return cmpErrorTypeImplementsType(err, expectedType)
195 218
 			}
196
-			return false, msgFunc(value)
219
+			return cmpErrorTypeEqualType(err, expectedType)
220
+		case nil:
221
+			return ResultFailure(fmt.Sprintf("invalid type for expected: nil"))
197 222
 		}
198 223
 
199
-		return false, fmt.Sprintf("%v (type %s) can not be nil", value, value.Type())
224
+		expectedType := reflect.TypeOf(expected)
225
+		switch {
226
+		case expectedType.Kind() == reflect.Struct:
227
+			return cmpErrorTypeEqualType(err, expectedType)
228
+		case isPtrToInterface(expectedType):
229
+			return cmpErrorTypeImplementsType(err, expectedType.Elem())
230
+		}
231
+		return ResultFailure(fmt.Sprintf("invalid type for expected: %T", expected))
200 232
 	}
201 233
 }
234
+
235
+func cmpErrorTypeFunc(err error, f func(error) bool) Result {
236
+	if f(err) {
237
+		return ResultSuccess
238
+	}
239
+	actual := "nil"
240
+	if err != nil {
241
+		actual = fmt.Sprintf("%s (%T)", err, err)
242
+	}
243
+	return ResultFailureTemplate(`error is {{ .Data.actual }}
244
+		{{- with callArg 1 }}, not {{ formatNode . }}{{end -}}`,
245
+		map[string]interface{}{"actual": actual})
246
+}
247
+
248
+func cmpErrorTypeEqualType(err error, expectedType reflect.Type) Result {
249
+	if err == nil {
250
+		return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
251
+	}
252
+	errValue := reflect.ValueOf(err)
253
+	if errValue.Type() == expectedType {
254
+		return ResultSuccess
255
+	}
256
+	return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
257
+}
258
+
259
+func cmpErrorTypeImplementsType(err error, expectedType reflect.Type) Result {
260
+	if err == nil {
261
+		return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
262
+	}
263
+	errValue := reflect.ValueOf(err)
264
+	if errValue.Type().Implements(expectedType) {
265
+		return ResultSuccess
266
+	}
267
+	return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
268
+}
269
+
270
+func isPtrToInterface(typ reflect.Type) bool {
271
+	return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Interface
272
+}
202 273
new file mode 100644
... ...
@@ -0,0 +1,94 @@
0
+package cmp
1
+
2
+import (
3
+	"bytes"
4
+	"fmt"
5
+	"go/ast"
6
+	"text/template"
7
+
8
+	"github.com/gotestyourself/gotestyourself/internal/source"
9
+)
10
+
11
+// Result of a Comparison.
12
+type Result interface {
13
+	Success() bool
14
+}
15
+
16
+type result struct {
17
+	success bool
18
+	message string
19
+}
20
+
21
+func (r result) Success() bool {
22
+	return r.success
23
+}
24
+
25
+func (r result) FailureMessage() string {
26
+	return r.message
27
+}
28
+
29
+// ResultSuccess is a constant which is returned by a ComparisonWithResult to
30
+// indicate success.
31
+var ResultSuccess = result{success: true}
32
+
33
+// ResultFailure returns a failed Result with a failure message.
34
+func ResultFailure(message string) Result {
35
+	return result{message: message}
36
+}
37
+
38
+// ResultFromError returns ResultSuccess if err is nil. Otherwise ResultFailure
39
+// is returned with the error message as the failure message.
40
+func ResultFromError(err error) Result {
41
+	if err == nil {
42
+		return ResultSuccess
43
+	}
44
+	return ResultFailure(err.Error())
45
+}
46
+
47
+type templatedResult struct {
48
+	success  bool
49
+	template string
50
+	data     map[string]interface{}
51
+}
52
+
53
+func (r templatedResult) Success() bool {
54
+	return r.success
55
+}
56
+
57
+func (r templatedResult) FailureMessage(args []ast.Expr) string {
58
+	msg, err := renderMessage(r, args)
59
+	if err != nil {
60
+		return fmt.Sprintf("failed to render failure message: %s", err)
61
+	}
62
+	return msg
63
+}
64
+
65
+// ResultFailureTemplate returns a Result with a template string and data which
66
+// can be used to format a failure message. The template may access data from .Data,
67
+// the comparison args with the callArg function, and the formatNode function may
68
+// be used to format the call args.
69
+func ResultFailureTemplate(template string, data map[string]interface{}) Result {
70
+	return templatedResult{template: template, data: data}
71
+}
72
+
73
+func renderMessage(result templatedResult, args []ast.Expr) (string, error) {
74
+	tmpl := template.New("failure").Funcs(template.FuncMap{
75
+		"formatNode": source.FormatNode,
76
+		"callArg": func(index int) ast.Expr {
77
+			if index >= len(args) {
78
+				return nil
79
+			}
80
+			return args[index]
81
+		},
82
+	})
83
+	var err error
84
+	tmpl, err = tmpl.Parse(result.template)
85
+	if err != nil {
86
+		return "", err
87
+	}
88
+	buf := new(bytes.Buffer)
89
+	err = tmpl.Execute(buf, map[string]interface{}{
90
+		"Data": result.data,
91
+	})
92
+	return buf.String(), err
93
+}
0 94
new file mode 100644
... ...
@@ -0,0 +1,107 @@
0
+package assert
1
+
2
+import (
3
+	"fmt"
4
+	"go/ast"
5
+
6
+	"github.com/gotestyourself/gotestyourself/assert/cmp"
7
+	"github.com/gotestyourself/gotestyourself/internal/format"
8
+	"github.com/gotestyourself/gotestyourself/internal/source"
9
+)
10
+
11
+func runComparison(
12
+	t TestingT,
13
+	argSelector argSelector,
14
+	f cmp.Comparison,
15
+	msgAndArgs ...interface{},
16
+) bool {
17
+	if ht, ok := t.(helperT); ok {
18
+		ht.Helper()
19
+	}
20
+	result := f()
21
+	if result.Success() {
22
+		return true
23
+	}
24
+
25
+	var message string
26
+	switch typed := result.(type) {
27
+	case resultWithComparisonArgs:
28
+		const stackIndex = 3 // Assert/Check, assert, runComparison
29
+		args, err := source.CallExprArgs(stackIndex)
30
+		if err != nil {
31
+			t.Log(err.Error())
32
+		}
33
+		message = typed.FailureMessage(filterPrintableExpr(argSelector(args)))
34
+	case resultBasic:
35
+		message = typed.FailureMessage()
36
+	default:
37
+		message = fmt.Sprintf("comparison returned invalid Result type: %T", result)
38
+	}
39
+
40
+	t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
41
+	return false
42
+}
43
+
44
+type resultWithComparisonArgs interface {
45
+	FailureMessage(args []ast.Expr) string
46
+}
47
+
48
+type resultBasic interface {
49
+	FailureMessage() string
50
+}
51
+
52
+// filterPrintableExpr filters the ast.Expr slice to only include Expr that are
53
+// easy to read when printed and contain relevant information to an assertion.
54
+//
55
+// Ident and SelectorExpr are included because they print nicely and the variable
56
+// names may provide additional context to their values.
57
+// BasicLit and CompositeLit are excluded because their source is equivalent to
58
+// their value, which is already available.
59
+// Other types are ignored for now, but could be added if they are relevant.
60
+func filterPrintableExpr(args []ast.Expr) []ast.Expr {
61
+	result := make([]ast.Expr, len(args))
62
+	for i, arg := range args {
63
+		if isShortPrintableExpr(arg) {
64
+			result[i] = arg
65
+			continue
66
+		}
67
+
68
+		if starExpr, ok := arg.(*ast.StarExpr); ok {
69
+			result[i] = starExpr.X
70
+			continue
71
+		}
72
+		result[i] = nil
73
+	}
74
+	return result
75
+}
76
+
77
+func isShortPrintableExpr(expr ast.Expr) bool {
78
+	switch expr.(type) {
79
+	case *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr:
80
+		return true
81
+	case *ast.BinaryExpr, *ast.UnaryExpr:
82
+		return true
83
+	default:
84
+		// CallExpr, ParenExpr, TypeAssertExpr, KeyValueExpr, StarExpr
85
+		return false
86
+	}
87
+}
88
+
89
+type argSelector func([]ast.Expr) []ast.Expr
90
+
91
+func argsAfterT(args []ast.Expr) []ast.Expr {
92
+	if len(args) < 1 {
93
+		return nil
94
+	}
95
+	return args[1:]
96
+}
97
+
98
+func argsFromComparisonCall(args []ast.Expr) []ast.Expr {
99
+	if len(args) < 1 {
100
+		return nil
101
+	}
102
+	if callExpr, ok := args[1].(*ast.CallExpr); ok {
103
+		return callExpr.Args
104
+	}
105
+	return nil
106
+}
... ...
@@ -45,7 +45,7 @@ func PatchAll(t assert.TestingT, env map[string]string) func() {
45 45
 	os.Clearenv()
46 46
 
47 47
 	for key, value := range env {
48
-		assert.NilError(t, os.Setenv(key, value))
48
+		assert.NilError(t, os.Setenv(key, value), "setenv %s=%s", key, value)
49 49
 	}
50 50
 	return func() {
51 51
 		if ht, ok := t.(helperT); ok {
... ...
@@ -53,7 +53,7 @@ func PatchAll(t assert.TestingT, env map[string]string) func() {
53 53
 		}
54 54
 		os.Clearenv()
55 55
 		for key, oldVal := range ToMap(oldEnv) {
56
-			assert.NilError(t, os.Setenv(key, oldVal))
56
+			assert.NilError(t, os.Setenv(key, oldVal), "setenv %s=%s", key, oldVal)
57 57
 		}
58 58
 	}
59 59
 }
... ...
@@ -63,17 +63,23 @@ func PatchAll(t assert.TestingT, env map[string]string) func() {
63 63
 func ToMap(env []string) map[string]string {
64 64
 	result := map[string]string{}
65 65
 	for _, raw := range env {
66
-		parts := strings.SplitN(raw, "=", 2)
67
-		switch len(parts) {
68
-		case 1:
69
-			result[raw] = ""
70
-		case 2:
71
-			result[parts[0]] = parts[1]
72
-		}
66
+		key, value := getParts(raw)
67
+		result[key] = value
73 68
 	}
74 69
 	return result
75 70
 }
76 71
 
72
+func getParts(raw string) (string, string) {
73
+	// Environment variables on windows can begin with =
74
+	// http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
75
+	parts := strings.SplitN(raw[1:], "=", 2)
76
+	key := raw[:1] + parts[0]
77
+	if len(parts) == 1 {
78
+		return key, ""
79
+	}
80
+	return key, parts[1]
81
+}
82
+
77 83
 // ChangeWorkingDir to the directory, and return a function which restores the
78 84
 // previous working directory.
79 85
 func ChangeWorkingDir(t assert.TestingT, dir string) func() {
... ...
@@ -4,6 +4,7 @@ import (
4 4
 	"io/ioutil"
5 5
 	"os"
6 6
 	"path/filepath"
7
+	"time"
7 8
 )
8 9
 
9 10
 // PathOp is a function which accepts a Path to perform some operation
... ...
@@ -125,3 +126,33 @@ func copyFile(source, dest string) error {
125 125
 	}
126 126
 	return ioutil.WriteFile(dest, content, 0644)
127 127
 }
128
+
129
+// WithSymlink creates a symlink in the directory which links to target.
130
+// Target must be a path relative to the directory.
131
+//
132
+// Note: the argument order is the inverse of os.Symlink to be consistent with
133
+// the other functions in this package.
134
+func WithSymlink(path, target string) PathOp {
135
+	return func(root Path) error {
136
+		return os.Symlink(filepath.Join(root.Path(), target), filepath.Join(root.Path(), path))
137
+	}
138
+}
139
+
140
+// WithHardlink creates a link in the directory which links to target.
141
+// Target must be a path relative to the directory.
142
+//
143
+// Note: the argument order is the inverse of os.Link to be consistent with
144
+// the other functions in this package.
145
+func WithHardlink(path, target string) PathOp {
146
+	return func(root Path) error {
147
+		return os.Link(filepath.Join(root.Path(), target), filepath.Join(root.Path(), path))
148
+	}
149
+}
150
+
151
+// WithTimestamps sets the access and modification times of the file system object
152
+// at path.
153
+func WithTimestamps(atime, mtime time.Time) PathOp {
154
+	return func(root Path) error {
155
+		return os.Chtimes(root.Path(), atime, mtime)
156
+	}
157
+}
... ...
@@ -10,11 +10,10 @@ import (
10 10
 	"strings"
11 11
 	"sync"
12 12
 	"time"
13
-)
14 13
 
15
-type testingT interface {
16
-	Fatalf(string, ...interface{})
17
-}
14
+	"github.com/gotestyourself/gotestyourself/assert"
15
+	"github.com/gotestyourself/gotestyourself/assert/cmp"
16
+)
18 17
 
19 18
 type helperT interface {
20 19
 	Helper()
... ...
@@ -53,23 +52,32 @@ type Result struct {
53 53
 
54 54
 // Assert compares the Result against the Expected struct, and fails the test if
55 55
 // any of the expectations are not met.
56
-// TODO: deprecate and replace with assert.CompareFunc
57
-func (r *Result) Assert(t testingT, exp Expected) *Result {
56
+//
57
+// This function is equivalent to assert.Assert(t, result.Equal(exp)).
58
+func (r *Result) Assert(t assert.TestingT, exp Expected) *Result {
58 59
 	if ht, ok := t.(helperT); ok {
59 60
 		ht.Helper()
60 61
 	}
61
-	err := r.Compare(exp)
62
-	if err == nil {
63
-		return r
62
+	assert.Assert(t, r.Equal(exp))
63
+	return r
64
+}
65
+
66
+// Equal compares the result to Expected. If the result doesn't match expected
67
+// returns a formatted failure message with the command, stdout, stderr, exit code,
68
+// and any failed expectations.
69
+func (r *Result) Equal(exp Expected) cmp.Comparison {
70
+	return func() cmp.Result {
71
+		return cmp.ResultFromError(r.match(exp))
64 72
 	}
65
-	t.Fatalf(err.Error() + "\n")
66
-	return nil
67 73
 }
68 74
 
69
-// Compare returns a formatted error with the command, stdout, stderr, exit
70
-// code, and any failed expectations
71
-// nolint: gocyclo
75
+// Compare the result to Expected and return an error if they do not match.
72 76
 func (r *Result) Compare(exp Expected) error {
77
+	return r.match(exp)
78
+}
79
+
80
+// nolint: gocyclo
81
+func (r *Result) match(exp Expected) error {
73 82
 	errors := []string{}
74 83
 	add := func(format string, args ...interface{}) {
75 84
 		errors = append(errors, fmt.Sprintf(format, args...))
... ...
@@ -2,31 +2,29 @@ package source
2 2
 
3 3
 import (
4 4
 	"bytes"
5
+	"fmt"
5 6
 	"go/ast"
6 7
 	"go/format"
7 8
 	"go/parser"
8 9
 	"go/token"
10
+	"os"
9 11
 	"runtime"
12
+	"strconv"
13
+	"strings"
10 14
 
11 15
 	"github.com/pkg/errors"
12 16
 )
13 17
 
14 18
 const baseStackIndex = 1
15 19
 
16
-// GetCondition returns the condition string by reading it from the file
17
-// identified in the callstack. In golang 1.9 the line number changed from
18
-// being the line where the statement ended to the line where the statement began.
19
-func GetCondition(stackIndex int, argPos int) (string, error) {
20
-	_, filename, lineNum, ok := runtime.Caller(baseStackIndex + stackIndex)
21
-	if !ok {
22
-		return "", errors.New("failed to get caller info")
23
-	}
24
-
25
-	node, err := getNodeAtLine(filename, lineNum)
20
+// FormattedCallExprArg returns the argument from an ast.CallExpr at the
21
+// index in the call stack. The argument is formatted using FormatNode.
22
+func FormattedCallExprArg(stackIndex int, argPos int) (string, error) {
23
+	args, err := CallExprArgs(stackIndex + 1)
26 24
 	if err != nil {
27 25
 		return "", err
28 26
 	}
29
-	return getArgSourceFromAST(node, argPos)
27
+	return FormatNode(args[argPos])
30 28
 }
31 29
 
32 30
 func getNodeAtLine(filename string, lineNum int) (ast.Node, error) {
... ...
@@ -38,7 +36,7 @@ func getNodeAtLine(filename string, lineNum int) (ast.Node, error) {
38 38
 
39 39
 	node := scanToLine(fileset, astFile, lineNum)
40 40
 	if node == nil {
41
-		return nil, errors.Wrapf(err,
41
+		return nil, errors.Errorf(
42 42
 			"failed to find an expression on line %d in %s", lineNum, filename)
43 43
 	}
44 44
 	return node, nil
... ...
@@ -60,32 +58,46 @@ func (v *scanToLineVisitor) Visit(node ast.Node) ast.Visitor {
60 60
 	if node == nil || v.matchedNode != nil {
61 61
 		return nil
62 62
 	}
63
-
64
-	var position token.Position
65
-	switch {
66
-	case runtime.Version() < "go1.9":
67
-		position = v.fileset.Position(node.End())
68
-	default:
69
-		position = v.fileset.Position(node.Pos())
70
-	}
71
-
72
-	if position.Line == v.lineNum {
63
+	if v.nodePosition(node).Line == v.lineNum {
73 64
 		v.matchedNode = node
74 65
 		return nil
75 66
 	}
76 67
 	return v
77 68
 }
78 69
 
79
-func getArgSourceFromAST(node ast.Node, argPos int) (string, error) {
70
+// In golang 1.9 the line number changed from being the line where the statement
71
+// ended to the line where the statement began.
72
+func (v *scanToLineVisitor) nodePosition(node ast.Node) token.Position {
73
+	if goVersionBefore19 {
74
+		return v.fileset.Position(node.End())
75
+	}
76
+	return v.fileset.Position(node.Pos())
77
+}
78
+
79
+var goVersionBefore19 = isGOVersionBefore19()
80
+
81
+func isGOVersionBefore19() bool {
82
+	version := runtime.Version()
83
+	// not a release version
84
+	if !strings.HasPrefix(version, "go") {
85
+		return false
86
+	}
87
+	version = strings.TrimPrefix(version, "go")
88
+	parts := strings.Split(version, ".")
89
+	if len(parts) < 2 {
90
+		return false
91
+	}
92
+	minor, err := strconv.ParseInt(parts[1], 10, 32)
93
+	return err == nil && parts[0] == "1" && minor < 9
94
+}
95
+
96
+func getCallExprArgs(node ast.Node) ([]ast.Expr, error) {
80 97
 	visitor := &callExprVisitor{}
81 98
 	ast.Walk(visitor, node)
82 99
 	if visitor.expr == nil {
83
-		return "", errors.Errorf("unexpected ast")
100
+		return nil, errors.New("failed to find call expression")
84 101
 	}
85
-
86
-	buf := new(bytes.Buffer)
87
-	err := format.Node(buf, token.NewFileSet(), visitor.expr.Args[argPos])
88
-	return buf.String(), err
102
+	return visitor.expr.Args, nil
89 103
 }
90 104
 
91 105
 type callExprVisitor struct {
... ...
@@ -93,17 +105,59 @@ type callExprVisitor struct {
93 93
 }
94 94
 
95 95
 func (v *callExprVisitor) Visit(node ast.Node) ast.Visitor {
96
-	switch typed := node.(type) {
97
-	case nil:
96
+	if v.expr != nil || node == nil {
98 97
 		return nil
99
-	case *ast.IfStmt:
100
-		ast.Walk(v, typed.Cond)
101
-	case *ast.CallExpr:
102
-		v.expr = typed
103 98
 	}
99
+	debug("visit (%T): %s", node, debugFormatNode{node})
104 100
 
105
-	if v.expr != nil {
101
+	if callExpr, ok := node.(*ast.CallExpr); ok {
102
+		v.expr = callExpr
106 103
 		return nil
107 104
 	}
108 105
 	return v
109 106
 }
107
+
108
+// FormatNode using go/format.Node and return the result as a string
109
+func FormatNode(node ast.Node) (string, error) {
110
+	buf := new(bytes.Buffer)
111
+	err := format.Node(buf, token.NewFileSet(), node)
112
+	return buf.String(), err
113
+}
114
+
115
+// CallExprArgs returns the ast.Expr slice for the args of an ast.CallExpr at
116
+// the index in the call stack.
117
+func CallExprArgs(stackIndex int) ([]ast.Expr, error) {
118
+	_, filename, lineNum, ok := runtime.Caller(baseStackIndex + stackIndex)
119
+	if !ok {
120
+		return nil, errors.New("failed to get call stack")
121
+	}
122
+	debug("call stack position: %s:%d", filename, lineNum)
123
+
124
+	node, err := getNodeAtLine(filename, lineNum)
125
+	if err != nil {
126
+		return nil, err
127
+	}
128
+	debug("found node (%T): %s", node, debugFormatNode{node})
129
+
130
+	return getCallExprArgs(node)
131
+}
132
+
133
+var debugEnabled = os.Getenv("GOTESTYOURSELF_DEBUG") != ""
134
+
135
+func debug(format string, args ...interface{}) {
136
+	if debugEnabled {
137
+		fmt.Fprintf(os.Stderr, "DEBUG: "+format+"\n", args...)
138
+	}
139
+}
140
+
141
+type debugFormatNode struct {
142
+	ast.Node
143
+}
144
+
145
+func (n debugFormatNode) String() string {
146
+	out, err := FormatNode(n.Node)
147
+	if err != nil {
148
+		return fmt.Sprintf("failed to format %s: %s", n.Node, err)
149
+	}
150
+	return out
151
+}
... ...
@@ -72,7 +72,7 @@ func ifCondition(t skipT, condition bool, msgAndArgs ...interface{}) {
72 72
 		stackIndex = 2
73 73
 		argPos     = 1
74 74
 	)
75
-	source, err := source.GetCondition(stackIndex, argPos)
75
+	source, err := source.FormattedCallExprArg(stackIndex, argPos)
76 76
 	if err != nil {
77 77
 		t.Log(err.Error())
78 78
 		t.Skip(format.Message(msgAndArgs...))
79 79
deleted file mode 100644
... ...
@@ -1,22 +0,0 @@
1
-Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
2
-
3
-Please consider promoting this project if you find it useful.
4
-
5
-Permission is hereby granted, free of charge, to any person 
6
-obtaining a copy of this software and associated documentation 
7
-files (the "Software"), to deal in the Software without restriction, 
8
-including without limitation the rights to use, copy, modify, merge, 
9
-publish, distribute, sublicense, and/or sell copies of the Software, 
10
-and to permit persons to whom the Software is furnished to do so, 
11
-subject to the following conditions:
12
-
13
-The above copyright notice and this permission notice shall be included
14
-in all copies or substantial portions of the Software.
15
-
16
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
17
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
18
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
19
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
20
-DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 
21
-OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
22
-OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 1
deleted file mode 100644
... ...
@@ -1,332 +0,0 @@
1
-Testify - Thou Shalt Write Tests
2
-================================
3
-
4
-[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify)
5
-
6
-Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.
7
-
8
-Features include:
9
-
10
-  * [Easy assertions](#assert-package)
11
-  * [Mocking](#mock-package)
12
-  * [HTTP response trapping](#http-package)
13
-  * [Testing suite interfaces and functions](#suite-package)
14
-
15
-Get started:
16
-
17
-  * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
18
-  * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing
19
-  * Check out the API Documentation http://godoc.org/github.com/stretchr/testify
20
-  * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc)
21
-  * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development)
22
-
23
-
24
-
25
-[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package
26
-
27
-The `assert` package provides some helpful methods that allow you to write better test code in Go.
28
-
29
-  * Prints friendly, easy to read failure descriptions
30
-  * Allows for very readable code
31
-  * Optionally annotate each assertion with a message
32
-
33
-See it in action:
34
-
35
-```go
36
-package yours
37
-
38
-import (
39
-  "testing"
40
-  "github.com/stretchr/testify/assert"
41
-)
42
-
43
-func TestSomething(t *testing.T) {
44
-
45
-  // assert equality
46
-  assert.Equal(t, 123, 123, "they should be equal")
47
-
48
-  // assert inequality
49
-  assert.NotEqual(t, 123, 456, "they should not be equal")
50
-
51
-  // assert for nil (good for errors)
52
-  assert.Nil(t, object)
53
-
54
-  // assert for not nil (good when you expect something)
55
-  if assert.NotNil(t, object) {
56
-
57
-    // now we know that object isn't nil, we are safe to make
58
-    // further assertions without causing any errors
59
-    assert.Equal(t, "Something", object.Value)
60
-
61
-  }
62
-
63
-}
64
-```
65
-
66
-  * Every assert func takes the `testing.T` object as the first argument.  This is how it writes the errors out through the normal `go test` capabilities.
67
-  * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
68
-
69
-if you assert many times, use the below:
70
-
71
-```go
72
-package yours
73
-
74
-import (
75
-  "testing"
76
-  "github.com/stretchr/testify/assert"
77
-)
78
-
79
-func TestSomething(t *testing.T) {
80
-  assert := assert.New(t)
81
-
82
-  // assert equality
83
-  assert.Equal(123, 123, "they should be equal")
84
-
85
-  // assert inequality
86
-  assert.NotEqual(123, 456, "they should not be equal")
87
-
88
-  // assert for nil (good for errors)
89
-  assert.Nil(object)
90
-
91
-  // assert for not nil (good when you expect something)
92
-  if assert.NotNil(object) {
93
-
94
-    // now we know that object isn't nil, we are safe to make
95
-    // further assertions without causing any errors
96
-    assert.Equal("Something", object.Value)
97
-  }
98
-}
99
-```
100
-
101
-[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package
102
-
103
-The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test.
104
-
105
-See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details.
106
-
107
-
108
-[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package
109
-
110
-The `http` package contains test objects useful for testing code that relies on the `net/http` package.  Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http).
111
-
112
-We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead.
113
-
114
-[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package
115
-
116
-The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
117
-
118
-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:
119
-
120
-```go
121
-package yours
122
-
123
-import (
124
-  "testing"
125
-  "github.com/stretchr/testify/mock"
126
-)
127
-
128
-/*
129
-  Test objects
130
-*/
131
-
132
-// MyMockedObject is a mocked object that implements an interface
133
-// that describes an object that the code I am testing relies on.
134
-type MyMockedObject struct{
135
-  mock.Mock
136
-}
137
-
138
-// DoSomething is a method on MyMockedObject that implements some interface
139
-// and just records the activity, and returns what the Mock object tells it to.
140
-//
141
-// In the real object, this method would do something useful, but since this
142
-// is a mocked object - we're just going to stub it out.
143
-//
144
-// NOTE: This method is not being tested here, code that uses this object is.
145
-func (m *MyMockedObject) DoSomething(number int) (bool, error) {
146
-
147
-  args := m.Called(number)
148
-  return args.Bool(0), args.Error(1)
149
-
150
-}
151
-
152
-/*
153
-  Actual test functions
154
-*/
155
-
156
-// TestSomething is an example of how to use our test object to
157
-// make assertions about some target code we are testing.
158
-func TestSomething(t *testing.T) {
159
-
160
-  // create an instance of our test object
161
-  testObj := new(MyMockedObject)
162
-
163
-  // setup expectations
164
-  testObj.On("DoSomething", 123).Return(true, nil)
165
-
166
-  // call the code we are testing
167
-  targetFuncThatDoesSomethingWithObj(testObj)
168
-
169
-  // assert that the expectations were met
170
-  testObj.AssertExpectations(t)
171
-
172
-}
173
-```
174
-
175
-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).
176
-
177
-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.
178
-
179
-[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package
180
-
181
-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.
182
-
183
-An example suite is shown below:
184
-
185
-```go
186
-// Basic imports
187
-import (
188
-    "testing"
189
-    "github.com/stretchr/testify/assert"
190
-    "github.com/stretchr/testify/suite"
191
-)
192
-
193
-// Define the suite, and absorb the built-in basic suite
194
-// functionality from testify - including a T() method which
195
-// returns the current testing context
196
-type ExampleTestSuite struct {
197
-    suite.Suite
198
-    VariableThatShouldStartAtFive int
199
-}
200
-
201
-// Make sure that VariableThatShouldStartAtFive is set to five
202
-// before each test
203
-func (suite *ExampleTestSuite) SetupTest() {
204
-    suite.VariableThatShouldStartAtFive = 5
205
-}
206
-
207
-// All methods that begin with "Test" are run as tests within a
208
-// suite.
209
-func (suite *ExampleTestSuite) TestExample() {
210
-    assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
211
-}
212
-
213
-// In order for 'go test' to run this suite, we need to create
214
-// a normal test function and pass our suite to suite.Run
215
-func TestExampleTestSuite(t *testing.T) {
216
-    suite.Run(t, new(ExampleTestSuite))
217
-}
218
-```
219
-
220
-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)
221
-
222
-For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
223
-
224
-`Suite` object has assertion methods:
225
-
226
-```go
227
-// Basic imports
228
-import (
229
-    "testing"
230
-    "github.com/stretchr/testify/suite"
231
-)
232
-
233
-// Define the suite, and absorb the built-in basic suite
234
-// functionality from testify - including assertion methods.
235
-type ExampleTestSuite struct {
236
-    suite.Suite
237
-    VariableThatShouldStartAtFive int
238
-}
239
-
240
-// Make sure that VariableThatShouldStartAtFive is set to five
241
-// before each test
242
-func (suite *ExampleTestSuite) SetupTest() {
243
-    suite.VariableThatShouldStartAtFive = 5
244
-}
245
-
246
-// All methods that begin with "Test" are run as tests within a
247
-// suite.
248
-func (suite *ExampleTestSuite) TestExample() {
249
-    suite.Equal(suite.VariableThatShouldStartAtFive, 5)
250
-}
251
-
252
-// In order for 'go test' to run this suite, we need to create
253
-// a normal test function and pass our suite to suite.Run
254
-func TestExampleTestSuite(t *testing.T) {
255
-    suite.Run(t, new(ExampleTestSuite))
256
-}
257
-```
258
-
259
-
260
-Installation
261
-============
262
-
263
-To install Testify, use `go get`:
264
-
265
-    * Latest version: go get github.com/stretchr/testify
266
-    * Specific version: go get gopkg.in/stretchr/testify.v1
267
-
268
-This will then make the following packages available to you:
269
-
270
-    github.com/stretchr/testify/assert
271
-    github.com/stretchr/testify/mock
272
-    github.com/stretchr/testify/http
273
-
274
-Import the `testify/assert` package into your code using this template:
275
-
276
-```go
277
-package yours
278
-
279
-import (
280
-  "testing"
281
-  "github.com/stretchr/testify/assert"
282
-)
283
-
284
-func TestSomething(t *testing.T) {
285
-
286
-  assert.True(t, true, "True is true!")
287
-
288
-}
289
-```
290
-
291
-
292
-Staying up to date
293
-==================
294
-
295
-To update Testify to the latest version, use `go get -u github.com/stretchr/testify`.
296
-
297
-
298
-Version History
299
-===============
300
-
301
-   * 1.0 - New package versioning strategy adopted.
302
-
303
-
304
-Contributing
305
-============
306
-
307
-Please feel free to submit issues, fork the repository and send pull requests!
308
-
309
-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.
310
-
311
-
312
-Licence
313
-=======
314
-Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
315
-
316
-Please consider promoting this project if you find it useful.
317
-
318
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
319
-
320
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
321
-
322
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
323 1
deleted file mode 100644
... ...
@@ -1,352 +0,0 @@
1
-/*
2
-* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
3
-* THIS FILE MUST NOT BE EDITED BY HAND
4
- */
5
-
6
-package assert
7
-
8
-import (
9
-	http "net/http"
10
-	url "net/url"
11
-	time "time"
12
-)
13
-
14
-// Condition uses a Comparison to assert a complex condition.
15
-func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool {
16
-	return Condition(a.t, comp, msgAndArgs...)
17
-}
18
-
19
-// Contains asserts that the specified string, list(array, slice...) or map contains the
20
-// specified substring or element.
21
-//
22
-//    a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'")
23
-//    a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
24
-//    a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
25
-//
26
-// Returns whether the assertion was successful (true) or not (false).
27
-func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
28
-	return Contains(a.t, s, contains, msgAndArgs...)
29
-}
30
-
31
-// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
32
-// a slice or a channel with len == 0.
33
-//
34
-//  a.Empty(obj)
35
-//
36
-// Returns whether the assertion was successful (true) or not (false).
37
-func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
38
-	return Empty(a.t, object, msgAndArgs...)
39
-}
40
-
41
-// Equal asserts that two objects are equal.
42
-//
43
-//    a.Equal(123, 123, "123 and 123 should be equal")
44
-//
45
-// Returns whether the assertion was successful (true) or not (false).
46
-//
47
-// Pointer variable equality is determined based on the equality of the
48
-// referenced values (as opposed to the memory addresses).
49
-func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
50
-	return Equal(a.t, expected, actual, msgAndArgs...)
51
-}
52
-
53
-// EqualError asserts that a function returned an error (i.e. not `nil`)
54
-// and that it is equal to the provided error.
55
-//
56
-//   actualObj, err := SomeFunction()
57
-//   a.EqualError(err,  expectedErrorString, "An error was expected")
58
-//
59
-// Returns whether the assertion was successful (true) or not (false).
60
-func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool {
61
-	return EqualError(a.t, theError, errString, msgAndArgs...)
62
-}
63
-
64
-// EqualValues asserts that two objects are equal or convertable to the same types
65
-// and equal.
66
-//
67
-//    a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal")
68
-//
69
-// Returns whether the assertion was successful (true) or not (false).
70
-func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
71
-	return EqualValues(a.t, expected, actual, msgAndArgs...)
72
-}
73
-
74
-// Error asserts that a function returned an error (i.e. not `nil`).
75
-//
76
-//   actualObj, err := SomeFunction()
77
-//   if a.Error(err, "An error was expected") {
78
-// 	   assert.Equal(t, err, expectedError)
79
-//   }
80
-//
81
-// Returns whether the assertion was successful (true) or not (false).
82
-func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool {
83
-	return Error(a.t, err, msgAndArgs...)
84
-}
85
-
86
-// Exactly asserts that two objects are equal is value and type.
87
-//
88
-//    a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal")
89
-//
90
-// Returns whether the assertion was successful (true) or not (false).
91
-func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
92
-	return Exactly(a.t, expected, actual, msgAndArgs...)
93
-}
94
-
95
-// Fail reports a failure through
96
-func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool {
97
-	return Fail(a.t, failureMessage, msgAndArgs...)
98
-}
99
-
100
-// FailNow fails test
101
-func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool {
102
-	return FailNow(a.t, failureMessage, msgAndArgs...)
103
-}
104
-
105
-// False asserts that the specified value is false.
106
-//
107
-//    a.False(myBool, "myBool should be false")
108
-//
109
-// Returns whether the assertion was successful (true) or not (false).
110
-func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool {
111
-	return False(a.t, value, msgAndArgs...)
112
-}
113
-
114
-// HTTPBodyContains asserts that a specified handler returns a
115
-// body that contains a string.
116
-//
117
-//  a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky")
118
-//
119
-// Returns whether the assertion was successful (true) or not (false).
120
-func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool {
121
-	return HTTPBodyContains(a.t, handler, method, url, values, str)
122
-}
123
-
124
-// HTTPBodyNotContains asserts that a specified handler returns a
125
-// body that does not contain a string.
126
-//
127
-//  a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky")
128
-//
129
-// Returns whether the assertion was successful (true) or not (false).
130
-func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool {
131
-	return HTTPBodyNotContains(a.t, handler, method, url, values, str)
132
-}
133
-
134
-// HTTPError asserts that a specified handler returns an error status code.
135
-//
136
-//  a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
137
-//
138
-// Returns whether the assertion was successful (true) or not (false).
139
-func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool {
140
-	return HTTPError(a.t, handler, method, url, values)
141
-}
142
-
143
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
144
-//
145
-//  a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
146
-//
147
-// Returns whether the assertion was successful (true) or not (false).
148
-func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool {
149
-	return HTTPRedirect(a.t, handler, method, url, values)
150
-}
151
-
152
-// HTTPSuccess asserts that a specified handler returns a success status code.
153
-//
154
-//  a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
155
-//
156
-// Returns whether the assertion was successful (true) or not (false).
157
-func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool {
158
-	return HTTPSuccess(a.t, handler, method, url, values)
159
-}
160
-
161
-// Implements asserts that an object is implemented by the specified interface.
162
-//
163
-//    a.Implements((*MyInterface)(nil), new(MyObject), "MyObject")
164
-func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
165
-	return Implements(a.t, interfaceObject, object, msgAndArgs...)
166
-}
167
-
168
-// InDelta asserts that the two numerals are within delta of each other.
169
-//
170
-// 	 a.InDelta(math.Pi, (22 / 7.0), 0.01)
171
-//
172
-// Returns whether the assertion was successful (true) or not (false).
173
-func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
174
-	return InDelta(a.t, expected, actual, delta, msgAndArgs...)
175
-}
176
-
177
-// InDeltaSlice is the same as InDelta, except it compares two slices.
178
-func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
179
-	return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...)
180
-}
181
-
182
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
183
-//
184
-// Returns whether the assertion was successful (true) or not (false).
185
-func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
186
-	return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
187
-}
188
-
189
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
190
-func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
191
-	return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
192
-}
193
-
194
-// IsType asserts that the specified objects are of the same type.
195
-func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
196
-	return IsType(a.t, expectedType, object, msgAndArgs...)
197
-}
198
-
199
-// JSONEq asserts that two JSON strings are equivalent.
200
-//
201
-//  a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
202
-//
203
-// Returns whether the assertion was successful (true) or not (false).
204
-func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool {
205
-	return JSONEq(a.t, expected, actual, msgAndArgs...)
206
-}
207
-
208
-// Len asserts that the specified object has specific length.
209
-// Len also fails if the object has a type that len() not accept.
210
-//
211
-//    a.Len(mySlice, 3, "The size of slice is not 3")
212
-//
213
-// Returns whether the assertion was successful (true) or not (false).
214
-func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool {
215
-	return Len(a.t, object, length, msgAndArgs...)
216
-}
217
-
218
-// Nil asserts that the specified object is nil.
219
-//
220
-//    a.Nil(err, "err should be nothing")
221
-//
222
-// Returns whether the assertion was successful (true) or not (false).
223
-func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool {
224
-	return Nil(a.t, object, msgAndArgs...)
225
-}
226
-
227
-// NoError asserts that a function returned no error (i.e. `nil`).
228
-//
229
-//   actualObj, err := SomeFunction()
230
-//   if a.NoError(err) {
231
-// 	   assert.Equal(t, actualObj, expectedObj)
232
-//   }
233
-//
234
-// Returns whether the assertion was successful (true) or not (false).
235
-func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
236
-	return NoError(a.t, err, msgAndArgs...)
237
-}
238
-
239
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
240
-// specified substring or element.
241
-//
242
-//    a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
243
-//    a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
244
-//    a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
245
-//
246
-// Returns whether the assertion was successful (true) or not (false).
247
-func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
248
-	return NotContains(a.t, s, contains, msgAndArgs...)
249
-}
250
-
251
-// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
252
-// a slice or a channel with len == 0.
253
-//
254
-//  if a.NotEmpty(obj) {
255
-//    assert.Equal(t, "two", obj[1])
256
-//  }
257
-//
258
-// Returns whether the assertion was successful (true) or not (false).
259
-func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool {
260
-	return NotEmpty(a.t, object, msgAndArgs...)
261
-}
262
-
263
-// NotEqual asserts that the specified values are NOT equal.
264
-//
265
-//    a.NotEqual(obj1, obj2, "two objects shouldn't be equal")
266
-//
267
-// Returns whether the assertion was successful (true) or not (false).
268
-//
269
-// Pointer variable equality is determined based on the equality of the
270
-// referenced values (as opposed to the memory addresses).
271
-func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
272
-	return NotEqual(a.t, expected, actual, msgAndArgs...)
273
-}
274
-
275
-// NotNil asserts that the specified object is not nil.
276
-//
277
-//    a.NotNil(err, "err should be something")
278
-//
279
-// Returns whether the assertion was successful (true) or not (false).
280
-func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool {
281
-	return NotNil(a.t, object, msgAndArgs...)
282
-}
283
-
284
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
285
-//
286
-//   a.NotPanics(func(){
287
-//     RemainCalm()
288
-//   }, "Calling RemainCalm() should NOT panic")
289
-//
290
-// Returns whether the assertion was successful (true) or not (false).
291
-func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
292
-	return NotPanics(a.t, f, msgAndArgs...)
293
-}
294
-
295
-// NotRegexp asserts that a specified regexp does not match a string.
296
-//
297
-//  a.NotRegexp(regexp.MustCompile("starts"), "it's starting")
298
-//  a.NotRegexp("^start", "it's not starting")
299
-//
300
-// Returns whether the assertion was successful (true) or not (false).
301
-func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
302
-	return NotRegexp(a.t, rx, str, msgAndArgs...)
303
-}
304
-
305
-// NotZero asserts that i is not the zero value for its type and returns the truth.
306
-func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool {
307
-	return NotZero(a.t, i, msgAndArgs...)
308
-}
309
-
310
-// Panics asserts that the code inside the specified PanicTestFunc panics.
311
-//
312
-//   a.Panics(func(){
313
-//     GoCrazy()
314
-//   }, "Calling GoCrazy() should panic")
315
-//
316
-// Returns whether the assertion was successful (true) or not (false).
317
-func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
318
-	return Panics(a.t, f, msgAndArgs...)
319
-}
320
-
321
-// Regexp asserts that a specified regexp matches a string.
322
-//
323
-//  a.Regexp(regexp.MustCompile("start"), "it's starting")
324
-//  a.Regexp("start...$", "it's not starting")
325
-//
326
-// Returns whether the assertion was successful (true) or not (false).
327
-func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
328
-	return Regexp(a.t, rx, str, msgAndArgs...)
329
-}
330
-
331
-// True asserts that the specified value is true.
332
-//
333
-//    a.True(myBool, "myBool should be true")
334
-//
335
-// Returns whether the assertion was successful (true) or not (false).
336
-func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool {
337
-	return True(a.t, value, msgAndArgs...)
338
-}
339
-
340
-// WithinDuration asserts that the two times are within duration delta of each other.
341
-//
342
-//   a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
343
-//
344
-// Returns whether the assertion was successful (true) or not (false).
345
-func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
346
-	return WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
347
-}
348
-
349
-// Zero asserts that i is the zero value for its type and returns the truth.
350
-func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool {
351
-	return Zero(a.t, i, msgAndArgs...)
352
-}
353 1
deleted file mode 100644
... ...
@@ -1,1069 +0,0 @@
1
-package assert
2
-
3
-import (
4
-	"bufio"
5
-	"bytes"
6
-	"encoding/json"
7
-	"fmt"
8
-	"math"
9
-	"reflect"
10
-	"regexp"
11
-	"runtime"
12
-	"strings"
13
-	"time"
14
-	"unicode"
15
-	"unicode/utf8"
16
-
17
-	"github.com/davecgh/go-spew/spew"
18
-	"github.com/pmezard/go-difflib/difflib"
19
-)
20
-
21
-// TestingT is an interface wrapper around *testing.T
22
-type TestingT interface {
23
-	Errorf(format string, args ...interface{})
24
-}
25
-
26
-// Comparison a custom function that returns true on success and false on failure
27
-type Comparison func() (success bool)
28
-
29
-/*
30
-	Helper functions
31
-*/
32
-
33
-// ObjectsAreEqual determines if two objects are considered equal.
34
-//
35
-// This function does no assertion of any kind.
36
-func ObjectsAreEqual(expected, actual interface{}) bool {
37
-
38
-	if expected == nil || actual == nil {
39
-		return expected == actual
40
-	}
41
-
42
-	return reflect.DeepEqual(expected, actual)
43
-
44
-}
45
-
46
-// ObjectsAreEqualValues gets whether two objects are equal, or if their
47
-// values are equal.
48
-func ObjectsAreEqualValues(expected, actual interface{}) bool {
49
-	if ObjectsAreEqual(expected, actual) {
50
-		return true
51
-	}
52
-
53
-	actualType := reflect.TypeOf(actual)
54
-	if actualType == nil {
55
-		return false
56
-	}
57
-	expectedValue := reflect.ValueOf(expected)
58
-	if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
59
-		// Attempt comparison after type conversion
60
-		return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
61
-	}
62
-
63
-	return false
64
-}
65
-
66
-/* CallerInfo is necessary because the assert functions use the testing object
67
-internally, causing it to print the file:line of the assert method, rather than where
68
-the problem actually occurred in calling code.*/
69
-
70
-// CallerInfo returns an array of strings containing the file and line number
71
-// of each stack frame leading from the current test to the assert call that
72
-// failed.
73
-func CallerInfo() []string {
74
-
75
-	pc := uintptr(0)
76
-	file := ""
77
-	line := 0
78
-	ok := false
79
-	name := ""
80
-
81
-	callers := []string{}
82
-	for i := 0; ; i++ {
83
-		pc, file, line, ok = runtime.Caller(i)
84
-		if !ok {
85
-			// The breaks below failed to terminate the loop, and we ran off the
86
-			// end of the call stack.
87
-			break
88
-		}
89
-
90
-		// This is a huge edge case, but it will panic if this is the case, see #180
91
-		if file == "<autogenerated>" {
92
-			break
93
-		}
94
-
95
-		f := runtime.FuncForPC(pc)
96
-		if f == nil {
97
-			break
98
-		}
99
-		name = f.Name()
100
-
101
-		// testing.tRunner is the standard library function that calls
102
-		// tests. Subtests are called directly by tRunner, without going through
103
-		// the Test/Benchmark/Example function that contains the t.Run calls, so
104
-		// with subtests we should break when we hit tRunner, without adding it
105
-		// to the list of callers.
106
-		if name == "testing.tRunner" {
107
-			break
108
-		}
109
-
110
-		parts := strings.Split(file, "/")
111
-		dir := parts[len(parts)-2]
112
-		file = parts[len(parts)-1]
113
-		if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
114
-			callers = append(callers, fmt.Sprintf("%s:%d", file, line))
115
-		}
116
-
117
-		// Drop the package
118
-		segments := strings.Split(name, ".")
119
-		name = segments[len(segments)-1]
120
-		if isTest(name, "Test") ||
121
-			isTest(name, "Benchmark") ||
122
-			isTest(name, "Example") {
123
-			break
124
-		}
125
-	}
126
-
127
-	return callers
128
-}
129
-
130
-// Stolen from the `go test` tool.
131
-// isTest tells whether name looks like a test (or benchmark, according to prefix).
132
-// It is a Test (say) if there is a character after Test that is not a lower-case letter.
133
-// We don't want TesticularCancer.
134
-func isTest(name, prefix string) bool {
135
-	if !strings.HasPrefix(name, prefix) {
136
-		return false
137
-	}
138
-	if len(name) == len(prefix) { // "Test" is ok
139
-		return true
140
-	}
141
-	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
142
-	return !unicode.IsLower(rune)
143
-}
144
-
145
-// getWhitespaceString returns a string that is long enough to overwrite the default
146
-// output from the go testing framework.
147
-func getWhitespaceString() string {
148
-
149
-	_, file, line, ok := runtime.Caller(1)
150
-	if !ok {
151
-		return ""
152
-	}
153
-	parts := strings.Split(file, "/")
154
-	file = parts[len(parts)-1]
155
-
156
-	return strings.Repeat(" ", len(fmt.Sprintf("%s:%d:        ", file, line)))
157
-
158
-}
159
-
160
-func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
161
-	if len(msgAndArgs) == 0 || msgAndArgs == nil {
162
-		return ""
163
-	}
164
-	if len(msgAndArgs) == 1 {
165
-		return msgAndArgs[0].(string)
166
-	}
167
-	if len(msgAndArgs) > 1 {
168
-		return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
169
-	}
170
-	return ""
171
-}
172
-
173
-// Aligns the provided message so that all lines after the first line start at the same location as the first line.
174
-// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
175
-// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
176
-// basis on which the alignment occurs).
177
-func indentMessageLines(message string, longestLabelLen int) string {
178
-	outBuf := new(bytes.Buffer)
179
-
180
-	for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
181
-		// no need to align first line because it starts at the correct location (after the label)
182
-		if i != 0 {
183
-			// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
184
-			outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen +1) + "\t")
185
-		}
186
-		outBuf.WriteString(scanner.Text())
187
-	}
188
-
189
-	return outBuf.String()
190
-}
191
-
192
-type failNower interface {
193
-	FailNow()
194
-}
195
-
196
-// FailNow fails test
197
-func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
198
-	Fail(t, failureMessage, msgAndArgs...)
199
-
200
-	// We cannot extend TestingT with FailNow() and
201
-	// maintain backwards compatibility, so we fallback
202
-	// to panicking when FailNow is not available in
203
-	// TestingT.
204
-	// See issue #263
205
-
206
-	if t, ok := t.(failNower); ok {
207
-		t.FailNow()
208
-	} else {
209
-		panic("test failed and t is missing `FailNow()`")
210
-	}
211
-	return false
212
-}
213
-
214
-// Fail reports a failure through
215
-func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
216
-	content := []labeledContent{
217
-		{"Error Trace", strings.Join(CallerInfo(), "\n\r\t\t\t")},
218
-		{"Error", failureMessage},
219
-	}
220
-
221
-	message := messageFromMsgAndArgs(msgAndArgs...)
222
-	if len(message) > 0 {
223
-		content = append(content, labeledContent{"Messages", message})
224
-	}
225
-
226
-	t.Errorf("\r" + getWhitespaceString() + labeledOutput(content...))
227
-
228
-	return false
229
-}
230
-
231
-type labeledContent struct {
232
-	label string
233
-	content string
234
-}
235
-
236
-// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
237
-//
238
-//   \r\t{{label}}:{{align_spaces}}\t{{content}}\n
239
-//
240
-// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
241
-// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
242
-// alignment is achieved, "\t{{content}}\n" is added for the output.
243
-//
244
-// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
245
-func labeledOutput(content ...labeledContent) string {
246
-	longestLabel := 0
247
-	for _, v := range content {
248
-		if len(v.label) > longestLabel {
249
-			longestLabel = len(v.label)
250
-		}
251
-	}
252
-	var output string
253
-	for _, v := range content {
254
-		output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
255
-	}
256
-	return output
257
-}
258
-
259
-// Implements asserts that an object is implemented by the specified interface.
260
-//
261
-//    assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
262
-func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
263
-
264
-	interfaceType := reflect.TypeOf(interfaceObject).Elem()
265
-
266
-	if !reflect.TypeOf(object).Implements(interfaceType) {
267
-		return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
268
-	}
269
-
270
-	return true
271
-
272
-}
273
-
274
-// IsType asserts that the specified objects are of the same type.
275
-func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
276
-
277
-	if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
278
-		return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
279
-	}
280
-
281
-	return true
282
-}
283
-
284
-// Equal asserts that two objects are equal.
285
-//
286
-//    assert.Equal(t, 123, 123, "123 and 123 should be equal")
287
-//
288
-// Returns whether the assertion was successful (true) or not (false).
289
-//
290
-// Pointer variable equality is determined based on the equality of the
291
-// referenced values (as opposed to the memory addresses).
292
-func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
293
-
294
-	if !ObjectsAreEqual(expected, actual) {
295
-		diff := diff(expected, actual)
296
-		expected, actual = formatUnequalValues(expected, actual)
297
-		return Fail(t, fmt.Sprintf("Not equal: \n"+
298
-			"expected: %s\n"+
299
-			"received: %s%s", expected, actual, diff), msgAndArgs...)
300
-	}
301
-
302
-	return true
303
-
304
-}
305
-
306
-// formatUnequalValues takes two values of arbitrary types and returns string
307
-// representations appropriate to be presented to the user.
308
-//
309
-// If the values are not of like type, the returned strings will be prefixed
310
-// with the type name, and the value will be enclosed in parenthesis similar
311
-// to a type conversion in the Go grammar.
312
-func formatUnequalValues(expected, actual interface{}) (e string, a string) {
313
-	if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
314
-		return fmt.Sprintf("%T(%#v)", expected, expected),
315
-			fmt.Sprintf("%T(%#v)", actual, actual)
316
-	}
317
-
318
-	return fmt.Sprintf("%#v", expected),
319
-		fmt.Sprintf("%#v", actual)
320
-}
321
-
322
-// EqualValues asserts that two objects are equal or convertable to the same types
323
-// and equal.
324
-//
325
-//    assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal")
326
-//
327
-// Returns whether the assertion was successful (true) or not (false).
328
-func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
329
-
330
-	if !ObjectsAreEqualValues(expected, actual) {
331
-		diff := diff(expected, actual)
332
-		expected, actual = formatUnequalValues(expected, actual)
333
-		return Fail(t, fmt.Sprintf("Not equal: \n"+
334
-			"expected: %s\n"+
335
-			"received: %s%s", expected, actual, diff), msgAndArgs...)
336
-	}
337
-
338
-	return true
339
-
340
-}
341
-
342
-// Exactly asserts that two objects are equal is value and type.
343
-//
344
-//    assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
345
-//
346
-// Returns whether the assertion was successful (true) or not (false).
347
-func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
348
-
349
-	aType := reflect.TypeOf(expected)
350
-	bType := reflect.TypeOf(actual)
351
-
352
-	if aType != bType {
353
-		return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...)
354
-	}
355
-
356
-	return Equal(t, expected, actual, msgAndArgs...)
357
-
358
-}
359
-
360
-// NotNil asserts that the specified object is not nil.
361
-//
362
-//    assert.NotNil(t, err, "err should be something")
363
-//
364
-// Returns whether the assertion was successful (true) or not (false).
365
-func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
366
-	if !isNil(object) {
367
-		return true
368
-	}
369
-	return Fail(t, "Expected value not to be nil.", msgAndArgs...)
370
-}
371
-
372
-// isNil checks if a specified object is nil or not, without Failing.
373
-func isNil(object interface{}) bool {
374
-	if object == nil {
375
-		return true
376
-	}
377
-
378
-	value := reflect.ValueOf(object)
379
-	kind := value.Kind()
380
-	if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
381
-		return true
382
-	}
383
-
384
-	return false
385
-}
386
-
387
-// Nil asserts that the specified object is nil.
388
-//
389
-//    assert.Nil(t, err, "err should be nothing")
390
-//
391
-// Returns whether the assertion was successful (true) or not (false).
392
-func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
393
-	if isNil(object) {
394
-		return true
395
-	}
396
-	return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
397
-}
398
-
399
-var numericZeros = []interface{}{
400
-	int(0),
401
-	int8(0),
402
-	int16(0),
403
-	int32(0),
404
-	int64(0),
405
-	uint(0),
406
-	uint8(0),
407
-	uint16(0),
408
-	uint32(0),
409
-	uint64(0),
410
-	float32(0),
411
-	float64(0),
412
-}
413
-
414
-// isEmpty gets whether the specified object is considered empty or not.
415
-func isEmpty(object interface{}) bool {
416
-
417
-	if object == nil {
418
-		return true
419
-	} else if object == "" {
420
-		return true
421
-	} else if object == false {
422
-		return true
423
-	}
424
-
425
-	for _, v := range numericZeros {
426
-		if object == v {
427
-			return true
428
-		}
429
-	}
430
-
431
-	objValue := reflect.ValueOf(object)
432
-
433
-	switch objValue.Kind() {
434
-	case reflect.Map:
435
-		fallthrough
436
-	case reflect.Slice, reflect.Chan:
437
-		{
438
-			return (objValue.Len() == 0)
439
-		}
440
-	case reflect.Struct:
441
-		switch object.(type) {
442
-		case time.Time:
443
-			return object.(time.Time).IsZero()
444
-		}
445
-	case reflect.Ptr:
446
-		{
447
-			if objValue.IsNil() {
448
-				return true
449
-			}
450
-			switch object.(type) {
451
-			case *time.Time:
452
-				return object.(*time.Time).IsZero()
453
-			default:
454
-				return false
455
-			}
456
-		}
457
-	}
458
-	return false
459
-}
460
-
461
-// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
462
-// a slice or a channel with len == 0.
463
-//
464
-//  assert.Empty(t, obj)
465
-//
466
-// Returns whether the assertion was successful (true) or not (false).
467
-func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
468
-
469
-	pass := isEmpty(object)
470
-	if !pass {
471
-		Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
472
-	}
473
-
474
-	return pass
475
-
476
-}
477
-
478
-// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
479
-// a slice or a channel with len == 0.
480
-//
481
-//  if assert.NotEmpty(t, obj) {
482
-//    assert.Equal(t, "two", obj[1])
483
-//  }
484
-//
485
-// Returns whether the assertion was successful (true) or not (false).
486
-func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
487
-
488
-	pass := !isEmpty(object)
489
-	if !pass {
490
-		Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
491
-	}
492
-
493
-	return pass
494
-
495
-}
496
-
497
-// getLen try to get length of object.
498
-// return (false, 0) if impossible.
499
-func getLen(x interface{}) (ok bool, length int) {
500
-	v := reflect.ValueOf(x)
501
-	defer func() {
502
-		if e := recover(); e != nil {
503
-			ok = false
504
-		}
505
-	}()
506
-	return true, v.Len()
507
-}
508
-
509
-// Len asserts that the specified object has specific length.
510
-// Len also fails if the object has a type that len() not accept.
511
-//
512
-//    assert.Len(t, mySlice, 3, "The size of slice is not 3")
513
-//
514
-// Returns whether the assertion was successful (true) or not (false).
515
-func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
516
-	ok, l := getLen(object)
517
-	if !ok {
518
-		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
519
-	}
520
-
521
-	if l != length {
522
-		return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
523
-	}
524
-	return true
525
-}
526
-
527
-// True asserts that the specified value is true.
528
-//
529
-//    assert.True(t, myBool, "myBool should be true")
530
-//
531
-// Returns whether the assertion was successful (true) or not (false).
532
-func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
533
-
534
-	if value != true {
535
-		return Fail(t, "Should be true", msgAndArgs...)
536
-	}
537
-
538
-	return true
539
-
540
-}
541
-
542
-// False asserts that the specified value is false.
543
-//
544
-//    assert.False(t, myBool, "myBool should be false")
545
-//
546
-// Returns whether the assertion was successful (true) or not (false).
547
-func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
548
-
549
-	if value != false {
550
-		return Fail(t, "Should be false", msgAndArgs...)
551
-	}
552
-
553
-	return true
554
-
555
-}
556
-
557
-// NotEqual asserts that the specified values are NOT equal.
558
-//
559
-//    assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
560
-//
561
-// Returns whether the assertion was successful (true) or not (false).
562
-//
563
-// Pointer variable equality is determined based on the equality of the
564
-// referenced values (as opposed to the memory addresses).
565
-func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
566
-
567
-	if ObjectsAreEqual(expected, actual) {
568
-		return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
569
-	}
570
-
571
-	return true
572
-
573
-}
574
-
575
-// containsElement try loop over the list check if the list includes the element.
576
-// return (false, false) if impossible.
577
-// return (true, false) if element was not found.
578
-// return (true, true) if element was found.
579
-func includeElement(list interface{}, element interface{}) (ok, found bool) {
580
-
581
-	listValue := reflect.ValueOf(list)
582
-	elementValue := reflect.ValueOf(element)
583
-	defer func() {
584
-		if e := recover(); e != nil {
585
-			ok = false
586
-			found = false
587
-		}
588
-	}()
589
-
590
-	if reflect.TypeOf(list).Kind() == reflect.String {
591
-		return true, strings.Contains(listValue.String(), elementValue.String())
592
-	}
593
-
594
-	if reflect.TypeOf(list).Kind() == reflect.Map {
595
-		mapKeys := listValue.MapKeys()
596
-		for i := 0; i < len(mapKeys); i++ {
597
-			if ObjectsAreEqual(mapKeys[i].Interface(), element) {
598
-				return true, true
599
-			}
600
-		}
601
-		return true, false
602
-	}
603
-
604
-	for i := 0; i < listValue.Len(); i++ {
605
-		if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
606
-			return true, true
607
-		}
608
-	}
609
-	return true, false
610
-
611
-}
612
-
613
-// Contains asserts that the specified string, list(array, slice...) or map contains the
614
-// specified substring or element.
615
-//
616
-//    assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
617
-//    assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
618
-//    assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
619
-//
620
-// Returns whether the assertion was successful (true) or not (false).
621
-func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
622
-
623
-	ok, found := includeElement(s, contains)
624
-	if !ok {
625
-		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
626
-	}
627
-	if !found {
628
-		return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
629
-	}
630
-
631
-	return true
632
-
633
-}
634
-
635
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
636
-// specified substring or element.
637
-//
638
-//    assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
639
-//    assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
640
-//    assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
641
-//
642
-// Returns whether the assertion was successful (true) or not (false).
643
-func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
644
-
645
-	ok, found := includeElement(s, contains)
646
-	if !ok {
647
-		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
648
-	}
649
-	if found {
650
-		return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
651
-	}
652
-
653
-	return true
654
-
655
-}
656
-
657
-// Condition uses a Comparison to assert a complex condition.
658
-func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
659
-	result := comp()
660
-	if !result {
661
-		Fail(t, "Condition failed!", msgAndArgs...)
662
-	}
663
-	return result
664
-}
665
-
666
-// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
667
-// methods, and represents a simple func that takes no arguments, and returns nothing.
668
-type PanicTestFunc func()
669
-
670
-// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
671
-func didPanic(f PanicTestFunc) (bool, interface{}) {
672
-
673
-	didPanic := false
674
-	var message interface{}
675
-	func() {
676
-
677
-		defer func() {
678
-			if message = recover(); message != nil {
679
-				didPanic = true
680
-			}
681
-		}()
682
-
683
-		// call the target function
684
-		f()
685
-
686
-	}()
687
-
688
-	return didPanic, message
689
-
690
-}
691
-
692
-// Panics asserts that the code inside the specified PanicTestFunc panics.
693
-//
694
-//   assert.Panics(t, func(){
695
-//     GoCrazy()
696
-//   }, "Calling GoCrazy() should panic")
697
-//
698
-// Returns whether the assertion was successful (true) or not (false).
699
-func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
700
-
701
-	if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
702
-		return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
703
-	}
704
-
705
-	return true
706
-}
707
-
708
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
709
-//
710
-//   assert.NotPanics(t, func(){
711
-//     RemainCalm()
712
-//   }, "Calling RemainCalm() should NOT panic")
713
-//
714
-// Returns whether the assertion was successful (true) or not (false).
715
-func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
716
-
717
-	if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
718
-		return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
719
-	}
720
-
721
-	return true
722
-}
723
-
724
-// WithinDuration asserts that the two times are within duration delta of each other.
725
-//
726
-//   assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
727
-//
728
-// Returns whether the assertion was successful (true) or not (false).
729
-func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
730
-
731
-	dt := expected.Sub(actual)
732
-	if dt < -delta || dt > delta {
733
-		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
734
-	}
735
-
736
-	return true
737
-}
738
-
739
-func toFloat(x interface{}) (float64, bool) {
740
-	var xf float64
741
-	xok := true
742
-
743
-	switch xn := x.(type) {
744
-	case uint8:
745
-		xf = float64(xn)
746
-	case uint16:
747
-		xf = float64(xn)
748
-	case uint32:
749
-		xf = float64(xn)
750
-	case uint64:
751
-		xf = float64(xn)
752
-	case int:
753
-		xf = float64(xn)
754
-	case int8:
755
-		xf = float64(xn)
756
-	case int16:
757
-		xf = float64(xn)
758
-	case int32:
759
-		xf = float64(xn)
760
-	case int64:
761
-		xf = float64(xn)
762
-	case float32:
763
-		xf = float64(xn)
764
-	case float64:
765
-		xf = float64(xn)
766
-	default:
767
-		xok = false
768
-	}
769
-
770
-	return xf, xok
771
-}
772
-
773
-// InDelta asserts that the two numerals are within delta of each other.
774
-//
775
-// 	 assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
776
-//
777
-// Returns whether the assertion was successful (true) or not (false).
778
-func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
779
-
780
-	af, aok := toFloat(expected)
781
-	bf, bok := toFloat(actual)
782
-
783
-	if !aok || !bok {
784
-		return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
785
-	}
786
-
787
-	if math.IsNaN(af) {
788
-		return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...)
789
-	}
790
-
791
-	if math.IsNaN(bf) {
792
-		return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
793
-	}
794
-
795
-	dt := af - bf
796
-	if dt < -delta || dt > delta {
797
-		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
798
-	}
799
-
800
-	return true
801
-}
802
-
803
-// InDeltaSlice is the same as InDelta, except it compares two slices.
804
-func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
805
-	if expected == nil || actual == nil ||
806
-		reflect.TypeOf(actual).Kind() != reflect.Slice ||
807
-		reflect.TypeOf(expected).Kind() != reflect.Slice {
808
-		return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
809
-	}
810
-
811
-	actualSlice := reflect.ValueOf(actual)
812
-	expectedSlice := reflect.ValueOf(expected)
813
-
814
-	for i := 0; i < actualSlice.Len(); i++ {
815
-		result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta)
816
-		if !result {
817
-			return result
818
-		}
819
-	}
820
-
821
-	return true
822
-}
823
-
824
-func calcRelativeError(expected, actual interface{}) (float64, error) {
825
-	af, aok := toFloat(expected)
826
-	if !aok {
827
-		return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
828
-	}
829
-	if af == 0 {
830
-		return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
831
-	}
832
-	bf, bok := toFloat(actual)
833
-	if !bok {
834
-		return 0, fmt.Errorf("expected value %q cannot be converted to float", actual)
835
-	}
836
-
837
-	return math.Abs(af-bf) / math.Abs(af), nil
838
-}
839
-
840
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
841
-//
842
-// Returns whether the assertion was successful (true) or not (false).
843
-func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
844
-	actualEpsilon, err := calcRelativeError(expected, actual)
845
-	if err != nil {
846
-		return Fail(t, err.Error(), msgAndArgs...)
847
-	}
848
-	if actualEpsilon > epsilon {
849
-		return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
850
-			"        < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...)
851
-	}
852
-
853
-	return true
854
-}
855
-
856
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
857
-func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
858
-	if expected == nil || actual == nil ||
859
-		reflect.TypeOf(actual).Kind() != reflect.Slice ||
860
-		reflect.TypeOf(expected).Kind() != reflect.Slice {
861
-		return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
862
-	}
863
-
864
-	actualSlice := reflect.ValueOf(actual)
865
-	expectedSlice := reflect.ValueOf(expected)
866
-
867
-	for i := 0; i < actualSlice.Len(); i++ {
868
-		result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
869
-		if !result {
870
-			return result
871
-		}
872
-	}
873
-
874
-	return true
875
-}
876
-
877
-/*
878
-	Errors
879
-*/
880
-
881
-// NoError asserts that a function returned no error (i.e. `nil`).
882
-//
883
-//   actualObj, err := SomeFunction()
884
-//   if assert.NoError(t, err) {
885
-//	   assert.Equal(t, actualObj, expectedObj)
886
-//   }
887
-//
888
-// Returns whether the assertion was successful (true) or not (false).
889
-func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
890
-	if err != nil {
891
-		return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
892
-	}
893
-
894
-	return true
895
-}
896
-
897
-// Error asserts that a function returned an error (i.e. not `nil`).
898
-//
899
-//   actualObj, err := SomeFunction()
900
-//   if assert.Error(t, err, "An error was expected") {
901
-//	   assert.Equal(t, err, expectedError)
902
-//   }
903
-//
904
-// Returns whether the assertion was successful (true) or not (false).
905
-func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
906
-
907
-	if err == nil {
908
-		return Fail(t, "An error is expected but got nil.", msgAndArgs...)
909
-	}
910
-
911
-	return true
912
-}
913
-
914
-// EqualError asserts that a function returned an error (i.e. not `nil`)
915
-// and that it is equal to the provided error.
916
-//
917
-//   actualObj, err := SomeFunction()
918
-//   assert.EqualError(t, err,  expectedErrorString, "An error was expected")
919
-//
920
-// Returns whether the assertion was successful (true) or not (false).
921
-func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
922
-	if !Error(t, theError, msgAndArgs...) {
923
-		return false
924
-	}
925
-	expected := errString
926
-	actual := theError.Error()
927
-	// don't need to use deep equals here, we know they are both strings
928
-	if expected != actual {
929
-		return Fail(t, fmt.Sprintf("Error message not equal:\n"+
930
-			"expected: %q\n"+
931
-			"received: %q", expected, actual), msgAndArgs...)
932
-	}
933
-	return true
934
-}
935
-
936
-// matchRegexp return true if a specified regexp matches a string.
937
-func matchRegexp(rx interface{}, str interface{}) bool {
938
-
939
-	var r *regexp.Regexp
940
-	if rr, ok := rx.(*regexp.Regexp); ok {
941
-		r = rr
942
-	} else {
943
-		r = regexp.MustCompile(fmt.Sprint(rx))
944
-	}
945
-
946
-	return (r.FindStringIndex(fmt.Sprint(str)) != nil)
947
-
948
-}
949
-
950
-// Regexp asserts that a specified regexp matches a string.
951
-//
952
-//  assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
953
-//  assert.Regexp(t, "start...$", "it's not starting")
954
-//
955
-// Returns whether the assertion was successful (true) or not (false).
956
-func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
957
-
958
-	match := matchRegexp(rx, str)
959
-
960
-	if !match {
961
-		Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
962
-	}
963
-
964
-	return match
965
-}
966
-
967
-// NotRegexp asserts that a specified regexp does not match a string.
968
-//
969
-//  assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
970
-//  assert.NotRegexp(t, "^start", "it's not starting")
971
-//
972
-// Returns whether the assertion was successful (true) or not (false).
973
-func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
974
-	match := matchRegexp(rx, str)
975
-
976
-	if match {
977
-		Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
978
-	}
979
-
980
-	return !match
981
-
982
-}
983
-
984
-// Zero asserts that i is the zero value for its type and returns the truth.
985
-func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
986
-	if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
987
-		return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
988
-	}
989
-	return true
990
-}
991
-
992
-// NotZero asserts that i is not the zero value for its type and returns the truth.
993
-func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
994
-	if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
995
-		return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
996
-	}
997
-	return true
998
-}
999
-
1000
-// JSONEq asserts that two JSON strings are equivalent.
1001
-//
1002
-//  assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1003
-//
1004
-// Returns whether the assertion was successful (true) or not (false).
1005
-func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1006
-	var expectedJSONAsInterface, actualJSONAsInterface interface{}
1007
-
1008
-	if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1009
-		return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1010
-	}
1011
-
1012
-	if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1013
-		return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1014
-	}
1015
-
1016
-	return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1017
-}
1018
-
1019
-func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1020
-	t := reflect.TypeOf(v)
1021
-	k := t.Kind()
1022
-
1023
-	if k == reflect.Ptr {
1024
-		t = t.Elem()
1025
-		k = t.Kind()
1026
-	}
1027
-	return t, k
1028
-}
1029
-
1030
-// diff returns a diff of both values as long as both are of the same type and
1031
-// are a struct, map, slice or array. Otherwise it returns an empty string.
1032
-func diff(expected interface{}, actual interface{}) string {
1033
-	if expected == nil || actual == nil {
1034
-		return ""
1035
-	}
1036
-
1037
-	et, ek := typeAndKind(expected)
1038
-	at, _ := typeAndKind(actual)
1039
-
1040
-	if et != at {
1041
-		return ""
1042
-	}
1043
-
1044
-	if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
1045
-		return ""
1046
-	}
1047
-
1048
-	e := spewConfig.Sdump(expected)
1049
-	a := spewConfig.Sdump(actual)
1050
-
1051
-	diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1052
-		A:        difflib.SplitLines(e),
1053
-		B:        difflib.SplitLines(a),
1054
-		FromFile: "Expected",
1055
-		FromDate: "",
1056
-		ToFile:   "Actual",
1057
-		ToDate:   "",
1058
-		Context:  1,
1059
-	})
1060
-
1061
-	return "\n\nDiff:\n" + diff
1062
-}
1063
-
1064
-var spewConfig = spew.ConfigState{
1065
-	Indent:                  " ",
1066
-	DisablePointerAddresses: true,
1067
-	DisableCapacities:       true,
1068
-	SortKeys:                true,
1069
-}
1070 1
deleted file mode 100644
... ...
@@ -1,45 +0,0 @@
1
-// Package assert provides 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 format 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
-package assert
46 1
deleted file mode 100644
... ...
@@ -1,10 +0,0 @@
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 1
deleted file mode 100644
... ...
@@ -1,16 +0,0 @@
1
-package assert
2
-
3
-// Assertions provides assertion methods around the
4
-// TestingT interface.
5
-type Assertions struct {
6
-	t TestingT
7
-}
8
-
9
-// New makes a new Assertions object for the specified TestingT.
10
-func New(t TestingT) *Assertions {
11
-	return &Assertions{
12
-		t: t,
13
-	}
14
-}
15
-
16
-//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl
17 1
deleted file mode 100644
... ...
@@ -1,106 +0,0 @@
1
-package assert
2
-
3
-import (
4
-	"fmt"
5
-	"net/http"
6
-	"net/http/httptest"
7
-	"net/url"
8
-	"strings"
9
-)
10
-
11
-// httpCode is a helper that returns HTTP code of the response. It returns -1
12
-// if building a new request fails.
13
-func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int {
14
-	w := httptest.NewRecorder()
15
-	req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
16
-	if err != nil {
17
-		return -1
18
-	}
19
-	handler(w, req)
20
-	return w.Code
21
-}
22
-
23
-// HTTPSuccess asserts that a specified handler returns a success status code.
24
-//
25
-//  assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
26
-//
27
-// Returns whether the assertion was successful (true) or not (false).
28
-func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
29
-	code := httpCode(handler, method, url, values)
30
-	if code == -1 {
31
-		return false
32
-	}
33
-	return code >= http.StatusOK && code <= http.StatusPartialContent
34
-}
35
-
36
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
37
-//
38
-//  assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
39
-//
40
-// Returns whether the assertion was successful (true) or not (false).
41
-func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
42
-	code := httpCode(handler, method, url, values)
43
-	if code == -1 {
44
-		return false
45
-	}
46
-	return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect
47
-}
48
-
49
-// HTTPError asserts that a specified handler returns an error status code.
50
-//
51
-//  assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
52
-//
53
-// Returns whether the assertion was successful (true) or not (false).
54
-func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
55
-	code := httpCode(handler, method, url, values)
56
-	if code == -1 {
57
-		return false
58
-	}
59
-	return code >= http.StatusBadRequest
60
-}
61
-
62
-// HTTPBody is a helper that returns HTTP body of the response. It returns
63
-// empty string if building a new request fails.
64
-func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string {
65
-	w := httptest.NewRecorder()
66
-	req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
67
-	if err != nil {
68
-		return ""
69
-	}
70
-	handler(w, req)
71
-	return w.Body.String()
72
-}
73
-
74
-// HTTPBodyContains asserts that a specified handler returns a
75
-// body that contains a string.
76
-//
77
-//  assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
78
-//
79
-// Returns whether the assertion was successful (true) or not (false).
80
-func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
81
-	body := HTTPBody(handler, method, url, values)
82
-
83
-	contains := strings.Contains(body, fmt.Sprint(str))
84
-	if !contains {
85
-		Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
86
-	}
87
-
88
-	return contains
89
-}
90
-
91
-// HTTPBodyNotContains asserts that a specified handler returns a
92
-// body that does not contain a string.
93
-//
94
-//  assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
95
-//
96
-// Returns whether the assertion was successful (true) or not (false).
97
-func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
98
-	body := HTTPBody(handler, method, url, values)
99
-
100
-	contains := strings.Contains(body, fmt.Sprint(str))
101
-	if contains {
102
-		Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
103
-	}
104
-
105
-	return !contains
106
-}
107 1
deleted file mode 100644
... ...
@@ -1,28 +0,0 @@
1
-// Package require implements the same assertions as the `assert` package but
2
-// stops test execution when a test fails.
3
-//
4
-// Example Usage
5
-//
6
-// The following is a complete example using require in a standard test function:
7
-//    import (
8
-//      "testing"
9
-//      "github.com/stretchr/testify/require"
10
-//    )
11
-//
12
-//    func TestSomething(t *testing.T) {
13
-//
14
-//      var a string = "Hello"
15
-//      var b string = "Hello"
16
-//
17
-//      require.Equal(t, a, b, "The two words should be the same.")
18
-//
19
-//    }
20
-//
21
-// Assertions
22
-//
23
-// The `require` package have same global functions as in the `assert` package,
24
-// but instead of returning a boolean result they call `t.FailNow()`.
25
-//
26
-// Every assertion function also takes an optional string message as the final argument,
27
-// allowing custom error messages to be appended to the message the assertion method outputs.
28
-package require
29 1
deleted file mode 100644
... ...
@@ -1,16 +0,0 @@
1
-package require
2
-
3
-// Assertions provides assertion methods around the
4
-// TestingT interface.
5
-type Assertions struct {
6
-	t TestingT
7
-}
8
-
9
-// New makes a new Assertions object for the specified TestingT.
10
-func New(t TestingT) *Assertions {
11
-	return &Assertions{
12
-		t: t,
13
-	}
14
-}
15
-
16
-//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl
17 1
deleted file mode 100644
... ...
@@ -1,429 +0,0 @@
1
-/*
2
-* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
3
-* THIS FILE MUST NOT BE EDITED BY HAND
4
- */
5
-
6
-package require
7
-
8
-import (
9
-	assert "github.com/stretchr/testify/assert"
10
-	http "net/http"
11
-	url "net/url"
12
-	time "time"
13
-)
14
-
15
-// Condition uses a Comparison to assert a complex condition.
16
-func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) {
17
-	if !assert.Condition(t, comp, msgAndArgs...) {
18
-		t.FailNow()
19
-	}
20
-}
21
-
22
-// Contains asserts that the specified string, list(array, slice...) or map contains the
23
-// specified substring or element.
24
-//
25
-//    assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
26
-//    assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
27
-//    assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
28
-//
29
-// Returns whether the assertion was successful (true) or not (false).
30
-func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
31
-	if !assert.Contains(t, s, contains, msgAndArgs...) {
32
-		t.FailNow()
33
-	}
34
-}
35
-
36
-// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
37
-// a slice or a channel with len == 0.
38
-//
39
-//  assert.Empty(t, obj)
40
-//
41
-// Returns whether the assertion was successful (true) or not (false).
42
-func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
43
-	if !assert.Empty(t, object, msgAndArgs...) {
44
-		t.FailNow()
45
-	}
46
-}
47
-
48
-// Equal asserts that two objects are equal.
49
-//
50
-//    assert.Equal(t, 123, 123, "123 and 123 should be equal")
51
-//
52
-// Returns whether the assertion was successful (true) or not (false).
53
-//
54
-// Pointer variable equality is determined based on the equality of the
55
-// referenced values (as opposed to the memory addresses).
56
-func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
57
-	if !assert.Equal(t, expected, actual, msgAndArgs...) {
58
-		t.FailNow()
59
-	}
60
-}
61
-
62
-// EqualError asserts that a function returned an error (i.e. not `nil`)
63
-// and that it is equal to the provided error.
64
-//
65
-//   actualObj, err := SomeFunction()
66
-//   assert.EqualError(t, err,  expectedErrorString, "An error was expected")
67
-//
68
-// Returns whether the assertion was successful (true) or not (false).
69
-func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) {
70
-	if !assert.EqualError(t, theError, errString, msgAndArgs...) {
71
-		t.FailNow()
72
-	}
73
-}
74
-
75
-// EqualValues asserts that two objects are equal or convertable to the same types
76
-// and equal.
77
-//
78
-//    assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal")
79
-//
80
-// Returns whether the assertion was successful (true) or not (false).
81
-func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
82
-	if !assert.EqualValues(t, expected, actual, msgAndArgs...) {
83
-		t.FailNow()
84
-	}
85
-}
86
-
87
-// Error asserts that a function returned an error (i.e. not `nil`).
88
-//
89
-//   actualObj, err := SomeFunction()
90
-//   if assert.Error(t, err, "An error was expected") {
91
-// 	   assert.Equal(t, err, expectedError)
92
-//   }
93
-//
94
-// Returns whether the assertion was successful (true) or not (false).
95
-func Error(t TestingT, err error, msgAndArgs ...interface{}) {
96
-	if !assert.Error(t, err, msgAndArgs...) {
97
-		t.FailNow()
98
-	}
99
-}
100
-
101
-// Exactly asserts that two objects are equal is value and type.
102
-//
103
-//    assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
104
-//
105
-// Returns whether the assertion was successful (true) or not (false).
106
-func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
107
-	if !assert.Exactly(t, expected, actual, msgAndArgs...) {
108
-		t.FailNow()
109
-	}
110
-}
111
-
112
-// Fail reports a failure through
113
-func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
114
-	if !assert.Fail(t, failureMessage, msgAndArgs...) {
115
-		t.FailNow()
116
-	}
117
-}
118
-
119
-// FailNow fails test
120
-func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
121
-	if !assert.FailNow(t, failureMessage, msgAndArgs...) {
122
-		t.FailNow()
123
-	}
124
-}
125
-
126
-// False asserts that the specified value is false.
127
-//
128
-//    assert.False(t, myBool, "myBool should be false")
129
-//
130
-// Returns whether the assertion was successful (true) or not (false).
131
-func False(t TestingT, value bool, msgAndArgs ...interface{}) {
132
-	if !assert.False(t, value, msgAndArgs...) {
133
-		t.FailNow()
134
-	}
135
-}
136
-
137
-// HTTPBodyContains asserts that a specified handler returns a
138
-// body that contains a string.
139
-//
140
-//  assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
141
-//
142
-// Returns whether the assertion was successful (true) or not (false).
143
-func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) {
144
-	if !assert.HTTPBodyContains(t, handler, method, url, values, str) {
145
-		t.FailNow()
146
-	}
147
-}
148
-
149
-// HTTPBodyNotContains asserts that a specified handler returns a
150
-// body that does not contain a string.
151
-//
152
-//  assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
153
-//
154
-// Returns whether the assertion was successful (true) or not (false).
155
-func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) {
156
-	if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) {
157
-		t.FailNow()
158
-	}
159
-}
160
-
161
-// HTTPError asserts that a specified handler returns an error status code.
162
-//
163
-//  assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
164
-//
165
-// Returns whether the assertion was successful (true) or not (false).
166
-func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) {
167
-	if !assert.HTTPError(t, handler, method, url, values) {
168
-		t.FailNow()
169
-	}
170
-}
171
-
172
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
173
-//
174
-//  assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
175
-//
176
-// Returns whether the assertion was successful (true) or not (false).
177
-func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) {
178
-	if !assert.HTTPRedirect(t, handler, method, url, values) {
179
-		t.FailNow()
180
-	}
181
-}
182
-
183
-// HTTPSuccess asserts that a specified handler returns a success status code.
184
-//
185
-//  assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
186
-//
187
-// Returns whether the assertion was successful (true) or not (false).
188
-func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) {
189
-	if !assert.HTTPSuccess(t, handler, method, url, values) {
190
-		t.FailNow()
191
-	}
192
-}
193
-
194
-// Implements asserts that an object is implemented by the specified interface.
195
-//
196
-//    assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
197
-func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
198
-	if !assert.Implements(t, interfaceObject, object, msgAndArgs...) {
199
-		t.FailNow()
200
-	}
201
-}
202
-
203
-// InDelta asserts that the two numerals are within delta of each other.
204
-//
205
-// 	 assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
206
-//
207
-// Returns whether the assertion was successful (true) or not (false).
208
-func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
209
-	if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) {
210
-		t.FailNow()
211
-	}
212
-}
213
-
214
-// InDeltaSlice is the same as InDelta, except it compares two slices.
215
-func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
216
-	if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) {
217
-		t.FailNow()
218
-	}
219
-}
220
-
221
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
222
-//
223
-// Returns whether the assertion was successful (true) or not (false).
224
-func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
225
-	if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) {
226
-		t.FailNow()
227
-	}
228
-}
229
-
230
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
231
-func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
232
-	if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) {
233
-		t.FailNow()
234
-	}
235
-}
236
-
237
-// IsType asserts that the specified objects are of the same type.
238
-func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
239
-	if !assert.IsType(t, expectedType, object, msgAndArgs...) {
240
-		t.FailNow()
241
-	}
242
-}
243
-
244
-// JSONEq asserts that two JSON strings are equivalent.
245
-//
246
-//  assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
247
-//
248
-// Returns whether the assertion was successful (true) or not (false).
249
-func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
250
-	if !assert.JSONEq(t, expected, actual, msgAndArgs...) {
251
-		t.FailNow()
252
-	}
253
-}
254
-
255
-// Len asserts that the specified object has specific length.
256
-// Len also fails if the object has a type that len() not accept.
257
-//
258
-//    assert.Len(t, mySlice, 3, "The size of slice is not 3")
259
-//
260
-// Returns whether the assertion was successful (true) or not (false).
261
-func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) {
262
-	if !assert.Len(t, object, length, msgAndArgs...) {
263
-		t.FailNow()
264
-	}
265
-}
266
-
267
-// Nil asserts that the specified object is nil.
268
-//
269
-//    assert.Nil(t, err, "err should be nothing")
270
-//
271
-// Returns whether the assertion was successful (true) or not (false).
272
-func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
273
-	if !assert.Nil(t, object, msgAndArgs...) {
274
-		t.FailNow()
275
-	}
276
-}
277
-
278
-// NoError asserts that a function returned no error (i.e. `nil`).
279
-//
280
-//   actualObj, err := SomeFunction()
281
-//   if assert.NoError(t, err) {
282
-// 	   assert.Equal(t, actualObj, expectedObj)
283
-//   }
284
-//
285
-// Returns whether the assertion was successful (true) or not (false).
286
-func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
287
-	if !assert.NoError(t, err, msgAndArgs...) {
288
-		t.FailNow()
289
-	}
290
-}
291
-
292
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
293
-// specified substring or element.
294
-//
295
-//    assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
296
-//    assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
297
-//    assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
298
-//
299
-// Returns whether the assertion was successful (true) or not (false).
300
-func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
301
-	if !assert.NotContains(t, s, contains, msgAndArgs...) {
302
-		t.FailNow()
303
-	}
304
-}
305
-
306
-// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
307
-// a slice or a channel with len == 0.
308
-//
309
-//  if assert.NotEmpty(t, obj) {
310
-//    assert.Equal(t, "two", obj[1])
311
-//  }
312
-//
313
-// Returns whether the assertion was successful (true) or not (false).
314
-func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
315
-	if !assert.NotEmpty(t, object, msgAndArgs...) {
316
-		t.FailNow()
317
-	}
318
-}
319
-
320
-// NotEqual asserts that the specified values are NOT equal.
321
-//
322
-//    assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
323
-//
324
-// Returns whether the assertion was successful (true) or not (false).
325
-//
326
-// Pointer variable equality is determined based on the equality of the
327
-// referenced values (as opposed to the memory addresses).
328
-func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
329
-	if !assert.NotEqual(t, expected, actual, msgAndArgs...) {
330
-		t.FailNow()
331
-	}
332
-}
333
-
334
-// NotNil asserts that the specified object is not nil.
335
-//
336
-//    assert.NotNil(t, err, "err should be something")
337
-//
338
-// Returns whether the assertion was successful (true) or not (false).
339
-func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
340
-	if !assert.NotNil(t, object, msgAndArgs...) {
341
-		t.FailNow()
342
-	}
343
-}
344
-
345
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
346
-//
347
-//   assert.NotPanics(t, func(){
348
-//     RemainCalm()
349
-//   }, "Calling RemainCalm() should NOT panic")
350
-//
351
-// Returns whether the assertion was successful (true) or not (false).
352
-func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
353
-	if !assert.NotPanics(t, f, msgAndArgs...) {
354
-		t.FailNow()
355
-	}
356
-}
357
-
358
-// NotRegexp asserts that a specified regexp does not match a string.
359
-//
360
-//  assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
361
-//  assert.NotRegexp(t, "^start", "it's not starting")
362
-//
363
-// Returns whether the assertion was successful (true) or not (false).
364
-func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
365
-	if !assert.NotRegexp(t, rx, str, msgAndArgs...) {
366
-		t.FailNow()
367
-	}
368
-}
369
-
370
-// NotZero asserts that i is not the zero value for its type and returns the truth.
371
-func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
372
-	if !assert.NotZero(t, i, msgAndArgs...) {
373
-		t.FailNow()
374
-	}
375
-}
376
-
377
-// Panics asserts that the code inside the specified PanicTestFunc panics.
378
-//
379
-//   assert.Panics(t, func(){
380
-//     GoCrazy()
381
-//   }, "Calling GoCrazy() should panic")
382
-//
383
-// Returns whether the assertion was successful (true) or not (false).
384
-func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
385
-	if !assert.Panics(t, f, msgAndArgs...) {
386
-		t.FailNow()
387
-	}
388
-}
389
-
390
-// Regexp asserts that a specified regexp matches a string.
391
-//
392
-//  assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
393
-//  assert.Regexp(t, "start...$", "it's not starting")
394
-//
395
-// Returns whether the assertion was successful (true) or not (false).
396
-func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
397
-	if !assert.Regexp(t, rx, str, msgAndArgs...) {
398
-		t.FailNow()
399
-	}
400
-}
401
-
402
-// True asserts that the specified value is true.
403
-//
404
-//    assert.True(t, myBool, "myBool should be true")
405
-//
406
-// Returns whether the assertion was successful (true) or not (false).
407
-func True(t TestingT, value bool, msgAndArgs ...interface{}) {
408
-	if !assert.True(t, value, msgAndArgs...) {
409
-		t.FailNow()
410
-	}
411
-}
412
-
413
-// WithinDuration asserts that the two times are within duration delta of each other.
414
-//
415
-//   assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
416
-//
417
-// Returns whether the assertion was successful (true) or not (false).
418
-func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
419
-	if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) {
420
-		t.FailNow()
421
-	}
422
-}
423
-
424
-// Zero asserts that i is the zero value for its type and returns the truth.
425
-func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
426
-	if !assert.Zero(t, i, msgAndArgs...) {
427
-		t.FailNow()
428
-	}
429
-}
430 1
deleted file mode 100644
... ...
@@ -1,353 +0,0 @@
1
-/*
2
-* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
3
-* THIS FILE MUST NOT BE EDITED BY HAND
4
- */
5
-
6
-package require
7
-
8
-import (
9
-	assert "github.com/stretchr/testify/assert"
10
-	http "net/http"
11
-	url "net/url"
12
-	time "time"
13
-)
14
-
15
-// Condition uses a Comparison to assert a complex condition.
16
-func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) {
17
-	Condition(a.t, comp, msgAndArgs...)
18
-}
19
-
20
-// Contains asserts that the specified string, list(array, slice...) or map contains the
21
-// specified substring or element.
22
-//
23
-//    a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'")
24
-//    a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
25
-//    a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
26
-//
27
-// Returns whether the assertion was successful (true) or not (false).
28
-func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) {
29
-	Contains(a.t, s, contains, msgAndArgs...)
30
-}
31
-
32
-// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
33
-// a slice or a channel with len == 0.
34
-//
35
-//  a.Empty(obj)
36
-//
37
-// Returns whether the assertion was successful (true) or not (false).
38
-func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) {
39
-	Empty(a.t, object, msgAndArgs...)
40
-}
41
-
42
-// Equal asserts that two objects are equal.
43
-//
44
-//    a.Equal(123, 123, "123 and 123 should be equal")
45
-//
46
-// Returns whether the assertion was successful (true) or not (false).
47
-//
48
-// Pointer variable equality is determined based on the equality of the
49
-// referenced values (as opposed to the memory addresses).
50
-func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
51
-	Equal(a.t, expected, actual, msgAndArgs...)
52
-}
53
-
54
-// EqualError asserts that a function returned an error (i.e. not `nil`)
55
-// and that it is equal to the provided error.
56
-//
57
-//   actualObj, err := SomeFunction()
58
-//   a.EqualError(err,  expectedErrorString, "An error was expected")
59
-//
60
-// Returns whether the assertion was successful (true) or not (false).
61
-func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) {
62
-	EqualError(a.t, theError, errString, msgAndArgs...)
63
-}
64
-
65
-// EqualValues asserts that two objects are equal or convertable to the same types
66
-// and equal.
67
-//
68
-//    a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal")
69
-//
70
-// Returns whether the assertion was successful (true) or not (false).
71
-func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
72
-	EqualValues(a.t, expected, actual, msgAndArgs...)
73
-}
74
-
75
-// Error asserts that a function returned an error (i.e. not `nil`).
76
-//
77
-//   actualObj, err := SomeFunction()
78
-//   if a.Error(err, "An error was expected") {
79
-// 	   assert.Equal(t, err, expectedError)
80
-//   }
81
-//
82
-// Returns whether the assertion was successful (true) or not (false).
83
-func (a *Assertions) Error(err error, msgAndArgs ...interface{}) {
84
-	Error(a.t, err, msgAndArgs...)
85
-}
86
-
87
-// Exactly asserts that two objects are equal is value and type.
88
-//
89
-//    a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal")
90
-//
91
-// Returns whether the assertion was successful (true) or not (false).
92
-func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
93
-	Exactly(a.t, expected, actual, msgAndArgs...)
94
-}
95
-
96
-// Fail reports a failure through
97
-func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) {
98
-	Fail(a.t, failureMessage, msgAndArgs...)
99
-}
100
-
101
-// FailNow fails test
102
-func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) {
103
-	FailNow(a.t, failureMessage, msgAndArgs...)
104
-}
105
-
106
-// False asserts that the specified value is false.
107
-//
108
-//    a.False(myBool, "myBool should be false")
109
-//
110
-// Returns whether the assertion was successful (true) or not (false).
111
-func (a *Assertions) False(value bool, msgAndArgs ...interface{}) {
112
-	False(a.t, value, msgAndArgs...)
113
-}
114
-
115
-// HTTPBodyContains asserts that a specified handler returns a
116
-// body that contains a string.
117
-//
118
-//  a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky")
119
-//
120
-// Returns whether the assertion was successful (true) or not (false).
121
-func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) {
122
-	HTTPBodyContains(a.t, handler, method, url, values, str)
123
-}
124
-
125
-// HTTPBodyNotContains asserts that a specified handler returns a
126
-// body that does not contain a string.
127
-//
128
-//  a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky")
129
-//
130
-// Returns whether the assertion was successful (true) or not (false).
131
-func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) {
132
-	HTTPBodyNotContains(a.t, handler, method, url, values, str)
133
-}
134
-
135
-// HTTPError asserts that a specified handler returns an error status code.
136
-//
137
-//  a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
138
-//
139
-// Returns whether the assertion was successful (true) or not (false).
140
-func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) {
141
-	HTTPError(a.t, handler, method, url, values)
142
-}
143
-
144
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
145
-//
146
-//  a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
147
-//
148
-// Returns whether the assertion was successful (true) or not (false).
149
-func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) {
150
-	HTTPRedirect(a.t, handler, method, url, values)
151
-}
152
-
153
-// HTTPSuccess asserts that a specified handler returns a success status code.
154
-//
155
-//  a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
156
-//
157
-// Returns whether the assertion was successful (true) or not (false).
158
-func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) {
159
-	HTTPSuccess(a.t, handler, method, url, values)
160
-}
161
-
162
-// Implements asserts that an object is implemented by the specified interface.
163
-//
164
-//    a.Implements((*MyInterface)(nil), new(MyObject), "MyObject")
165
-func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
166
-	Implements(a.t, interfaceObject, object, msgAndArgs...)
167
-}
168
-
169
-// InDelta asserts that the two numerals are within delta of each other.
170
-//
171
-// 	 a.InDelta(math.Pi, (22 / 7.0), 0.01)
172
-//
173
-// Returns whether the assertion was successful (true) or not (false).
174
-func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
175
-	InDelta(a.t, expected, actual, delta, msgAndArgs...)
176
-}
177
-
178
-// InDeltaSlice is the same as InDelta, except it compares two slices.
179
-func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
180
-	InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...)
181
-}
182
-
183
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
184
-//
185
-// Returns whether the assertion was successful (true) or not (false).
186
-func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
187
-	InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
188
-}
189
-
190
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
191
-func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
192
-	InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
193
-}
194
-
195
-// IsType asserts that the specified objects are of the same type.
196
-func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
197
-	IsType(a.t, expectedType, object, msgAndArgs...)
198
-}
199
-
200
-// JSONEq asserts that two JSON strings are equivalent.
201
-//
202
-//  a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
203
-//
204
-// Returns whether the assertion was successful (true) or not (false).
205
-func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) {
206
-	JSONEq(a.t, expected, actual, msgAndArgs...)
207
-}
208
-
209
-// Len asserts that the specified object has specific length.
210
-// Len also fails if the object has a type that len() not accept.
211
-//
212
-//    a.Len(mySlice, 3, "The size of slice is not 3")
213
-//
214
-// Returns whether the assertion was successful (true) or not (false).
215
-func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) {
216
-	Len(a.t, object, length, msgAndArgs...)
217
-}
218
-
219
-// Nil asserts that the specified object is nil.
220
-//
221
-//    a.Nil(err, "err should be nothing")
222
-//
223
-// Returns whether the assertion was successful (true) or not (false).
224
-func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) {
225
-	Nil(a.t, object, msgAndArgs...)
226
-}
227
-
228
-// NoError asserts that a function returned no error (i.e. `nil`).
229
-//
230
-//   actualObj, err := SomeFunction()
231
-//   if a.NoError(err) {
232
-// 	   assert.Equal(t, actualObj, expectedObj)
233
-//   }
234
-//
235
-// Returns whether the assertion was successful (true) or not (false).
236
-func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
237
-	NoError(a.t, err, msgAndArgs...)
238
-}
239
-
240
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
241
-// specified substring or element.
242
-//
243
-//    a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
244
-//    a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
245
-//    a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
246
-//
247
-// Returns whether the assertion was successful (true) or not (false).
248
-func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) {
249
-	NotContains(a.t, s, contains, msgAndArgs...)
250
-}
251
-
252
-// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
253
-// a slice or a channel with len == 0.
254
-//
255
-//  if a.NotEmpty(obj) {
256
-//    assert.Equal(t, "two", obj[1])
257
-//  }
258
-//
259
-// Returns whether the assertion was successful (true) or not (false).
260
-func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
261
-	NotEmpty(a.t, object, msgAndArgs...)
262
-}
263
-
264
-// NotEqual asserts that the specified values are NOT equal.
265
-//
266
-//    a.NotEqual(obj1, obj2, "two objects shouldn't be equal")
267
-//
268
-// Returns whether the assertion was successful (true) or not (false).
269
-//
270
-// Pointer variable equality is determined based on the equality of the
271
-// referenced values (as opposed to the memory addresses).
272
-func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
273
-	NotEqual(a.t, expected, actual, msgAndArgs...)
274
-}
275
-
276
-// NotNil asserts that the specified object is not nil.
277
-//
278
-//    a.NotNil(err, "err should be something")
279
-//
280
-// Returns whether the assertion was successful (true) or not (false).
281
-func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) {
282
-	NotNil(a.t, object, msgAndArgs...)
283
-}
284
-
285
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
286
-//
287
-//   a.NotPanics(func(){
288
-//     RemainCalm()
289
-//   }, "Calling RemainCalm() should NOT panic")
290
-//
291
-// Returns whether the assertion was successful (true) or not (false).
292
-func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) {
293
-	NotPanics(a.t, f, msgAndArgs...)
294
-}
295
-
296
-// NotRegexp asserts that a specified regexp does not match a string.
297
-//
298
-//  a.NotRegexp(regexp.MustCompile("starts"), "it's starting")
299
-//  a.NotRegexp("^start", "it's not starting")
300
-//
301
-// Returns whether the assertion was successful (true) or not (false).
302
-func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) {
303
-	NotRegexp(a.t, rx, str, msgAndArgs...)
304
-}
305
-
306
-// NotZero asserts that i is not the zero value for its type and returns the truth.
307
-func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) {
308
-	NotZero(a.t, i, msgAndArgs...)
309
-}
310
-
311
-// Panics asserts that the code inside the specified PanicTestFunc panics.
312
-//
313
-//   a.Panics(func(){
314
-//     GoCrazy()
315
-//   }, "Calling GoCrazy() should panic")
316
-//
317
-// Returns whether the assertion was successful (true) or not (false).
318
-func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) {
319
-	Panics(a.t, f, msgAndArgs...)
320
-}
321
-
322
-// Regexp asserts that a specified regexp matches a string.
323
-//
324
-//  a.Regexp(regexp.MustCompile("start"), "it's starting")
325
-//  a.Regexp("start...$", "it's not starting")
326
-//
327
-// Returns whether the assertion was successful (true) or not (false).
328
-func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) {
329
-	Regexp(a.t, rx, str, msgAndArgs...)
330
-}
331
-
332
-// True asserts that the specified value is true.
333
-//
334
-//    a.True(myBool, "myBool should be true")
335
-//
336
-// Returns whether the assertion was successful (true) or not (false).
337
-func (a *Assertions) True(value bool, msgAndArgs ...interface{}) {
338
-	True(a.t, value, msgAndArgs...)
339
-}
340
-
341
-// WithinDuration asserts that the two times are within duration delta of each other.
342
-//
343
-//   a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
344
-//
345
-// Returns whether the assertion was successful (true) or not (false).
346
-func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
347
-	WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
348
-}
349
-
350
-// Zero asserts that i is the zero value for its type and returns the truth.
351
-func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) {
352
-	Zero(a.t, i, msgAndArgs...)
353
-}
354 1
deleted file mode 100644
... ...
@@ -1,9 +0,0 @@
1
-package require
2
-
3
-// TestingT is an interface wrapper around *testing.T
4
-type TestingT interface {
5
-	Errorf(format string, args ...interface{})
6
-	FailNow()
7
-}
8
-
9
-//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl