Update go dependencies

This commit is contained in:
Manuel de Brito Fontes 2018-05-26 11:27:53 -04:00 committed by Manuel Alejandro de Brito Fontes
parent 15ffb51394
commit bb4d483837
No known key found for this signature in database
GPG key ID: 786136016A8BA02A
1621 changed files with 86368 additions and 284392 deletions

View file

@ -1,12 +1,14 @@
language: go
go:
- 1.6
- 1.7
- 1.8
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
install:
- go get -v ./...
- go get github.com/onsi/ginkgo
- go install github.com/onsi/ginkgo/ginkgo
script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --failOnPending --randomizeSuites --race
script: $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && go vet

View file

@ -1,5 +1,30 @@
## HEAD
### Features
- Make string pretty diff user configurable (#273) [eb112ce, 649b44d]
### Fixes
- Use httputil.DumpRequest to pretty-print unhandled requests (#278) [a4ff0fc, b7d1a52]
- fix typo floa32 > float32 (#272) [041ae3b, 6e33911]
- Fix link to documentation on adding your own matchers (#270) [bb2c830, fcebc62]
- Use setters and getters to avoid race condition (#262) [13057c3, a9c79f1]
- Avoid sending a signal if the process is not alive (#259) [b8043e5, 4fc1762]
- Improve message from AssignableToTypeOf when expected value is nil (#281) [9c1fb20]
## 1.3.0
Improvements:
- The `Equal` matcher matches byte slices more performantly.
- Improved how `MatchError` matches error strings.
- `MatchXML` ignores the order of xml node attributes.
- Improve support for XUnit style golang tests. ([#254](https://github.com/onsi/gomega/issues/254))
Bug Fixes:
- Diff generation now handles multi-byte sequences correctly.
- Multiple goroutines can now call `gexec.Build` concurrently.
## 1.2.0
Improvements:

View file

@ -6,6 +6,9 @@ Your contributions to Gomega are essential for its long-term maintenance and imp
- Ensure adequate test coverage:
- Make sure to add appropriate unit tests
- Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR
- Please run following linter locally `go vet ./...` and make sure output does not contain any warnings
- Update the documentation. In addition to standard `godoc` comments Gomega has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR.
Thanks for supporting Gomega!
If you're a committer, check out RELEASING.md to learn how to cut a release.
Thanks for supporting Gomega!

12
vendor/github.com/onsi/gomega/RELEASING.md generated vendored Normal file
View file

@ -0,0 +1,12 @@
A Gomega release is a tagged sha and a GitHub release. To cut a release:
1. Ensure CHANGELOG.md is up to date.
- Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release
- Categorize the changes into
- Breaking Changes (requires a major version)
- New Features (minor version)
- Fixes (fix version)
- Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact)
2. Update GOMEGA_VERSION in `gomega_dsl.go`
3. Push a commit with the version number as the commit message (e.g. `v1.3.0`)
4. Create a new [GitHub release](https://help.github.com/articles/creating-releases/) with the version number as the tag (e.g. `v1.3.0`). List the key changes in the release notes.

View file

@ -30,6 +30,9 @@ Set PrintContextObjects = true to enable printing of the context internals.
*/
var PrintContextObjects = false
// TruncatedDiff choose if we should display a truncated pretty diff or not
var TruncatedDiff = true
// Ctx interface defined here to keep backwards compatability with go < 1.7
// It matches the context.Context interface
type Ctx interface {
@ -82,7 +85,7 @@ to equal |
*/
func MessageWithDiff(actual, message, expected string) string {
if len(actual) >= truncateThreshold && len(expected) >= truncateThreshold {
if TruncatedDiff && len(actual) >= truncateThreshold && len(expected) >= truncateThreshold {
diffPoint := findFirstMismatch(actual, expected)
formattedActual := truncateAndFormat(actual, diffPoint)
formattedExpected := truncateAndFormat(expected, diffPoint)
@ -123,7 +126,7 @@ func findFirstMismatch(a, b string) int {
bSlice := strings.Split(b, "")
for index, str := range aSlice {
if index > len(b) - 1 {
if index > len(bSlice)-1 {
return index
}
if str != bSlice[index] {

View file

@ -1,13 +0,0 @@
package format_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestFormat(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Format Suite")
}

View file

@ -1,590 +0,0 @@
package format_test
import (
"fmt"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
)
//recursive struct
type StringAlias string
type ByteAlias []byte
type IntAlias int
type AStruct struct {
Exported string
}
type SimpleStruct struct {
Name string
Enumeration int
Veritas bool
Data []byte
secret uint32
}
type ComplexStruct struct {
Strings []string
SimpleThings []*SimpleStruct
DataMaps map[int]ByteAlias
}
type SecretiveStruct struct {
boolValue bool
intValue int
uintValue uint
uintptrValue uintptr
floatValue float32
complexValue complex64
chanValue chan bool
funcValue func()
pointerValue *int
sliceValue []string
byteSliceValue []byte
stringValue string
arrValue [3]int
byteArrValue [3]byte
mapValue map[string]int
structValue AStruct
interfaceValue interface{}
}
type GoStringer struct {
}
func (g GoStringer) GoString() string {
return "go-string"
}
func (g GoStringer) String() string {
return "string"
}
type Stringer struct {
}
func (g Stringer) String() string {
return "string"
}
type ctx struct {
}
func (c *ctx) Deadline() (deadline time.Time, ok bool) {
return time.Time{}, false
}
func (c *ctx) Done() <-chan struct{} {
return nil
}
func (c *ctx) Err() error {
return nil
}
func (c *ctx) Value(key interface{}) interface{} {
return nil
}
var _ = Describe("Format", func() {
match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher {
if len(args) > 0 {
valueRepresentation = fmt.Sprintf(valueRepresentation, args...)
}
return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation))
}
matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher {
if len(args) > 0 {
valueRepresentation = fmt.Sprintf(valueRepresentation, args...)
}
return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation))
}
hashMatchingRegexp := func(entries ...string) string {
entriesSwitch := "(" + strings.Join(entries, "|") + ")"
arr := make([]string, len(entries))
for i := range arr {
arr[i] = entriesSwitch
}
return "{" + strings.Join(arr, ", ") + "}"
}
Describe("Message", func() {
Context("with only an actual value", func() {
It("should print out an indented formatted representation of the value and the message", func() {
Ω(Message(3, "to be three.")).Should(Equal("Expected\n <int>: 3\nto be three."))
})
})
Context("with an actual and an expected value", func() {
It("should print out an indented formatted representatino of both values, and the message", func() {
Ω(Message(3, "to equal", 4)).Should(Equal("Expected\n <int>: 3\nto equal\n <int>: 4"))
})
})
})
Describe("MessageWithDiff", func() {
It("shows the exact point where two long strings differ", func() {
stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedLongStringFailureMessage))
})
It("truncates the start of long strings that differ only at their end", func() {
stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz"
Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedStartStringFailureMessage))
})
It("truncates the start of long strings that differ only in length", func() {
smallString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
largeString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Ω(MessageWithDiff(largeString, "to equal", smallString)).Should(Equal(expectedTruncatedStartSizeFailureMessage))
Ω(MessageWithDiff(smallString, "to equal", largeString)).Should(Equal(expectedTruncatedStartSizeSwappedFailureMessage))
})
It("truncates the end of long strings that differ only at their start", func() {
stringWithB := "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stringWithZ := "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedEndStringFailureMessage))
})
})
Describe("IndentString", func() {
It("should indent the string", func() {
Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz"))
})
})
Describe("Object", func() {
Describe("formatting boolean values", func() {
It("should give the type and format values correctly", func() {
Ω(Object(true, 1)).Should(match("bool", "true"))
Ω(Object(false, 1)).Should(match("bool", "false"))
})
})
Describe("formatting numbers", func() {
It("should give the type and format values correctly", func() {
Ω(Object(int(3), 1)).Should(match("int", "3"))
Ω(Object(int8(3), 1)).Should(match("int8", "3"))
Ω(Object(int16(3), 1)).Should(match("int16", "3"))
Ω(Object(int32(3), 1)).Should(match("int32", "3"))
Ω(Object(int64(3), 1)).Should(match("int64", "3"))
Ω(Object(uint(3), 1)).Should(match("uint", "3"))
Ω(Object(uint8(3), 1)).Should(match("uint8", "3"))
Ω(Object(uint16(3), 1)).Should(match("uint16", "3"))
Ω(Object(uint32(3), 1)).Should(match("uint32", "3"))
Ω(Object(uint64(3), 1)).Should(match("uint64", "3"))
})
It("should handle uintptr differently", func() {
Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3"))
})
})
Describe("formatting channels", func() {
It("should give the type and format values correctly", func() {
c := make(chan<- bool, 3)
c <- true
c <- false
Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c))
})
})
Describe("formatting strings", func() {
It("should give the type and format values correctly", func() {
s := "a\nb\nc"
Ω(Object(s, 1)).Should(match("string", `a
b
c`))
})
})
Describe("formatting []byte slices", func() {
Context("when the slice is made of printable bytes", func() {
It("should present it as string", func() {
b := []byte("a b c")
Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a b c`))
})
})
Context("when the slice contains non-printable bytes", func() {
It("should present it as slice", func() {
b := []byte("a b c\n\x01\x02\x03\xff\x1bH")
Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:12, cap:\d+`, `\[97, 32, 98, 32, 99, 10, 1, 2, 3, 255, 27, 72\]`))
})
})
})
Describe("formatting functions", func() {
It("should give the type and format values correctly", func() {
f := func(a string, b []int) ([]byte, error) {
return []byte("abc"), nil
}
Ω(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f))
})
})
Describe("formatting pointers", func() {
It("should give the type and dereference the value to format it correctly", func() {
a := 3
Ω(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3"))
})
Context("when there are pointers to pointers...", func() {
It("should recursively deference the pointer until it gets to a value", func() {
a := 3
var b *int
var c **int
var d ***int
b = &a
c = &b
d = &c
Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3"))
})
})
Context("when the pointer points to nil", func() {
It("should say nil and not explode", func() {
var a *AStruct
Ω(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil"))
})
})
})
Describe("formatting arrays", func() {
It("should give the type and format values correctly", func() {
w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"}
Ω(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`))
})
Context("with byte arrays", func() {
It("should give the type and format values correctly", func() {
w := [3]byte{17, 28, 19}
Ω(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`))
})
})
})
Describe("formatting slices", func() {
It("should include the length and capacity in the type information", func() {
s := make([]bool, 3, 4)
Ω(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]"))
})
Context("when the slice contains long entries", func() {
It("should format the entries with newlines", func() {
w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"}
expected := `[
"Josiah Edward Bartlet",
"Toby Ziegler",
"CJ Cregg",
]`
Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected))
})
})
})
Describe("formatting maps", func() {
It("should include the length in the type information", func() {
m := make(map[int]bool, 5)
m[3] = true
m[4] = false
Ω(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false")))
})
Context("when the slice contains long entries", func() {
It("should format the entries with newlines", func() {
m := map[string][]byte{}
m["Josiah Edward Bartlet"] = []byte("Martin Sheen")
m["Toby Ziegler"] = []byte("Richard Schiff")
m["CJ Cregg"] = []byte("Allison Janney")
expected := `{
("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"),
("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"),
("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"),
}`
Ω(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected))
})
})
})
Describe("formatting structs", func() {
It("should include the struct name and the field names", func() {
s := SimpleStruct{
Name: "Oswald",
Enumeration: 17,
Veritas: true,
Data: []byte("datum"),
secret: 1983,
}
Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`))
})
Context("when the struct contains long entries", func() {
It("should format the entries with new lines", func() {
s := &SimpleStruct{
Name: "Mithrandir Gandalf Greyhame",
Enumeration: 2021,
Veritas: true,
Data: []byte("wizard"),
secret: 3,
}
Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{
Name: "Mithrandir Gandalf Greyhame",
Enumeration: 2021,
Veritas: true,
Data: "wizard",
secret: 3,
}`))
})
})
})
Describe("formatting nil values", func() {
It("should print out nil", func() {
Ω(Object(nil, 1)).Should(match("nil", "nil"))
var typedNil *AStruct
Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil"))
var c chan<- bool
Ω(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil"))
var s []string
Ω(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil"))
var m map[string]bool
Ω(Object(m, 1)).Should(match("map[string]bool | len:0", "nil"))
})
})
Describe("formatting aliased types", func() {
It("should print out the correct alias type", func() {
Ω(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`))
Ω(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`))
Ω(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3"))
})
})
Describe("handling nested things", func() {
It("should produce a correctly nested representation", func() {
s := ComplexStruct{
Strings: []string{"lots", "of", "short", "strings"},
SimpleThings: []*SimpleStruct{
{"short", 7, true, []byte("succinct"), 17},
{"something longer", 427, true, []byte("designed to wrap around nicely"), 30},
},
DataMaps: map[int]ByteAlias{
17: ByteAlias("some substantially longer chunks of data"),
1138: ByteAlias("that should make things wrap"),
},
}
expected := `{
Strings: \["lots", "of", "short", "strings"\],
SimpleThings: \[
{Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17},
{
Name: "something longer",
Enumeration: 427,
Veritas: true,
Data: "designed to wrap around nicely",
secret: 30,
},
\],
DataMaps: {
(17: "some substantially longer chunks of data"|1138: "that should make things wrap"),
(17: "some substantially longer chunks of data"|1138: "that should make things wrap"),
},
}`
Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected))
})
})
Describe("formatting times", func() {
It("should format time as RFC3339", func() {
t := time.Date(2016, 10, 31, 9, 57, 23, 12345, time.UTC)
Ω(Object(t, 1)).Should(match("time.Time", `2016-10-31T09:57:23.000012345Z`))
})
})
})
Describe("Handling unexported fields in structs", func() {
It("should handle all the various types correctly", func() {
a := int(5)
s := SecretiveStruct{
boolValue: true,
intValue: 3,
uintValue: 4,
uintptrValue: 5,
floatValue: 6.0,
complexValue: complex(5.0, 3.0),
chanValue: make(chan bool, 2),
funcValue: func() {},
pointerValue: &a,
sliceValue: []string{"string", "slice"},
byteSliceValue: []byte("bytes"),
stringValue: "a string",
arrValue: [3]int{11, 12, 13},
byteArrValue: [3]byte{17, 20, 32},
mapValue: map[string]int{"a key": 20, "b key": 30},
structValue: AStruct{"exported"},
interfaceValue: map[string]int{"a key": 17},
}
expected := fmt.Sprintf(`{
boolValue: true,
intValue: 3,
uintValue: 4,
uintptrValue: 0x5,
floatValue: 6,
complexValue: \(5\+3i\),
chanValue: %p,
funcValue: %p,
pointerValue: 5,
sliceValue: \["string", "slice"\],
byteSliceValue: "bytes",
stringValue: "a string",
arrValue: \[11, 12, 13\],
byteArrValue: \[17, 20, 32\],
mapValue: %s,
structValue: {Exported: "exported"},
interfaceValue: {"a key": 17},
}`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`))
Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected))
})
})
Describe("Handling interfaces", func() {
It("should unpack the interface", func() {
outerHash := map[string]interface{}{}
innerHash := map[string]int{}
innerHash["inner"] = 3
outerHash["integer"] = 2
outerHash["map"] = innerHash
expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`)
Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected))
})
})
Describe("Handling recursive things", func() {
It("should not go crazy...", func() {
m := map[string]interface{}{}
m["integer"] = 2
m["map"] = m
Ω(Object(m, 1)).Should(ContainSubstring("..."))
})
It("really should not go crazy...", func() {
type complexKey struct {
Value map[interface{}]int
}
complexObject := complexKey{}
complexObject.Value = make(map[interface{}]int)
complexObject.Value[&complexObject] = 2
Ω(Object(complexObject, 1)).Should(ContainSubstring("..."))
})
})
Describe("When instructed to use the Stringer representation", func() {
BeforeEach(func() {
UseStringerRepresentation = true
})
AfterEach(func() {
UseStringerRepresentation = false
})
Context("when passed a GoStringer", func() {
It("should use what GoString() returns", func() {
Ω(Object(GoStringer{}, 1)).Should(ContainSubstring("<format_test.GoStringer>: go-string"))
})
})
Context("when passed a stringer", func() {
It("should use what String() returns", func() {
Ω(Object(Stringer{}, 1)).Should(ContainSubstring("<format_test.Stringer>: string"))
})
})
})
Describe("Printing a context.Context field", func() {
type structWithContext struct {
Context Ctx
Value string
}
context := ctx{}
objWithContext := structWithContext{Value: "some-value", Context: &context}
It("Suppresses the content by default", func() {
Ω(Object(objWithContext, 1)).Should(ContainSubstring("<suppressed context>"))
})
It("Doesn't supress the context if it's the object being printed", func() {
Ω(Object(context, 1)).ShouldNot(MatchRegexp("^.*<suppressed context>$"))
})
Context("PrintContextObjects is set", func() {
BeforeEach(func() {
PrintContextObjects = true
})
AfterEach(func() {
PrintContextObjects = false
})
It("Prints the context", func() {
Ω(Object(objWithContext, 1)).ShouldNot(ContainSubstring("<suppressed context>"))
})
})
})
})
var expectedLongStringFailureMessage = strings.TrimSpace(`
Expected
<string>: "...aaaaabaaaaa..."
to equal |
<string>: "...aaaaazaaaaa..."
`)
var expectedTruncatedEndStringFailureMessage = strings.TrimSpace(`
Expected
<string>: "baaaaa..."
to equal |
<string>: "zaaaaa..."
`)
var expectedTruncatedStartStringFailureMessage = strings.TrimSpace(`
Expected
<string>: "...aaaaab"
to equal |
<string>: "...aaaaaz"
`)
var expectedTruncatedStartSizeFailureMessage = strings.TrimSpace(`
Expected
<string>: "...aaaaaa"
to equal |
<string>: "...aaaaa"
`)
var expectedTruncatedStartSizeSwappedFailureMessage = strings.TrimSpace(`
Expected
<string>: "...aaaa"
to equal |
<string>: "...aaaaa"
`)

View file

@ -24,11 +24,12 @@ import (
"github.com/onsi/gomega/types"
)
const GOMEGA_VERSION = "1.2.0"
const GOMEGA_VERSION = "1.4.0"
const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil.
If you're using Ginkgo then you probably forgot to put your assertion in an It().
Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT().
Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations.
`
var globalFailHandler types.GomegaFailHandler
@ -45,7 +46,11 @@ func RegisterFailHandler(handler types.GomegaFailHandler) {
}
//RegisterTestingT connects Gomega to Golang's XUnit style
//Testing.T tests. You'll need to call this at the top of each XUnit style test:
//Testing.T tests. It is now deprecated and you should use NewGomegaWithT() instead.
//
//Legacy Documentation:
//
//You'll need to call this at the top of each XUnit style test:
//
// func TestFarmHasCow(t *testing.T) {
// RegisterTestingT(t)
@ -58,6 +63,8 @@ func RegisterFailHandler(handler types.GomegaFailHandler) {
// pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests
// in parallel as the global fail handler cannot point to more than one testing.T at a time.
//
// NewGomegaWithT() does not have this limitation
//
// (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*).
func RegisterTestingT(t types.GomegaTestingT) {
RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailHandler(t))
@ -308,6 +315,60 @@ type GomegaAssertion interface {
//OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it
type OmegaMatcher types.GomegaMatcher
//GomegaWithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage
//Gomega's rich ecosystem of matchers in standard `testing` test suites.
//
//Use `NewGomegaWithT` to instantiate a `GomegaWithT`
type GomegaWithT struct {
t types.GomegaTestingT
}
//NewGomegaWithT takes a *testing.T and returngs a `GomegaWithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with
//Gomega's rich ecosystem of matchers in standard `testing` test suits.
//
// func TestFarmHasCow(t *testing.T) {
// g := GomegaWithT(t)
//
// f := farm.New([]string{"Cow", "Horse"})
// g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
// }
func NewGomegaWithT(t types.GomegaTestingT) *GomegaWithT {
return &GomegaWithT{
t: t,
}
}
//See documentation for Expect
func (g *GomegaWithT) Expect(actual interface{}, extra ...interface{}) GomegaAssertion {
return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), 0, extra...)
}
//See documentation for Eventually
func (g *GomegaWithT) Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion {
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0)
}
//See documentation for Consistently
func (g *GomegaWithT) Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion {
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0)
}
func toDuration(input interface{}) time.Duration {
duration, ok := input.(time.Duration)
if ok {

View file

@ -1,13 +0,0 @@
package assertion_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestAssertion(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Assertion Suite")
}

View file

@ -1,252 +0,0 @@
package assertion_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/internal/assertion"
"github.com/onsi/gomega/internal/fakematcher"
)
var _ = Describe("Assertion", func() {
var (
a *Assertion
failureMessage string
failureCallerSkip int
matcher *fakematcher.FakeMatcher
)
input := "The thing I'm testing"
var fakeFailHandler = func(message string, callerSkip ...int) {
failureMessage = message
if len(callerSkip) == 1 {
failureCallerSkip = callerSkip[0]
}
}
BeforeEach(func() {
matcher = &fakematcher.FakeMatcher{}
failureMessage = ""
failureCallerSkip = 0
a = New(input, fakeFailHandler, 1)
})
Context("when called", func() {
It("should pass the provided input value to the matcher", func() {
a.Should(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.ShouldNot(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.To(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.ToNot(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.NotTo(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
})
})
Context("when the matcher succeeds", func() {
BeforeEach(func() {
matcher.MatchesToReturn = true
matcher.ErrToReturn = nil
})
Context("and a positive assertion is being made", func() {
It("should not call the failure callback", func() {
a.Should(matcher)
Ω(failureMessage).Should(Equal(""))
})
It("should be true", func() {
Ω(a.Should(matcher)).Should(BeTrue())
})
})
Context("and a negative assertion is being made", func() {
It("should call the failure callback", func() {
a.ShouldNot(matcher)
Ω(failureMessage).Should(Equal("negative: The thing I'm testing"))
Ω(failureCallerSkip).Should(Equal(3))
})
It("should be false", func() {
Ω(a.ShouldNot(matcher)).Should(BeFalse())
})
})
})
Context("when the matcher fails", func() {
BeforeEach(func() {
matcher.MatchesToReturn = false
matcher.ErrToReturn = nil
})
Context("and a positive assertion is being made", func() {
It("should call the failure callback", func() {
a.Should(matcher)
Ω(failureMessage).Should(Equal("positive: The thing I'm testing"))
Ω(failureCallerSkip).Should(Equal(3))
})
It("should be false", func() {
Ω(a.Should(matcher)).Should(BeFalse())
})
})
Context("and a negative assertion is being made", func() {
It("should not call the failure callback", func() {
a.ShouldNot(matcher)
Ω(failureMessage).Should(Equal(""))
})
It("should be true", func() {
Ω(a.ShouldNot(matcher)).Should(BeTrue())
})
})
})
Context("When reporting a failure", func() {
BeforeEach(func() {
matcher.MatchesToReturn = false
matcher.ErrToReturn = nil
})
Context("and there is an optional description", func() {
It("should append the description to the failure message", func() {
a.Should(matcher, "A description")
Ω(failureMessage).Should(Equal("A description\npositive: The thing I'm testing"))
Ω(failureCallerSkip).Should(Equal(3))
})
})
Context("and there are multiple arguments to the optional description", func() {
It("should append the formatted description to the failure message", func() {
a.Should(matcher, "A description of [%d]", 3)
Ω(failureMessage).Should(Equal("A description of [3]\npositive: The thing I'm testing"))
Ω(failureCallerSkip).Should(Equal(3))
})
})
})
Context("When the matcher returns an error", func() {
BeforeEach(func() {
matcher.ErrToReturn = errors.New("Kaboom!")
})
Context("and a positive assertion is being made", func() {
It("should call the failure callback", func() {
matcher.MatchesToReturn = true
a.Should(matcher)
Ω(failureMessage).Should(Equal("Kaboom!"))
Ω(failureCallerSkip).Should(Equal(3))
})
})
Context("and a negative assertion is being made", func() {
It("should call the failure callback", func() {
matcher.MatchesToReturn = false
a.ShouldNot(matcher)
Ω(failureMessage).Should(Equal("Kaboom!"))
Ω(failureCallerSkip).Should(Equal(3))
})
})
It("should always be false", func() {
Ω(a.Should(matcher)).Should(BeFalse())
Ω(a.ShouldNot(matcher)).Should(BeFalse())
})
})
Context("when there are extra parameters", func() {
It("(a simple example)", func() {
Ω(func() (string, int, error) {
return "foo", 0, nil
}()).Should(Equal("foo"))
})
Context("when the parameters are all nil or zero", func() {
It("should invoke the matcher", func() {
matcher.MatchesToReturn = true
matcher.ErrToReturn = nil
var typedNil []string
a = New(input, fakeFailHandler, 1, 0, nil, typedNil)
result := a.Should(matcher)
Ω(result).Should(BeTrue())
Ω(matcher.ReceivedActual).Should(Equal(input))
Ω(failureMessage).Should(BeZero())
})
})
Context("when any of the parameters are not nil or zero", func() {
It("should call the failure callback", func() {
matcher.MatchesToReturn = false
matcher.ErrToReturn = nil
a = New(input, fakeFailHandler, 1, errors.New("foo"))
result := a.Should(matcher)
Ω(result).Should(BeFalse())
Ω(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called")
Ω(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 1)
result = a.ShouldNot(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("1"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
result = a.To(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
result = a.ToNot(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
result = a.NotTo(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
Ω(failureCallerSkip).Should(Equal(3))
})
})
})
Context("Making an assertion without a registered fail handler", func() {
It("should panic", func() {
defer func() {
e := recover()
RegisterFailHandler(Fail)
if e == nil {
Fail("expected a panic to have occurred")
}
}()
RegisterFailHandler(nil)
Ω(true).Should(BeTrue())
})
})
})

View file

@ -1,13 +0,0 @@
package asyncassertion_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestAsyncAssertion(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "AsyncAssertion Suite")
}

View file

@ -1,345 +0,0 @@
package asyncassertion_test
import (
"errors"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/internal/asyncassertion"
)
var _ = Describe("Async Assertion", func() {
var (
failureMessage string
callerSkip int
)
var fakeFailHandler = func(message string, skip ...int) {
failureMessage = message
callerSkip = skip[0]
}
BeforeEach(func() {
failureMessage = ""
callerSkip = 0
})
Describe("Eventually", func() {
Context("the positive case", func() {
It("should poll the function and matcher", func() {
counter := 0
a := New(AsyncAssertionTypeEventually, func() int {
counter++
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(BeNumerically("==", 5))
Ω(failureMessage).Should(BeZero())
})
It("should continue when the matcher errors", func() {
counter := 0
a := New(AsyncAssertionTypeEventually, func() interface{} {
counter++
if counter == 5 {
return "not-a-number" //this should cause the matcher to error
}
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(BeNumerically("==", 5), "My description %d", 2)
Ω(failureMessage).Should(ContainSubstring("Timed out after"))
Ω(failureMessage).Should(ContainSubstring("My description 2"))
Ω(callerSkip).Should(Equal(4))
})
It("should be able to timeout", func() {
counter := 0
a := New(AsyncAssertionTypeEventually, func() int {
counter++
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(BeNumerically(">", 100), "My description %d", 2)
Ω(counter).Should(BeNumerically(">", 8))
Ω(counter).Should(BeNumerically("<=", 10))
Ω(failureMessage).Should(ContainSubstring("Timed out after"))
Ω(failureMessage).Should(MatchRegexp(`\<int\>: \d`), "Should pass the correct value to the matcher message formatter.")
Ω(failureMessage).Should(ContainSubstring("My description 2"))
Ω(callerSkip).Should(Equal(4))
})
})
Context("the negative case", func() {
It("should poll the function and matcher", func() {
counter := 0
a := New(AsyncAssertionTypeEventually, func() int {
counter += 1
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(BeNumerically("<", 3))
Ω(counter).Should(Equal(3))
Ω(failureMessage).Should(BeZero())
})
It("should timeout when the matcher errors", func() {
a := New(AsyncAssertionTypeEventually, func() interface{} {
return 0 //this should cause the matcher to error
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(HaveLen(0), "My description %d", 2)
Ω(failureMessage).Should(ContainSubstring("Timed out after"))
Ω(failureMessage).Should(ContainSubstring("Error:"))
Ω(failureMessage).Should(ContainSubstring("My description 2"))
Ω(callerSkip).Should(Equal(4))
})
It("should be able to timeout", func() {
a := New(AsyncAssertionTypeEventually, func() int {
return 0
}, fakeFailHandler, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(Equal(0), "My description %d", 2)
Ω(failureMessage).Should(ContainSubstring("Timed out after"))
Ω(failureMessage).Should(ContainSubstring("<int>: 0"), "Should pass the correct value to the matcher message formatter.")
Ω(failureMessage).Should(ContainSubstring("My description 2"))
Ω(callerSkip).Should(Equal(4))
})
})
Context("with a function that returns multiple values", func() {
It("should eventually succeed if the additional arguments are nil", func() {
i := 0
Eventually(func() (int, error) {
i++
return i, nil
}).Should(Equal(10))
})
It("should eventually timeout if the additional arguments are not nil", func() {
i := 0
a := New(AsyncAssertionTypeEventually, func() (int, error) {
i++
return i, errors.New("bam")
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(Equal(2))
Ω(failureMessage).Should(ContainSubstring("Timed out after"))
Ω(failureMessage).Should(ContainSubstring("Error:"))
Ω(failureMessage).Should(ContainSubstring("bam"))
Ω(callerSkip).Should(Equal(4))
})
})
Context("Making an assertion without a registered fail handler", func() {
It("should panic", func() {
defer func() {
e := recover()
RegisterFailHandler(Fail)
if e == nil {
Fail("expected a panic to have occurred")
}
}()
RegisterFailHandler(nil)
c := make(chan bool, 1)
c <- true
Eventually(c).Should(Receive())
})
})
})
Describe("Consistently", func() {
Describe("The positive case", func() {
Context("when the matcher consistently passes for the duration", func() {
It("should pass", func() {
calls := 0
a := New(AsyncAssertionTypeConsistently, func() string {
calls++
return "foo"
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(Equal("foo"))
Ω(calls).Should(BeNumerically(">", 8))
Ω(calls).Should(BeNumerically("<=", 10))
Ω(failureMessage).Should(BeZero())
})
})
Context("when the matcher fails at some point", func() {
It("should fail", func() {
calls := 0
a := New(AsyncAssertionTypeConsistently, func() interface{} {
calls++
if calls > 5 {
return "bar"
}
return "foo"
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(Equal("foo"))
Ω(failureMessage).Should(ContainSubstring("to equal"))
Ω(callerSkip).Should(Equal(4))
})
})
Context("when the matcher errors at some point", func() {
It("should fail", func() {
calls := 0
a := New(AsyncAssertionTypeConsistently, func() interface{} {
calls++
if calls > 5 {
return 3
}
return []int{1, 2, 3}
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(HaveLen(3))
Ω(failureMessage).Should(ContainSubstring("HaveLen matcher expects"))
Ω(callerSkip).Should(Equal(4))
})
})
})
Describe("The negative case", func() {
Context("when the matcher consistently passes for the duration", func() {
It("should pass", func() {
c := make(chan bool)
a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(Receive())
Ω(failureMessage).Should(BeZero())
})
})
Context("when the matcher fails at some point", func() {
It("should fail", func() {
c := make(chan bool)
go func() {
time.Sleep(time.Duration(100 * time.Millisecond))
c <- true
}()
a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(Receive())
Ω(failureMessage).Should(ContainSubstring("not to receive anything"))
})
})
Context("when the matcher errors at some point", func() {
It("should fail", func() {
calls := 0
a := New(AsyncAssertionTypeConsistently, func() interface{} {
calls++
return calls
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(BeNumerically(">", 5))
Ω(failureMessage).Should(ContainSubstring("not to be >"))
Ω(callerSkip).Should(Equal(4))
})
})
})
Context("with a function that returns multiple values", func() {
It("should consistently succeed if the additional arguments are nil", func() {
i := 2
Consistently(func() (int, error) {
i++
return i, nil
}).Should(BeNumerically(">=", 2))
})
It("should eventually timeout if the additional arguments are not nil", func() {
i := 2
a := New(AsyncAssertionTypeEventually, func() (int, error) {
i++
return i, errors.New("bam")
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(BeNumerically(">=", 2))
Ω(failureMessage).Should(ContainSubstring("Error:"))
Ω(failureMessage).Should(ContainSubstring("bam"))
Ω(callerSkip).Should(Equal(4))
})
})
Context("Making an assertion without a registered fail handler", func() {
It("should panic", func() {
defer func() {
e := recover()
RegisterFailHandler(Fail)
if e == nil {
Fail("expected a panic to have occurred")
}
}()
RegisterFailHandler(nil)
c := make(chan bool)
Consistently(c).ShouldNot(Receive())
})
})
})
Context("when passed a function with the wrong # or arguments & returns", func() {
It("should panic", func() {
Ω(func() {
New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1)
}).Should(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1)
}).Should(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1)
}).ShouldNot(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1)
}).ShouldNot(Panic())
})
})
Describe("bailing early", func() {
Context("when actual is a value", func() {
It("Eventually should bail out and fail early if the matcher says to", func() {
c := make(chan bool)
close(c)
t := time.Now()
failures := InterceptGomegaFailures(func() {
Eventually(c, 0.1).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond))
Ω(failures).Should(HaveLen(1))
})
})
Context("when actual is a function", func() {
It("should never bail early", func() {
c := make(chan bool)
close(c)
t := time.Now()
failures := InterceptGomegaFailures(func() {
Eventually(func() chan bool {
return c
}, 0.1).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond))
Ω(failures).Should(HaveLen(1))
})
})
})
})

View file

@ -1,12 +0,0 @@
package testingtsupport_test
import (
. "github.com/onsi/gomega"
"testing"
)
func TestTestingT(t *testing.T) {
RegisterTestingT(t)
Ω(true).Should(BeTrue())
}

View file

@ -53,7 +53,7 @@ func BeFalse() types.GomegaMatcher {
//HaveOccurred succeeds if actual is a non-nil error
//The typical Go error checking pattern looks like:
// err := SomethingThatMightFail()
// Ω(err).ShouldNot(HaveOccurred())
// Expect(err).ShouldNot(HaveOccurred())
func HaveOccurred() types.GomegaMatcher {
return &matchers.HaveOccurredMatcher{}
}
@ -61,10 +61,10 @@ func HaveOccurred() types.GomegaMatcher {
//Succeed passes if actual is a nil error
//Succeed is intended to be used with functions that return a single error value. Instead of
// err := SomethingThatMightFail()
// Ω(err).ShouldNot(HaveOccurred())
// Expect(err).ShouldNot(HaveOccurred())
//
//You can write:
// Ω(SomethingThatMightFail()).Should(Succeed())
// Expect(SomethingThatMightFail()).Should(Succeed())
//
//It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect
//functions automatically trigger failure if any return values after the first return value are non-zero/non-nil.
@ -76,8 +76,8 @@ func Succeed() types.GomegaMatcher {
//MatchError succeeds if actual is a non-nil error that matches the passed in string/error.
//
//These are valid use-cases:
// Ω(err).Should(MatchError("an error")) //asserts that err.Error() == "an error"
// Ω(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual)
// Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error"
// Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual)
//
//It is an error for err to be nil or an object that does not implement the Error interface
func MatchError(expected interface{}) types.GomegaMatcher {
@ -106,11 +106,11 @@ func BeClosed() types.GomegaMatcher {
//
//Receive returns immediately and never blocks:
//
//- If there is nothing on the channel `c` then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
//- If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
//
//- If the channel `c` is closed then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
//- If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
//
//- If there is something on the channel `c` ready to be read, then Ω(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail.
//- If there is something on the channel `c` ready to be read, then Expect(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail.
//
//If you have a go-routine running in the background that will write to channel `c` you can:
// Eventually(c).Should(Receive())
@ -121,7 +121,7 @@ func BeClosed() types.GomegaMatcher {
// Consistently(c).ShouldNot(Receive())
//
//You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:
// Ω(c).Should(Receive(Equal("foo")))
// Expect(c).Should(Receive(Equal("foo")))
//
//When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.
//
@ -134,8 +134,8 @@ func BeClosed() types.GomegaMatcher {
//Finally, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type:
// var myThing thing
// Eventually(thingChan).Should(Receive(&myThing))
// Ω(myThing.Sprocket).Should(Equal("foo"))
// Ω(myThing.IsValid()).Should(BeTrue())
// Expect(myThing.Sprocket).Should(Equal("foo"))
// Expect(myThing.IsValid()).Should(BeTrue())
func Receive(args ...interface{}) types.GomegaMatcher {
var arg interface{}
if len(args) > 0 {
@ -153,9 +153,9 @@ func Receive(args ...interface{}) types.GomegaMatcher {
//
//BeSent never blocks:
//
//- If the channel `c` is not ready to receive then Ω(c).Should(BeSent("foo")) will fail immediately
//- If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately
//- If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout
//- If the channel `c` is closed then Ω(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately
//- If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately
//
//Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with).
//Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends.
@ -259,7 +259,7 @@ func BeZero() types.GomegaMatcher {
//ContainElement succeeds if actual contains the passed in element.
//By default ContainElement() uses Equal() to perform the match, however a
//matcher can be passed in instead:
// Ω([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))
// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))
//
//Actual must be an array, slice or map.
//For maps, ContainElement searches through the map's values.
@ -269,19 +269,19 @@ func ContainElement(element interface{}) types.GomegaMatcher {
}
}
//ConsistOf succeeds if actual contains preciely the elements passed into the matcher. The ordering of the elements does not matter.
//ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter.
//By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
//
// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo"))
// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo"))
// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo")))
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo"))
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo"))
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo")))
//
//Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.
//
//You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it
//is the only element passed in to ConsistOf:
//
// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))
//
//Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule.
func ConsistOf(elements ...interface{}) types.GomegaMatcher {
@ -293,7 +293,7 @@ func ConsistOf(elements ...interface{}) types.GomegaMatcher {
//HaveKey succeeds if actual is a map with the passed in key.
//By default HaveKey uses Equal() to perform the match, however a
//matcher can be passed in instead:
// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
func HaveKey(key interface{}) types.GomegaMatcher {
return &matchers.HaveKeyMatcher{
Key: key,
@ -303,8 +303,8 @@ func HaveKey(key interface{}) types.GomegaMatcher {
//HaveKeyWithValue succeeds if actual is a map with the passed in key and value.
//By default HaveKeyWithValue uses Equal() to perform the match, however a
//matcher can be passed in instead:
// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))
func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher {
return &matchers.HaveKeyWithValueMatcher{
Key: key,
@ -314,15 +314,15 @@ func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher {
//BeNumerically performs numerical assertions in a type-agnostic way.
//Actual and expected should be numbers, though the specific type of
//number is irrelevant (floa32, float64, uint8, etc...).
//number is irrelevant (float32, float64, uint8, etc...).
//
//There are six, self-explanatory, supported comparators:
// Ω(1.0).Should(BeNumerically("==", 1))
// Ω(1.0).Should(BeNumerically("~", 0.999, 0.01))
// Ω(1.0).Should(BeNumerically(">", 0.9))
// Ω(1.0).Should(BeNumerically(">=", 1.0))
// Ω(1.0).Should(BeNumerically("<", 3))
// Ω(1.0).Should(BeNumerically("<=", 1.0))
// Expect(1.0).Should(BeNumerically("==", 1))
// Expect(1.0).Should(BeNumerically("~", 0.999, 0.01))
// Expect(1.0).Should(BeNumerically(">", 0.9))
// Expect(1.0).Should(BeNumerically(">=", 1.0))
// Expect(1.0).Should(BeNumerically("<", 3))
// Expect(1.0).Should(BeNumerically("<=", 1.0))
func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher {
return &matchers.BeNumericallyMatcher{
Comparator: comparator,
@ -332,8 +332,8 @@ func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatc
//BeTemporally compares time.Time's like BeNumerically
//Actual and expected must be time.Time. The comparators are the same as for BeNumerically
// Ω(time.Now()).Should(BeTemporally(">", time.Time{}))
// Ω(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
// Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
// Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher {
return &matchers.BeTemporallyMatcher{
Comparator: comparator,
@ -344,10 +344,10 @@ func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Dura
//BeAssignableToTypeOf succeeds if actual is assignable to the type of expected.
//It will return an error when one of the values is nil.
// Ω(0).Should(BeAssignableToTypeOf(0)) // Same values
// Ω(5).Should(BeAssignableToTypeOf(-1)) // different values same type
// Ω("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
// Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
// Expect(0).Should(BeAssignableToTypeOf(0)) // Same values
// Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type
// Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
// Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher {
return &matchers.AssignableToTypeOfMatcher{
Expected: expected,
@ -366,13 +366,13 @@ func BeAnExistingFile() types.GomegaMatcher {
return &matchers.BeAnExistingFileMatcher{}
}
//BeARegularFile succeeds iff a file exists and is a regular file.
//BeARegularFile succeeds if a file exists and is a regular file.
//Actual must be a string representing the abs path to the file being checked.
func BeARegularFile() types.GomegaMatcher {
return &matchers.BeARegularFileMatcher{}
}
//BeADirectory succeeds iff a file exists and is a directory.
//BeADirectory succeeds if a file exists and is a directory.
//Actual must be a string representing the abs path to the file being checked.
func BeADirectory() types.GomegaMatcher {
return &matchers.BeADirectoryMatcher{}
@ -388,7 +388,7 @@ func And(ms ...types.GomegaMatcher) types.GomegaMatcher {
}
//SatisfyAll is an alias for And().
// Ω("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher {
return And(matchers...)
}

View file

@ -1,103 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
"github.com/onsi/gomega/types"
)
// sample data
var (
// example input
input = "hi"
// some matchers that succeed against the input
true1 = HaveLen(2)
true2 = Equal("hi")
true3 = MatchRegexp("hi")
// some matchers that fail against the input.
false1 = HaveLen(1)
false2 = Equal("hip")
false3 = MatchRegexp("hope")
)
// verifyFailureMessage expects the matcher to fail with the given input, and verifies the failure message.
func verifyFailureMessage(m types.GomegaMatcher, input string, expectedFailureMsgFragment string) {
Expect(m.Match(input)).To(BeFalse())
Expect(m.FailureMessage(input)).To(Equal(
"Expected\n <string>: " + input + "\n" + expectedFailureMsgFragment))
}
var _ = Describe("AndMatcher", func() {
It("works with positive cases", func() {
Expect(input).To(And())
Expect(input).To(And(true1))
Expect(input).To(And(true1, true2))
Expect(input).To(And(true1, true2, true3))
// use alias
Expect(input).To(SatisfyAll(true1, true2, true3))
})
It("works with negative cases", func() {
Expect(input).ToNot(And(false1, false2))
Expect(input).ToNot(And(true1, true2, false3))
Expect(input).ToNot(And(true1, false2, false3))
Expect(input).ToNot(And(false1, true1, true2))
})
Context("failure messages", func() {
Context("when match fails", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(And(false1, true1), input, "to have length 1")
verifyFailureMessage(And(true1, false2), input, "to equal\n <string>: hip")
verifyFailureMessage(And(true1, true2, false3), input, "to match regular expression\n <string>: hope")
})
})
Context("when match succeeds, but expected it to fail", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(Not(And(true1, true2)), input,
`To not satisfy all of these matchers: [%!s(*matchers.HaveLenMatcher=&{2}) %!s(*matchers.EqualMatcher=&{hi})]`)
})
})
})
Context("MatchMayChangeInTheFuture", func() {
Context("Match returned false", func() {
Context("returns value of the failed matcher", func() {
It("false if failed matcher not going to change", func() {
// 3 matchers: 1st returns true, 2nd returns false and is not going to change, 3rd is never called
m := And(Not(BeNil()), Or(), Equal(1))
Expect(m.Match("hi")).To(BeFalse())
Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // empty Or() indicates not going to change
})
It("true if failed matcher indicates it might change", func() {
// 3 matchers: 1st returns true, 2nd returns false and "might" change, 3rd is never called
m := And(Not(BeNil()), Equal(5), Equal(1))
Expect(m.Match("hi")).To(BeFalse())
Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // Equal(5) indicates it might change
})
})
})
Context("Match returned true", func() {
It("returns true if any of the matchers could change", func() {
// 3 matchers, all return true, and all could change
m := And(Not(BeNil()), Equal("hi"), HaveLen(2))
Expect(m.Match("hi")).To(BeTrue())
Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // all 3 of these matchers default to 'true'
})
It("returns false if none of the matchers could change", func() {
// empty And() has the property of always matching, and never can change since there are no sub-matchers that could change
m := And()
Expect(m.Match("anything")).To(BeTrue())
Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse())
// And() with 3 sub-matchers that return true, and can't change
m = And(And(), And(), And())
Expect(m.Match("hi")).To(BeTrue())
Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // the 3 empty And()'s won't change
})
})
})
})

View file

@ -12,8 +12,12 @@ type AssignableToTypeOfMatcher struct {
}
func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil || matcher.Expected == nil {
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
} else if matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare type to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
} else if actual == nil {
return false, nil
}
actualType := reflect.TypeOf(actual)

View file

@ -1,30 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("AssignableToTypeOf", func() {
Context("When asserting assignability between types", func() {
It("should do the right thing", func() {
Ω(0).Should(BeAssignableToTypeOf(0))
Ω(5).Should(BeAssignableToTypeOf(-1))
Ω("foo").Should(BeAssignableToTypeOf("bar"))
Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
Ω(0).ShouldNot(BeAssignableToTypeOf("bar"))
Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{}))
Ω("foo").ShouldNot(BeAssignableToTypeOf(42))
})
})
Context("When asserting nil values", func() {
It("should error", func() {
success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -0,0 +1,14 @@
package matchers
import (
"encoding/xml"
"strings"
)
type attributesSlice []xml.Attr
func (attrs attributesSlice) Len() int { return len(attrs) }
func (attrs attributesSlice) Less(i, j int) bool {
return strings.Compare(attrs[i].Name.Local, attrs[j].Name.Local) == -1
}
func (attrs attributesSlice) Swap(i, j int) { attrs[i], attrs[j] = attrs[j], attrs[i] }

View file

@ -1,40 +0,0 @@
package matchers_test
import (
"io/ioutil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeADirectoryMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeADirectory())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).ShouldNot(BeADirectory())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).Should(BeADirectory())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeADirectoryMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeADirectoryMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,40 +0,0 @@
package matchers_test
import (
"io/ioutil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeARegularFileMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeARegularFile())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).Should(BeARegularFile())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).ShouldNot(BeARegularFile())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeARegularFileMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeARegularFileMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,40 +0,0 @@
package matchers_test
import (
"io/ioutil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeAnExistingFileMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeAnExistingFile())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).Should(BeAnExistingFile())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).Should(BeAnExistingFile())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeAnExistingFileMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeAnExistingFileMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeClosedMatcher struct {

View file

@ -1,70 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeClosedMatcher", func() {
Context("when passed a channel", func() {
It("should do the right thing", func() {
openChannel := make(chan bool)
Ω(openChannel).ShouldNot(BeClosed())
var openReaderChannel <-chan bool
openReaderChannel = openChannel
Ω(openReaderChannel).ShouldNot(BeClosed())
closedChannel := make(chan bool)
close(closedChannel)
Ω(closedChannel).Should(BeClosed())
var closedReaderChannel <-chan bool
closedReaderChannel = closedChannel
Ω(closedReaderChannel).Should(BeClosed())
})
})
Context("when passed a send-only channel", func() {
It("should error", func() {
openChannel := make(chan bool)
var openWriterChannel chan<- bool
openWriterChannel = openChannel
success, err := (&BeClosedMatcher{}).Match(openWriterChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
closedChannel := make(chan bool)
close(closedChannel)
var closedWriterChannel chan<- bool
closedWriterChannel = closedChannel
success, err = (&BeClosedMatcher{}).Match(closedWriterChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed something else", func() {
It("should error", func() {
var nilChannel chan bool
success, err := (&BeClosedMatcher{}).Match(nilChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeClosedMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeClosedMatcher{}).Match(7)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,52 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeEmpty", func() {
Context("when passed a supported type", func() {
It("should do the right thing", func() {
Ω("").Should(BeEmpty())
Ω(" ").ShouldNot(BeEmpty())
Ω([0]int{}).Should(BeEmpty())
Ω([1]int{1}).ShouldNot(BeEmpty())
Ω([]int{}).Should(BeEmpty())
Ω([]int{1}).ShouldNot(BeEmpty())
Ω(map[string]int{}).Should(BeEmpty())
Ω(map[string]int{"a": 1}).ShouldNot(BeEmpty())
c := make(chan bool, 1)
Ω(c).Should(BeEmpty())
c <- true
Ω(c).ShouldNot(BeEmpty())
})
})
Context("when passed a correctly typed nil", func() {
It("should be true", func() {
var nilSlice []int
Ω(nilSlice).Should(BeEmpty())
var nilMap map[int]string
Ω(nilMap).Should(BeEmpty())
})
})
Context("when passed an unsupported type", func() {
It("should error", func() {
success, err := (&BeEmptyMatcher{}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeEmptyMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeEquivalentToMatcher struct {

View file

@ -1,50 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeEquivalentTo", func() {
Context("when asserting that nil is equivalent to nil", func() {
It("should error", func() {
success, err := (&BeEquivalentToMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("When asserting on nil", func() {
It("should do the right thing", func() {
Ω("foo").ShouldNot(BeEquivalentTo(nil))
Ω(nil).ShouldNot(BeEquivalentTo(3))
Ω([]int{1, 2}).ShouldNot(BeEquivalentTo(nil))
})
})
Context("When asserting on type aliases", func() {
It("should the right thing", func() {
Ω(StringAlias("foo")).Should(BeEquivalentTo("foo"))
Ω("foo").Should(BeEquivalentTo(StringAlias("foo")))
Ω(StringAlias("foo")).ShouldNot(BeEquivalentTo("bar"))
Ω("foo").ShouldNot(BeEquivalentTo(StringAlias("bar")))
})
})
Context("When asserting on numbers", func() {
It("should convert actual to expected and do the right thing", func() {
Ω(5).Should(BeEquivalentTo(5))
Ω(5.0).Should(BeEquivalentTo(5.0))
Ω(5).Should(BeEquivalentTo(5.0))
Ω(5).ShouldNot(BeEquivalentTo("5"))
Ω(5).ShouldNot(BeEquivalentTo(3))
//Here be dragons!
Ω(5.1).Should(BeEquivalentTo(5))
Ω(5).ShouldNot(BeEquivalentTo(5.1))
})
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,20 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeFalse", func() {
It("should handle true and false correctly", func() {
Ω(true).ShouldNot(BeFalse())
Ω(false).Should(BeFalse())
})
It("should only support booleans", func() {
success, err := (&BeFalseMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})

View file

@ -1,61 +0,0 @@
package matchers_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeIdenticalTo", func() {
Context("when asserting that nil equals nil", func() {
It("should error", func() {
success, err := (&BeIdenticalToMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
It("should treat the same pointer to a struct as identical", func() {
mySpecialStruct := myCustomType{}
Ω(&mySpecialStruct).Should(BeIdenticalTo(&mySpecialStruct))
Ω(&myCustomType{}).ShouldNot(BeIdenticalTo(&mySpecialStruct))
})
It("should be strict about types", func() {
Ω(5).ShouldNot(BeIdenticalTo("5"))
Ω(5).ShouldNot(BeIdenticalTo(5.0))
Ω(5).ShouldNot(BeIdenticalTo(3))
})
It("should treat primtives as identical", func() {
Ω("5").Should(BeIdenticalTo("5"))
Ω("5").ShouldNot(BeIdenticalTo("55"))
Ω(5.55).Should(BeIdenticalTo(5.55))
Ω(5.55).ShouldNot(BeIdenticalTo(6.66))
Ω(5).Should(BeIdenticalTo(5))
Ω(5).ShouldNot(BeIdenticalTo(55))
})
It("should treat the same pointers to a slice as identical", func() {
mySlice := []int{1, 2}
Ω(&mySlice).Should(BeIdenticalTo(&mySlice))
Ω(&mySlice).ShouldNot(BeIdenticalTo(&[]int{1, 2}))
})
It("should treat the same pointers to a map as identical", func() {
myMap := map[string]string{"a": "b", "c": "d"}
Ω(&myMap).Should(BeIdenticalTo(&myMap))
Ω(myMap).ShouldNot(BeIdenticalTo(map[string]string{"a": "b", "c": "d"}))
})
It("should treat the same pointers to an error as identical", func() {
myError := errors.New("foo")
Ω(&myError).Should(BeIdenticalTo(&myError))
Ω(errors.New("foo")).ShouldNot(BeIdenticalTo(errors.New("bar")))
})
})

View file

@ -1,28 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("BeNil", func() {
It("should succeed when passed nil", func() {
Ω(nil).Should(BeNil())
})
It("should succeed when passed a typed nil", func() {
var a []int
Ω(a).Should(BeNil())
})
It("should succeed when passing nil pointer", func() {
var f *struct{}
Ω(f).Should(BeNil())
})
It("should not succeed when not passed nil", func() {
Ω(0).ShouldNot(BeNil())
Ω(false).ShouldNot(BeNil())
Ω("").ShouldNot(BeNil())
})
})

View file

@ -1,148 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeNumerically", func() {
Context("when passed a number", func() {
It("should support ==", func() {
Ω(uint32(5)).Should(BeNumerically("==", 5))
Ω(float64(5.0)).Should(BeNumerically("==", 5))
Ω(int8(5)).Should(BeNumerically("==", 5))
})
It("should not have false positives", func() {
Ω(5.1).ShouldNot(BeNumerically("==", 5))
Ω(5).ShouldNot(BeNumerically("==", 5.1))
})
It("should support >", func() {
Ω(uint32(5)).Should(BeNumerically(">", 4))
Ω(float64(5.0)).Should(BeNumerically(">", 4.9))
Ω(int8(5)).Should(BeNumerically(">", 4))
Ω(uint32(5)).ShouldNot(BeNumerically(">", 5))
Ω(float64(5.0)).ShouldNot(BeNumerically(">", 5.0))
Ω(int8(5)).ShouldNot(BeNumerically(">", 5))
})
It("should support <", func() {
Ω(uint32(5)).Should(BeNumerically("<", 6))
Ω(float64(5.0)).Should(BeNumerically("<", 5.1))
Ω(int8(5)).Should(BeNumerically("<", 6))
Ω(uint32(5)).ShouldNot(BeNumerically("<", 5))
Ω(float64(5.0)).ShouldNot(BeNumerically("<", 5.0))
Ω(int8(5)).ShouldNot(BeNumerically("<", 5))
})
It("should support >=", func() {
Ω(uint32(5)).Should(BeNumerically(">=", 4))
Ω(float64(5.0)).Should(BeNumerically(">=", 4.9))
Ω(int8(5)).Should(BeNumerically(">=", 4))
Ω(uint32(5)).Should(BeNumerically(">=", 5))
Ω(float64(5.0)).Should(BeNumerically(">=", 5.0))
Ω(int8(5)).Should(BeNumerically(">=", 5))
Ω(uint32(5)).ShouldNot(BeNumerically(">=", 6))
Ω(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1))
Ω(int8(5)).ShouldNot(BeNumerically(">=", 6))
})
It("should support <=", func() {
Ω(uint32(5)).Should(BeNumerically("<=", 6))
Ω(float64(5.0)).Should(BeNumerically("<=", 5.1))
Ω(int8(5)).Should(BeNumerically("<=", 6))
Ω(uint32(5)).Should(BeNumerically("<=", 5))
Ω(float64(5.0)).Should(BeNumerically("<=", 5.0))
Ω(int8(5)).Should(BeNumerically("<=", 5))
Ω(uint32(5)).ShouldNot(BeNumerically("<=", 4))
Ω(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9))
Ω(int8(5)).Should(BeNumerically("<=", 5))
})
Context("when passed ~", func() {
Context("when passed a float", func() {
Context("and there is no precision parameter", func() {
It("should default to 1e-8", func() {
Ω(5.00000001).Should(BeNumerically("~", 5.00000002))
Ω(5.00000001).ShouldNot(BeNumerically("~", 5.0000001))
})
})
Context("and there is a precision parameter", func() {
It("should use the precision parameter", func() {
Ω(5.1).Should(BeNumerically("~", 5.19, 0.1))
Ω(5.1).Should(BeNumerically("~", 5.01, 0.1))
Ω(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1))
Ω(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1))
})
})
})
Context("when passed an int/uint", func() {
Context("and there is no precision parameter", func() {
It("should just do strict equality", func() {
Ω(5).Should(BeNumerically("~", 5))
Ω(5).ShouldNot(BeNumerically("~", 6))
Ω(uint(5)).ShouldNot(BeNumerically("~", 6))
})
})
Context("and there is a precision parameter", func() {
It("should use precision paramter", func() {
Ω(5).Should(BeNumerically("~", 6, 2))
Ω(5).ShouldNot(BeNumerically("~", 8, 2))
Ω(uint(5)).Should(BeNumerically("~", 6, 1))
})
})
})
})
})
Context("when passed a non-number", func() {
It("should error", func() {
success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{5}}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "=="}).Match(5)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed an unsupported comparator", func() {
It("should error", func() {
success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []interface{}{5}}).Match(4)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,106 +0,0 @@
package matchers_test
import (
. "github.com/onsi/gomega/matchers"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("BeSent", func() {
Context("when passed a channel and a matching type", func() {
Context("when the channel is ready to receive", func() {
It("should succeed and send the value down the channel", func() {
c := make(chan string)
d := make(chan string)
go func() {
val := <-c
d <- val
}()
time.Sleep(10 * time.Millisecond)
Ω(c).Should(BeSent("foo"))
Eventually(d).Should(Receive(Equal("foo")))
})
It("should succeed (with a buffered channel)", func() {
c := make(chan string, 1)
Ω(c).Should(BeSent("foo"))
Ω(<-c).Should(Equal("foo"))
})
})
Context("when the channel is not ready to receive", func() {
It("should fail and not send down the channel", func() {
c := make(chan string)
Ω(c).ShouldNot(BeSent("foo"))
Consistently(c).ShouldNot(Receive())
})
})
Context("when the channel is eventually ready to receive", func() {
It("should succeed", func() {
c := make(chan string)
d := make(chan string)
go func() {
time.Sleep(30 * time.Millisecond)
val := <-c
d <- val
}()
Eventually(c).Should(BeSent("foo"))
Eventually(d).Should(Receive(Equal("foo")))
})
})
Context("when the channel is closed", func() {
It("should error", func() {
c := make(chan string)
close(c)
success, err := (&BeSentMatcher{Arg: "foo"}).Match(c)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
It("should short-circuit Eventually", func() {
c := make(chan string)
close(c)
t := time.Now()
failures := InterceptGomegaFailures(func() {
Eventually(c, 10.0).Should(BeSent("foo"))
})
Ω(failures).Should(HaveLen(1))
Ω(time.Since(t)).Should(BeNumerically("<", time.Second))
})
})
})
Context("when passed a channel and a non-matching type", func() {
It("should error", func() {
success, err := (&BeSentMatcher{Arg: "foo"}).Match(make(chan int, 1))
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed a receive-only channel", func() {
It("should error", func() {
var c <-chan string
c = make(chan string, 1)
success, err := (&BeSentMatcher{Arg: "foo"}).Match(c)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed a nonchannel", func() {
It("should error", func() {
success, err := (&BeSentMatcher{Arg: "foo"}).Match("bar")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"time"
"github.com/onsi/gomega/format"
)
type BeTemporallyMatcher struct {

View file

@ -1,98 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
"time"
)
var _ = Describe("BeTemporally", func() {
var t0, t1, t2 time.Time
BeforeEach(func() {
t0 = time.Now()
t1 = t0.Add(time.Second)
t2 = t0.Add(-time.Second)
})
Context("When comparing times", func() {
It("should support ==", func() {
Ω(t0).Should(BeTemporally("==", t0))
Ω(t1).ShouldNot(BeTemporally("==", t0))
Ω(t0).ShouldNot(BeTemporally("==", t1))
Ω(t0).ShouldNot(BeTemporally("==", time.Time{}))
})
It("should support >", func() {
Ω(t0).Should(BeTemporally(">", t2))
Ω(t0).ShouldNot(BeTemporally(">", t0))
Ω(t2).ShouldNot(BeTemporally(">", t0))
})
It("should support <", func() {
Ω(t0).Should(BeTemporally("<", t1))
Ω(t0).ShouldNot(BeTemporally("<", t0))
Ω(t1).ShouldNot(BeTemporally("<", t0))
})
It("should support >=", func() {
Ω(t0).Should(BeTemporally(">=", t2))
Ω(t0).Should(BeTemporally(">=", t0))
Ω(t0).ShouldNot(BeTemporally(">=", t1))
})
It("should support <=", func() {
Ω(t0).Should(BeTemporally("<=", t1))
Ω(t0).Should(BeTemporally("<=", t0))
Ω(t0).ShouldNot(BeTemporally("<=", t2))
})
Context("when passed ~", func() {
Context("and there is no precision parameter", func() {
BeforeEach(func() {
t1 = t0.Add(time.Millisecond / 2)
t2 = t0.Add(-2 * time.Millisecond)
})
It("should approximate", func() {
Ω(t0).Should(BeTemporally("~", t0))
Ω(t0).Should(BeTemporally("~", t1))
Ω(t0).ShouldNot(BeTemporally("~", t2))
})
})
Context("and there is a precision parameter", func() {
BeforeEach(func() {
t2 = t0.Add(3 * time.Second)
})
It("should use precision paramter", func() {
d := 2 * time.Second
Ω(t0).Should(BeTemporally("~", t0, d))
Ω(t0).Should(BeTemporally("~", t1, d))
Ω(t0).ShouldNot(BeTemporally("~", t2, d))
})
})
})
})
Context("when passed a non-time", func() {
It("should error", func() {
success, err := (&BeTemporallyMatcher{Comparator: "==", CompareTo: t0}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&BeTemporallyMatcher{Comparator: "=="}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed an unsupported comparator", func() {
It("should error", func() {
success, err := (&BeTemporallyMatcher{Comparator: "!=", CompareTo: t0}).Match(t2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,20 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("BeTrue", func() {
It("should handle true and false correctly", func() {
Ω(true).Should(BeTrue())
Ω(false).ShouldNot(BeTrue())
})
It("should only support booleans", func() {
success, err := (&BeTrueMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})

View file

@ -1,8 +1,9 @@
package matchers
import (
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeZeroMatcher struct {

View file

@ -1,30 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("BeZero", func() {
It("should succeed if the passed in object is the zero value for its type", func() {
Ω(nil).Should(BeZero())
Ω("").Should(BeZero())
Ω(" ").ShouldNot(BeZero())
Ω(0).Should(BeZero())
Ω(1).ShouldNot(BeZero())
Ω(0.0).Should(BeZero())
Ω(0.1).ShouldNot(BeZero())
// Ω([]int{}).Should(BeZero())
Ω([]int{1}).ShouldNot(BeZero())
// Ω(map[string]int{}).Should(BeZero())
Ω(map[string]int{"a": 1}).ShouldNot(BeZero())
Ω(myCustomType{}).Should(BeZero())
Ω(myCustomType{s: "a"}).ShouldNot(BeZero())
})
})

View file

@ -1,75 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("ConsistOf", func() {
Context("with a slice", func() {
It("should do the right thing", func() {
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo"))
})
})
Context("with an array", func() {
It("should do the right thing", func() {
Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo"))
})
})
Context("with a map", func() {
It("should apply to the values", func() {
Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "foo"))
})
})
Context("with anything else", func() {
It("should error", func() {
failures := InterceptGomegaFailures(func() {
Ω("foo").Should(ConsistOf("f", "o", "o"))
})
Ω(failures).Should(HaveLen(1))
})
})
Context("when passed matchers", func() {
It("should pass if the matchers pass", func() {
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), "baz"))
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba")))
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("foo")))
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("^ba")))
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("turducken")))
})
It("should not depend on the order of the matchers", func() {
Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(1), ContainElement(2)))
Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(2), ContainElement(1)))
})
Context("when a matcher errors", func() {
It("should soldier on", func() {
Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar"))
Ω([]interface{}{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar"))
})
})
})
Context("when passed exactly one argument, and that argument is a slice", func() {
It("should match against the elements of that argument", func() {
Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf([]string{"foo", "bar", "baz"}))
})
})
})

View file

@ -1,76 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("ContainElement", func() {
Context("when passed a supported type", func() {
Context("and expecting a non-matcher", func() {
It("should do the right thing", func() {
Ω([2]int{1, 2}).Should(ContainElement(2))
Ω([2]int{1, 2}).ShouldNot(ContainElement(3))
Ω([]int{1, 2}).Should(ContainElement(2))
Ω([]int{1, 2}).ShouldNot(ContainElement(3))
Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(2))
Ω(map[int]int{3: 1, 4: 2}).ShouldNot(ContainElement(3))
arr := make([]myCustomType, 2)
arr[0] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}
arr[1] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "c"}}
Ω(arr).Should(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}))
Ω(arr).ShouldNot(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"b", "c"}}))
})
})
Context("and expecting a matcher", func() {
It("should pass each element through the matcher", func() {
Ω([]int{1, 2, 3}).Should(ContainElement(BeNumerically(">=", 3)))
Ω([]int{1, 2, 3}).ShouldNot(ContainElement(BeNumerically(">", 3)))
Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(BeNumerically(">=", 2)))
Ω(map[string]int{"foo": 1, "bar": 2}).ShouldNot(ContainElement(BeNumerically(">", 2)))
})
It("should power through even if the matcher ever fails", func() {
Ω([]interface{}{1, 2, "3", 4}).Should(ContainElement(BeNumerically(">=", 3)))
})
It("should fail if the matcher fails", func() {
actual := []interface{}{1, 2, "3", "4"}
success, err := (&ContainElementMatcher{Element: BeNumerically(">=", 3)}).Match(actual)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})
Context("when passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
var nilSlice []int
Ω(nilSlice).ShouldNot(ContainElement(1))
var nilMap map[int]string
Ω(nilMap).ShouldNot(ContainElement("foo"))
})
})
Context("when passed an unsupported type", func() {
It("should error", func() {
success, err := (&ContainElementMatcher{Element: 0}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&ContainElementMatcher{Element: 0}).Match("abc")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&ContainElementMatcher{Element: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"strings"
"github.com/onsi/gomega/format"
)
type ContainSubstringMatcher struct {

View file

@ -1,36 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("ContainSubstringMatcher", func() {
Context("when actual is a string", func() {
It("should match against the string", func() {
Ω("Marvelous").Should(ContainSubstring("rve"))
Ω("Marvelous").ShouldNot(ContainSubstring("boo"))
})
})
Context("when the matcher is called with multiple arguments", func() {
It("should pass the string and arguments to sprintf", func() {
Ω("Marvelous3").Should(ContainSubstring("velous%d", 3))
})
})
Context("when actual is a stringer", func() {
It("should call the stringer and match agains the returned string", func() {
Ω(&myStringer{a: "Abc3"}).Should(ContainSubstring("bc3"))
})
})
Context("when actual is neither a string nor a stringer", func() {
It("should error", func() {
success, err := (&ContainSubstringMatcher{Substr: "2"}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,6 +1,7 @@
package matchers
import (
"bytes"
"fmt"
"reflect"
@ -15,6 +16,14 @@ func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error)
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
}
// Shortcut for byte slices.
// Comparing long byte slices with reflect.DeepEqual is very slow,
// so use bytes.Equal if actual and expected are both byte slices.
if actualByteSlice, ok := actual.([]byte); ok {
if expectedByteSlice, ok := matcher.Expected.([]byte); ok {
return bytes.Equal(actualByteSlice, expectedByteSlice), nil
}
}
return reflect.DeepEqual(actual, matcher.Expected), nil
}

View file

@ -1,78 +0,0 @@
package matchers_test
import (
"errors"
"strings"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("Equal", func() {
Context("when asserting that nil equals nil", func() {
It("should error", func() {
success, err := (&EqualMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("When asserting equality between objects", func() {
It("should do the right thing", func() {
Ω(5).Should(Equal(5))
Ω(5.0).Should(Equal(5.0))
Ω(5).ShouldNot(Equal("5"))
Ω(5).ShouldNot(Equal(5.0))
Ω(5).ShouldNot(Equal(3))
Ω("5").Should(Equal("5"))
Ω([]int{1, 2}).Should(Equal([]int{1, 2}))
Ω([]int{1, 2}).ShouldNot(Equal([]int{2, 1}))
Ω(map[string]string{"a": "b", "c": "d"}).Should(Equal(map[string]string{"a": "b", "c": "d"}))
Ω(map[string]string{"a": "b", "c": "d"}).ShouldNot(Equal(map[string]string{"a": "b", "c": "e"}))
Ω(errors.New("foo")).Should(Equal(errors.New("foo")))
Ω(errors.New("foo")).ShouldNot(Equal(errors.New("bar")))
Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).Should(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}))
Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "bar", n: 3, f: 2.0, arr: []string{"a", "b"}}))
Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 2, f: 2.0, arr: []string{"a", "b"}}))
Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 3.0, arr: []string{"a", "b"}}))
Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b", "c"}}))
})
})
Describe("failure messages", func() {
It("shows the two strings simply when they are short", func() {
subject := EqualMatcher{Expected: "eric"}
failureMessage := subject.FailureMessage("tim")
Ω(failureMessage).To(BeEquivalentTo(expectedShortStringFailureMessage))
})
It("shows the exact point where two long strings differ", func() {
stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
subject := EqualMatcher{Expected: stringWithZ}
failureMessage := subject.FailureMessage(stringWithB)
Ω(failureMessage).To(BeEquivalentTo(expectedLongStringFailureMessage))
})
})
})
var expectedShortStringFailureMessage = strings.TrimSpace(`
Expected
<string>: tim
to equal
<string>: eric
`)
var expectedLongStringFailureMessage = strings.TrimSpace(`
Expected
<string>: "...aaaaabaaaaa..."
to equal |
<string>: "...aaaaazaaaaa..."
`)

View file

@ -1,50 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HaveCap", func() {
Context("when passed a supported type", func() {
It("should do the right thing", func() {
Ω([0]int{}).Should(HaveCap(0))
Ω([2]int{1}).Should(HaveCap(2))
Ω([]int{}).Should(HaveCap(0))
Ω([]int{1, 2, 3, 4, 5}[:2]).Should(HaveCap(5))
Ω(make([]int, 0, 5)).Should(HaveCap(5))
c := make(chan bool, 3)
Ω(c).Should(HaveCap(3))
c <- true
c <- true
Ω(c).Should(HaveCap(3))
Ω(make(chan bool)).Should(HaveCap(0))
})
})
Context("when passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
var nilSlice []int
Ω(nilSlice).Should(HaveCap(0))
var nilChan chan int
Ω(nilChan).Should(HaveCap(0))
})
})
Context("when passed an unsupported type", func() {
It("should error", func() {
success, err := (&HaveCapMatcher{Count: 0}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&HaveCapMatcher{Count: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type HaveKeyMatcher struct {

View file

@ -1,73 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HaveKey", func() {
var (
stringKeys map[string]int
intKeys map[int]string
objKeys map[*myCustomType]string
customA *myCustomType
customB *myCustomType
)
BeforeEach(func() {
stringKeys = map[string]int{"foo": 2, "bar": 3}
intKeys = map[int]string{2: "foo", 3: "bar"}
customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}}
customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}
objKeys = map[*myCustomType]string{customA: "aardvark", customB: "kangaroo"}
})
Context("when passed a map", func() {
It("should do the right thing", func() {
Ω(stringKeys).Should(HaveKey("foo"))
Ω(stringKeys).ShouldNot(HaveKey("baz"))
Ω(intKeys).Should(HaveKey(2))
Ω(intKeys).ShouldNot(HaveKey(4))
Ω(objKeys).Should(HaveKey(customA))
Ω(objKeys).Should(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}))
Ω(objKeys).ShouldNot(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}}))
})
})
Context("when passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
var nilMap map[int]string
Ω(nilMap).ShouldNot(HaveKey("foo"))
})
})
Context("when the passed in key is actually a matcher", func() {
It("should pass each element through the matcher", func() {
Ω(stringKeys).Should(HaveKey(ContainSubstring("oo")))
Ω(stringKeys).ShouldNot(HaveKey(ContainSubstring("foobar")))
})
It("should fail if the matcher ever fails", func() {
actual := map[int]string{1: "a", 3: "b", 2: "c"}
success, err := (&HaveKeyMatcher{Key: ContainSubstring("ar")}).Match(actual)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed something that is not a map", func() {
It("should error", func() {
success, err := (&HaveKeyMatcher{Key: "foo"}).Match([]string{"foo"})
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&HaveKeyMatcher{Key: "foo"}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type HaveKeyWithValueMatcher struct {

View file

@ -1,82 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HaveKeyWithValue", func() {
var (
stringKeys map[string]int
intKeys map[int]string
objKeys map[*myCustomType]*myCustomType
customA *myCustomType
customB *myCustomType
)
BeforeEach(func() {
stringKeys = map[string]int{"foo": 2, "bar": 3}
intKeys = map[int]string{2: "foo", 3: "bar"}
customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}}
customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}
objKeys = map[*myCustomType]*myCustomType{customA: customA, customB: customA}
})
Context("when passed a map", func() {
It("should do the right thing", func() {
Ω(stringKeys).Should(HaveKeyWithValue("foo", 2))
Ω(stringKeys).ShouldNot(HaveKeyWithValue("foo", 1))
Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 2))
Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 1))
Ω(intKeys).Should(HaveKeyWithValue(2, "foo"))
Ω(intKeys).ShouldNot(HaveKeyWithValue(4, "foo"))
Ω(intKeys).ShouldNot(HaveKeyWithValue(2, "baz"))
Ω(objKeys).Should(HaveKeyWithValue(customA, customA))
Ω(objKeys).Should(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}, &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}}))
Ω(objKeys).ShouldNot(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}}, customA))
})
})
Context("when passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
var nilMap map[int]string
Ω(nilMap).ShouldNot(HaveKeyWithValue("foo", "bar"))
})
})
Context("when the passed in key or value is actually a matcher", func() {
It("should pass each element through the matcher", func() {
Ω(stringKeys).Should(HaveKeyWithValue(ContainSubstring("oo"), 2))
Ω(intKeys).Should(HaveKeyWithValue(2, ContainSubstring("oo")))
Ω(stringKeys).ShouldNot(HaveKeyWithValue(ContainSubstring("foobar"), 2))
})
It("should fail if the matcher ever fails", func() {
actual := map[int]string{1: "a", 3: "b", 2: "c"}
success, err := (&HaveKeyWithValueMatcher{Key: ContainSubstring("ar"), Value: 2}).Match(actual)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
otherActual := map[string]int{"a": 1, "b": 2, "c": 3}
success, err = (&HaveKeyWithValueMatcher{Key: "a", Value: ContainSubstring("1")}).Match(otherActual)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed something that is not a map", func() {
It("should error", func() {
success, err := (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match([]string{"foo"})
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,53 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HaveLen", func() {
Context("when passed a supported type", func() {
It("should do the right thing", func() {
Ω("").Should(HaveLen(0))
Ω("AA").Should(HaveLen(2))
Ω([0]int{}).Should(HaveLen(0))
Ω([2]int{1, 2}).Should(HaveLen(2))
Ω([]int{}).Should(HaveLen(0))
Ω([]int{1, 2, 3}).Should(HaveLen(3))
Ω(map[string]int{}).Should(HaveLen(0))
Ω(map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}).Should(HaveLen(4))
c := make(chan bool, 3)
Ω(c).Should(HaveLen(0))
c <- true
c <- true
Ω(c).Should(HaveLen(2))
})
})
Context("when passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
var nilSlice []int
Ω(nilSlice).Should(HaveLen(0))
var nilMap map[int]string
Ω(nilMap).Should(HaveLen(0))
})
})
Context("when passed an unsupported type", func() {
It("should error", func() {
success, err := (&HaveLenMatcher{Count: 0}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&HaveLenMatcher{Count: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,58 +0,0 @@
package matchers_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
type CustomErr struct {
msg string
}
func (e *CustomErr) Error() string {
return e.msg
}
var _ = Describe("HaveOccurred", func() {
It("should succeed if matching an error", func() {
Ω(errors.New("Foo")).Should(HaveOccurred())
})
It("should not succeed with nil", func() {
Ω(nil).ShouldNot(HaveOccurred())
})
It("should only support errors and nil", func() {
success, err := (&HaveOccurredMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&HaveOccurredMatcher{}).Match("")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
It("doesn't support non-error type", func() {
success, err := (&HaveOccurredMatcher{}).Match(AnyType{})
Ω(success).Should(BeFalse())
Ω(err).Should(MatchError("Expected an error-type. Got:\n <matchers_test.AnyType>: {}"))
})
It("doesn't support non-error pointer type", func() {
success, err := (&HaveOccurredMatcher{}).Match(&AnyType{})
Ω(success).Should(BeFalse())
Ω(err).Should(MatchError(MatchRegexp(`Expected an error-type. Got:\n <*matchers_test.AnyType | 0x[[:xdigit:]]+>: {}`)))
})
It("should succeed with pointer types that conform to error interface", func() {
err := &CustomErr{"ohai"}
Ω(err).Should(HaveOccurred())
})
It("should not succeed with nil pointers to types that conform to error interface", func() {
var err *CustomErr = nil
Ω(err).ShouldNot(HaveOccurred())
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,36 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HavePrefixMatcher", func() {
Context("when actual is a string", func() {
It("should match a string prefix", func() {
Ω("Ab").Should(HavePrefix("A"))
Ω("A").ShouldNot(HavePrefix("Ab"))
})
})
Context("when the matcher is called with multiple arguments", func() {
It("should pass the string and arguments to sprintf", func() {
Ω("C3PO").Should(HavePrefix("C%dP", 3))
})
})
Context("when actual is a stringer", func() {
It("should call the stringer and match against the returned string", func() {
Ω(&myStringer{a: "Ab"}).Should(HavePrefix("A"))
})
})
Context("when actual is neither a string nor a stringer", func() {
It("should error", func() {
success, err := (&HavePrefixMatcher{Prefix: "2"}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)

View file

@ -1,36 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("HaveSuffixMatcher", func() {
Context("when actual is a string", func() {
It("should match a string suffix", func() {
Ω("Ab").Should(HaveSuffix("b"))
Ω("A").ShouldNot(HaveSuffix("Ab"))
})
})
Context("when the matcher is called with multiple arguments", func() {
It("should pass the string and arguments to sprintf", func() {
Ω("C3PO").Should(HaveSuffix("%dPO", 3))
})
})
Context("when actual is a stringer", func() {
It("should call the stringer and match against the returned string", func() {
Ω(&myStringer{a: "Ab"}).Should(HaveSuffix("b"))
})
})
Context("when actual is neither a string nor a stringer", func() {
It("should error", func() {
success, err := (&HaveSuffixMatcher{Suffix: "2"}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type MatchErrorMatcher struct {
@ -21,14 +22,14 @@ func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err e
actualErr := actual.(error)
if isString(matcher.Expected) {
return reflect.DeepEqual(actualErr.Error(), matcher.Expected), nil
}
if isError(matcher.Expected) {
return reflect.DeepEqual(actualErr, matcher.Expected), nil
}
if isString(matcher.Expected) {
return actualErr.Error() == matcher.Expected, nil
}
var subMatcher omegaMatcher
var hasSubMatcher bool
if matcher.Expected != nil {

View file

@ -1,93 +0,0 @@
package matchers_test
import (
"errors"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
type CustomError struct {
}
func (c CustomError) Error() string {
return "an error"
}
var _ = Describe("MatchErrorMatcher", func() {
Context("When asserting against an error", func() {
It("should succeed when matching with an error", func() {
err := errors.New("an error")
fmtErr := fmt.Errorf("an error")
customErr := CustomError{}
Ω(err).Should(MatchError(errors.New("an error")))
Ω(err).ShouldNot(MatchError(errors.New("another error")))
Ω(fmtErr).Should(MatchError(errors.New("an error")))
Ω(customErr).Should(MatchError(CustomError{}))
})
It("should succeed when matching with a string", func() {
err := errors.New("an error")
fmtErr := fmt.Errorf("an error")
customErr := CustomError{}
Ω(err).Should(MatchError("an error"))
Ω(err).ShouldNot(MatchError("another error"))
Ω(fmtErr).Should(MatchError("an error"))
Ω(customErr).Should(MatchError("an error"))
})
Context("when passed a matcher", func() {
It("should pass if the matcher passes against the error string", func() {
err := errors.New("error 123 abc")
Ω(err).Should(MatchError(MatchRegexp(`\d{3}`)))
})
It("should fail if the matcher fails against the error string", func() {
err := errors.New("no digits")
Ω(err).ShouldNot(MatchError(MatchRegexp(`\d`)))
})
})
It("should fail when passed anything else", func() {
actualErr := errors.New("an error")
_, err := (&MatchErrorMatcher{
Expected: []byte("an error"),
}).Match(actualErr)
Ω(err).Should(HaveOccurred())
_, err = (&MatchErrorMatcher{
Expected: 3,
}).Match(actualErr)
Ω(err).Should(HaveOccurred())
})
})
Context("when passed nil", func() {
It("should fail", func() {
_, err := (&MatchErrorMatcher{
Expected: "an error",
}).Match(nil)
Ω(err).Should(HaveOccurred())
})
})
Context("when passed a non-error", func() {
It("should fail", func() {
_, err := (&MatchErrorMatcher{
Expected: "an error",
}).Match("an error")
Ω(err).Should(HaveOccurred())
_, err = (&MatchErrorMatcher{
Expected: "an error",
}).Match(3)
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -1,97 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("MatchJSONMatcher", func() {
Context("When passed stringifiables", func() {
It("should succeed if the JSON matches", func() {
Ω("{}").Should(MatchJSON("{}"))
Ω(`{"a":1}`).Should(MatchJSON(`{"a":1}`))
Ω(`{
"a":1
}`).Should(MatchJSON(`{"a":1}`))
Ω(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`))
Ω(`{"a":1}`).ShouldNot(MatchJSON(`{"b":2, "a":1}`))
Ω(`{"a":"a", "b":"b"}`).ShouldNot(MatchJSON(`{"a":"a", "b":"b", "c":"c"}`))
Ω(`{"a":"a", "b":"b", "c":"c"}`).ShouldNot(MatchJSON(`{"a":"a", "b":"b"}`))
Ω(`{"a":null, "b":null}`).ShouldNot(MatchJSON(`{"c":"c", "d":"d"}`))
Ω(`{"a":null, "b":null, "c":null}`).ShouldNot(MatchJSON(`{"a":null, "b":null, "d":null}`))
})
It("should work with byte arrays", func() {
Ω([]byte("{}")).Should(MatchJSON([]byte("{}")))
Ω("{}").Should(MatchJSON([]byte("{}")))
Ω([]byte("{}")).Should(MatchJSON("{}"))
})
})
Context("when a key mismatch is found", func() {
It("reports the first found mismatch", func() {
subject := MatchJSONMatcher{JSONToMatch: `5`}
actual := `7`
subject.Match(actual)
failureMessage := subject.FailureMessage(`7`)
Ω(failureMessage).ToNot(ContainSubstring("first mismatched key"))
subject = MatchJSONMatcher{JSONToMatch: `{"a": 1, "b.g": {"c": 2, "1": ["hello", "see ya"]}}`}
actual = `{"a": 1, "b.g": {"c": 2, "1": ["hello", "goodbye"]}}`
subject.Match(actual)
failureMessage = subject.FailureMessage(actual)
Ω(failureMessage).To(ContainSubstring(`first mismatched key: "b.g"."1"[1]`))
})
})
Context("when the expected is not valid JSON", func() {
It("should error and explain why", func() {
success, err := (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("Actual 'oops' should be valid JSON"))
})
})
Context("when the actual is not valid JSON", func() {
It("should error and explain why", func() {
success, err := (&MatchJSONMatcher{JSONToMatch: `oops`}).Match(`{}`)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("Expected 'oops' should be valid JSON"))
})
})
Context("when the expected is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchJSONMatcher{JSONToMatch: 2}).Match("{}")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n <int>: 2"))
success, err = (&MatchJSONMatcher{JSONToMatch: nil}).Match("{}")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n <nil>: nil"))
})
})
Context("when the actual is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n <int>: 2"))
success, err = (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n <nil>: nil"))
})
})
})

View file

@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"regexp"
"github.com/onsi/gomega/format"
)
type MatchRegexpMatcher struct {

View file

@ -1,44 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("MatchRegexp", func() {
Context("when actual is a string", func() {
It("should match against the string", func() {
Ω(" a2!bla").Should(MatchRegexp(`\d!`))
Ω(" a2!bla").ShouldNot(MatchRegexp(`[A-Z]`))
})
})
Context("when actual is a stringer", func() {
It("should call the stringer and match agains the returned string", func() {
Ω(&myStringer{a: "Abc3"}).Should(MatchRegexp(`[A-Z][a-z]+\d`))
})
})
Context("when the matcher is called with multiple arguments", func() {
It("should pass the string and arguments to sprintf", func() {
Ω(" a23!bla").Should(MatchRegexp(`\d%d!`, 3))
})
})
Context("when actual is neither a string nor a stringer", func() {
It("should error", func() {
success, err := (&MatchRegexpMatcher{Regexp: `\d`}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when the passed in regexp fails to compile", func() {
It("should error", func() {
success, err := (&MatchRegexpMatcher{Regexp: "("}).Match("Foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})

View file

@ -7,6 +7,7 @@ import (
"fmt"
"io"
"reflect"
"sort"
"strings"
"github.com/onsi/gomega/format"
@ -82,6 +83,8 @@ func parseXmlContent(content string) (*xmlNode, error) {
switch tok := tok.(type) {
case xml.StartElement:
attrs := attributesSlice(tok.Attr)
sort.Sort(attrs)
allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr})
case xml.EndElement:
if len(allNodes) > 1 {

View file

@ -1,90 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("MatchXMLMatcher", func() {
var (
sample_01 = readFileContents("test_data/xml/sample_01.xml")
sample_02 = readFileContents("test_data/xml/sample_02.xml")
sample_03 = readFileContents("test_data/xml/sample_03.xml")
sample_04 = readFileContents("test_data/xml/sample_04.xml")
sample_05 = readFileContents("test_data/xml/sample_05.xml")
sample_06 = readFileContents("test_data/xml/sample_06.xml")
sample_07 = readFileContents("test_data/xml/sample_07.xml")
sample_08 = readFileContents("test_data/xml/sample_08.xml")
sample_09 = readFileContents("test_data/xml/sample_09.xml")
sample_10 = readFileContents("test_data/xml/sample_10.xml")
sample_11 = readFileContents("test_data/xml/sample_11.xml")
)
Context("When passed stringifiables", func() {
It("should succeed if the XML matches", func() {
Ω(sample_01).Should(MatchXML(sample_01)) // same XML
Ω(sample_01).Should(MatchXML(sample_02)) // same XML with blank lines
Ω(sample_01).Should(MatchXML(sample_03)) // same XML with different formatting
Ω(sample_01).ShouldNot(MatchXML(sample_04)) // same structures with different values
Ω(sample_01).ShouldNot(MatchXML(sample_05)) // different structures
Ω(sample_06).ShouldNot(MatchXML(sample_07)) // same xml names with different namespaces
Ω(sample_07).ShouldNot(MatchXML(sample_08)) // same structures with different values
Ω(sample_09).ShouldNot(MatchXML(sample_10)) // same structures with different attribute values
Ω(sample_11).Should(MatchXML(sample_11)) // with non UTF-8 encoding
})
It("should work with byte arrays", func() {
Ω([]byte(sample_01)).Should(MatchXML([]byte(sample_01)))
Ω([]byte(sample_01)).Should(MatchXML(sample_01))
Ω(sample_01).Should(MatchXML([]byte(sample_01)))
})
})
Context("when the expected is not valid XML", func() {
It("should error and explain why", func() {
success, err := (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(`oops`)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("Actual 'oops' should be valid XML"))
})
})
Context("when the actual is not valid XML", func() {
It("should error and explain why", func() {
success, err := (&MatchXMLMatcher{XMLToMatch: `oops`}).Match(sample_01)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("Expected 'oops' should be valid XML"))
})
})
Context("when the expected is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchXMLMatcher{XMLToMatch: 2}).Match(sample_01)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n <int>: 2"))
success, err = (&MatchXMLMatcher{XMLToMatch: nil}).Match(sample_01)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n <nil>: nil"))
})
})
Context("when the actual is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(2)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n <int>: 2"))
success, err = (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n <nil>: nil"))
})
})
})

View file

@ -1,94 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("MatchYAMLMatcher", func() {
Context("When passed stringifiables", func() {
It("should succeed if the YAML matches", func() {
Expect("---").Should(MatchYAML(""))
Expect("a: 1").Should(MatchYAML(`{"a":1}`))
Expect("a: 1\nb: 2").Should(MatchYAML(`{"b":2, "a":1}`))
})
It("should explain if the YAML does not match when it should", func() {
message := (&MatchYAMLMatcher{YAMLToMatch: "a: 1"}).FailureMessage("b: 2")
Expect(message).To(MatchRegexp(`Expected\s+<string>: b: 2\s+to match YAML of\s+<string>: a: 1`))
})
It("should normalise the expected and actual when explaining if the YAML does not match when it should", func() {
message := (&MatchYAMLMatcher{YAMLToMatch: "a: 'one'"}).FailureMessage("{b: two}")
Expect(message).To(MatchRegexp(`Expected\s+<string>: b: two\s+to match YAML of\s+<string>: a: one`))
})
It("should explain if the YAML matches when it should not", func() {
message := (&MatchYAMLMatcher{YAMLToMatch: "a: 1"}).NegatedFailureMessage("a: 1")
Expect(message).To(MatchRegexp(`Expected\s+<string>: a: 1\s+not to match YAML of\s+<string>: a: 1`))
})
It("should normalise the expected and actual when explaining if the YAML matches when it should not", func() {
message := (&MatchYAMLMatcher{YAMLToMatch: "a: 'one'"}).NegatedFailureMessage("{a: one}")
Expect(message).To(MatchRegexp(`Expected\s+<string>: a: one\s+not to match YAML of\s+<string>: a: one`))
})
It("should fail if the YAML does not match", func() {
Expect("a: 1").ShouldNot(MatchYAML(`{"b":2, "a":1}`))
})
It("should work with byte arrays", func() {
Expect([]byte("a: 1")).Should(MatchYAML([]byte("a: 1")))
Expect("a: 1").Should(MatchYAML([]byte("a: 1")))
Expect([]byte("a: 1")).Should(MatchYAML("a: 1"))
})
})
Context("when the expected is not valid YAML", func() {
It("should error and explain why", func() {
success, err := (&MatchYAMLMatcher{YAMLToMatch: ""}).Match("good:\nbad")
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("Actual 'good:\nbad' should be valid YAML"))
})
})
Context("when the actual is not valid YAML", func() {
It("should error and explain why", func() {
success, err := (&MatchYAMLMatcher{YAMLToMatch: "good:\nbad"}).Match("")
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("Expected 'good:\nbad' should be valid YAML"))
})
})
Context("when the expected is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchYAMLMatcher{YAMLToMatch: 2}).Match("")
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n <int>: 2"))
success, err = (&MatchYAMLMatcher{YAMLToMatch: nil}).Match("")
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n <nil>: nil"))
})
})
Context("when the actual is neither a string nor a stringer nor a byte array", func() {
It("should error", func() {
success, err := (&MatchYAMLMatcher{YAMLToMatch: ""}).Match(2)
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n <int>: 2"))
success, err = (&MatchYAMLMatcher{YAMLToMatch: ""}).Match(nil)
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n <nil>: nil"))
})
})
})

View file

@ -1,50 +0,0 @@
package matchers_test
import (
"fmt"
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type myStringer struct {
a string
}
func (s *myStringer) String() string {
return s.a
}
type StringAlias string
type myCustomType struct {
s string
n int
f float32
arr []string
}
func Test(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Gomega Matchers")
}
func readFileContents(filePath string) []byte {
f := openFile(filePath)
b, err := ioutil.ReadAll(f)
if err != nil {
panic(fmt.Errorf("failed to read file contents: %v", err))
}
return b
}
func openFile(filePath string) *os.File {
f, err := os.Open(filePath)
if err != nil {
panic(fmt.Errorf("failed to open file: %v", err))
}
return f
}

View file

@ -1,57 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("NotMatcher", func() {
Context("basic examples", func() {
It("works", func() {
Expect(input).To(Not(false1))
Expect(input).To(Not(Not(true2)))
Expect(input).ToNot(Not(true3))
Expect(input).ToNot(Not(Not(false1)))
Expect(input).To(Not(Not(Not(false2))))
})
})
Context("De Morgan's laws", func() {
It("~(A && B) == ~A || ~B", func() {
Expect(input).To(Not(And(false1, false2)))
Expect(input).To(Or(Not(false1), Not(false2)))
})
It("~(A || B) == ~A && ~B", func() {
Expect(input).To(Not(Or(false1, false2)))
Expect(input).To(And(Not(false1), Not(false2)))
})
})
Context("failure messages are opposite of original matchers' failure messages", func() {
Context("when match fails", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(Not(HaveLen(2)), input, "not to have length 2")
})
})
Context("when match succeeds, but expected it to fail", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(Not(Not(HaveLen(3))), input, "to have length 3")
})
})
})
Context("MatchMayChangeInTheFuture()", func() {
It("Propagates value from wrapped matcher", func() {
m := Not(Or()) // an empty Or() always returns false, and indicates it cannot change
Expect(m.Match("anything")).To(BeTrue())
Expect(m.(*NotMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse())
})
It("Defaults to true", func() {
m := Not(Equal(1)) // Equal does not have this method
Expect(m.Match(2)).To(BeTrue())
Expect(m.(*NotMatcher).MatchMayChangeInTheFuture(2)).To(BeTrue()) // defaults to true
})
})
})

View file

@ -1,85 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("OrMatcher", func() {
It("works with positive cases", func() {
Expect(input).To(Or(true1))
Expect(input).To(Or(true1, true2))
Expect(input).To(Or(true1, false1))
Expect(input).To(Or(false1, true2))
Expect(input).To(Or(true1, true2, true3))
Expect(input).To(Or(true1, true2, false3))
Expect(input).To(Or(true1, false2, true3))
Expect(input).To(Or(false1, true2, true3))
Expect(input).To(Or(true1, false2, false3))
Expect(input).To(Or(false1, false2, true3))
// use alias
Expect(input).To(SatisfyAny(false1, false2, true3))
})
It("works with negative cases", func() {
Expect(input).ToNot(Or())
Expect(input).ToNot(Or(false1))
Expect(input).ToNot(Or(false1, false2))
Expect(input).ToNot(Or(false1, false2, false3))
})
Context("failure messages", func() {
Context("when match fails", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(Or(false1, false2), input,
"To satisfy at least one of these matchers: [%!s(*matchers.HaveLenMatcher=&{1}) %!s(*matchers.EqualMatcher=&{hip})]")
})
})
Context("when match succeeds, but expected it to fail", func() {
It("gives a descriptive message", func() {
verifyFailureMessage(Not(Or(true1, true2)), input, `not to have length 2`)
})
})
})
Context("MatchMayChangeInTheFuture", func() {
Context("Match returned false", func() {
It("returns true if any of the matchers could change", func() {
// 3 matchers, all return false, and all could change
m := Or(BeNil(), Equal("hip"), HaveLen(1))
Expect(m.Match("hi")).To(BeFalse())
Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // all 3 of these matchers default to 'true'
})
It("returns false if none of the matchers could change", func() {
// empty Or() has the property of never matching, and never can change since there are no sub-matchers that could change
m := Or()
Expect(m.Match("anything")).To(BeFalse())
Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse())
// Or() with 3 sub-matchers that return false, and can't change
m = Or(Or(), Or(), Or())
Expect(m.Match("hi")).To(BeFalse())
Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // the 3 empty Or()'s won't change
})
})
Context("Match returned true", func() {
Context("returns value of the successful matcher", func() {
It("false if successful matcher not going to change", func() {
// 3 matchers: 1st returns false, 2nd returns true and is not going to change, 3rd is never called
m := Or(BeNil(), And(), Equal(1))
Expect(m.Match("hi")).To(BeTrue())
Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse())
})
It("true if successful matcher indicates it might change", func() {
// 3 matchers: 1st returns false, 2nd returns true and "might" change, 3rd is never called
m := Or(Not(BeNil()), Equal("hi"), Equal(1))
Expect(m.Match("hi")).To(BeTrue())
Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // Equal("hi") indicates it might change
})
})
})
})
})

View file

@ -1,45 +0,0 @@
package matchers_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("Panic", func() {
Context("when passed something that's not a function that takes zero arguments and returns nothing", func() {
It("should error", func() {
success, err := (&PanicMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(func(foo string) {})
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(func() string { return "bar" })
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when passed a function of the correct type", func() {
It("should call the function and pass if the function panics", func() {
Ω(func() { panic("ack!") }).Should(Panic())
Ω(func() {}).ShouldNot(Panic())
})
})
Context("when assertion fails", func() {
It("should print the object passed to Panic", func() {
failuresMessages := InterceptGomegaFailures(func() {
Ω(func() { panic("ack!") }).ShouldNot(Panic())
})
Ω(failuresMessages).Should(ConsistOf(MatchRegexp("not to panic, but panicked with\\s*<string>: ack!")))
})
})
})

View file

@ -1,280 +0,0 @@
package matchers_test
import (
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
type kungFuActor interface {
DrunkenMaster() bool
}
type jackie struct {
name string
}
func (j *jackie) DrunkenMaster() bool {
return true
}
var _ = Describe("ReceiveMatcher", func() {
Context("with no argument", func() {
Context("for a buffered channel", func() {
It("should succeed", func() {
channel := make(chan bool, 1)
Ω(channel).ShouldNot(Receive())
channel <- true
Ω(channel).Should(Receive())
})
})
Context("for an unbuffered channel", func() {
It("should succeed (eventually)", func() {
channel := make(chan bool)
Ω(channel).ShouldNot(Receive())
go func() {
time.Sleep(10 * time.Millisecond)
channel <- true
}()
Eventually(channel).Should(Receive())
})
})
})
Context("with a pointer argument", func() {
Context("of the correct type", func() {
It("should write the value received on the channel to the pointer", func() {
channel := make(chan int, 1)
var value int
Ω(channel).ShouldNot(Receive(&value))
Ω(value).Should(BeZero())
channel <- 17
Ω(channel).Should(Receive(&value))
Ω(value).Should(Equal(17))
})
})
Context("to various types of objects", func() {
It("should work", func() {
//channels of strings
stringChan := make(chan string, 1)
stringChan <- "foo"
var s string
Ω(stringChan).Should(Receive(&s))
Ω(s).Should(Equal("foo"))
//channels of slices
sliceChan := make(chan []bool, 1)
sliceChan <- []bool{true, true, false}
var sl []bool
Ω(sliceChan).Should(Receive(&sl))
Ω(sl).Should(Equal([]bool{true, true, false}))
//channels of channels
chanChan := make(chan chan bool, 1)
c := make(chan bool)
chanChan <- c
var receivedC chan bool
Ω(chanChan).Should(Receive(&receivedC))
Ω(receivedC).Should(Equal(c))
//channels of interfaces
jackieChan := make(chan kungFuActor, 1)
aJackie := &jackie{name: "Jackie Chan"}
jackieChan <- aJackie
var theJackie kungFuActor
Ω(jackieChan).Should(Receive(&theJackie))
Ω(theJackie).Should(Equal(aJackie))
})
})
Context("of the wrong type", func() {
It("should error", func() {
channel := make(chan int)
var incorrectType bool
success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
var notAPointer int
success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
})
Context("with a matcher", func() {
It("should defer to the underlying matcher", func() {
intChannel := make(chan int, 1)
intChannel <- 3
Ω(intChannel).Should(Receive(Equal(3)))
intChannel <- 2
Ω(intChannel).ShouldNot(Receive(Equal(3)))
stringChannel := make(chan []string, 1)
stringChannel <- []string{"foo", "bar", "baz"}
Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo"))))
stringChannel <- []string{"foo", "bar", "baz"}
Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago"))))
})
It("should defer to the underlying matcher for the message", func() {
matcher := Receive(Equal(3))
channel := make(chan int, 1)
channel <- 2
matcher.Match(channel)
Ω(matcher.FailureMessage(channel)).Should(MatchRegexp(`Expected\s+<int>: 2\s+to equal\s+<int>: 3`))
channel <- 3
matcher.Match(channel)
Ω(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+<int>: 3\s+not to equal\s+<int>: 3`))
})
It("should work just fine with Eventually", func() {
stringChannel := make(chan string)
go func() {
time.Sleep(5 * time.Millisecond)
stringChannel <- "A"
time.Sleep(5 * time.Millisecond)
stringChannel <- "B"
}()
Eventually(stringChannel).Should(Receive(Equal("B")))
})
Context("if the matcher errors", func() {
It("should error", func() {
channel := make(chan int, 1)
channel <- 3
success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("if nothing is received", func() {
It("should fail", func() {
channel := make(chan int, 1)
success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).ShouldNot(HaveOccurred())
})
})
})
Context("When actual is a *closed* channel", func() {
Context("for a buffered channel", func() {
It("should work until it hits the end of the buffer", func() {
channel := make(chan bool, 1)
channel <- true
close(channel)
Ω(channel).Should(Receive())
Ω(channel).ShouldNot(Receive())
})
})
Context("for an unbuffered channel", func() {
It("should always fail", func() {
channel := make(chan bool)
close(channel)
Ω(channel).ShouldNot(Receive())
})
})
})
Context("When actual is a send-only channel", func() {
It("should error", func() {
channel := make(chan bool)
var writerChannel chan<- bool
writerChannel = channel
success, err := (&ReceiveMatcher{}).Match(writerChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Context("when acutal is a non-channel", func() {
It("should error", func() {
var nilChannel chan bool
success, err := (&ReceiveMatcher{}).Match(nilChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&ReceiveMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
success, err = (&ReceiveMatcher{}).Match(3)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
})
})
Describe("when used with eventually and a custom matcher", func() {
It("should return the matcher's error when a failing value is received on the channel, instead of the must receive something failure", func() {
failures := InterceptGomegaFailures(func() {
c := make(chan string, 0)
Eventually(c, 0.01).Should(Receive(Equal("hello")))
})
Ω(failures[0]).Should(ContainSubstring("When passed a matcher, ReceiveMatcher's channel *must* receive something."))
failures = InterceptGomegaFailures(func() {
c := make(chan string, 1)
c <- "hi"
Eventually(c, 0.01).Should(Receive(Equal("hello")))
})
Ω(failures[0]).Should(ContainSubstring("<string>: hello"))
})
})
Describe("Bailing early", func() {
It("should bail early when passed a closed channel", func() {
c := make(chan bool)
close(c)
t := time.Now()
failures := InterceptGomegaFailures(func() {
Eventually(c).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
})
It("should bail early when passed a non-channel", func() {
t := time.Now()
failures := InterceptGomegaFailures(func() {
Eventually(3).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
})
})
})

View file

@ -1,62 +0,0 @@
package matchers_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
func Erroring() error {
return errors.New("bam")
}
func NotErroring() error {
return nil
}
type AnyType struct{}
func Invalid() *AnyType {
return nil
}
var _ = Describe("Succeed", func() {
It("should succeed if the function succeeds", func() {
Ω(NotErroring()).Should(Succeed())
})
It("should succeed (in the negated) if the function errored", func() {
Ω(Erroring()).ShouldNot(Succeed())
})
It("should not if passed a non-error", func() {
success, err := (&SucceedMatcher{}).Match(Invalid())
Ω(success).Should(BeFalse())
Ω(err).Should(MatchError("Expected an error-type. Got:\n <*matchers_test.AnyType | 0x0>: nil"))
})
It("doesn't support non-error type", func() {
success, err := (&SucceedMatcher{}).Match(AnyType{})
Ω(success).Should(BeFalse())
Ω(err).Should(MatchError("Expected an error-type. Got:\n <matchers_test.AnyType>: {}"))
})
It("doesn't support non-error pointer type", func() {
success, err := (&SucceedMatcher{}).Match(&AnyType{})
Ω(success).Should(BeFalse())
Ω(err).Should(MatchError(MatchRegexp(`Expected an error-type. Got:\n <*matchers_test.AnyType | 0x[[:xdigit:]]+>: {}`)))
})
It("should not succeed with pointer types that conform to error interface", func() {
err := &CustomErr{"ohai"}
Ω(err).ShouldNot(Succeed())
})
It("should succeed with nil pointers to types that conform to error interface", func() {
var err *CustomErr = nil
Ω(err).Should(Succeed())
})
})

View file

@ -15,12 +15,12 @@ type BipartiteGraph struct {
func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) {
left := NodeOrderedSet{}
for i, _ := range leftValues {
left = append(left, Node{i})
left = append(left, Node{Id: i})
}
right := NodeOrderedSet{}
for j, _ := range rightValues {
right = append(right, Node{j + len(left)})
right = append(right, Node{Id: j + len(left)})
}
edges := EdgeSet{}
@ -32,7 +32,7 @@ func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(in
}
if neighbours {
edges = append(edges, Edge{left[i], right[j]})
edges = append(edges, Edge{Node1: left[i], Node2: right[j]})
}
}
}

View file

@ -1,102 +0,0 @@
package matchers_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
)
var _ = Describe("WithTransformMatcher", func() {
var plus1 = func(i int) int { return i + 1 }
Context("Panic if transform function invalid", func() {
panicsWithTransformer := func(transform interface{}) {
ExpectWithOffset(1, func() { WithTransform(transform, nil) }).To(Panic())
}
It("nil", func() {
panicsWithTransformer(nil)
})
Context("Invalid number of args, but correct return value count", func() {
It("zero", func() {
panicsWithTransformer(func() int { return 5 })
})
It("two", func() {
panicsWithTransformer(func(i, j int) int { return 5 })
})
})
Context("Invalid number of return values, but correct number of arguments", func() {
It("zero", func() {
panicsWithTransformer(func(i int) {})
})
It("two", func() {
panicsWithTransformer(func(i int) (int, int) { return 5, 6 })
})
})
})
It("works with positive cases", func() {
Expect(1).To(WithTransform(plus1, Equal(2)))
Expect(1).To(WithTransform(plus1, WithTransform(plus1, Equal(3))))
Expect(1).To(WithTransform(plus1, And(Equal(2), BeNumerically(">", 1))))
// transform expects custom type
type S struct {
A int
B string
}
transformer := func(s S) string { return s.B }
Expect(S{1, "hi"}).To(WithTransform(transformer, Equal("hi")))
// transform expects interface
errString := func(e error) string { return e.Error() }
Expect(errors.New("abc")).To(WithTransform(errString, Equal("abc")))
})
It("works with negative cases", func() {
Expect(1).ToNot(WithTransform(plus1, Equal(3)))
Expect(1).ToNot(WithTransform(plus1, WithTransform(plus1, Equal(2))))
})
Context("failure messages", func() {
Context("when match fails", func() {
It("gives a descriptive message", func() {
m := WithTransform(plus1, Equal(3))
Expect(m.Match(1)).To(BeFalse())
Expect(m.FailureMessage(1)).To(Equal("Expected\n <int>: 2\nto equal\n <int>: 3"))
})
})
Context("when match succeeds, but expected it to fail", func() {
It("gives a descriptive message", func() {
m := Not(WithTransform(plus1, Equal(3)))
Expect(m.Match(2)).To(BeFalse())
Expect(m.FailureMessage(2)).To(Equal("Expected\n <int>: 3\nnot to equal\n <int>: 3"))
})
})
Context("actual value is incompatible with transform function's argument type", func() {
It("gracefully fails if transform cannot be performed", func() {
m := WithTransform(plus1, Equal(3))
result, err := m.Match("hi") // give it a string but transform expects int; doesn't panic
Expect(result).To(BeFalse())
Expect(err).To(MatchError("Transform function expects 'int' but we have 'string'"))
})
})
})
Context("MatchMayChangeInTheFuture()", func() {
It("Propagates value from wrapped matcher on the transformed value", func() {
m := WithTransform(plus1, Or()) // empty Or() always returns false, and indicates it cannot change
Expect(m.Match(1)).To(BeFalse())
Expect(m.(*WithTransformMatcher).MatchMayChangeInTheFuture(1)).To(BeFalse()) // empty Or() indicates cannot change
})
It("Defaults to true", func() {
m := WithTransform(plus1, Equal(2)) // Equal does not have this method
Expect(m.Match(1)).To(BeTrue())
Expect(m.(*WithTransformMatcher).MatchMayChangeInTheFuture(1)).To(BeTrue()) // defaults to true
})
})
})

View file

@ -9,7 +9,7 @@ type GomegaTestingT interface {
//All Gomega matchers must implement the GomegaMatcher interface
//
//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding_your_own_matchers
//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers
type GomegaMatcher interface {
Match(actual interface{}) (success bool, err error)
FailureMessage(actual interface{}) (message string)