Update dependencies

- uses newer version of go-ethereum required for go1.11
This commit is contained in:
Rob Mulholand
2018-09-13 16:14:35 -05:00
parent 939ead0c82
commit 560305f601
2356 changed files with 331656 additions and 128304 deletions
+9 -5
View File
@@ -1,12 +1,16 @@
language: go
go:
- 1.6
- 1.7
- 1.8
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
install:
- go get -v ./...
- env GO111MODULE=on go get -v ./...
- env GO111MODULE=on go build ./...
- go get github.com/onsi/ginkgo
- go install github.com/onsi/ginkgo/ginkgo
script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --failOnPending --randomizeSuites --race
script: env GO111MODULE=on $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && env GO111MODULE=on go vet
+45 -1
View File
@@ -1,4 +1,48 @@
## HEAD
## 1.4.2
### Fixes:
- Add go.mod and go.sum files to define the gomega go module [f3de367, a085d30]
- Work around go vet issue with Go v1.11 (#300) [40dd6ad]
- Better output when using with go XUnit-style tests, fixes #255 (#297) [29a4b97]
- Fix MatchJSON fail to parse json.RawMessage (#298) [ae19f1b]
- show threshold in failure message of BeNumericallyMatcher (#293) [4bbecc8]
## 1.4.1
### Fixes:
- Update documentation formatting and examples (#289) [9be8410]
- allow 'Receive' matcher to be used with concrete types (#286) [41673fd]
- Fix data race in ghttp server (#283) [7ac6b01]
- Travis badge should only show master [cc102ab]
## 1.4.0
### 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
+4 -1
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!
+1 -1
View File
@@ -1,6 +1,6 @@
![Gomega: Ginkgo's Preferred Matcher Library](http://onsi.github.io/gomega/images/gomega.png)
[![Build Status](https://travis-ci.org/onsi/gomega.svg)](https://travis-ci.org/onsi/gomega)
[![Build Status](https://travis-ci.org/onsi/gomega.svg?branch=master)](https://travis-ci.org/onsi/gomega)
Jump straight to the [docs](http://onsi.github.io/gomega/) to learn about Gomega, including a list of [all available matchers](http://onsi.github.io/gomega/#provided-matchers).
+12
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.
+5 -2
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] {
+93 -56
View File
@@ -119,13 +119,13 @@ var _ = Describe("Format", func() {
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."))
Expect(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"))
Expect(Message(3, "to equal", 4)).Should(Equal("Expected\n <int>: 3\nto equal\n <int>: 4"))
})
})
})
@@ -135,63 +135,87 @@ var _ = Describe("Format", func() {
stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedLongStringFailureMessage))
Expect(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))
Expect(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))
Expect(MessageWithDiff(largeString, "to equal", smallString)).Should(Equal(expectedTruncatedStartSizeFailureMessage))
Expect(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))
Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedEndStringFailureMessage))
})
It("handles multi-byte sequences correctly", func() {
stringA := "• abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1"
stringB := "• abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
Expect(MessageWithDiff(stringA, "to equal", stringB)).Should(Equal(expectedTruncatedMultiByteFailureMessage))
})
Context("With truncated diff disabled", func() {
BeforeEach(func() {
TruncatedDiff = false
})
AfterEach(func() {
TruncatedDiff = true
})
It("should show the full diff", func() {
stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedFullFailureDiff))
})
})
})
Describe("IndentString", func() {
It("should indent the string", func() {
Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz"))
Expect(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"))
Expect(Object(true, 1)).Should(match("bool", "true"))
Expect(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"))
Expect(Object(int(3), 1)).Should(match("int", "3"))
Expect(Object(int8(3), 1)).Should(match("int8", "3"))
Expect(Object(int16(3), 1)).Should(match("int16", "3"))
Expect(Object(int32(3), 1)).Should(match("int32", "3"))
Expect(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"))
Expect(Object(uint(3), 1)).Should(match("uint", "3"))
Expect(Object(uint8(3), 1)).Should(match("uint8", "3"))
Expect(Object(uint16(3), 1)).Should(match("uint16", "3"))
Expect(Object(uint32(3), 1)).Should(match("uint32", "3"))
Expect(Object(uint64(3), 1)).Should(match("uint64", "3"))
})
It("should handle uintptr differently", func() {
Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3"))
Expect(Object(uintptr(3), 1)).Should(match("uintptr", "0x3"))
})
})
@@ -200,14 +224,14 @@ var _ = Describe("Format", func() {
c := make(chan<- bool, 3)
c <- true
c <- false
Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c))
Expect(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
Expect(Object(s, 1)).Should(match("string", `a
b
c`))
})
@@ -217,13 +241,13 @@ var _ = Describe("Format", 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`))
Expect(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\]`))
Expect(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:12, cap:\d+`, `\[97, 32, 98, 32, 99, 10, 1, 2, 3, 255, 27, 72\]`))
})
})
})
@@ -233,14 +257,14 @@ var _ = Describe("Format", 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))
Expect(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"))
Expect(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3"))
})
Context("when there are pointers to pointers...", func() {
@@ -253,14 +277,14 @@ var _ = Describe("Format", func() {
c = &b
d = &c
Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3"))
Expect(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"))
Expect(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil"))
})
})
})
@@ -268,13 +292,13 @@ var _ = Describe("Format", func() {
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"]`))
Expect(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]`))
Expect(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`))
})
})
})
@@ -282,7 +306,7 @@ var _ = Describe("Format", func() {
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]"))
Expect(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]"))
})
Context("when the slice contains long entries", func() {
@@ -293,7 +317,7 @@ var _ = Describe("Format", func() {
"Toby Ziegler",
"CJ Cregg",
]`
Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected))
Expect(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected))
})
})
})
@@ -303,7 +327,7 @@ var _ = Describe("Format", 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")))
Expect(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false")))
})
Context("when the slice contains long entries", func() {
@@ -317,7 +341,7 @@ var _ = Describe("Format", func() {
("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))
Expect(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected))
})
})
})
@@ -332,7 +356,7 @@ var _ = Describe("Format", func() {
secret: 1983,
}
Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`))
Expect(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() {
@@ -345,7 +369,7 @@ var _ = Describe("Format", func() {
secret: 3,
}
Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{
Expect(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{
Name: "Mithrandir Gandalf Greyhame",
Enumeration: 2021,
Veritas: true,
@@ -358,23 +382,23 @@ var _ = Describe("Format", func() {
Describe("formatting nil values", func() {
It("should print out nil", func() {
Ω(Object(nil, 1)).Should(match("nil", "nil"))
Expect(Object(nil, 1)).Should(match("nil", "nil"))
var typedNil *AStruct
Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil"))
Expect(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"))
Expect(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"))
Expect(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"))
Expect(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"))
Expect(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`))
Expect(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`))
Expect(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3"))
})
})
@@ -408,14 +432,14 @@ var _ = Describe("Format", func() {
(17: "some substantially longer chunks of data"|1138: "that should make things wrap"),
},
}`
Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected))
Expect(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`))
Expect(Object(t, 1)).Should(match("time.Time", `2016-10-31T09:57:23.000012345Z`))
})
})
})
@@ -463,7 +487,7 @@ var _ = Describe("Format", func() {
interfaceValue: {"a key": 17},
}`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`))
Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected))
Expect(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected))
})
})
@@ -477,7 +501,7 @@ var _ = Describe("Format", func() {
outerHash["map"] = innerHash
expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`)
Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected))
Expect(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected))
})
})
@@ -486,7 +510,7 @@ var _ = Describe("Format", func() {
m := map[string]interface{}{}
m["integer"] = 2
m["map"] = m
Ω(Object(m, 1)).Should(ContainSubstring("..."))
Expect(Object(m, 1)).Should(ContainSubstring("..."))
})
It("really should not go crazy...", func() {
@@ -498,7 +522,7 @@ var _ = Describe("Format", func() {
complexObject.Value = make(map[interface{}]int)
complexObject.Value[&complexObject] = 2
Ω(Object(complexObject, 1)).Should(ContainSubstring("..."))
Expect(Object(complexObject, 1)).Should(ContainSubstring("..."))
})
})
@@ -513,13 +537,13 @@ var _ = Describe("Format", func() {
Context("when passed a GoStringer", func() {
It("should use what GoString() returns", func() {
Ω(Object(GoStringer{}, 1)).Should(ContainSubstring("<format_test.GoStringer>: go-string"))
Expect(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"))
Expect(Object(Stringer{}, 1)).Should(ContainSubstring("<format_test.Stringer>: string"))
})
})
})
@@ -535,11 +559,11 @@ var _ = Describe("Format", func() {
objWithContext := structWithContext{Value: "some-value", Context: &context}
It("Suppresses the content by default", func() {
Ω(Object(objWithContext, 1)).Should(ContainSubstring("<suppressed context>"))
Expect(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>$"))
Expect(Object(context, 1)).ShouldNot(MatchRegexp("^.*<suppressed context>$"))
})
Context("PrintContextObjects is set", func() {
@@ -552,7 +576,7 @@ var _ = Describe("Format", func() {
})
It("Prints the context", func() {
Ω(Object(objWithContext, 1)).ShouldNot(ContainSubstring("<suppressed context>"))
Expect(Object(objWithContext, 1)).ShouldNot(ContainSubstring("<suppressed context>"))
})
})
})
@@ -588,3 +612,16 @@ Expected
to equal |
<string>: "...aaaaa"
`)
var expectedTruncatedMultiByteFailureMessage = strings.TrimSpace(`
Expected
<string>: "...tuvwxyz1"
to equal |
<string>: "...tuvwxyz"
`)
var expectedFullFailureDiff = strings.TrimSpace(`
Expected
<string>: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
to equal
<string>: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
`)
+31 -31
View File
@@ -33,20 +33,20 @@ var _ = Describe("Buffer", func() {
It("should return everything that's been written", func() {
buffer.Write([]byte("abc"))
buffer.Write([]byte("def"))
Ω(buffer.Contents()).Should(Equal([]byte("abcdef")))
Expect(buffer.Contents()).Should(Equal([]byte("abcdef")))
Ω(buffer).Should(Say("bcd"))
Ω(buffer.Contents()).Should(Equal([]byte("abcdef")))
Expect(buffer).Should(Say("bcd"))
Expect(buffer.Contents()).Should(Equal([]byte("abcdef")))
})
})
Describe("creating a buffer with bytes", func() {
It("should create the buffer with the cursor set to the beginning", func() {
buffer := BufferWithBytes([]byte("abcdef"))
Ω(buffer.Contents()).Should(Equal([]byte("abcdef")))
Ω(buffer).Should(Say("abc"))
Ω(buffer).ShouldNot(Say("abc"))
Ω(buffer).Should(Say("def"))
Expect(buffer.Contents()).Should(Equal([]byte("abcdef")))
Expect(buffer).Should(Say("abc"))
Expect(buffer).ShouldNot(Say("abc"))
Expect(buffer).Should(Say("def"))
})
})
@@ -56,7 +56,7 @@ var _ = Describe("Buffer", func() {
reader := bytes.NewBuffer([]byte("abcdef"))
buffer := BufferReader(reader)
Eventually(buffer).Should(Say("abc"))
Ω(buffer).ShouldNot(Say("abc"))
Expect(buffer).ShouldNot(Say("abc"))
Eventually(buffer).Should(Say("def"))
Eventually(buffer.Closed).Should(BeTrue())
})
@@ -72,7 +72,7 @@ var _ = Describe("Buffer", func() {
failures := InterceptGomegaFailures(func() {
Eventually(buffer, 100*time.Millisecond).Should(Say("abc"))
})
Ω(failures).ShouldNot(BeEmpty())
Expect(failures).ShouldNot(BeEmpty())
fastReader := SlowReader{
R: bytes.NewBuffer([]byte("abcdef")),
@@ -91,19 +91,19 @@ var _ = Describe("Buffer", func() {
dest := make([]byte, 3)
n, err := buffer.Read(dest)
Ω(err).ShouldNot(HaveOccurred())
Ω(n).Should(Equal(3))
Ω(string(dest)).Should(Equal("abc"))
Expect(err).ShouldNot(HaveOccurred())
Expect(n).Should(Equal(3))
Expect(string(dest)).Should(Equal("abc"))
dest = make([]byte, 3)
n, err = buffer.Read(dest)
Ω(err).ShouldNot(HaveOccurred())
Ω(n).Should(Equal(2))
Ω(string(dest[:n])).Should(Equal("de"))
Expect(err).ShouldNot(HaveOccurred())
Expect(n).Should(Equal(2))
Expect(string(dest[:n])).Should(Equal("de"))
n, err = buffer.Read(dest)
Ω(err).Should(Equal(io.EOF))
Ω(n).Should(Equal(0))
Expect(err).Should(Equal(io.EOF))
Expect(n).Should(Equal(0))
})
Context("after the buffer has been closed", func() {
@@ -114,8 +114,8 @@ var _ = Describe("Buffer", func() {
dest := make([]byte, 3)
n, err := buffer.Read(dest)
Ω(err).Should(HaveOccurred())
Ω(n).Should(Equal(0))
Expect(err).Should(HaveOccurred())
Expect(n).Should(Equal(0))
})
})
})
@@ -137,7 +137,7 @@ var _ = Describe("Buffer", func() {
Fail("should not have gotten here")
}
Ω(gotIt).Should(BeTrue())
Expect(gotIt).Should(BeTrue())
Eventually(A).Should(BeClosed())
buffer.Write([]byte("f"))
@@ -150,8 +150,8 @@ var _ = Describe("Buffer", func() {
It("should fast-forward the buffer upon detection", func(done Done) {
buffer.Write([]byte("abcde"))
<-buffer.Detect("abc")
Ω(buffer).ShouldNot(Say("abc"))
Ω(buffer).Should(Say("de"))
Expect(buffer).ShouldNot(Say("abc"))
Expect(buffer).Should(Say("de"))
close(done)
})
@@ -159,10 +159,10 @@ var _ = Describe("Buffer", func() {
buffer.Write([]byte("abcde"))
A := buffer.Detect("abc")
time.Sleep(20 * time.Millisecond) //give the goroutine a chance to detect and write to the channel
Ω(buffer).Should(Say("abcd"))
Expect(buffer).Should(Say("abcd"))
<-A
Ω(buffer).ShouldNot(Say("d"))
Ω(buffer).Should(Say("e"))
Expect(buffer).ShouldNot(Say("d"))
Expect(buffer).Should(Say("e"))
Eventually(A).Should(BeClosed())
close(done)
})
@@ -175,7 +175,7 @@ var _ = Describe("Buffer", func() {
Eventually(A).Should(BeClosed())
Eventually(B).Should(BeClosed())
Ω(buffer).Should(Say("bcde"))
Expect(buffer).Should(Say("bcde"))
<-buffer.Detect("f")
close(done)
})
@@ -184,22 +184,22 @@ var _ = Describe("Buffer", func() {
Describe("closing the buffer", func() {
It("should error when further write attempts are made", func() {
_, err := buffer.Write([]byte("abc"))
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
buffer.Close()
_, err = buffer.Write([]byte("def"))
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
Ω(buffer.Contents()).Should(Equal([]byte("abc")))
Expect(buffer.Contents()).Should(Equal([]byte("abc")))
})
It("should be closed", func() {
Ω(buffer.Closed()).Should(BeFalse())
Expect(buffer.Closed()).Should(BeFalse())
buffer.Close()
Ω(buffer.Closed()).Should(BeTrue())
Expect(buffer.Closed()).Should(BeTrue())
})
})
})
+12 -12
View File
@@ -68,7 +68,7 @@ var _ = Describe("Io Wrappers", func() {
})
It("returns with no error", func() {
Ω(timeoutCloser.Close()).Should(Succeed())
Expect(timeoutCloser.Close()).Should(Succeed())
})
})
@@ -78,7 +78,7 @@ var _ = Describe("Io Wrappers", func() {
})
It("returns the error", func() {
Ω(timeoutCloser.Close()).Should(MatchError("boom"))
Expect(timeoutCloser.Close()).Should(MatchError("boom"))
})
})
@@ -91,7 +91,7 @@ var _ = Describe("Io Wrappers", func() {
})
It("returns ErrTimeout", func() {
Ω(timeoutCloser.Close()).Should(MatchError(ErrTimeout))
Expect(timeoutCloser.Close()).Should(MatchError(ErrTimeout))
})
})
})
@@ -112,9 +112,9 @@ var _ = Describe("Io Wrappers", func() {
It("returns with no error", func() {
p := make([]byte, 5)
n, err := timeoutReader.Read(p)
Ω(n).Should(Equal(5))
Ω(err).ShouldNot(HaveOccurred())
Ω(p).Should(Equal([]byte("aaaaa")))
Expect(n).Should(Equal(5))
Expect(err).ShouldNot(HaveOccurred())
Expect(p).Should(Equal([]byte("aaaaa")))
})
})
@@ -126,7 +126,7 @@ var _ = Describe("Io Wrappers", func() {
It("returns the error", func() {
p := make([]byte, 5)
_, err := timeoutReader.Read(p)
Ω(err).Should(MatchError("boom"))
Expect(err).Should(MatchError("boom"))
})
})
@@ -138,7 +138,7 @@ var _ = Describe("Io Wrappers", func() {
It("returns ErrTimeout", func() {
p := make([]byte, 5)
_, err := timeoutReader.Read(p)
Ω(err).Should(MatchError(ErrTimeout))
Expect(err).Should(MatchError(ErrTimeout))
})
})
})
@@ -158,8 +158,8 @@ var _ = Describe("Io Wrappers", func() {
It("returns with no error", func() {
n, err := timeoutWriter.Write([]byte("aaaaa"))
Ω(n).Should(Equal(5))
Ω(err).ShouldNot(HaveOccurred())
Expect(n).Should(Equal(5))
Expect(err).ShouldNot(HaveOccurred())
})
})
@@ -170,7 +170,7 @@ var _ = Describe("Io Wrappers", func() {
It("returns the error", func() {
_, err := timeoutWriter.Write([]byte("aaaaa"))
Ω(err).Should(MatchError("boom"))
Expect(err).Should(MatchError("boom"))
})
})
@@ -181,7 +181,7 @@ var _ = Describe("Io Wrappers", func() {
It("returns ErrTimeout", func() {
_, err := timeoutWriter.Write([]byte("aaaaa"))
Ω(err).Should(MatchError(ErrTimeout))
Expect(err).Should(MatchError(ErrTimeout))
})
})
})
+3 -4
View File
@@ -15,7 +15,7 @@ type BufferProvider interface {
/*
Say is a Gomega matcher that operates on gbytes.Buffers:
Ω(buffer).Should(Say("something"))
Expect(buffer).Should(Say("something"))
will succeed if the unread portion of the buffer matches the regular expression "something".
@@ -36,12 +36,11 @@ In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer()
If the buffer is closed, the Say matcher will tell Eventually to abort.
*/
func Say(expected string, args ...interface{}) *sayMatcher {
formattedRegexp := expected
if len(args) > 0 {
formattedRegexp = fmt.Sprintf(expected, args...)
expected = fmt.Sprintf(expected, args...)
}
return &sayMatcher{
re: regexp.MustCompile(formattedRegexp),
re: regexp.MustCompile(expected),
}
}
+38 -32
View File
@@ -1,9 +1,10 @@
package gbytes_test
import (
. "github.com/onsi/gomega/gbytes"
"time"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
@@ -27,36 +28,41 @@ var _ = Describe("SayMatcher", func() {
Context("when actual is not a gexec Buffer, or a BufferProvider", func() {
It("should error", func() {
failures := InterceptGomegaFailures(func() {
Ω("foo").Should(Say("foo"))
Expect("foo").Should(Say("foo"))
})
Ω(failures[0]).Should(ContainSubstring("*gbytes.Buffer"))
Expect(failures[0]).Should(ContainSubstring("*gbytes.Buffer"))
})
})
Context("when a match is found", func() {
It("should succeed", func() {
Ω(buffer).Should(Say("abc"))
Expect(buffer).Should(Say("abc"))
})
It("should support printf-like formatting", func() {
Ω(buffer).Should(Say("a%sc", "b"))
Expect(buffer).Should(Say("a%sc", "b"))
})
It("should match literal %", func() {
buffer.Write([]byte("%"))
Expect(buffer).Should(Say("abc%"))
})
It("should use a regular expression", func() {
Ω(buffer).Should(Say("a.c"))
Expect(buffer).Should(Say("a.c"))
})
It("should fastforward the buffer", func() {
buffer.Write([]byte("def"))
Ω(buffer).Should(Say("abcd"))
Ω(buffer).Should(Say("ef"))
Ω(buffer).ShouldNot(Say("[a-z]"))
Expect(buffer).Should(Say("abcd"))
Expect(buffer).Should(Say("ef"))
Expect(buffer).ShouldNot(Say("[a-z]"))
})
})
Context("when no match is found", func() {
It("should not error", func() {
Ω(buffer).ShouldNot(Say("def"))
Expect(buffer).ShouldNot(Say("def"))
})
Context("when the buffer is closed", func() {
@@ -70,65 +76,65 @@ var _ = Describe("SayMatcher", func() {
Eventually(buffer).Should(Say("def"))
})
Eventually(buffer).ShouldNot(Say("def"))
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
t = time.Now()
Eventually(buffer).Should(Say("abc"))
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
})
It("should abort a consistently", func() {
t := time.Now()
Consistently(buffer, 2.0).ShouldNot(Say("def"))
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
})
It("should not error with a synchronous matcher", func() {
Ω(buffer).ShouldNot(Say("def"))
Ω(buffer).Should(Say("abc"))
Expect(buffer).ShouldNot(Say("def"))
Expect(buffer).Should(Say("abc"))
})
})
})
Context("when a positive match fails", func() {
It("should report where it got stuck", func() {
Ω(buffer).Should(Say("abc"))
Expect(buffer).Should(Say("abc"))
buffer.Write([]byte("def"))
failures := InterceptGomegaFailures(func() {
Ω(buffer).Should(Say("abc"))
Expect(buffer).Should(Say("abc"))
})
Ω(failures[0]).Should(ContainSubstring("Got stuck at:"))
Ω(failures[0]).Should(ContainSubstring("def"))
Expect(failures[0]).Should(ContainSubstring("Got stuck at:"))
Expect(failures[0]).Should(ContainSubstring("def"))
})
})
Context("when a negative match fails", func() {
It("should report where it got stuck", func() {
failures := InterceptGomegaFailures(func() {
Ω(buffer).ShouldNot(Say("abc"))
Expect(buffer).ShouldNot(Say("abc"))
})
Ω(failures[0]).Should(ContainSubstring("Saw:"))
Ω(failures[0]).Should(ContainSubstring("Which matches the unexpected:"))
Ω(failures[0]).Should(ContainSubstring("abc"))
Expect(failures[0]).Should(ContainSubstring("Saw:"))
Expect(failures[0]).Should(ContainSubstring("Which matches the unexpected:"))
Expect(failures[0]).Should(ContainSubstring("abc"))
})
})
Context("when a match is not found", func() {
It("should not fastforward the buffer", func() {
Ω(buffer).ShouldNot(Say("def"))
Ω(buffer).Should(Say("abc"))
Expect(buffer).ShouldNot(Say("def"))
Expect(buffer).Should(Say("abc"))
})
})
Context("a nice real-life example", func() {
It("should behave well", func() {
Ω(buffer).Should(Say("abc"))
Expect(buffer).Should(Say("abc"))
go func() {
time.Sleep(10 * time.Millisecond)
buffer.Write([]byte("def"))
}()
Ω(buffer).ShouldNot(Say("def"))
Expect(buffer).ShouldNot(Say("def"))
Eventually(buffer).Should(Say("def"))
})
})
@@ -139,10 +145,10 @@ var _ = Describe("SayMatcher", func() {
buffer: NewBuffer(),
}
Ω(s).ShouldNot(Say("abc"))
Expect(s).ShouldNot(Say("abc"))
s.Buffer().Write([]byte("abc"))
Ω(s).Should(Say("abc"))
Expect(s).Should(Say("abc"))
})
It("should abort an eventually", func() {
@@ -156,8 +162,8 @@ var _ = Describe("SayMatcher", func() {
failures := InterceptGomegaFailures(func() {
Eventually(s).Should(Say("def"))
})
Ω(failures).Should(HaveLen(1))
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
})
})
})
+17 -4
View File
@@ -3,12 +3,14 @@ package gexec
import (
"errors"
"fmt"
"go/build"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
)
@@ -21,17 +23,18 @@ var (
Build uses go build to compile the package at packagePath. The resulting binary is saved off in a temporary directory.
A path pointing to this binary is returned.
Build uses the $GOPATH set in your environment. It passes the variadic args on to `go build`.
Build uses the $GOPATH set in your environment. If $GOPATH is not set and you are using Go 1.8+,
it will use the default GOPATH instead. It passes the variadic args on to `go build`.
*/
func Build(packagePath string, args ...string) (compiledPath string, err error) {
return doBuild(os.Getenv("GOPATH"), packagePath, nil, args...)
return doBuild(build.Default.GOPATH, packagePath, nil, args...)
}
/*
BuildWithEnvironment is identical to Build but allows you to specify env vars to be set at build time.
*/
func BuildWithEnvironment(packagePath string, env []string, args ...string) (compiledPath string, err error) {
return doBuild(os.Getenv("GOPATH"), packagePath, env, args...)
return doBuild(build.Default.GOPATH, packagePath, env, args...)
}
/*
@@ -41,6 +44,16 @@ func BuildIn(gopath string, packagePath string, args ...string) (compiledPath st
return doBuild(gopath, packagePath, nil, args...)
}
func replaceGoPath(environ []string, newGoPath string) []string {
newEnviron := []string{}
for _, v := range environ {
if !strings.HasPrefix(v, "GOPATH=") {
newEnviron = append(newEnviron, v)
}
}
return append(newEnviron, "GOPATH="+newGoPath)
}
func doBuild(gopath, packagePath string, env []string, args ...string) (compiledPath string, err error) {
tmpDir, err := temporaryDirectory()
if err != nil {
@@ -60,7 +73,7 @@ func doBuild(gopath, packagePath string, env []string, args ...string) (compiled
cmdArgs = append(cmdArgs, "-o", executable, packagePath)
build := exec.Command("go", cmdArgs...)
build.Env = append([]string{"GOPATH=" + gopath}, os.Environ()...)
build.Env = replaceGoPath(os.Environ(), gopath)
build.Env = append(build.Env, env...)
output, err := build.CombinedOutput()
+62 -9
View File
@@ -1,7 +1,10 @@
package gexec_test
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
@@ -14,13 +17,13 @@ var _ = Describe(".Build", func() {
Context("when there have been previous calls to Build", func() {
BeforeEach(func() {
_, err := gexec.Build(packagePath)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("compiles the specified package", func() {
compiledPath, err := gexec.Build(packagePath)
Ω(err).ShouldNot(HaveOccurred())
Ω(compiledPath).Should(BeAnExistingFile())
Expect(err).ShouldNot(HaveOccurred())
Expect(compiledPath).Should(BeAnExistingFile())
})
Context("and CleanupBuildArtifacts has been called", func() {
@@ -31,8 +34,8 @@ var _ = Describe(".Build", func() {
It("compiles the specified package", func() {
var err error
fireflyPath, err = gexec.Build(packagePath)
Ω(err).ShouldNot(HaveOccurred())
Ω(fireflyPath).Should(BeAnExistingFile())
Expect(err).ShouldNot(HaveOccurred())
Expect(fireflyPath).Should(BeAnExistingFile())
})
})
})
@@ -47,13 +50,63 @@ var _ = Describe(".BuildWithEnvironment", func() {
It("compiles the specified package with the specified env vars", func() {
compiledPath, err := gexec.BuildWithEnvironment(packagePath, env)
Ω(err).ShouldNot(HaveOccurred())
Ω(compiledPath).Should(BeAnExistingFile())
Expect(err).ShouldNot(HaveOccurred())
Expect(compiledPath).Should(BeAnExistingFile())
})
It("returns the environment to a good state", func() {
_, err = gexec.BuildWithEnvironment(packagePath, env)
Ω(err).ShouldNot(HaveOccurred())
Ω(os.Environ()).ShouldNot(ContainElement("GOOS=linux"))
Expect(err).ShouldNot(HaveOccurred())
Expect(os.Environ()).ShouldNot(ContainElement("GOOS=linux"))
})
})
var _ = Describe(".BuildIn", func() {
const (
target = "github.com/onsi/gomega/gexec/_fixture/firefly/"
)
var (
original string
gopath string
)
BeforeEach(func() {
var err error
original = os.Getenv("GOPATH")
gopath, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
copyFile(filepath.Join("_fixture", "firefly", "main.go"), filepath.Join(gopath, "src", target), "main.go")
Expect(os.Setenv("GOPATH", filepath.Join(os.TempDir(), "emptyFakeGopath"))).To(Succeed())
Expect(os.Environ()).To(ContainElement(fmt.Sprintf("GOPATH=%s", filepath.Join(os.TempDir(), "emptyFakeGopath"))))
})
AfterEach(func() {
if original == "" {
Expect(os.Unsetenv("GOPATH")).To(Succeed())
} else {
Expect(os.Setenv("GOPATH", original)).To(Succeed())
}
if gopath != "" {
os.RemoveAll(gopath)
}
})
It("appends the gopath env var", func() {
_, err := gexec.BuildIn(gopath, target)
Expect(err).NotTo(HaveOccurred())
})
It("resets GOPATH to its original value", func() {
_, err := gexec.BuildIn(gopath, target)
Expect(err).NotTo(HaveOccurred())
Expect(os.Getenv("GOPATH")).To(Equal(filepath.Join(os.TempDir(), "emptyFakeGopath")))
})
})
func copyFile(source, directory, basename string) {
Expect(os.MkdirAll(directory, 0755)).To(Succeed())
content, err := ioutil.ReadFile(source)
Expect(err).NotTo(HaveOccurred())
Expect(ioutil.WriteFile(filepath.Join(directory, basename), content, 0644)).To(Succeed())
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
/*
The Exit matcher operates on a session:
Ω(session).Should(Exit(<optional status code>))
Expect(session).Should(Exit(<optional status code>))
Exit passes if the session has already exited.
+25 -24
View File
@@ -1,10 +1,11 @@
package gexec_test
import (
. "github.com/onsi/gomega/gexec"
"os/exec"
"time"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
@@ -23,79 +24,79 @@ var _ = Describe("ExitMatcher", func() {
var err error
command = exec.Command(fireflyPath, "0")
session, err = Start(command, nil, nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
Describe("when passed something that is an Exiter", func() {
It("should act normally", func() {
failures := InterceptGomegaFailures(func() {
Ω(NeverExits{}).Should(Exit())
Expect(NeverExits{}).Should(Exit())
})
Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
Expect(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
})
})
Describe("when passed something that is not an Exiter", func() {
It("should error", func() {
failures := InterceptGomegaFailures(func() {
Ω("aardvark").Should(Exit())
Expect("aardvark").Should(Exit())
})
Ω(failures[0]).Should(ContainSubstring("Exit must be passed a gexec.Exiter"))
Expect(failures[0]).Should(ContainSubstring("Exit must be passed a gexec.Exiter"))
})
})
Context("with no exit code", func() {
It("should say the right things when it fails", func() {
Ω(session).ShouldNot(Exit())
Expect(session).ShouldNot(Exit())
failures := InterceptGomegaFailures(func() {
Ω(session).Should(Exit())
Expect(session).Should(Exit())
})
Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
Expect(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
Eventually(session).Should(Exit())
Ω(session).Should(Exit())
Expect(session).Should(Exit())
failures = InterceptGomegaFailures(func() {
Ω(session).ShouldNot(Exit())
Expect(session).ShouldNot(Exit())
})
Ω(failures[0]).Should(ContainSubstring("Expected process not to exit. It did."))
Expect(failures[0]).Should(ContainSubstring("Expected process not to exit. It did."))
})
})
Context("with an exit code", func() {
It("should say the right things when it fails", func() {
Ω(session).ShouldNot(Exit(0))
Ω(session).ShouldNot(Exit(1))
Expect(session).ShouldNot(Exit(0))
Expect(session).ShouldNot(Exit(1))
failures := InterceptGomegaFailures(func() {
Ω(session).Should(Exit(0))
Expect(session).Should(Exit(0))
})
Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
Expect(failures[0]).Should(ContainSubstring("Expected process to exit. It did not."))
Eventually(session).Should(Exit(0))
Ω(session).Should(Exit(0))
Expect(session).Should(Exit(0))
failures = InterceptGomegaFailures(func() {
Ω(session).Should(Exit(1))
Expect(session).Should(Exit(1))
})
Ω(failures[0]).Should(ContainSubstring("to match exit code:"))
Expect(failures[0]).Should(ContainSubstring("to match exit code:"))
Ω(session).ShouldNot(Exit(1))
Expect(session).ShouldNot(Exit(1))
failures = InterceptGomegaFailures(func() {
Ω(session).ShouldNot(Exit(0))
Expect(session).ShouldNot(Exit(0))
})
Ω(failures[0]).Should(ContainSubstring("not to match exit code:"))
Expect(failures[0]).Should(ContainSubstring("not to match exit code:"))
})
})
@@ -106,8 +107,8 @@ var _ = Describe("ExitMatcher", func() {
failures := InterceptGomegaFailures(func() {
Eventually(session).Should(Exit(1))
})
Ω(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
})
})
})
+1 -1
View File
@@ -14,7 +14,7 @@ func TestGexec(t *testing.T) {
BeforeSuite(func() {
var err error
fireflyPath, err = gexec.Build("./_fixture/firefly")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
AfterSuite(func() {
+1 -1
View File
@@ -28,7 +28,7 @@ var _ = Describe("PrefixedWriter", func() {
writer.Write([]byte("\ntuv\nwx"))
writer.Write([]byte("yz\n\n"))
Ω(buffer.String()).Should(Equal(`[p]abcdef
Expect(buffer.String()).Should(Equal(`[p]abcdef
[p]hij
[p]
[p]
+13 -15
View File
@@ -7,7 +7,6 @@ import (
"io"
"os"
"os/exec"
"reflect"
"sync"
"syscall"
@@ -40,12 +39,12 @@ Start starts the passed-in *exec.Cmd command. It wraps the command in a *gexec.
The session pipes the command's stdout and stderr to two *gbytes.Buffers available as properties on the session: session.Out and session.Err.
These buffers can be used with the gbytes.Say matcher to match against unread output:
Ω(session.Out).Should(gbytes.Say("foo-out"))
Ω(session.Err).Should(gbytes.Say("foo-err"))
Expect(session.Out).Should(gbytes.Say("foo-out"))
Expect(session.Err).Should(gbytes.Say("foo-err"))
In addition, Session satisfies the gbytes.BufferProvider interface and provides the stdout *gbytes.Buffer. This allows you to replace the first line, above, with:
Ω(session).Should(gbytes.Say("foo-out"))
Expect(session).Should(gbytes.Say("foo-out"))
When outWriter and/or errWriter are non-nil, the session will pipe stdout and/or stderr output both into the session *gybtes.Buffers and to the passed-in outWriter/errWriter.
This is useful for capturing the process's output or logging it to screen. In particular, when using Ginkgo it can be convenient to direct output to the GinkgoWriter:
@@ -57,7 +56,7 @@ This will log output when running tests in verbose mode, but - otherwise - will
The session wrapper is responsible for waiting on the *exec.Cmd command. You *should not* call command.Wait() yourself.
Instead, to assert that the command has exited you can use the gexec.Exit matcher:
Ω(session).Should(gexec.Exit())
Expect(session).Should(gexec.Exit())
When the session exits it closes the stdout and stderr gbytes buffers. This will short circuit any
Eventuallys waiting for the buffers to Say something.
@@ -78,11 +77,11 @@ func Start(command *exec.Cmd, outWriter io.Writer, errWriter io.Writer) (*Sessio
commandOut, commandErr = session.Out, session.Err
if outWriter != nil && !reflect.ValueOf(outWriter).IsNil() {
if outWriter != nil {
commandOut = io.MultiWriter(commandOut, outWriter)
}
if errWriter != nil && !reflect.ValueOf(errWriter).IsNil() {
if errWriter != nil {
commandErr = io.MultiWriter(commandErr, errWriter)
}
@@ -152,11 +151,7 @@ If the command has already exited, Kill returns silently.
The session is returned to enable chaining.
*/
func (s *Session) Kill() *Session {
if s.ExitCode() != -1 {
return s
}
s.Command.Process.Kill()
return s
return s.Signal(syscall.SIGKILL)
}
/*
@@ -189,10 +184,9 @@ If the command has already exited, Signal returns silently.
The session is returned to enable chaining.
*/
func (s *Session) Signal(signal os.Signal) *Session {
if s.ExitCode() != -1 {
return s
if s.processIsAlive() {
s.Command.Process.Signal(signal)
}
s.Command.Process.Signal(signal)
return s
}
@@ -216,6 +210,10 @@ func (s *Session) monitorForExit(exited chan<- struct{}) {
close(exited)
}
func (s *Session) processIsAlive() bool {
return s.ExitCode() == -1 && s.Command.Process != nil
}
var trackedSessions = []*Session{}
var trackedSessionsMutex = &sync.Mutex{}
+80 -95
View File
@@ -1,6 +1,8 @@
package gexec_test
import (
"io"
"io/ioutil"
"os/exec"
"syscall"
"time"
@@ -16,7 +18,7 @@ var _ = Describe("Session", func() {
var command *exec.Cmd
var session *Session
var outWriter, errWriter *Buffer
var outWriter, errWriter io.Writer
BeforeEach(func() {
outWriter = nil
@@ -27,12 +29,12 @@ var _ = Describe("Session", func() {
command = exec.Command(fireflyPath)
var err error
session, err = Start(command, outWriter, errWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
Context("running a command", func() {
It("should start the process", func() {
Ω(command.Process).ShouldNot(BeNil())
Expect(command.Process).ShouldNot(BeNil())
})
It("should wrap the process's stdout and stderr with gbytes buffers", func(done Done) {
@@ -60,36 +62,35 @@ var _ = Describe("Session", func() {
Describe("providing the exit code", func() {
It("should provide the app's exit code", func() {
Ω(session.ExitCode()).Should(Equal(-1))
Expect(session.ExitCode()).Should(Equal(-1))
Eventually(session).Should(Exit())
Ω(session.ExitCode()).Should(BeNumerically(">=", 0))
Ω(session.ExitCode()).Should(BeNumerically("<", 3))
Expect(session.ExitCode()).Should(BeNumerically(">=", 0))
Expect(session.ExitCode()).Should(BeNumerically("<", 3))
})
})
Describe("wait", func() {
It("should wait till the command exits", func() {
Ω(session.ExitCode()).Should(Equal(-1))
Ω(session.Wait().ExitCode()).Should(BeNumerically(">=", 0))
Ω(session.Wait().ExitCode()).Should(BeNumerically("<", 3))
Expect(session.ExitCode()).Should(Equal(-1))
Expect(session.Wait().ExitCode()).Should(BeNumerically(">=", 0))
Expect(session.Wait().ExitCode()).Should(BeNumerically("<", 3))
})
})
Describe("exited", func() {
It("should close when the command exits", func() {
Eventually(session.Exited).Should(BeClosed())
Ω(session.ExitCode()).ShouldNot(Equal(-1))
Expect(session.ExitCode()).ShouldNot(Equal(-1))
})
})
Describe("kill", func() {
It("should kill the command and don't wait for it to exit", func() {
It("should kill the command", func() {
session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session.Kill()
Ω(session).ShouldNot(Exit(), "Should not exit immediately...")
Eventually(session).Should(Exit(128 + 9))
})
})
@@ -97,10 +98,9 @@ var _ = Describe("Session", func() {
Describe("interrupt", func() {
It("should interrupt the command", func() {
session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session.Interrupt()
Ω(session).ShouldNot(Exit(), "Should not exit immediately...")
Eventually(session).Should(Exit(128 + 2))
})
})
@@ -108,10 +108,9 @@ var _ = Describe("Session", func() {
Describe("terminate", func() {
It("should terminate the command", func() {
session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session.Terminate()
Ω(session).ShouldNot(Exit(), "Should not exit immediately...")
Eventually(session).Should(Exit(128 + 15))
})
})
@@ -119,12 +118,18 @@ var _ = Describe("Session", func() {
Describe("signal", func() {
It("should send the signal to the command", func() {
session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session.Signal(syscall.SIGABRT)
Ω(session).ShouldNot(Exit(), "Should not exit immediately...")
Eventually(session).Should(Exit(128 + 6))
})
It("should ignore sending a signal if the command did not start", func() {
session, err := Start(exec.Command("notexisting"), GinkgoWriter, GinkgoWriter)
Expect(err).To(HaveOccurred())
Expect(func() { session.Signal(syscall.SIGUSR1) }).NotTo(Panic())
})
})
Context("tracking sessions", func() {
@@ -135,13 +140,13 @@ var _ = Describe("Session", func() {
Describe("kill", func() {
It("should kill all the started sessions", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Kill()
@@ -150,25 +155,15 @@ var _ = Describe("Session", func() {
Eventually(session3).Should(Exit(128 + 9))
})
It("should not wait for exit", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Kill()
Ω(session1).ShouldNot(Exit(), "Should not exit immediately...")
Eventually(session1).Should(Exit(128 + 9))
})
It("should not track unstarted sessions", func() {
_, err := Start(exec.Command("does not exist", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Kill()
@@ -181,31 +176,31 @@ var _ = Describe("Session", func() {
Describe("killAndWait", func() {
It("should kill all the started sessions and wait for them to finish", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
KillAndWait()
Ω(session1).Should(Exit(128+9), "Should have exited")
Ω(session2).Should(Exit(128+9), "Should have exited")
Ω(session3).Should(Exit(128+9), "Should have exited")
Expect(session1).Should(Exit(128+9), "Should have exited")
Expect(session2).Should(Exit(128+9), "Should have exited")
Expect(session3).Should(Exit(128+9), "Should have exited")
})
})
Describe("terminate", func() {
It("should terminate all the started sessions", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Terminate()
@@ -213,46 +208,37 @@ var _ = Describe("Session", func() {
Eventually(session2).Should(Exit(128 + 15))
Eventually(session3).Should(Exit(128 + 15))
})
It("should not wait for exit", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Terminate()
Ω(session1).ShouldNot(Exit(), "Should not exit immediately...")
})
})
Describe("terminateAndWait", func() {
It("should terminate all the started sessions, and wait for them to exit", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
TerminateAndWait()
Ω(session1).Should(Exit(128+15), "Should have exited")
Ω(session2).Should(Exit(128+15), "Should have exited")
Ω(session3).Should(Exit(128+15), "Should have exited")
Expect(session1).Should(Exit(128+15), "Should have exited")
Expect(session2).Should(Exit(128+15), "Should have exited")
Expect(session3).Should(Exit(128+15), "Should have exited")
})
})
Describe("signal", func() {
It("should signal all the started sessions", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Signal(syscall.SIGABRT)
@@ -260,27 +246,18 @@ var _ = Describe("Session", func() {
Eventually(session2).Should(Exit(128 + 6))
Eventually(session3).Should(Exit(128 + 6))
})
It("should not wait", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Signal(syscall.SIGABRT)
Ω(session1).ShouldNot(Exit(), "Should not exit immediately...")
})
})
Describe("interrupt", func() {
It("should interrupt all the started sessions, and not wait", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session2, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
session3, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Interrupt()
@@ -288,15 +265,6 @@ var _ = Describe("Session", func() {
Eventually(session2).Should(Exit(128 + 2))
Eventually(session3).Should(Exit(128 + 2))
})
It("should not wait", func() {
session1, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
Interrupt()
Ω(session1).ShouldNot(Exit(), "Should not exit immediately...")
})
})
})
@@ -304,10 +272,10 @@ var _ = Describe("Session", func() {
It("should close the buffers", func() {
Eventually(session).Should(Exit())
Ω(session.Out.Closed()).Should(BeTrue())
Ω(session.Err.Closed()).Should(BeTrue())
Expect(session.Out.Closed()).Should(BeTrue())
Expect(session.Err.Closed()).Should(BeTrue())
Ω(session.Out).Should(Say("We've done the impossible, and that makes us mighty"))
Expect(session.Out).Should(Say("We've done the impossible, and that makes us mighty"))
})
var So = It
@@ -317,35 +285,52 @@ var _ = Describe("Session", func() {
failures := InterceptGomegaFailures(func() {
Eventually(session).Should(Say("blah blah blah blah blah"))
})
Ω(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
})
})
Context("when wrapping out and err", func() {
var (
outWriterBuffer, errWriterBuffer *Buffer
)
BeforeEach(func() {
outWriter = NewBuffer()
errWriter = NewBuffer()
outWriterBuffer = NewBuffer()
outWriter = outWriterBuffer
errWriterBuffer = NewBuffer()
errWriter = errWriterBuffer
})
It("should route to both the provided writers and the gbytes buffers", func() {
Eventually(session.Out).Should(Say("We've done the impossible, and that makes us mighty"))
Eventually(session.Err).Should(Say("Ah, curse your sudden but inevitable betrayal!"))
Ω(outWriter.Contents()).Should(ContainSubstring("We've done the impossible, and that makes us mighty"))
Ω(errWriter.Contents()).Should(ContainSubstring("Ah, curse your sudden but inevitable betrayal!"))
Expect(outWriterBuffer.Contents()).Should(ContainSubstring("We've done the impossible, and that makes us mighty"))
Expect(errWriterBuffer.Contents()).Should(ContainSubstring("Ah, curse your sudden but inevitable betrayal!"))
Eventually(session).Should(Exit())
Ω(outWriter.Contents()).Should(Equal(session.Out.Contents()))
Ω(errWriter.Contents()).Should(Equal(session.Err.Contents()))
Expect(outWriterBuffer.Contents()).Should(Equal(session.Out.Contents()))
Expect(errWriterBuffer.Contents()).Should(Equal(session.Err.Contents()))
})
Context("when discarding the output of the command", func() {
BeforeEach(func() {
outWriter = ioutil.Discard
errWriter = ioutil.Discard
})
It("executes succesfuly", func() {
Eventually(session).Should(Exit())
})
})
})
Describe("when the command fails to start", func() {
It("should return an error", func() {
_, err := Start(exec.Command("agklsjdfas"), nil, nil)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
})
})
})
+26 -26
View File
@@ -31,18 +31,18 @@ func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc {
//Alternatively you can pass in a matcher (ContainSubstring("/foo") and MatchRegexp("/foo/[a-f0-9]+") for example)
func VerifyRequest(method string, path interface{}, rawQuery ...string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Ω(req.Method).Should(Equal(method), "Method mismatch")
Expect(req.Method).Should(Equal(method), "Method mismatch")
switch p := path.(type) {
case types.GomegaMatcher:
Ω(req.URL.Path).Should(p, "Path mismatch")
Expect(req.URL.Path).Should(p, "Path mismatch")
default:
Ω(req.URL.Path).Should(Equal(path), "Path mismatch")
Expect(req.URL.Path).Should(Equal(path), "Path mismatch")
}
if len(rawQuery) > 0 {
values, err := url.ParseQuery(rawQuery[0])
Ω(err).ShouldNot(HaveOccurred(), "Expected RawQuery is malformed")
Expect(err).ShouldNot(HaveOccurred(), "Expected RawQuery is malformed")
Ω(req.URL.Query()).Should(Equal(values), "RawQuery mismatch")
Expect(req.URL.Query()).Should(Equal(values), "RawQuery mismatch")
}
}
}
@@ -51,7 +51,7 @@ func VerifyRequest(method string, path interface{}, rawQuery ...string) http.Han
//specified value
func VerifyContentType(contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Ω(req.Header.Get("Content-Type")).Should(Equal(contentType))
Expect(req.Header.Get("Content-Type")).Should(Equal(contentType))
}
}
@@ -60,12 +60,12 @@ func VerifyContentType(contentType string) http.HandlerFunc {
func VerifyBasicAuth(username string, password string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
Ω(auth).ShouldNot(Equal(""), "Authorization header must be specified")
Expect(auth).ShouldNot(Equal(""), "Authorization header must be specified")
decoded, err := base64.StdEncoding.DecodeString(auth[6:])
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(string(decoded)).Should(Equal(fmt.Sprintf("%s:%s", username, password)), "Authorization mismatch")
Expect(string(decoded)).Should(Equal(fmt.Sprintf("%s:%s", username, password)), "Authorization mismatch")
}
}
@@ -78,7 +78,7 @@ func VerifyHeader(header http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
for key, values := range header {
key = http.CanonicalHeaderKey(key)
Ω(req.Header[key]).Should(Equal(values), "Header mismatch for key: %s", key)
Expect(req.Header[key]).Should(Equal(values), "Header mismatch for key: %s", key)
}
}
}
@@ -97,8 +97,8 @@ func VerifyBody(expectedBody []byte) http.HandlerFunc {
func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
req.Body.Close()
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(Equal(expectedBody), "Body Mismatch")
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal(expectedBody), "Body Mismatch")
},
)
}
@@ -113,8 +113,8 @@ func VerifyJSON(expectedJSON string) http.HandlerFunc {
func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
req.Body.Close()
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(MatchJSON(expectedJSON), "JSON Mismatch")
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(MatchJSON(expectedJSON), "JSON Mismatch")
},
)
}
@@ -124,7 +124,7 @@ func VerifyJSON(expectedJSON string) http.HandlerFunc {
//that matches the object
func VerifyJSONRepresenting(object interface{}) http.HandlerFunc {
data, err := json.Marshal(object)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
return CombineHandlers(
VerifyContentType("application/json"),
VerifyJSON(string(data)),
@@ -138,9 +138,9 @@ func VerifyJSONRepresenting(object interface{}) http.HandlerFunc {
func VerifyForm(values url.Values) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
for key, vals := range values {
Ω(r.Form[key]).Should(Equal(vals), "Form mismatch for key: %s", key)
Expect(r.Form[key]).Should(Equal(vals), "Form mismatch for key: %s", key)
}
}
}
@@ -161,19 +161,19 @@ func VerifyProtoRepresenting(expected proto.Message) http.HandlerFunc {
VerifyContentType("application/x-protobuf"),
func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Body.Close()
expectedType := reflect.TypeOf(expected)
actualValuePtr := reflect.New(expectedType.Elem())
actual, ok := actualValuePtr.Interface().(proto.Message)
Ω(ok).Should(BeTrue(), "Message value is not a proto.Message")
Expect(ok).Should(BeTrue(), "Message value is not a proto.Message")
err = proto.Unmarshal(body, actual)
Ω(err).ShouldNot(HaveOccurred(), "Failed to unmarshal protobuf")
Expect(err).ShouldNot(HaveOccurred(), "Failed to unmarshal protobuf")
Ω(actual).Should(Equal(expected), "ProtoBuf Mismatch")
Expect(actual).Should(Equal(expected), "ProtoBuf Mismatch")
},
)
}
@@ -203,7 +203,7 @@ func RespondWith(statusCode int, body interface{}, optionalHeader ...http.Header
case []byte:
w.Write(x)
default:
Ω(body).Should(BeNil(), "Invalid type for body. Should be string or []byte.")
Expect(body).Should(BeNil(), "Invalid type for body. Should be string or []byte.")
}
}
}
@@ -230,7 +230,7 @@ func RespondWithPtr(statusCode *int, body interface{}, optionalHeader ...http.He
case *[]byte:
w.Write(*x)
default:
Ω(body).Should(BeNil(), "Invalid type for body. Should be string or []byte.")
Expect(body).Should(BeNil(), "Invalid type for body. Should be string or []byte.")
}
}
}
@@ -244,7 +244,7 @@ Also, RespondWithJSONEncoded can be given an optional http.Header. The headers
*/
func RespondWithJSONEncoded(statusCode int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc {
data, err := json.Marshal(object)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
@@ -271,7 +271,7 @@ Since the http.Header can be mutated after the fact you don't need to pass in a
func RespondWithJSONEncodedPtr(statusCode *int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := json.Marshal(object)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
headers = optionalHeader[0]
@@ -294,7 +294,7 @@ func RespondWithJSONEncodedPtr(statusCode *int, object interface{}, optionalHead
func RespondWithProto(statusCode int, message proto.Message, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := proto.Marshal(message)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
+76 -35
View File
@@ -47,7 +47,7 @@ A more comprehensive example is available at https://onsi.github.io/gomega/#_tes
})
It("should return the returned sprockets", func() {
Ω(client.Sprockets()).Should(Equal(sprockets))
Expect(client.Sprockets()).Should(Equal(sprockets))
})
})
@@ -57,7 +57,7 @@ A more comprehensive example is available at https://onsi.github.io/gomega/#_tes
})
It("should return an empty list of sprockets", func() {
Ω(client.Sprockets()).Should(BeEmpty())
Expect(client.Sprockets()).Should(BeEmpty())
})
})
@@ -68,8 +68,8 @@ A more comprehensive example is available at https://onsi.github.io/gomega/#_tes
It("should return an AuthenticationError error", func() {
sprockets, err := client.Sprockets()
Ω(sprockets).Should(BeEmpty())
Ω(err).Should(MatchError(AuthenticationError))
Expect(sprockets).Should(BeEmpty())
Expect(err).Should(MatchError(AuthenticationError))
})
})
@@ -80,8 +80,8 @@ A more comprehensive example is available at https://onsi.github.io/gomega/#_tes
It("should return an InternalError error", func() {
sprockets, err := client.Sprockets()
Ω(sprockets).Should(BeEmpty())
Ω(err).Should(MatchError(InternalError))
Expect(sprockets).Should(BeEmpty())
Expect(err).Should(MatchError(InternalError))
})
})
})
@@ -97,7 +97,7 @@ A more comprehensive example is available at https://onsi.github.io/gomega/#_tes
})
It("should make the request with a filter", func() {
Ω(client.Sprockets("food")).Should(Equal(sprockets))
Expect(client.Sprockets("food")).Should(Equal(sprockets))
})
})
})
@@ -111,6 +111,7 @@ import (
"io/ioutil"
"net/http"
"net/http/httptest"
"net/http/httputil"
"reflect"
"regexp"
"strings"
@@ -123,7 +124,7 @@ func new() *Server {
return &Server{
AllowUnhandledRequests: false,
UnhandledRequestStatusCode: http.StatusInternalServerError,
writeLock: &sync.Mutex{},
rwMutex: &sync.RWMutex{},
}
}
@@ -160,11 +161,13 @@ type Server struct {
HTTPTestServer *httptest.Server
//Defaults to false. If set to true, the Server will allow more requests than there are registered handlers.
//Direct use of this property is deprecated and is likely to be removed, use GetAllowUnhandledRequests and SetAllowUnhandledRequests instead.
AllowUnhandledRequests bool
//The status code returned when receiving an unhandled request.
//Defaults to http.StatusInternalServerError.
//Only applies if AllowUnhandledRequests is true
//Direct use of this property is deprecated and is likely to be removed, use GetUnhandledRequestStatusCode and SetUnhandledRequestStatusCode instead.
UnhandledRequestStatusCode int
//If provided, ghttp will log about each request received to the provided io.Writer
@@ -176,8 +179,8 @@ type Server struct {
requestHandlers []http.HandlerFunc
routedHandlers []routedHandler
writeLock *sync.Mutex
calls int
rwMutex *sync.RWMutex
calls int
}
//Start() starts an unstarted ghttp server. It is a catastrophic error to call Start more than once (thanks, httptest).
@@ -187,20 +190,24 @@ func (s *Server) Start() {
//URL() returns a url that will hit the server
func (s *Server) URL() string {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.HTTPTestServer.URL
}
//Addr() returns the address on which the server is listening.
func (s *Server) Addr() string {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.HTTPTestServer.Listener.Addr().String()
}
//Close() should be called at the end of each test. It spins down and cleans up the test server.
func (s *Server) Close() {
s.writeLock.Lock()
s.rwMutex.Lock()
server := s.HTTPTestServer
s.HTTPTestServer = nil
s.writeLock.Unlock()
s.rwMutex.Unlock()
if server != nil {
server.Close()
@@ -213,10 +220,10 @@ func (s *Server) Close() {
//1. If the request matches a handler registered with RouteToHandler, that handler is called.
//2. Otherwise, if there are handlers registered via AppendHandlers, those handlers are called in order.
//3. If all registered handlers have been called then:
// a) If AllowUnhandledRequests is true, the request will be handled with response code of UnhandledRequestStatusCode
// a) If AllowUnhandledRequests is set to true, the request will be handled with response code of UnhandledRequestStatusCode
// b) If AllowUnhandledRequests is false, the request will not be handled and the current test will be marked as failed.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.writeLock.Lock()
s.rwMutex.Lock()
defer func() {
e := recover()
if e != nil {
@@ -240,7 +247,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
recover()
}()
Ω(e).Should(BeNil(), "Handler Panicked")
Expect(e).Should(BeNil(), "Handler Panicked")
}()
if s.Writer != nil {
@@ -249,29 +256,31 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.receivedRequests = append(s.receivedRequests, req)
if routedHandler, ok := s.handlerForRoute(req.Method, req.URL.Path); ok {
s.writeLock.Unlock()
s.rwMutex.Unlock()
routedHandler(w, req)
} else if s.calls < len(s.requestHandlers) {
h := s.requestHandlers[s.calls]
s.calls++
s.writeLock.Unlock()
s.rwMutex.Unlock()
h(w, req)
} else {
s.writeLock.Unlock()
if s.AllowUnhandledRequests {
s.rwMutex.Unlock()
if s.GetAllowUnhandledRequests() {
ioutil.ReadAll(req.Body)
req.Body.Close()
w.WriteHeader(s.UnhandledRequestStatusCode)
w.WriteHeader(s.GetUnhandledRequestStatusCode())
} else {
Ω(req).Should(BeNil(), "Received Unhandled Request")
formatted, err := httputil.DumpRequest(req, true)
Expect(err).NotTo(HaveOccurred(), "Encountered error while dumping HTTP request")
Expect(string(formatted)).Should(BeNil(), "Received Unhandled Request")
}
}
}
//ReceivedRequests is an array containing all requests received by the server (both handled and unhandled requests)
func (s *Server) ReceivedRequests() []*http.Request {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.receivedRequests
}
@@ -281,8 +290,8 @@ func (s *Server) ReceivedRequests() []*http.Request {
//
//The path may be either a string object or a *regexp.Regexp.
func (s *Server) RouteToHandler(method string, path interface{}, handler http.HandlerFunc) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
rh := routedHandler{
method: method,
@@ -327,8 +336,8 @@ func (s *Server) handlerForRoute(method string, path string) (http.HandlerFunc,
//AppendHandlers will appends http.HandlerFuncs to the server's list of registered handlers. The first incoming request is handled by the first handler, the second by the second, etc...
func (s *Server) AppendHandlers(handlers ...http.HandlerFunc) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.requestHandlers = append(s.requestHandlers, handlers...)
}
@@ -337,23 +346,23 @@ func (s *Server) AppendHandlers(handlers ...http.HandlerFunc) {
//This is useful, for example, when a server has been set up in a shared context, but must be tweaked
//for a particular test.
func (s *Server) SetHandler(index int, handler http.HandlerFunc) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.requestHandlers[index] = handler
}
//GetHandler returns the handler registered at the passed in index.
func (s *Server) GetHandler(index int) http.HandlerFunc {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.requestHandlers[index]
}
func (s *Server) Reset() {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.HTTPTestServer.CloseClientConnections()
s.calls = 0
@@ -374,8 +383,40 @@ func (s *Server) WrapHandler(index int, handler http.HandlerFunc) {
}
func (s *Server) CloseClientConnections() {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.HTTPTestServer.CloseClientConnections()
}
//SetAllowUnhandledRequests enables the server to accept unhandled requests.
func (s *Server) SetAllowUnhandledRequests(allowUnhandledRequests bool) {
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.AllowUnhandledRequests = allowUnhandledRequests
}
//GetAllowUnhandledRequests returns true if the server accepts unhandled requests.
func (s *Server) GetAllowUnhandledRequests() bool {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.AllowUnhandledRequests
}
//SetUnhandledRequestStatusCode status code to be returned when the server receives unhandled requests
func (s *Server) SetUnhandledRequestStatusCode(statusCode int) {
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
s.UnhandledRequestStatusCode = statusCode
}
//GetUnhandledRequestStatusCode returns the current status code being returned for unhandled requests
func (s *Server) GetUnhandledRequestStatusCode() int {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
return s.UnhandledRequestStatusCode
}
+153 -149
View File
@@ -38,13 +38,13 @@ var _ = Describe("TestServer", func() {
s.AppendHandlers(func(w http.ResponseWriter, req *http.Request) {})
http.Get(s.URL() + "/")
Ω(s.ReceivedRequests()).Should(HaveLen(1))
Expect(s.ReceivedRequests()).Should(HaveLen(1))
})
It("clears all handlers and call counts", func() {
s.Reset()
Ω(s.ReceivedRequests()).Should(HaveLen(0))
Ω(func() { s.GetHandler(0) }).Should(Panic())
Expect(s.ReceivedRequests()).Should(HaveLen(0))
Expect(func() { s.GetHandler(0) }).Should(Panic())
})
})
@@ -57,55 +57,59 @@ var _ = Describe("TestServer", func() {
)
client := http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
resp, err := client.Get(s.URL())
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(200))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(200))
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
s.CloseClientConnections()
resp, err = client.Get(s.URL())
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(200))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(200))
body2, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(body2).ShouldNot(Equal(body))
Expect(body2).ShouldNot(Equal(body))
})
})
Describe("closing server mulitple times", func() {
It("should not fail", func() {
s.Close()
Ω(s.Close).ShouldNot(Panic())
Expect(s.Close).ShouldNot(Panic())
})
})
Describe("allowing unhandled requests", func() {
It("is not permitted by default", func() {
Expect(s.GetAllowUnhandledRequests()).To(BeFalse())
})
Context("when true", func() {
BeforeEach(func() {
s.AllowUnhandledRequests = true
s.UnhandledRequestStatusCode = http.StatusForbidden
s.SetAllowUnhandledRequests(true)
s.SetUnhandledRequestStatusCode(http.StatusForbidden)
resp, err = http.Get(s.URL() + "/foo")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should allow unhandled requests and respond with the passed in status code", func() {
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusForbidden))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusForbidden))
data, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(data).Should(BeEmpty())
Expect(err).ShouldNot(HaveOccurred())
Expect(data).Should(BeEmpty())
})
It("should record the requests", func() {
Ω(s.ReceivedRequests()).Should(HaveLen(1))
Ω(s.ReceivedRequests()[0].URL.Path).Should(Equal("/foo"))
Expect(s.ReceivedRequests()).Should(HaveLen(1))
Expect(s.ReceivedRequests()[0].URL.Path).Should(Equal("/foo"))
})
})
@@ -115,7 +119,7 @@ var _ = Describe("TestServer", func() {
http.Get(s.URL() + "/foo")
})
Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
Expect(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
})
})
})
@@ -152,12 +156,12 @@ var _ = Describe("TestServer", func() {
http.Post(s.URL()+"/routed", "application/json", nil)
})
Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
Ω(failures).Should(HaveLen(4))
Expect(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
Expect(failures).Should(HaveLen(4))
http.Post(s.URL()+"/routed3", "application/json", nil)
Ω(called).Should(Equal([]string{"r1", "r2", "A", "r1", "r2", "B", "r2"}))
Expect(called).Should(Equal([]string{"r1", "r2", "A", "r1", "r2", "B", "r2"}))
})
It("should override routed handlers when reregistered", func() {
@@ -171,21 +175,21 @@ var _ = Describe("TestServer", func() {
http.Get(s.URL() + "/routed")
http.Post(s.URL()+"/routed7", "application/json", nil)
Ω(called).Should(Equal([]string{"r3", "r4"}))
Expect(called).Should(Equal([]string{"r3", "r4"}))
})
It("should call the appended handlers, in order, as requests come in", func() {
http.Get(s.URL() + "/foo")
Ω(called).Should(Equal([]string{"A"}))
Expect(called).Should(Equal([]string{"A"}))
http.Get(s.URL() + "/foo")
Ω(called).Should(Equal([]string{"A", "B"}))
Expect(called).Should(Equal([]string{"A", "B"}))
failures := InterceptGomegaFailures(func() {
http.Get(s.URL() + "/foo")
})
Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
Expect(failures[0]).Should(ContainSubstring("Received Unhandled Request"))
})
Describe("Overwriting an existing handler", func() {
@@ -198,14 +202,14 @@ var _ = Describe("TestServer", func() {
It("should override the specified handler", func() {
http.Get(s.URL() + "/foo")
http.Get(s.URL() + "/foo")
Ω(called).Should(Equal([]string{"C", "B"}))
Expect(called).Should(Equal([]string{"C", "B"}))
})
})
Describe("Getting an existing handler", func() {
It("should return the handler func", func() {
s.GetHandler(1)(nil, nil)
Ω(called).Should(Equal([]string{"B"}))
Expect(called).Should(Equal([]string{"B"}))
})
})
@@ -219,14 +223,14 @@ var _ = Describe("TestServer", func() {
It("should wrap the existing handler in a new handler", func() {
http.Get(s.URL() + "/foo")
http.Get(s.URL() + "/foo")
Ω(called).Should(Equal([]string{"A", "C", "B"}))
Expect(called).Should(Equal([]string{"A", "C", "B"}))
})
})
})
Describe("When a handler fails", func() {
BeforeEach(func() {
s.UnhandledRequestStatusCode = http.StatusForbidden //just to be clear that 500s aren't coming from unhandled requests
s.SetUnhandledRequestStatusCode(http.StatusForbidden) //just to be clear that 500s aren't coming from unhandled requests
})
Context("because the handler has panicked", func() {
@@ -244,16 +248,16 @@ var _ = Describe("TestServer", func() {
resp, err = http.Get(s.URL())
})
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusInternalServerError))
Ω(failures).Should(ConsistOf(ContainSubstring("Handler Panicked")))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusInternalServerError))
Expect(failures).Should(ConsistOf(ContainSubstring("Handler Panicked")))
})
})
Context("because an assertion has failed", func() {
BeforeEach(func() {
s.AppendHandlers(func(w http.ResponseWriter, req *http.Request) {
// Ω(true).Should(BeFalse()) <-- would be nice to do it this way, but the test just can't be written this way
// Expect(true).Should(BeFalse()) <-- would be nice to do it this way, but the test just can't be written this way
By("We're cheating a bit here -- we're throwing a GINKGO_PANIC which simulates a failed assertion")
panic(GINKGO_PANIC)
@@ -263,8 +267,8 @@ var _ = Describe("TestServer", func() {
It("should respond with a 500 and *not* make a failing assertion, instead relying on Ginkgo to have already been notified of the error", func() {
resp, err := http.Get(s.URL())
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusInternalServerError))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusInternalServerError))
})
})
})
@@ -280,10 +284,10 @@ var _ = Describe("TestServer", func() {
It("should write to the buffer when a request comes in", func() {
http.Get(s.URL() + "/foo")
Ω(buf).Should(gbytes.Say("GHTTP Received Request: GET - /foo\n"))
Expect(buf).Should(gbytes.Say("GHTTP Received Request: GET - /foo\n"))
http.Post(s.URL()+"/bar", "", nil)
Ω(buf).Should(gbytes.Say("GHTTP Received Request: POST - /bar\n"))
Expect(buf).Should(gbytes.Say("GHTTP Received Request: POST - /bar\n"))
})
})
@@ -295,28 +299,28 @@ var _ = Describe("TestServer", func() {
It("should verify the method, path", func() {
resp, err = http.Get(s.URL() + "/foo?baz=bar")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the method, path", func() {
failures := InterceptGomegaFailures(func() {
http.Get(s.URL() + "/foo2")
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("should verify the method, path", func() {
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/foo", "application/json", nil)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
Context("when passed a rawQuery", func() {
It("should also be possible to verify the rawQuery", func() {
s.SetHandler(0, VerifyRequest("GET", "/foo", "baz=bar"))
resp, err = http.Get(s.URL() + "/foo?baz=bar")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should match irregardless of query parameter ordering", func() {
@@ -328,7 +332,7 @@ var _ = Describe("TestServer", func() {
}.Encode()
resp, err = http.Get(u.String())
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
})
@@ -336,7 +340,7 @@ var _ = Describe("TestServer", func() {
It("should apply the matcher", func() {
s.SetHandler(0, VerifyRequest("GET", MatchRegexp(`/foo/[a-f]*/3`)))
resp, err = http.Get(s.URL() + "/foo/abcdefa/3")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
})
})
@@ -351,22 +355,22 @@ var _ = Describe("TestServer", func() {
It("should verify the content type", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Set("Content-Type", "application/octet-stream")
resp, err = http.DefaultClient.Do(req)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the content type", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Set("Content-Type", "application/json")
failures := InterceptGomegaFailures(func() {
http.DefaultClient.Do(req)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -380,32 +384,32 @@ var _ = Describe("TestServer", func() {
It("should verify basic auth", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.SetBasicAuth("bob", "password")
resp, err = http.DefaultClient.Do(req)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify basic auth", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.SetBasicAuth("bob", "bassword")
failures := InterceptGomegaFailures(func() {
http.DefaultClient.Do(req)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("should require basic auth header", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
failures := InterceptGomegaFailures(func() {
http.DefaultClient.Do(req)
})
Ω(failures).Should(ContainElement(ContainSubstring("Authorization header must be specified")))
Expect(failures).Should(ContainElement(ContainSubstring("Authorization header must be specified")))
})
})
@@ -423,19 +427,19 @@ var _ = Describe("TestServer", func() {
It("should verify the headers", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Add("Accept", "jpeg")
req.Header.Add("Accept", "png")
req.Header.Add("Cache-Control", "omicron")
req.Header.Add("return-path", "hobbiton")
resp, err = http.DefaultClient.Do(req)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the headers", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Add("Schmaccept", "jpeg")
req.Header.Add("Schmaccept", "png")
req.Header.Add("Cache-Control", "omicron")
@@ -444,7 +448,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
http.DefaultClient.Do(req)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -460,19 +464,19 @@ var _ = Describe("TestServer", func() {
It("should verify the headers", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Add("Accept", "jpeg")
req.Header.Add("Accept", "png")
req.Header.Add("Cache-Control", "omicron")
req.Header.Add("return-path", "hobbiton")
resp, err = http.DefaultClient.Do(req)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the headers", func() {
req, err := http.NewRequest("GET", s.URL()+"/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
req.Header.Add("Accept", "jpeg")
req.Header.Add("Cache-Control", "omicron")
req.Header.Add("return-path", "hobbiton")
@@ -480,7 +484,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
http.DefaultClient.Do(req)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -494,14 +498,14 @@ var _ = Describe("TestServer", func() {
It("should verify the body", func() {
resp, err = http.Post(s.URL()+"/foo", "", bytes.NewReader([]byte("some body")))
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the body", func() {
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/foo", "", bytes.NewReader([]byte("wrong body")))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -515,21 +519,21 @@ var _ = Describe("TestServer", func() {
It("should verify the json body and the content type", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`{"b":2, "a":3}`)))
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the json body and the content type", func() {
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`{"b":2, "a":4}`)))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("should verify the json body and the content type", func() {
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/foo", "application/not-json", bytes.NewReader([]byte(`{"b":2, "a":3}`)))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -543,14 +547,14 @@ var _ = Describe("TestServer", func() {
It("should verify the json body and the content type", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`[1,3,5]`)))
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the json body and the content type", func() {
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`[1,3]`)))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -577,13 +581,13 @@ var _ = Describe("TestServer", func() {
It("should verify form values", func() {
resp, err = http.Get(s.URL() + "/foo?" + formValues.Encode())
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should ignore extra values", func() {
formValues.Add("extra", "value")
resp, err = http.Get(s.URL() + "/foo?" + formValues.Encode())
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("fail on missing values", func() {
@@ -591,7 +595,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.Get(s.URL() + "/foo?" + formValues.Encode())
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("fail on incorrect values", func() {
@@ -599,7 +603,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.Get(s.URL() + "/foo?" + formValues.Encode())
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -616,13 +620,13 @@ var _ = Describe("TestServer", func() {
It("should verify form values", func() {
resp, err = http.PostForm(s.URL()+"/foo", formValues)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should ignore extra values", func() {
formValues.Add("extra", "value")
resp, err = http.PostForm(s.URL()+"/foo", formValues)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("fail on missing values", func() {
@@ -630,7 +634,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.PostForm(s.URL()+"/foo", formValues)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("fail on incorrect values", func() {
@@ -638,7 +642,7 @@ var _ = Describe("TestServer", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.PostForm(s.URL()+"/foo", formValues)
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
})
@@ -654,14 +658,14 @@ var _ = Describe("TestServer", func() {
It("verifies the form value", func() {
resp, err = http.Get(s.URL() + "/foo?users=user1&users=user2")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("verifies the form value", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.Get(s.URL() + "/foo?users=user1")
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -675,14 +679,14 @@ var _ = Describe("TestServer", func() {
It("verifies the form value", func() {
resp, err = http.PostForm(s.URL()+"/foo", url.Values{"users": []string{"user1", "user2"}})
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("verifies the form value", func() {
failures := InterceptGomegaFailures(func() {
resp, err = http.PostForm(s.URL()+"/foo", url.Values{"users": []string{"user1"}})
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
})
@@ -703,10 +707,10 @@ var _ = Describe("TestServer", func() {
It("verifies the proto body and the content type", func() {
serialized, err := proto.Marshal(message)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", bytes.NewReader(serialized))
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should verify the proto body and the content type", func() {
@@ -715,22 +719,22 @@ var _ = Describe("TestServer", func() {
Id: proto.Int32(0),
Metadata: proto.String("some metadata"),
})
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/proto", "application/x-protobuf", bytes.NewReader(serialized))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
It("should verify the proto body and the content type", func() {
serialized, err := proto.Marshal(message)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
failures := InterceptGomegaFailures(func() {
http.Post(s.URL()+"/proto", "application/not-x-protobuf", bytes.NewReader(serialized))
})
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -748,22 +752,22 @@ var _ = Describe("TestServer", func() {
It("should return the response", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
body, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(Equal([]byte("sweet")))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal([]byte("sweet")))
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusOK))
Expect(resp.StatusCode).Should(Equal(http.StatusOK))
body, err = ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(Equal([]byte("sour")))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal([]byte("sour")))
})
})
@@ -777,11 +781,11 @@ var _ = Describe("TestServer", func() {
It("should return the headers too", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Ω(ioutil.ReadAll(resp.Body)).Should(Equal([]byte("sweet")))
Ω(resp.Header.Get("X-Custom-Header")).Should(Equal("my header"))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(ioutil.ReadAll(resp.Body)).Should(Equal([]byte("sweet")))
Expect(resp.Header.Get("X-Custom-Header")).Should(Equal("my header"))
})
})
})
@@ -810,22 +814,22 @@ var _ = Describe("TestServer", func() {
stringBody = "treat"
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
body, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(Equal([]byte("tasty")))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal([]byte("tasty")))
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
body, err = ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(Equal([]byte("treat")))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal([]byte("treat")))
})
Context("when passed a nil body", func() {
@@ -839,13 +843,13 @@ var _ = Describe("TestServer", func() {
It("should return an empty body and not explode", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusOK))
Expect(err).ShouldNot(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusOK))
body, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(BeEmpty())
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(BeEmpty())
Ω(s.ReceivedRequests()).Should(HaveLen(1))
Expect(s.ReceivedRequests()).Should(HaveLen(1))
})
})
})
@@ -861,20 +865,20 @@ var _ = Describe("TestServer", func() {
It("should return the response", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
body, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(MatchJSON("[1,2,3]"))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(MatchJSON("[1,2,3]"))
})
It("should set the Content-Type header to application/json", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
})
})
@@ -893,16 +897,16 @@ var _ = Describe("TestServer", func() {
It("should preserve those headers", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
Expect(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
})
It("should set the Content-Type header to application/json", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
})
Context("when setting the Content-Type explicitly", func() {
@@ -912,9 +916,9 @@ var _ = Describe("TestServer", func() {
It("should use the Content-Type header that was explicitly set", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"}))
})
})
})
@@ -946,20 +950,20 @@ var _ = Describe("TestServer", func() {
Value: "Codes",
}
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
body, err := ioutil.ReadAll(resp.Body)
Ω(err).ShouldNot(HaveOccurred())
Ω(body).Should(MatchJSON(`{"Key": "Jim", "Value": "Codes"}`))
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(MatchJSON(`{"Key": "Jim", "Value": "Codes"}`))
})
It("should set the Content-Type header to application/json", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
})
})
@@ -980,16 +984,16 @@ var _ = Describe("TestServer", func() {
It("should preserve those headers", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
Expect(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
})
It("should set the Content-Type header to application/json", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"}))
})
Context("when setting the Content-Type explicitly", func() {
@@ -999,9 +1003,9 @@ var _ = Describe("TestServer", func() {
It("should use the Content-Type header that was explicitly set", func() {
resp, err = http.Post(s.URL()+"/foo", "application/json", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"}))
})
})
})
@@ -1026,21 +1030,21 @@ var _ = Describe("TestServer", func() {
It("should return the response", func() {
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.StatusCode).Should(Equal(http.StatusCreated))
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
var received protobuf.SimpleMessage
body, err := ioutil.ReadAll(resp.Body)
err = proto.Unmarshal(body, &received)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
})
It("should set the Content-Type header to application/x-protobuf", func() {
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/x-protobuf"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/x-protobuf"}))
})
})
@@ -1059,16 +1063,16 @@ var _ = Describe("TestServer", func() {
It("should preserve those headers", func() {
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
Expect(resp.Header["Stuff"]).Should(Equal([]string{"things"}))
})
It("should set the Content-Type header to application/x-protobuf", func() {
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/x-protobuf"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"application/x-protobuf"}))
})
Context("when setting the Content-Type explicitly", func() {
@@ -1078,9 +1082,9 @@ var _ = Describe("TestServer", func() {
It("should use the Content-Type header that was explicitly set", func() {
resp, err = http.Post(s.URL()+"/proto", "application/x-protobuf", nil)
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
Ω(resp.Header["Content-Type"]).Should(Equal([]string{"not-x-protobuf"}))
Expect(resp.Header["Content-Type"]).Should(Equal([]string{"not-x-protobuf"}))
})
})
})
+15
View File
@@ -0,0 +1,15 @@
module github.com/onsi/gomega
require (
github.com/fsnotify/fsnotify v1.4.7 // indirect
github.com/golang/protobuf v1.2.0
github.com/hpcloud/tail v1.0.0 // indirect
github.com/onsi/ginkgo v1.6.0
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f // indirect
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e // indirect
golang.org/x/text v0.3.0 // indirect
gopkg.in/fsnotify.v1 v1.4.7 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
gopkg.in/yaml.v2 v2.2.1
)
+24
View File
@@ -0,0 +1,24 @@
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+87 -19
View File
@@ -24,14 +24,15 @@ import (
"github.com/onsi/gomega/types"
)
const GOMEGA_VERSION = "1.2.0"
const GOMEGA_VERSION = "1.4.2"
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
var globalFailWrapper *types.GomegaFailWrapper
var defaultEventuallyTimeout = time.Second
var defaultEventuallyPollingInterval = 10 * time.Millisecond
@@ -41,26 +42,39 @@ var defaultConsistentlyPollingInterval = 10 * time.Millisecond
//RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails
//the fail handler passed into RegisterFailHandler is called.
func RegisterFailHandler(handler types.GomegaFailHandler) {
globalFailHandler = handler
if handler == nil {
globalFailWrapper = nil
return
}
globalFailWrapper = &types.GomegaFailWrapper{
Fail: handler,
TWithHelper: testingtsupport.EmptyTWithHelper{},
}
}
//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.
//
// func TestFarmHasCow(t *testing.T) {
// RegisterTestingT(t)
//Legacy Documentation:
//
// f := farm.New([]string{"Cow", "Horse"})
// Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
// }
//You'll need to call this at the top of each XUnit style test:
//
// func TestFarmHasCow(t *testing.T) {
// RegisterTestingT(t)
//
// f := farm.New([]string{"Cow", "Horse"})
// Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
// }
//
// Note that this *testing.T is registered *globally* by Gomega (this is why you don't have to
// 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))
RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail)
}
//InterceptGomegaHandlers runs a given callback and returns an array of
@@ -73,7 +87,7 @@ func RegisterTestingT(t types.GomegaTestingT) {
//This is most useful when testing custom matchers, but can also be used to check
//on a value using a Gomega assertion without causing a test failure.
func InterceptGomegaFailures(f func()) []string {
originalHandler := globalFailHandler
originalHandler := globalFailWrapper.Fail
failures := []string{}
RegisterFailHandler(func(message string, callerSkip ...int) {
failures = append(failures, message)
@@ -84,7 +98,7 @@ func InterceptGomegaFailures(f func()) []string {
}
//Ω wraps an actual value allowing assertions to be made on it:
// Ω("foo").Should(Equal("foo"))
// Ω("foo").Should(Equal("foo"))
//
//If Ω is passed more than one argument it will pass the *first* argument to the matcher.
//All subsequent arguments will be required to be nil/zero.
@@ -105,7 +119,7 @@ func Ω(actual interface{}, extra ...interface{}) GomegaAssertion {
}
//Expect wraps an actual value allowing assertions to be made on it:
// Expect("foo").To(Equal("foo"))
// Expect("foo").To(Equal("foo"))
//
//If Expect is passed more than one argument it will pass the *first* argument to the matcher.
//All subsequent arguments will be required to be nil/zero.
@@ -135,10 +149,10 @@ func Expect(actual interface{}, extra ...interface{}) GomegaAssertion {
//error message to refer to the calling line in the test (as opposed to the line in the helper function)
//set the first argument of `ExpectWithOffset` appropriately.
func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) GomegaAssertion {
if globalFailHandler == nil {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
return assertion.New(actual, globalFailHandler, offset, extra...)
return assertion.New(actual, globalFailWrapper, offset, extra...)
}
//Eventually wraps an actual value allowing assertions to be made on it.
@@ -185,7 +199,7 @@ func Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAsserti
//initial argument to indicate an offset in the call stack. This is useful when building helper
//functions that contain matchers. To learn more, read about `ExpectWithOffset`.
func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion {
if globalFailHandler == nil {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultEventuallyTimeout
@@ -196,7 +210,7 @@ func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailHandler, timeoutInterval, pollingInterval, offset)
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
//Consistently wraps an actual value allowing assertions to be made on it.
@@ -230,7 +244,7 @@ func Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAsser
//initial argument to indicate an offset in the call stack. This is useful when building helper
//functions that contain matchers. To learn more, read about `ExpectWithOffset`.
func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion {
if globalFailHandler == nil {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultConsistentlyDuration
@@ -241,7 +255,7 @@ func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interfa
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailHandler, timeoutInterval, pollingInterval, offset)
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
//Set the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses.
@@ -308,6 +322,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.BuildTestingTGomegaFailWrapper(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.BuildTestingTGomegaFailWrapper(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.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
func toDuration(input interface{}) time.Duration {
duration, ok := input.(time.Duration)
if ok {
+22 -8
View File
@@ -13,10 +13,14 @@ import (
//MatchAllElements succeeds if every element of a slice matches the element matcher it maps to
//through the id function, and every element matcher is matched.
// Expect([]string{"a", "b"}).To(MatchAllElements(idFn, matchers.Elements{
// "a": BeEqual("a"),
// "b": BeEqual("b"),
// })
// idFn := func(element interface{}) string {
// return fmt.Sprintf("%v", element)
// }
//
// Expect([]string{"a", "b"}).To(MatchAllElements(idFn, Elements{
// "a": Equal("a"),
// "b": Equal("b"),
// }))
func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher {
return &ElementsMatcher{
Identifier: identifier,
@@ -26,10 +30,20 @@ func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatc
//MatchElements succeeds if each element of a slice matches the element matcher it maps to
//through the id function. It can ignore extra elements and/or missing elements.
// Expect([]string{"a", "c"}).To(MatchElements(idFn, IgnoreMissing|IgnoreExtra, matchers.Elements{
// "a": BeEqual("a")
// "b": BeEqual("b"),
// })
// idFn := func(element interface{}) string {
// return fmt.Sprintf("%v", element)
// }
//
// Expect([]string{"a", "b", "c"}).To(MatchElements(idFn, IgnoreExtras, Elements{
// "a": Equal("a"),
// "b": Equal("b"),
// }))
// Expect([]string{"a", "c"}).To(MatchElements(idFn, IgnoreMissing, Elements{
// "a": Equal("a"),
// "b": Equal("b"),
// "c": Equal("c"),
// "d": Equal("d"),
// }))
func MatchElements(identifier Identifier, options Options, elements Elements) types.GomegaMatcher {
return &ElementsMatcher{
Identifier: identifier,
+45 -45
View File
@@ -19,22 +19,22 @@ var _ = Describe("Slice", func() {
"b": Equal("b"),
"a": Equal("a"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(missingElements).ShouldNot(m, "should fail with missing elements")
Ω(extraElements).ShouldNot(m, "should fail with extra elements")
Ω(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Ω(nils).ShouldNot(m, "should fail with an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(missingElements).ShouldNot(m, "should fail with missing elements")
Expect(extraElements).ShouldNot(m, "should fail with extra elements")
Expect(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Expect(nils).ShouldNot(m, "should fail with an uninitialized slice")
m = MatchAllElements(id, Elements{
"a": Equal("a"),
"b": Equal("fail"),
})
Ω(allElements).ShouldNot(m, "should run nested matchers")
Expect(allElements).ShouldNot(m, "should run nested matchers")
m = MatchAllElements(id, Elements{})
Ω(empty).Should(m, "should handle empty slices")
Ω(allElements).ShouldNot(m, "should handle only empty slices")
Ω(nils).Should(m, "should handle nil slices")
Expect(empty).Should(m, "should handle empty slices")
Expect(allElements).ShouldNot(m, "should handle only empty slices")
Expect(nils).Should(m, "should handle nil slices")
})
It("should ignore extra elements", func() {
@@ -42,11 +42,11 @@ var _ = Describe("Slice", func() {
"b": Equal("b"),
"a": Equal("a"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(missingElements).ShouldNot(m, "should fail with missing elements")
Ω(extraElements).Should(m, "should ignore extra elements")
Ω(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Ω(nils).ShouldNot(m, "should fail with an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(missingElements).ShouldNot(m, "should fail with missing elements")
Expect(extraElements).Should(m, "should ignore extra elements")
Expect(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Expect(nils).ShouldNot(m, "should fail with an uninitialized slice")
})
It("should ignore missing elements", func() {
@@ -54,11 +54,11 @@ var _ = Describe("Slice", func() {
"a": Equal("a"),
"b": Equal("b"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(missingElements).Should(m, "should ignore missing elements")
Ω(extraElements).ShouldNot(m, "should fail with extra elements")
Ω(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Ω(nils).Should(m, "should ignore an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(missingElements).Should(m, "should ignore missing elements")
Expect(extraElements).ShouldNot(m, "should fail with extra elements")
Expect(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Expect(nils).Should(m, "should ignore an uninitialized slice")
})
It("should ignore missing and extra elements", func() {
@@ -66,17 +66,17 @@ var _ = Describe("Slice", func() {
"a": Equal("a"),
"b": Equal("b"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(missingElements).Should(m, "should ignore missing elements")
Ω(extraElements).Should(m, "should ignore extra elements")
Ω(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Ω(nils).Should(m, "should ignore an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(missingElements).Should(m, "should ignore missing elements")
Expect(extraElements).Should(m, "should ignore extra elements")
Expect(duplicateElements).ShouldNot(m, "should fail with duplicate elements")
Expect(nils).Should(m, "should ignore an uninitialized slice")
m = MatchElements(id, IgnoreExtras|IgnoreMissing, Elements{
"a": Equal("a"),
"b": Equal("fail"),
})
Ω(allElements).ShouldNot(m, "should run nested matchers")
Expect(allElements).ShouldNot(m, "should run nested matchers")
})
Context("with elements that share a key", func() {
@@ -94,11 +94,11 @@ var _ = Describe("Slice", func() {
"a": ContainSubstring("1"),
"b": ContainSubstring("1"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Ω(extraElements).ShouldNot(m, "should reject with extra keys")
Ω(missingElements).ShouldNot(m, "should reject with missing keys")
Ω(nils).ShouldNot(m, "should fail with an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Expect(extraElements).ShouldNot(m, "should reject with extra keys")
Expect(missingElements).ShouldNot(m, "should reject with missing keys")
Expect(nils).ShouldNot(m, "should fail with an uninitialized slice")
})
It("should ignore missing", func() {
@@ -106,11 +106,11 @@ var _ = Describe("Slice", func() {
"a": ContainSubstring("1"),
"b": ContainSubstring("1"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Ω(extraElements).ShouldNot(m, "should reject with extra keys")
Ω(missingElements).Should(m, "should allow missing keys")
Ω(nils).Should(m, "should allow an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Expect(extraElements).ShouldNot(m, "should reject with extra keys")
Expect(missingElements).Should(m, "should allow missing keys")
Expect(nils).Should(m, "should allow an uninitialized slice")
})
It("should ignore extras", func() {
@@ -118,11 +118,11 @@ var _ = Describe("Slice", func() {
"a": ContainSubstring("1"),
"b": ContainSubstring("1"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Ω(extraElements).Should(m, "should allow extra keys")
Ω(missingElements).ShouldNot(m, "should reject missing keys")
Ω(nils).ShouldNot(m, "should reject an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Expect(extraElements).Should(m, "should allow extra keys")
Expect(missingElements).ShouldNot(m, "should reject missing keys")
Expect(nils).ShouldNot(m, "should reject an uninitialized slice")
})
It("should ignore missing and extras", func() {
@@ -130,11 +130,11 @@ var _ = Describe("Slice", func() {
"a": ContainSubstring("1"),
"b": ContainSubstring("1"),
})
Ω(allElements).Should(m, "should match all elements")
Ω(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Ω(extraElements).Should(m, "should allow extra keys")
Ω(missingElements).Should(m, "should allow missing keys")
Ω(nils).Should(m, "should allow an uninitialized slice")
Expect(allElements).Should(m, "should match all elements")
Expect(includingBadElements).ShouldNot(m, "should reject if a member fails the matcher")
Expect(extraElements).Should(m, "should allow extra keys")
Expect(missingElements).Should(m, "should allow missing keys")
Expect(nils).Should(m, "should allow an uninitialized slice")
})
})
})
+35 -8
View File
@@ -14,10 +14,21 @@ import (
//MatchAllFields succeeds if every field of a struct matches the field matcher associated with
//it, and every element matcher is matched.
// Expect([]string{"a", "b"}).To(MatchAllFields(gstruct.Fields{
// "a": BeEqual("a"),
// "b": BeEqual("b"),
// })
// actual := struct{
// A int
// B []bool
// C string
// }{
// A: 5,
// B: []bool{true, false},
// C: "foo",
// }
//
// Expect(actual).To(MatchAllFields(Fields{
// "A": Equal(5),
// "B": ConsistOf(true, false),
// "C": Equal("foo"),
// }))
func MatchAllFields(fields Fields) types.GomegaMatcher {
return &FieldsMatcher{
Fields: fields,
@@ -26,10 +37,26 @@ func MatchAllFields(fields Fields) types.GomegaMatcher {
//MatchFields succeeds if each element of a struct matches the field matcher associated with
//it. It can ignore extra fields and/or missing fields.
// Expect([]string{"a", "c"}).To(MatchFields(IgnoreMissing|IgnoreExtra, gstruct.Fields{
// "a": BeEqual("a")
// "b": BeEqual("b"),
// })
// actual := struct{
// A int
// B []bool
// C string
// }{
// A: 5,
// B: []bool{true, false},
// C: "foo",
// }
//
// Expect(actual).To(MatchFields(IgnoreExtras, Fields{
// "A": Equal(5),
// "B": ConsistOf(true, false),
// }))
// Expect(actual).To(MatchFields(IgnoreMissing, Fields{
// "A": Equal(5),
// "B": ConsistOf(true, false),
// "C": Equal("foo"),
// "D": Equal("extra"),
// }))
func MatchFields(options Options, fields Fields) types.GomegaMatcher {
return &FieldsMatcher{
Fields: fields,
+20 -20
View File
@@ -17,22 +17,22 @@ var _ = Describe("Struct", func() {
"B": Equal("b"),
"A": Equal("a"),
})
Ω(allFields).Should(m, "should match all fields")
Ω(missingFields).ShouldNot(m, "should fail with missing fields")
Ω(extraFields).ShouldNot(m, "should fail with extra fields")
Ω(emptyFields).ShouldNot(m, "should fail with empty fields")
Expect(allFields).Should(m, "should match all fields")
Expect(missingFields).ShouldNot(m, "should fail with missing fields")
Expect(extraFields).ShouldNot(m, "should fail with extra fields")
Expect(emptyFields).ShouldNot(m, "should fail with empty fields")
m = MatchAllFields(Fields{
"A": Equal("a"),
"B": Equal("fail"),
})
Ω(allFields).ShouldNot(m, "should run nested matchers")
Expect(allFields).ShouldNot(m, "should run nested matchers")
})
It("should handle empty structs", func() {
m := MatchAllFields(Fields{})
Ω(struct{}{}).Should(m, "should handle empty structs")
Ω(allFields).ShouldNot(m, "should fail with extra fields")
Expect(struct{}{}).Should(m, "should handle empty structs")
Expect(allFields).ShouldNot(m, "should fail with extra fields")
})
It("should ignore missing fields", func() {
@@ -40,10 +40,10 @@ var _ = Describe("Struct", func() {
"B": Equal("b"),
"A": Equal("a"),
})
Ω(allFields).Should(m, "should match all fields")
Ω(missingFields).Should(m, "should ignore missing fields")
Ω(extraFields).ShouldNot(m, "should fail with extra fields")
Ω(emptyFields).ShouldNot(m, "should fail with empty fields")
Expect(allFields).Should(m, "should match all fields")
Expect(missingFields).Should(m, "should ignore missing fields")
Expect(extraFields).ShouldNot(m, "should fail with extra fields")
Expect(emptyFields).ShouldNot(m, "should fail with empty fields")
})
It("should ignore extra fields", func() {
@@ -51,10 +51,10 @@ var _ = Describe("Struct", func() {
"B": Equal("b"),
"A": Equal("a"),
})
Ω(allFields).Should(m, "should match all fields")
Ω(missingFields).ShouldNot(m, "should fail with missing fields")
Ω(extraFields).Should(m, "should ignore extra fields")
Ω(emptyFields).ShouldNot(m, "should fail with empty fields")
Expect(allFields).Should(m, "should match all fields")
Expect(missingFields).ShouldNot(m, "should fail with missing fields")
Expect(extraFields).Should(m, "should ignore extra fields")
Expect(emptyFields).ShouldNot(m, "should fail with empty fields")
})
It("should ignore missing and extra fields", func() {
@@ -62,15 +62,15 @@ var _ = Describe("Struct", func() {
"B": Equal("b"),
"A": Equal("a"),
})
Ω(allFields).Should(m, "should match all fields")
Ω(missingFields).Should(m, "should ignore missing fields")
Ω(extraFields).Should(m, "should ignore extra fields")
Ω(emptyFields).ShouldNot(m, "should fail with empty fields")
Expect(allFields).Should(m, "should match all fields")
Expect(missingFields).Should(m, "should ignore missing fields")
Expect(extraFields).Should(m, "should ignore extra fields")
Expect(emptyFields).ShouldNot(m, "should fail with empty fields")
m = MatchFields(IgnoreMissing|IgnoreExtras, Fields{
"A": Equal("a"),
"B": Equal("fail"),
})
Ω(allFields).ShouldNot(m, "should run nested matchers")
Expect(allFields).ShouldNot(m, "should run nested matchers")
})
})
+8 -8
View File
@@ -8,16 +8,16 @@ import (
var _ = Describe("Ignore", func() {
It("should always succeed", func() {
Ω(nil).Should(Ignore())
Ω(struct{}{}).Should(Ignore())
Ω(0).Should(Ignore())
Ω(false).Should(Ignore())
Expect(nil).Should(Ignore())
Expect(struct{}{}).Should(Ignore())
Expect(0).Should(Ignore())
Expect(false).Should(Ignore())
})
It("should always fail", func() {
Ω(nil).ShouldNot(Reject())
Ω(struct{}{}).ShouldNot(Reject())
Ω(1).ShouldNot(Reject())
Ω(true).ShouldNot(Reject())
Expect(nil).ShouldNot(Reject())
Expect(struct{}{}).ShouldNot(Reject())
Expect(1).ShouldNot(Reject())
Expect(true).ShouldNot(Reject())
})
})
+6 -6
View File
@@ -9,25 +9,25 @@ import (
var _ = Describe("PointTo", func() {
It("should fail when passed nil", func() {
var p *struct{}
Ω(p).Should(BeNil())
Expect(p).Should(BeNil())
})
It("should succeed when passed non-nil pointer", func() {
var s struct{}
Ω(&s).Should(PointTo(Ignore()))
Expect(&s).Should(PointTo(Ignore()))
})
It("should unwrap the pointee value", func() {
i := 1
Ω(&i).Should(PointTo(Equal(1)))
Ω(&i).ShouldNot(PointTo(Equal(2)))
Expect(&i).Should(PointTo(Equal(1)))
Expect(&i).ShouldNot(PointTo(Equal(2)))
})
It("should work with nested pointers", func() {
i := 1
ip := &i
ipp := &ip
Ω(ipp).Should(PointTo(PointTo(Equal(1))))
Ω(ipp).ShouldNot(PointTo(PointTo(Equal(2))))
Expect(ipp).Should(PointTo(PointTo(Equal(1))))
Expect(ipp).ShouldNot(PointTo(PointTo(Equal(2))))
})
})
+13 -6
View File
@@ -9,37 +9,42 @@ import (
type Assertion struct {
actualInput interface{}
fail types.GomegaFailHandler
failWrapper *types.GomegaFailWrapper
offset int
extra []interface{}
}
func New(actualInput interface{}, fail types.GomegaFailHandler, offset int, extra ...interface{}) *Assertion {
func New(actualInput interface{}, failWrapper *types.GomegaFailWrapper, offset int, extra ...interface{}) *Assertion {
return &Assertion{
actualInput: actualInput,
fail: fail,
failWrapper: failWrapper,
offset: offset,
extra: extra,
}
}
func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
}
func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
}
func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
}
func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
}
func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
}
@@ -55,8 +60,9 @@ func (assertion *Assertion) buildDescription(optionalDescription ...interface{})
func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool {
matches, err := matcher.Match(assertion.actualInput)
description := assertion.buildDescription(optionalDescription...)
assertion.failWrapper.TWithHelper.Helper()
if err != nil {
assertion.fail(description+err.Error(), 2+assertion.offset)
assertion.failWrapper.Fail(description+err.Error(), 2+assertion.offset)
return false
}
if matches != desiredMatch {
@@ -66,7 +72,7 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool
} else {
message = matcher.NegatedFailureMessage(assertion.actualInput)
}
assertion.fail(description+message, 2+assertion.offset)
assertion.failWrapper.Fail(description+message, 2+assertion.offset)
return false
}
@@ -80,7 +86,8 @@ func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool {
}
description := assertion.buildDescription(optionalDescription...)
assertion.fail(description+message, 2+assertion.offset)
assertion.failWrapper.TWithHelper.Helper()
assertion.failWrapper.Fail(description+message, 2+assertion.offset)
return false
}
+60 -54
View File
@@ -3,10 +3,13 @@ package assertion_test
import (
"errors"
"github.com/onsi/gomega/internal/testingtsupport"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/internal/assertion"
"github.com/onsi/gomega/internal/fakematcher"
"github.com/onsi/gomega/types"
)
var _ = Describe("Assertion", func() {
@@ -19,45 +22,48 @@ var _ = Describe("Assertion", func() {
input := "The thing I'm testing"
var fakeFailHandler = func(message string, callerSkip ...int) {
failureMessage = message
if len(callerSkip) == 1 {
failureCallerSkip = callerSkip[0]
}
var fakeFailWrapper = &types.GomegaFailWrapper{
Fail: func(message string, callerSkip ...int) {
failureMessage = message
if len(callerSkip) == 1 {
failureCallerSkip = callerSkip[0]
}
},
TWithHelper: testingtsupport.EmptyTWithHelper{},
}
BeforeEach(func() {
matcher = &fakematcher.FakeMatcher{}
failureMessage = ""
failureCallerSkip = 0
a = New(input, fakeFailHandler, 1)
a = New(input, fakeFailWrapper, 1)
})
Context("when called", func() {
It("should pass the provided input value to the matcher", func() {
a.Should(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.ShouldNot(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.To(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.ToNot(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(matcher.ReceivedActual).Should(Equal(input))
matcher.ReceivedActual = ""
a.NotTo(matcher)
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(matcher.ReceivedActual).Should(Equal(input))
})
})
@@ -70,23 +76,23 @@ var _ = Describe("Assertion", func() {
Context("and a positive assertion is being made", func() {
It("should not call the failure callback", func() {
a.Should(matcher)
Ω(failureMessage).Should(Equal(""))
Expect(failureMessage).Should(Equal(""))
})
It("should be true", func() {
Ω(a.Should(matcher)).Should(BeTrue())
Expect(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))
Expect(failureMessage).Should(Equal("negative: The thing I'm testing"))
Expect(failureCallerSkip).Should(Equal(3))
})
It("should be false", func() {
Ω(a.ShouldNot(matcher)).Should(BeFalse())
Expect(a.ShouldNot(matcher)).Should(BeFalse())
})
})
})
@@ -100,23 +106,23 @@ var _ = Describe("Assertion", func() {
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))
Expect(failureMessage).Should(Equal("positive: The thing I'm testing"))
Expect(failureCallerSkip).Should(Equal(3))
})
It("should be false", func() {
Ω(a.Should(matcher)).Should(BeFalse())
Expect(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(""))
Expect(failureMessage).Should(Equal(""))
})
It("should be true", func() {
Ω(a.ShouldNot(matcher)).Should(BeTrue())
Expect(a.ShouldNot(matcher)).Should(BeTrue())
})
})
})
@@ -130,16 +136,16 @@ var _ = Describe("Assertion", func() {
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))
Expect(failureMessage).Should(Equal("A description\npositive: The thing I'm testing"))
Expect(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))
Expect(failureMessage).Should(Equal("A description of [3]\npositive: The thing I'm testing"))
Expect(failureCallerSkip).Should(Equal(3))
})
})
})
@@ -153,8 +159,8 @@ var _ = Describe("Assertion", func() {
It("should call the failure callback", func() {
matcher.MatchesToReturn = true
a.Should(matcher)
Ω(failureMessage).Should(Equal("Kaboom!"))
Ω(failureCallerSkip).Should(Equal(3))
Expect(failureMessage).Should(Equal("Kaboom!"))
Expect(failureCallerSkip).Should(Equal(3))
})
})
@@ -162,20 +168,20 @@ var _ = Describe("Assertion", func() {
It("should call the failure callback", func() {
matcher.MatchesToReturn = false
a.ShouldNot(matcher)
Ω(failureMessage).Should(Equal("Kaboom!"))
Ω(failureCallerSkip).Should(Equal(3))
Expect(failureMessage).Should(Equal("Kaboom!"))
Expect(failureCallerSkip).Should(Equal(3))
})
})
It("should always be false", func() {
Ω(a.Should(matcher)).Should(BeFalse())
Ω(a.ShouldNot(matcher)).Should(BeFalse())
Expect(a.Should(matcher)).Should(BeFalse())
Expect(a.ShouldNot(matcher)).Should(BeFalse())
})
})
Context("when there are extra parameters", func() {
It("(a simple example)", func() {
Ω(func() (string, int, error) {
Expect(func() (string, int, error) {
return "foo", 0, nil
}()).Should(Equal("foo"))
})
@@ -186,13 +192,13 @@ var _ = Describe("Assertion", func() {
matcher.ErrToReturn = nil
var typedNil []string
a = New(input, fakeFailHandler, 1, 0, nil, typedNil)
a = New(input, fakeFailWrapper, 1, 0, nil, typedNil)
result := a.Should(matcher)
Ω(result).Should(BeTrue())
Ω(matcher.ReceivedActual).Should(Equal(input))
Expect(result).Should(BeTrue())
Expect(matcher.ReceivedActual).Should(Equal(input))
Ω(failureMessage).Should(BeZero())
Expect(failureMessage).Should(BeZero())
})
})
@@ -201,36 +207,36 @@ var _ = Describe("Assertion", func() {
matcher.MatchesToReturn = false
matcher.ErrToReturn = nil
a = New(input, fakeFailHandler, 1, errors.New("foo"))
a = New(input, fakeFailWrapper, 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"))
Expect(result).Should(BeFalse())
Expect(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called")
Expect(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 1)
a = New(input, fakeFailWrapper, 1, nil, 1)
result = a.ShouldNot(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("1"))
Expect(result).Should(BeFalse())
Expect(failureMessage).Should(ContainSubstring("1"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"})
result = a.To(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
Expect(result).Should(BeFalse())
Expect(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"})
result = a.ToNot(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
Expect(result).Should(BeFalse())
Expect(failureMessage).Should(ContainSubstring("foo"))
failureMessage = ""
a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"})
a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"})
result = a.NotTo(matcher)
Ω(result).Should(BeFalse())
Ω(failureMessage).Should(ContainSubstring("foo"))
Ω(failureCallerSkip).Should(Equal(3))
Expect(result).Should(BeFalse())
Expect(failureMessage).Should(ContainSubstring("foo"))
Expect(failureCallerSkip).Should(Equal(3))
})
})
})
@@ -246,7 +252,7 @@ var _ = Describe("Assertion", func() {
}()
RegisterFailHandler(nil)
Ω(true).Should(BeTrue())
Expect(true).Should(BeTrue())
})
})
})
+9 -4
View File
@@ -22,11 +22,11 @@ type AsyncAssertion struct {
actualInput interface{}
timeoutInterval time.Duration
pollingInterval time.Duration
fail types.GomegaFailHandler
failWrapper *types.GomegaFailWrapper
offset int
}
func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.GomegaFailHandler, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion {
func New(asyncType AsyncAssertionType, actualInput interface{}, failWrapper *types.GomegaFailWrapper, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion {
actualType := reflect.TypeOf(actualInput)
if actualType.Kind() == reflect.Func {
if actualType.NumIn() != 0 || actualType.NumOut() == 0 {
@@ -37,7 +37,7 @@ func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.Gomeg
return &AsyncAssertion{
asyncType: asyncType,
actualInput: actualInput,
fail: fail,
failWrapper: failWrapper,
timeoutInterval: timeoutInterval,
pollingInterval: pollingInterval,
offset: offset,
@@ -45,10 +45,12 @@ func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.Gomeg
}
func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.match(matcher, true, optionalDescription...)
}
func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
assertion.failWrapper.TWithHelper.Helper()
return assertion.match(matcher, false, optionalDescription...)
}
@@ -110,6 +112,8 @@ func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch
matches, err = matcher.Match(value)
}
assertion.failWrapper.TWithHelper.Helper()
fail := func(preamble string) {
errMsg := ""
message := ""
@@ -122,7 +126,8 @@ func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch
message = matcher.NegatedFailureMessage(value)
}
}
assertion.fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset)
assertion.failWrapper.TWithHelper.Helper()
assertion.failWrapper.Fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset)
}
if assertion.asyncType == AsyncAssertionTypeEventually {
@@ -4,9 +4,12 @@ import (
"errors"
"time"
"github.com/onsi/gomega/internal/testingtsupport"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/internal/asyncassertion"
"github.com/onsi/gomega/types"
)
var _ = Describe("Async Assertion", func() {
@@ -15,9 +18,12 @@ var _ = Describe("Async Assertion", func() {
callerSkip int
)
var fakeFailHandler = func(message string, skip ...int) {
failureMessage = message
callerSkip = skip[0]
var fakeFailWrapper = &types.GomegaFailWrapper{
Fail: func(message string, skip ...int) {
failureMessage = message
callerSkip = skip[0]
},
TWithHelper: testingtsupport.EmptyTWithHelper{},
}
BeforeEach(func() {
@@ -32,10 +38,10 @@ var _ = Describe("Async Assertion", func() {
a := New(AsyncAssertionTypeEventually, func() int {
counter++
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.Should(BeNumerically("==", 5))
Ω(failureMessage).Should(BeZero())
Expect(failureMessage).Should(BeZero())
})
It("should continue when the matcher errors", func() {
@@ -46,13 +52,13 @@ var _ = Describe("Async Assertion", func() {
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)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("Timed out after"))
Expect(failureMessage).Should(ContainSubstring("My description 2"))
Expect(callerSkip).Should(Equal(4))
})
It("should be able to timeout", func() {
@@ -60,16 +66,16 @@ var _ = Describe("Async Assertion", func() {
a := New(AsyncAssertionTypeEventually, func() int {
counter++
return counter
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, 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))
Expect(counter).Should(BeNumerically(">", 8))
Expect(counter).Should(BeNumerically("<=", 10))
Expect(failureMessage).Should(ContainSubstring("Timed out after"))
Expect(failureMessage).Should(MatchRegexp(`\<int\>: \d`), "Should pass the correct value to the matcher message formatter.")
Expect(failureMessage).Should(ContainSubstring("My description 2"))
Expect(callerSkip).Should(Equal(4))
})
})
@@ -79,38 +85,38 @@ var _ = Describe("Async Assertion", func() {
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)
}, fakeFailWrapper, 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())
Expect(counter).Should(Equal(3))
Expect(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)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("Timed out after"))
Expect(failureMessage).Should(ContainSubstring("Error:"))
Expect(failureMessage).Should(ContainSubstring("My description 2"))
Expect(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)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("Timed out after"))
Expect(failureMessage).Should(ContainSubstring("<int>: 0"), "Should pass the correct value to the matcher message formatter.")
Expect(failureMessage).Should(ContainSubstring("My description 2"))
Expect(callerSkip).Should(Equal(4))
})
})
@@ -128,13 +134,13 @@ var _ = Describe("Async Assertion", func() {
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)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("Timed out after"))
Expect(failureMessage).Should(ContainSubstring("Error:"))
Expect(failureMessage).Should(ContainSubstring("bam"))
Expect(callerSkip).Should(Equal(4))
})
})
@@ -164,12 +170,12 @@ var _ = Describe("Async Assertion", func() {
a := New(AsyncAssertionTypeConsistently, func() string {
calls++
return "foo"
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, 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())
Expect(calls).Should(BeNumerically(">", 8))
Expect(calls).Should(BeNumerically("<=", 10))
Expect(failureMessage).Should(BeZero())
})
})
@@ -182,11 +188,11 @@ var _ = Describe("Async Assertion", func() {
return "bar"
}
return "foo"
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("to equal"))
Expect(callerSkip).Should(Equal(4))
})
})
@@ -199,11 +205,11 @@ var _ = Describe("Async Assertion", func() {
return 3
}
return []int{1, 2, 3}
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("HaveLen matcher expects"))
Expect(callerSkip).Should(Equal(4))
})
})
})
@@ -212,10 +218,10 @@ var _ = Describe("Async Assertion", 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 := New(AsyncAssertionTypeConsistently, c, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a.ShouldNot(Receive())
Ω(failureMessage).Should(BeZero())
Expect(failureMessage).Should(BeZero())
})
})
@@ -227,10 +233,10 @@ var _ = Describe("Async Assertion", func() {
c <- true
}()
a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
a := New(AsyncAssertionTypeConsistently, c, fakeFailWrapper, 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"))
Expect(failureMessage).Should(ContainSubstring("not to receive anything"))
})
})
@@ -240,11 +246,11 @@ var _ = Describe("Async Assertion", func() {
a := New(AsyncAssertionTypeConsistently, func() interface{} {
calls++
return calls
}, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("not to be >"))
Expect(callerSkip).Should(Equal(4))
})
})
})
@@ -263,12 +269,12 @@ var _ = Describe("Async Assertion", func() {
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)
}, fakeFailWrapper, 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))
Expect(failureMessage).Should(ContainSubstring("Error:"))
Expect(failureMessage).Should(ContainSubstring("bam"))
Expect(callerSkip).Should(Equal(4))
})
})
@@ -291,20 +297,20 @@ var _ = Describe("Async Assertion", func() {
Context("when passed a function with the wrong # or arguments & returns", func() {
It("should panic", func() {
Ω(func() {
New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1)
Expect(func() {
New(AsyncAssertionTypeEventually, func() {}, fakeFailWrapper, 0, 0, 1)
}).Should(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1)
Expect(func() {
New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailWrapper, 0, 0, 1)
}).Should(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1)
Expect(func() {
New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailWrapper, 0, 0, 1)
}).ShouldNot(Panic())
Ω(func() {
New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1)
Expect(func() {
New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailWrapper, 0, 0, 1)
}).ShouldNot(Panic())
})
})
@@ -319,9 +325,9 @@ var _ = Describe("Async Assertion", func() {
failures := InterceptGomegaFailures(func() {
Eventually(c, 0.1).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond))
Expect(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
@@ -336,9 +342,9 @@ var _ = Describe("Async Assertion", func() {
return c
}, 0.1).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond))
Expect(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(failures).Should(HaveLen(1))
})
})
})
+32 -12
View File
@@ -8,30 +8,50 @@ import (
"github.com/onsi/gomega/types"
)
var StackTracePruneRE = regexp.MustCompile(`\/gomega\/|\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`)
type EmptyTWithHelper struct{}
func (e EmptyTWithHelper) Helper() {}
type gomegaTestingT interface {
Fatalf(format string, args ...interface{})
}
func BuildTestingTGomegaFailHandler(t gomegaTestingT) types.GomegaFailHandler {
return func(message string, callerSkip ...int) {
skip := 1
if len(callerSkip) > 0 {
skip = callerSkip[0]
func BuildTestingTGomegaFailWrapper(t gomegaTestingT) *types.GomegaFailWrapper {
tWithHelper, hasHelper := t.(types.TWithHelper)
if !hasHelper {
tWithHelper = EmptyTWithHelper{}
}
fail := func(message string, callerSkip ...int) {
if hasHelper {
tWithHelper.Helper()
t.Fatalf("\n%s", message)
} else {
skip := 2
if len(callerSkip) > 0 {
skip += callerSkip[0]
}
stackTrace := pruneStack(string(debug.Stack()), skip)
t.Fatalf("\n%s\n%s\n", stackTrace, message)
}
stackTrace := pruneStack(string(debug.Stack()), skip)
t.Fatalf("\n%s\n%s", stackTrace, message)
}
return &types.GomegaFailWrapper{
Fail: fail,
TWithHelper: tWithHelper,
}
}
func pruneStack(fullStackTrace string, skip int) string {
stack := strings.Split(fullStackTrace, "\n")
if len(stack) > 2*(skip+1) {
stack = stack[2*(skip+1):]
stack := strings.Split(fullStackTrace, "\n")[1:]
if len(stack) > 2*skip {
stack = stack[2*skip:]
}
prunedStack := []string{}
re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`)
for i := 0; i < len(stack)/2; i++ {
if !re.Match([]byte(stack[i*2])) {
if !StackTracePruneRE.Match([]byte(stack[i*2])) {
prunedStack = append(prunedStack, stack[i*2])
prunedStack = append(prunedStack, stack[i*2+1])
}
@@ -1,8 +1,14 @@
package testingtsupport_test
import (
"regexp"
"time"
"github.com/onsi/gomega/internal/testingtsupport"
. "github.com/onsi/gomega"
"fmt"
"testing"
)
@@ -10,3 +16,77 @@ func TestTestingT(t *testing.T) {
RegisterTestingT(t)
Ω(true).Should(BeTrue())
}
type FakeTWithHelper struct {
LastFatal string
}
func (f *FakeTWithHelper) Fatalf(format string, args ...interface{}) {
f.LastFatal = fmt.Sprintf(format, args...)
}
func TestGomegaWithTWithoutHelper(t *testing.T) {
g := NewGomegaWithT(t)
testingtsupport.StackTracePruneRE = regexp.MustCompile(`\/ginkgo\/`)
f := &FakeTWithHelper{}
testG := NewGomegaWithT(f)
testG.Expect("foo").To(Equal("foo"))
g.Expect(f.LastFatal).To(BeZero())
testG.Expect("foo").To(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo"))
g.Expect(f.LastFatal).To(ContainSubstring("testingtsupport_test"), "It should include a stacktrace")
testG.Eventually("foo2", time.Millisecond).Should(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo2"))
testG.Consistently("foo3", time.Millisecond).Should(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo3"))
}
type FakeTWithoutHelper struct {
LastFatal string
HelperCount int
}
func (f *FakeTWithoutHelper) Fatalf(format string, args ...interface{}) {
f.LastFatal = fmt.Sprintf(format, args...)
}
func (f *FakeTWithoutHelper) Helper() {
f.HelperCount += 1
}
func (f *FakeTWithoutHelper) ResetHelper() {
f.HelperCount = 0
}
func TestGomegaWithTWithHelper(t *testing.T) {
g := NewGomegaWithT(t)
f := &FakeTWithoutHelper{}
testG := NewGomegaWithT(f)
testG.Expect("foo").To(Equal("foo"))
g.Expect(f.LastFatal).To(BeZero())
g.Expect(f.HelperCount).To(BeNumerically(">", 0))
f.ResetHelper()
testG.Expect("foo").To(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo"))
g.Expect(f.LastFatal).NotTo(ContainSubstring("testingtsupport_test"), "It should _not_ include a stacktrace")
g.Expect(f.HelperCount).To(BeNumerically(">", 0))
f.ResetHelper()
testG.Eventually("foo2", time.Millisecond).Should(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo2"))
g.Expect(f.HelperCount).To(BeNumerically(">", 0))
f.ResetHelper()
testG.Consistently("foo3", time.Millisecond).Should(Equal("bar"))
g.Expect(f.LastFatal).To(ContainSubstring("<string>: foo3"))
g.Expect(f.HelperCount).To(BeNumerically(">", 0))
}
+38 -38
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...)
}
+5 -1
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)
@@ -9,22 +9,38 @@ import (
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 }{}))
Expect(0).Should(BeAssignableToTypeOf(0))
Expect(5).Should(BeAssignableToTypeOf(-1))
Expect("foo").Should(BeAssignableToTypeOf("bar"))
Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
Ω(0).ShouldNot(BeAssignableToTypeOf("bar"))
Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{}))
Ω("foo").ShouldNot(BeAssignableToTypeOf(42))
Expect(0).ShouldNot(BeAssignableToTypeOf("bar"))
Expect(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{}))
Expect("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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
Context("When actual is nil and expected is not nil", func() {
It("should return false without error", func() {
success, err := (&AssignableToTypeOfMatcher{Expected: 17}).Match(nil)
Expect(success).Should(BeFalse())
Expect(err).ShouldNot(HaveOccurred())
})
})
Context("When actual is not nil and expected is nil", func() {
It("should error", func() {
success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(17)
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
})
+14
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] }
+9 -9
View File
@@ -12,29 +12,29 @@ import (
var _ = Describe("BeADirectoryMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeADirectory())
Expect("/dne/test").ShouldNot(BeADirectory())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).ShouldNot(BeADirectory())
Expect(tmpFile.Name()).ShouldNot(BeADirectory())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).Should(BeADirectory())
Expect(tmpDir).Should(BeADirectory())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeADirectoryMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeADirectoryMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+9 -9
View File
@@ -12,29 +12,29 @@ import (
var _ = Describe("BeARegularFileMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeARegularFile())
Expect("/dne/test").ShouldNot(BeARegularFile())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).Should(BeARegularFile())
Expect(tmpFile.Name()).Should(BeARegularFile())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).ShouldNot(BeARegularFile())
Expect(tmpDir).ShouldNot(BeARegularFile())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeARegularFileMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeARegularFileMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+9 -9
View File
@@ -12,29 +12,29 @@ import (
var _ = Describe("BeAnExistingFileMatcher", func() {
Context("when passed a string", func() {
It("should do the right thing", func() {
Ω("/dne/test").ShouldNot(BeAnExistingFile())
Expect("/dne/test").ShouldNot(BeAnExistingFile())
tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
Ω(tmpFile.Name()).Should(BeAnExistingFile())
Expect(tmpFile.Name()).Should(BeAnExistingFile())
tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir")
Ω(err).ShouldNot(HaveOccurred())
Expect(err).ShouldNot(HaveOccurred())
defer os.Remove(tmpDir)
Ω(tmpDir).Should(BeAnExistingFile())
Expect(tmpDir).Should(BeAnExistingFile())
})
})
Context("when passed something else", func() {
It("should error", func() {
success, err := (&BeAnExistingFileMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeAnExistingFileMatcher{}).Match(true)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeClosedMatcher struct {
+14 -14
View File
@@ -10,20 +10,20 @@ var _ = Describe("BeClosedMatcher", func() {
Context("when passed a channel", func() {
It("should do the right thing", func() {
openChannel := make(chan bool)
Ω(openChannel).ShouldNot(BeClosed())
Expect(openChannel).ShouldNot(BeClosed())
var openReaderChannel <-chan bool
openReaderChannel = openChannel
Ω(openReaderChannel).ShouldNot(BeClosed())
Expect(openReaderChannel).ShouldNot(BeClosed())
closedChannel := make(chan bool)
close(closedChannel)
Ω(closedChannel).Should(BeClosed())
Expect(closedChannel).Should(BeClosed())
var closedReaderChannel <-chan bool
closedReaderChannel = closedChannel
Ω(closedReaderChannel).Should(BeClosed())
Expect(closedReaderChannel).Should(BeClosed())
})
})
@@ -34,8 +34,8 @@ var _ = Describe("BeClosedMatcher", func() {
openWriterChannel = openChannel
success, err := (&BeClosedMatcher{}).Match(openWriterChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
closedChannel := make(chan bool)
close(closedChannel)
@@ -44,8 +44,8 @@ var _ = Describe("BeClosedMatcher", func() {
closedWriterChannel = closedChannel
success, err = (&BeClosedMatcher{}).Match(closedWriterChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
@@ -55,16 +55,16 @@ var _ = Describe("BeClosedMatcher", func() {
var nilChannel chan bool
success, err := (&BeClosedMatcher{}).Match(nilChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeClosedMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeClosedMatcher{}).Match(7)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+16 -16
View File
@@ -9,44 +9,44 @@ import (
var _ = Describe("BeEmpty", func() {
Context("when passed a supported type", func() {
It("should do the right thing", func() {
Ω("").Should(BeEmpty())
Ω(" ").ShouldNot(BeEmpty())
Expect("").Should(BeEmpty())
Expect(" ").ShouldNot(BeEmpty())
Ω([0]int{}).Should(BeEmpty())
Ω([1]int{1}).ShouldNot(BeEmpty())
Expect([0]int{}).Should(BeEmpty())
Expect([1]int{1}).ShouldNot(BeEmpty())
Ω([]int{}).Should(BeEmpty())
Ω([]int{1}).ShouldNot(BeEmpty())
Expect([]int{}).Should(BeEmpty())
Expect([]int{1}).ShouldNot(BeEmpty())
Ω(map[string]int{}).Should(BeEmpty())
Ω(map[string]int{"a": 1}).ShouldNot(BeEmpty())
Expect(map[string]int{}).Should(BeEmpty())
Expect(map[string]int{"a": 1}).ShouldNot(BeEmpty())
c := make(chan bool, 1)
Ω(c).Should(BeEmpty())
Expect(c).Should(BeEmpty())
c <- true
Ω(c).ShouldNot(BeEmpty())
Expect(c).ShouldNot(BeEmpty())
})
})
Context("when passed a correctly typed nil", func() {
It("should be true", func() {
var nilSlice []int
Ω(nilSlice).Should(BeEmpty())
Expect(nilSlice).Should(BeEmpty())
var nilMap map[int]string
Ω(nilMap).Should(BeEmpty())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeEmptyMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeEquivalentToMatcher struct {
+16 -16
View File
@@ -11,40 +11,40 @@ var _ = Describe("BeEquivalentTo", func() {
It("should error", func() {
success, err := (&BeEquivalentToMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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))
Expect("foo").ShouldNot(BeEquivalentTo(nil))
Expect(nil).ShouldNot(BeEquivalentTo(3))
Expect([]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")))
Expect(StringAlias("foo")).Should(BeEquivalentTo("foo"))
Expect("foo").Should(BeEquivalentTo(StringAlias("foo")))
Expect(StringAlias("foo")).ShouldNot(BeEquivalentTo("bar"))
Expect("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))
Expect(5).Should(BeEquivalentTo(5))
Expect(5.0).Should(BeEquivalentTo(5.0))
Expect(5).Should(BeEquivalentTo(5.0))
Ω(5).ShouldNot(BeEquivalentTo("5"))
Ω(5).ShouldNot(BeEquivalentTo(3))
Expect(5).ShouldNot(BeEquivalentTo("5"))
Expect(5).ShouldNot(BeEquivalentTo(3))
//Here be dragons!
Ω(5.1).Should(BeEquivalentTo(5))
Ω(5).ShouldNot(BeEquivalentTo(5.1))
Expect(5.1).Should(BeEquivalentTo(5))
Expect(5).ShouldNot(BeEquivalentTo(5.1))
})
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+4 -4
View File
@@ -8,13 +8,13 @@ import (
var _ = Describe("BeFalse", func() {
It("should handle true and false correctly", func() {
Ω(true).ShouldNot(BeFalse())
Ω(false).Should(BeFalse())
Expect(true).ShouldNot(BeFalse())
Expect(false).Should(BeFalse())
})
It("should only support booleans", func() {
success, err := (&BeFalseMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
+19 -19
View File
@@ -13,49 +13,49 @@ var _ = Describe("BeIdenticalTo", func() {
It("should error", func() {
success, err := (&BeIdenticalToMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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))
Expect(&mySpecialStruct).Should(BeIdenticalTo(&mySpecialStruct))
Expect(&myCustomType{}).ShouldNot(BeIdenticalTo(&mySpecialStruct))
})
It("should be strict about types", func() {
Ω(5).ShouldNot(BeIdenticalTo("5"))
Ω(5).ShouldNot(BeIdenticalTo(5.0))
Ω(5).ShouldNot(BeIdenticalTo(3))
Expect(5).ShouldNot(BeIdenticalTo("5"))
Expect(5).ShouldNot(BeIdenticalTo(5.0))
Expect(5).ShouldNot(BeIdenticalTo(3))
})
It("should treat primtives as identical", func() {
Ω("5").Should(BeIdenticalTo("5"))
Ω("5").ShouldNot(BeIdenticalTo("55"))
Expect("5").Should(BeIdenticalTo("5"))
Expect("5").ShouldNot(BeIdenticalTo("55"))
Ω(5.55).Should(BeIdenticalTo(5.55))
Ω(5.55).ShouldNot(BeIdenticalTo(6.66))
Expect(5.55).Should(BeIdenticalTo(5.55))
Expect(5.55).ShouldNot(BeIdenticalTo(6.66))
Ω(5).Should(BeIdenticalTo(5))
Ω(5).ShouldNot(BeIdenticalTo(55))
Expect(5).Should(BeIdenticalTo(5))
Expect(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}))
Expect(&mySlice).Should(BeIdenticalTo(&mySlice))
Expect(&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"}))
Expect(&myMap).Should(BeIdenticalTo(&myMap))
Expect(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")))
Expect(&myError).Should(BeIdenticalTo(&myError))
Expect(errors.New("foo")).ShouldNot(BeIdenticalTo(errors.New("bar")))
})
})
+6 -6
View File
@@ -7,22 +7,22 @@ import (
var _ = Describe("BeNil", func() {
It("should succeed when passed nil", func() {
Ω(nil).Should(BeNil())
Expect(nil).Should(BeNil())
})
It("should succeed when passed a typed nil", func() {
var a []int
Ω(a).Should(BeNil())
Expect(a).Should(BeNil())
})
It("should succeed when passing nil pointer", func() {
var f *struct{}
Ω(f).Should(BeNil())
Expect(f).Should(BeNil())
})
It("should not succeed when not passed nil", func() {
Ω(0).ShouldNot(BeNil())
Ω(false).ShouldNot(BeNil())
Ω("").ShouldNot(BeNil())
Expect(0).ShouldNot(BeNil())
Expect(false).ShouldNot(BeNil())
Expect("").ShouldNot(BeNil())
})
})
+14 -2
View File
@@ -13,11 +13,23 @@ type BeNumericallyMatcher struct {
}
func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) {
return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo[0])
return matcher.FormatFailureMessage(actual, false)
}
func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo[0])
return matcher.FormatFailureMessage(actual, true)
}
func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, negated bool) (message string) {
if len(matcher.CompareTo) == 1 {
message = fmt.Sprintf("to be %s", matcher.Comparator)
} else {
message = fmt.Sprintf("to be within %v of %s", matcher.CompareTo[1], matcher.Comparator)
}
if negated {
message = "not " + message
}
return format.Message(actual, message, matcher.CompareTo[0])
}
func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) {
+87 -63
View File
@@ -9,79 +9,103 @@ import (
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))
Expect(uint32(5)).Should(BeNumerically("==", 5))
Expect(float64(5.0)).Should(BeNumerically("==", 5))
Expect(int8(5)).Should(BeNumerically("==", 5))
})
It("should not have false positives", func() {
Ω(5.1).ShouldNot(BeNumerically("==", 5))
Ω(5).ShouldNot(BeNumerically("==", 5.1))
Expect(5.1).ShouldNot(BeNumerically("==", 5))
Expect(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))
Expect(uint32(5)).Should(BeNumerically(">", 4))
Expect(float64(5.0)).Should(BeNumerically(">", 4.9))
Expect(int8(5)).Should(BeNumerically(">", 4))
Ω(uint32(5)).ShouldNot(BeNumerically(">", 5))
Ω(float64(5.0)).ShouldNot(BeNumerically(">", 5.0))
Ω(int8(5)).ShouldNot(BeNumerically(">", 5))
Expect(uint32(5)).ShouldNot(BeNumerically(">", 5))
Expect(float64(5.0)).ShouldNot(BeNumerically(">", 5.0))
Expect(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))
Expect(uint32(5)).Should(BeNumerically("<", 6))
Expect(float64(5.0)).Should(BeNumerically("<", 5.1))
Expect(int8(5)).Should(BeNumerically("<", 6))
Ω(uint32(5)).ShouldNot(BeNumerically("<", 5))
Ω(float64(5.0)).ShouldNot(BeNumerically("<", 5.0))
Ω(int8(5)).ShouldNot(BeNumerically("<", 5))
Expect(uint32(5)).ShouldNot(BeNumerically("<", 5))
Expect(float64(5.0)).ShouldNot(BeNumerically("<", 5.0))
Expect(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))
Expect(uint32(5)).Should(BeNumerically(">=", 4))
Expect(float64(5.0)).Should(BeNumerically(">=", 4.9))
Expect(int8(5)).Should(BeNumerically(">=", 4))
Ω(uint32(5)).Should(BeNumerically(">=", 5))
Ω(float64(5.0)).Should(BeNumerically(">=", 5.0))
Ω(int8(5)).Should(BeNumerically(">=", 5))
Expect(uint32(5)).Should(BeNumerically(">=", 5))
Expect(float64(5.0)).Should(BeNumerically(">=", 5.0))
Expect(int8(5)).Should(BeNumerically(">=", 5))
Ω(uint32(5)).ShouldNot(BeNumerically(">=", 6))
Ω(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1))
Ω(int8(5)).ShouldNot(BeNumerically(">=", 6))
Expect(uint32(5)).ShouldNot(BeNumerically(">=", 6))
Expect(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1))
Expect(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))
Expect(uint32(5)).Should(BeNumerically("<=", 6))
Expect(float64(5.0)).Should(BeNumerically("<=", 5.1))
Expect(int8(5)).Should(BeNumerically("<=", 6))
Ω(uint32(5)).Should(BeNumerically("<=", 5))
Ω(float64(5.0)).Should(BeNumerically("<=", 5.0))
Ω(int8(5)).Should(BeNumerically("<=", 5))
Expect(uint32(5)).Should(BeNumerically("<=", 5))
Expect(float64(5.0)).Should(BeNumerically("<=", 5.0))
Expect(int8(5)).Should(BeNumerically("<=", 5))
Ω(uint32(5)).ShouldNot(BeNumerically("<=", 4))
Ω(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9))
Ω(int8(5)).Should(BeNumerically("<=", 5))
Expect(uint32(5)).ShouldNot(BeNumerically("<=", 4))
Expect(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9))
Expect(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))
Expect(5.00000001).Should(BeNumerically("~", 5.00000002))
Expect(5.00000001).ShouldNot(BeNumerically("~", 5.0000001))
})
It("should show failure message", func(){
actual := BeNumerically("~", 4.98).FailureMessage(123)
expected := "Expected\n <int>: 123\nto be ~\n <float64>: 4.98"
Expect(actual).To(Equal(expected))
})
It("should show negated failure message", func(){
actual := BeNumerically("~", 4.98).NegatedFailureMessage(123)
expected := "Expected\n <int>: 123\nnot to be ~\n <float64>: 4.98"
Expect(actual).To(Equal(expected))
})
})
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))
Expect(5.1).Should(BeNumerically("~", 5.19, 0.1))
Expect(5.1).Should(BeNumerically("~", 5.01, 0.1))
Expect(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1))
Expect(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1))
})
It("should show precision in failure message", func(){
actual := BeNumerically("~", 4.98, 0.1).FailureMessage(123)
expected := "Expected\n <int>: 123\nto be within 0.1 of ~\n <float64>: 4.98"
Expect(actual).To(Equal(expected))
})
It("should show precision in negated failure message", func(){
actual := BeNumerically("~", 4.98, 0.1).NegatedFailureMessage(123)
expected := "Expected\n <int>: 123\nnot to be within 0.1 of ~\n <float64>: 4.98"
Expect(actual).To(Equal(expected))
})
})
})
@@ -89,17 +113,17 @@ var _ = Describe("BeNumerically", func() {
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))
Expect(5).Should(BeNumerically("~", 5))
Expect(5).ShouldNot(BeNumerically("~", 6))
Expect(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))
Expect(5).Should(BeNumerically("~", 6, 2))
Expect(5).ShouldNot(BeNumerically("~", 8, 2))
Expect(uint(5)).Should(BeNumerically("~", 6, 1))
})
})
})
@@ -109,40 +133,40 @@ var _ = Describe("BeNumerically", func() {
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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "=="}).Match(5)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+16 -15
View File
@@ -1,9 +1,10 @@
package matchers_test
import (
. "github.com/onsi/gomega/matchers"
"time"
. "github.com/onsi/gomega/matchers"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
@@ -21,21 +22,21 @@ var _ = Describe("BeSent", func() {
time.Sleep(10 * time.Millisecond)
Ω(c).Should(BeSent("foo"))
Expect(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"))
Expect(c).Should(BeSent("foo"))
Expect(<-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"))
Expect(c).ShouldNot(BeSent("foo"))
Consistently(c).ShouldNot(Receive())
})
})
@@ -60,8 +61,8 @@ var _ = Describe("BeSent", func() {
c := make(chan string)
close(c)
success, err := (&BeSentMatcher{Arg: "foo"}).Match(c)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
It("should short-circuit Eventually", func() {
@@ -72,8 +73,8 @@ var _ = Describe("BeSent", func() {
failures := InterceptGomegaFailures(func() {
Eventually(c, 10.0).Should(BeSent("foo"))
})
Ω(failures).Should(HaveLen(1))
Ω(time.Since(t)).Should(BeNumerically("<", time.Second))
Expect(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<", time.Second))
})
})
})
@@ -81,8 +82,8 @@ var _ = Describe("BeSent", func() {
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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
@@ -91,16 +92,16 @@ var _ = Describe("BeSent", func() {
var c <-chan string
c = make(chan string, 1)
success, err := (&BeSentMatcher{Arg: "foo"}).Match(c)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"time"
"github.com/onsi/gomega/format"
)
type BeTemporallyMatcher struct {
+30 -29
View File
@@ -1,10 +1,11 @@
package matchers_test
import (
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
"time"
)
var _ = Describe("BeTemporally", func() {
@@ -19,34 +20,34 @@ var _ = Describe("BeTemporally", func() {
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{}))
Expect(t0).Should(BeTemporally("==", t0))
Expect(t1).ShouldNot(BeTemporally("==", t0))
Expect(t0).ShouldNot(BeTemporally("==", t1))
Expect(t0).ShouldNot(BeTemporally("==", time.Time{}))
})
It("should support >", func() {
Ω(t0).Should(BeTemporally(">", t2))
Ω(t0).ShouldNot(BeTemporally(">", t0))
Ω(t2).ShouldNot(BeTemporally(">", t0))
Expect(t0).Should(BeTemporally(">", t2))
Expect(t0).ShouldNot(BeTemporally(">", t0))
Expect(t2).ShouldNot(BeTemporally(">", t0))
})
It("should support <", func() {
Ω(t0).Should(BeTemporally("<", t1))
Ω(t0).ShouldNot(BeTemporally("<", t0))
Ω(t1).ShouldNot(BeTemporally("<", t0))
Expect(t0).Should(BeTemporally("<", t1))
Expect(t0).ShouldNot(BeTemporally("<", t0))
Expect(t1).ShouldNot(BeTemporally("<", t0))
})
It("should support >=", func() {
Ω(t0).Should(BeTemporally(">=", t2))
Ω(t0).Should(BeTemporally(">=", t0))
Ω(t0).ShouldNot(BeTemporally(">=", t1))
Expect(t0).Should(BeTemporally(">=", t2))
Expect(t0).Should(BeTemporally(">=", t0))
Expect(t0).ShouldNot(BeTemporally(">=", t1))
})
It("should support <=", func() {
Ω(t0).Should(BeTemporally("<=", t1))
Ω(t0).Should(BeTemporally("<=", t0))
Ω(t0).ShouldNot(BeTemporally("<=", t2))
Expect(t0).Should(BeTemporally("<=", t1))
Expect(t0).Should(BeTemporally("<=", t0))
Expect(t0).ShouldNot(BeTemporally("<=", t2))
})
Context("when passed ~", func() {
@@ -56,9 +57,9 @@ var _ = Describe("BeTemporally", func() {
t2 = t0.Add(-2 * time.Millisecond)
})
It("should approximate", func() {
Ω(t0).Should(BeTemporally("~", t0))
Ω(t0).Should(BeTemporally("~", t1))
Ω(t0).ShouldNot(BeTemporally("~", t2))
Expect(t0).Should(BeTemporally("~", t0))
Expect(t0).Should(BeTemporally("~", t1))
Expect(t0).ShouldNot(BeTemporally("~", t2))
})
})
@@ -68,9 +69,9 @@ var _ = Describe("BeTemporally", func() {
})
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))
Expect(t0).Should(BeTemporally("~", t0, d))
Expect(t0).Should(BeTemporally("~", t1, d))
Expect(t0).ShouldNot(BeTemporally("~", t2, d))
})
})
})
@@ -79,20 +80,20 @@ var _ = Describe("BeTemporally", func() {
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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&BeTemporallyMatcher{Comparator: "=="}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+4 -4
View File
@@ -8,13 +8,13 @@ import (
var _ = Describe("BeTrue", func() {
It("should handle true and false correctly", func() {
Ω(true).Should(BeTrue())
Ω(false).ShouldNot(BeTrue())
Expect(true).Should(BeTrue())
Expect(false).ShouldNot(BeTrue())
})
It("should only support booleans", func() {
success, err := (&BeTrueMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
+2 -1
View File
@@ -1,8 +1,9 @@
package matchers
import (
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type BeZeroMatcher struct {
+13 -13
View File
@@ -7,24 +7,24 @@ import (
var _ = Describe("BeZero", func() {
It("should succeed if the passed in object is the zero value for its type", func() {
Ω(nil).Should(BeZero())
Expect(nil).Should(BeZero())
Ω("").Should(BeZero())
Ω(" ").ShouldNot(BeZero())
Expect("").Should(BeZero())
Expect(" ").ShouldNot(BeZero())
Ω(0).Should(BeZero())
Ω(1).ShouldNot(BeZero())
Expect(0).Should(BeZero())
Expect(1).ShouldNot(BeZero())
Ω(0.0).Should(BeZero())
Ω(0.1).ShouldNot(BeZero())
Expect(0.0).Should(BeZero())
Expect(0.1).ShouldNot(BeZero())
// Ω([]int{}).Should(BeZero())
Ω([]int{1}).ShouldNot(BeZero())
// Expect([]int{}).Should(BeZero())
Expect([]int{1}).ShouldNot(BeZero())
// Ω(map[string]int{}).Should(BeZero())
Ω(map[string]int{"a": 1}).ShouldNot(BeZero())
// Expect(map[string]int{}).Should(BeZero())
Expect(map[string]int{"a": 1}).ShouldNot(BeZero())
Ω(myCustomType{}).Should(BeZero())
Ω(myCustomType{s: "a"}).ShouldNot(BeZero())
Expect(myCustomType{}).Should(BeZero())
Expect(myCustomType{s: "a"}).ShouldNot(BeZero())
})
})
+25 -25
View File
@@ -8,29 +8,29 @@ import (
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"))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Expect([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Expect([]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"))
Expect([3]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Expect([3]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Expect([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Expect([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"))
Expect(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("foo", "bar", "baz"))
Expect(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("baz", "bar", "foo"))
Expect(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo"))
Expect(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "foo"))
})
})
@@ -38,38 +38,38 @@ var _ = Describe("ConsistOf", func() {
Context("with anything else", func() {
It("should error", func() {
failures := InterceptGomegaFailures(func() {
Ω("foo").Should(ConsistOf("f", "o", "o"))
Expect("foo").Should(ConsistOf("f", "o", "o"))
})
Ω(failures).Should(HaveLen(1))
Expect(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")))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), "baz"))
Expect([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba")))
Expect([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("foo")))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("^ba")))
Expect([]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)))
Expect([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(1), ContainElement(2)))
Expect([][]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"))
Expect([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar"))
Expect([]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"}))
Expect([]string{"foo", "bar", "baz"}).Should(ConsistOf([]string{"foo", "bar", "baz"}))
})
})
})
+23 -23
View File
@@ -10,40 +10,40 @@ 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))
Expect([2]int{1, 2}).Should(ContainElement(2))
Expect([2]int{1, 2}).ShouldNot(ContainElement(3))
Ω([]int{1, 2}).Should(ContainElement(2))
Ω([]int{1, 2}).ShouldNot(ContainElement(3))
Expect([]int{1, 2}).Should(ContainElement(2))
Expect([]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))
Expect(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(2))
Expect(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"}}))
Expect(arr).Should(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}))
Expect(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)))
Expect([]int{1, 2, 3}).Should(ContainElement(BeNumerically(">=", 3)))
Expect([]int{1, 2, 3}).ShouldNot(ContainElement(BeNumerically(">", 3)))
Expect(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(BeNumerically(">=", 2)))
Expect(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)))
Expect([]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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
@@ -51,26 +51,26 @@ var _ = Describe("ContainElement", func() {
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))
Expect(nilSlice).ShouldNot(ContainElement(1))
var nilMap map[int]string
Ω(nilMap).ShouldNot(ContainElement("foo"))
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&ContainElementMatcher{Element: 0}).Match("abc")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&ContainElementMatcher{Element: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"strings"
"github.com/onsi/gomega/format"
)
type ContainSubstringMatcher struct {
+6 -6
View File
@@ -9,28 +9,28 @@ import (
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"))
Expect("Marvelous").Should(ContainSubstring("rve"))
Expect("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))
Expect("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"))
Expect(&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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+9
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
}
+23 -21
View File
@@ -14,33 +14,35 @@ var _ = Describe("Equal", func() {
It("should error", func() {
success, err := (&EqualMatcher{Expected: nil}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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))
Expect(5).Should(Equal(5))
Expect(5.0).Should(Equal(5.0))
Ω(5).ShouldNot(Equal("5"))
Ω(5).ShouldNot(Equal(5.0))
Ω(5).ShouldNot(Equal(3))
Expect(5).ShouldNot(Equal("5"))
Expect(5).ShouldNot(Equal(5.0))
Expect(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")))
Expect("5").Should(Equal("5"))
Expect([]int{1, 2}).Should(Equal([]int{1, 2}))
Expect([]int{1, 2}).ShouldNot(Equal([]int{2, 1}))
Expect([]byte{'f', 'o', 'o'}).Should(Equal([]byte{'f', 'o', 'o'}))
Expect([]byte{'f', 'o', 'o'}).ShouldNot(Equal([]byte{'b', 'a', 'r'}))
Expect(map[string]string{"a": "b", "c": "d"}).Should(Equal(map[string]string{"a": "b", "c": "d"}))
Expect(map[string]string{"a": "b", "c": "d"}).ShouldNot(Equal(map[string]string{"a": "b", "c": "e"}))
Expect(errors.New("foo")).Should(Equal(errors.New("foo")))
Expect(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"}}))
Expect(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"}}))
Expect(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"}}))
Expect(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"}}))
Expect(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"}}))
Expect(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"}}))
})
})
@@ -49,7 +51,7 @@ var _ = Describe("Equal", func() {
subject := EqualMatcher{Expected: "eric"}
failureMessage := subject.FailureMessage("tim")
Ω(failureMessage).To(BeEquivalentTo(expectedShortStringFailureMessage))
Expect(failureMessage).To(BeEquivalentTo(expectedShortStringFailureMessage))
})
It("shows the exact point where two long strings differ", func() {
@@ -59,7 +61,7 @@ var _ = Describe("Equal", func() {
subject := EqualMatcher{Expected: stringWithZ}
failureMessage := subject.FailureMessage(stringWithB)
Ω(failureMessage).To(BeEquivalentTo(expectedLongStringFailureMessage))
Expect(failureMessage).To(BeEquivalentTo(expectedLongStringFailureMessage))
})
})
})
+14 -14
View File
@@ -9,42 +9,42 @@ import (
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))
Expect([0]int{}).Should(HaveCap(0))
Expect([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))
Expect([]int{}).Should(HaveCap(0))
Expect([]int{1, 2, 3, 4, 5}[:2]).Should(HaveCap(5))
Expect(make([]int, 0, 5)).Should(HaveCap(5))
c := make(chan bool, 3)
Ω(c).Should(HaveCap(3))
Expect(c).Should(HaveCap(3))
c <- true
c <- true
Ω(c).Should(HaveCap(3))
Expect(c).Should(HaveCap(3))
Ω(make(chan bool)).Should(HaveCap(0))
Expect(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))
Expect(nilSlice).Should(HaveCap(0))
var nilChan chan int
Ω(nilChan).Should(HaveCap(0))
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&HaveCapMatcher{Count: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type HaveKeyMatcher struct {
+16 -16
View File
@@ -26,48 +26,48 @@ var _ = Describe("HaveKey", func() {
Context("when passed a map", func() {
It("should do the right thing", func() {
Ω(stringKeys).Should(HaveKey("foo"))
Ω(stringKeys).ShouldNot(HaveKey("baz"))
Expect(stringKeys).Should(HaveKey("foo"))
Expect(stringKeys).ShouldNot(HaveKey("baz"))
Ω(intKeys).Should(HaveKey(2))
Ω(intKeys).ShouldNot(HaveKey(4))
Expect(intKeys).Should(HaveKey(2))
Expect(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"}}))
Expect(objKeys).Should(HaveKey(customA))
Expect(objKeys).Should(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}))
Expect(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"))
Expect(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")))
Expect(stringKeys).Should(HaveKey(ContainSubstring("oo")))
Expect(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())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&HaveKeyMatcher{Key: "foo"}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"reflect"
"github.com/onsi/gomega/format"
)
type HaveKeyWithValueMatcher struct {
+22 -22
View File
@@ -26,57 +26,57 @@ var _ = Describe("HaveKeyWithValue", func() {
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))
Expect(stringKeys).Should(HaveKeyWithValue("foo", 2))
Expect(stringKeys).ShouldNot(HaveKeyWithValue("foo", 1))
Expect(stringKeys).ShouldNot(HaveKeyWithValue("baz", 2))
Expect(stringKeys).ShouldNot(HaveKeyWithValue("baz", 1))
Ω(intKeys).Should(HaveKeyWithValue(2, "foo"))
Ω(intKeys).ShouldNot(HaveKeyWithValue(4, "foo"))
Ω(intKeys).ShouldNot(HaveKeyWithValue(2, "baz"))
Expect(intKeys).Should(HaveKeyWithValue(2, "foo"))
Expect(intKeys).ShouldNot(HaveKeyWithValue(4, "foo"))
Expect(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))
Expect(objKeys).Should(HaveKeyWithValue(customA, customA))
Expect(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"}}))
Expect(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"))
Expect(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))
Expect(stringKeys).Should(HaveKeyWithValue(ContainSubstring("oo"), 2))
Expect(intKeys).Should(HaveKeyWithValue(2, ContainSubstring("oo")))
Expect(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())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+16 -16
View File
@@ -9,45 +9,45 @@ import (
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))
Expect("").Should(HaveLen(0))
Expect("AA").Should(HaveLen(2))
Ω([0]int{}).Should(HaveLen(0))
Ω([2]int{1, 2}).Should(HaveLen(2))
Expect([0]int{}).Should(HaveLen(0))
Expect([2]int{1, 2}).Should(HaveLen(2))
Ω([]int{}).Should(HaveLen(0))
Ω([]int{1, 2, 3}).Should(HaveLen(3))
Expect([]int{}).Should(HaveLen(0))
Expect([]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))
Expect(map[string]int{}).Should(HaveLen(0))
Expect(map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}).Should(HaveLen(4))
c := make(chan bool, 3)
Ω(c).Should(HaveLen(0))
Expect(c).Should(HaveLen(0))
c <- true
c <- true
Ω(c).Should(HaveLen(2))
Expect(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))
Expect(nilSlice).Should(HaveLen(0))
var nilMap map[int]string
Ω(nilMap).Should(HaveLen(0))
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&HaveLenMatcher{Count: 0}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+13 -12
View File
@@ -2,6 +2,7 @@ package matchers_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
@@ -17,42 +18,42 @@ func (e *CustomErr) Error() string {
var _ = Describe("HaveOccurred", func() {
It("should succeed if matching an error", func() {
Ω(errors.New("Foo")).Should(HaveOccurred())
Expect(errors.New("Foo")).Should(HaveOccurred())
})
It("should not succeed with nil", func() {
Ω(nil).ShouldNot(HaveOccurred())
Expect(nil).ShouldNot(HaveOccurred())
})
It("should only support errors and nil", func() {
success, err := (&HaveOccurredMatcher{}).Match("foo")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&HaveOccurredMatcher{}).Match("")
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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>: {}"))
Expect(success).Should(BeFalse())
Expect(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:]]+>: {}`)))
Expect(success).Should(BeFalse())
Expect(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())
Expect(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())
Expect(err).ShouldNot(HaveOccurred())
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+6 -6
View File
@@ -9,28 +9,28 @@ import (
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"))
Expect("Ab").Should(HavePrefix("A"))
Expect("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))
Expect("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"))
Expect(&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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+1
View File
@@ -2,6 +2,7 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
+6 -6
View File
@@ -9,28 +9,28 @@ import (
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"))
Expect("Ab").Should(HaveSuffix("b"))
Expect("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))
Expect("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"))
Expect(&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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+6 -5
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 {
+29 -15
View File
@@ -3,6 +3,7 @@ package matchers_test
import (
"errors"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
@@ -22,11 +23,11 @@ var _ = Describe("MatchErrorMatcher", func() {
fmtErr := fmt.Errorf("an error")
customErr := CustomError{}
Ω(err).Should(MatchError(errors.New("an error")))
Ω(err).ShouldNot(MatchError(errors.New("another error")))
Expect(err).Should(MatchError(errors.New("an error")))
Expect(err).ShouldNot(MatchError(errors.New("another error")))
Ω(fmtErr).Should(MatchError(errors.New("an error")))
Ω(customErr).Should(MatchError(CustomError{}))
Expect(fmtErr).Should(MatchError(errors.New("an error")))
Expect(customErr).Should(MatchError(CustomError{}))
})
It("should succeed when matching with a string", func() {
@@ -34,23 +35,23 @@ var _ = Describe("MatchErrorMatcher", func() {
fmtErr := fmt.Errorf("an error")
customErr := CustomError{}
Ω(err).Should(MatchError("an error"))
Ω(err).ShouldNot(MatchError("another error"))
Expect(err).Should(MatchError("an error"))
Expect(err).ShouldNot(MatchError("another error"))
Ω(fmtErr).Should(MatchError("an error"))
Ω(customErr).Should(MatchError("an error"))
Expect(fmtErr).Should(MatchError("an error"))
Expect(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}`)))
Expect(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`)))
Expect(err).ShouldNot(MatchError(MatchRegexp(`\d`)))
})
})
@@ -59,12 +60,12 @@ var _ = Describe("MatchErrorMatcher", func() {
_, err := (&MatchErrorMatcher{
Expected: []byte("an error"),
}).Match(actualErr)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
_, err = (&MatchErrorMatcher{
Expected: 3,
}).Match(actualErr)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
})
})
@@ -73,7 +74,7 @@ var _ = Describe("MatchErrorMatcher", func() {
_, err := (&MatchErrorMatcher{
Expected: "an error",
}).Match(nil)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
})
})
@@ -82,12 +83,25 @@ var _ = Describe("MatchErrorMatcher", func() {
_, err := (&MatchErrorMatcher{
Expected: "an error",
}).Match("an error")
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
_, err = (&MatchErrorMatcher{
Expected: "an error",
}).Match(3)
Ω(err).Should(HaveOccurred())
Expect(err).Should(HaveOccurred())
})
})
Context("when passed an error that is also a string", func() {
It("should use it as an error", func() {
var e mockErr = "mockErr"
// this fails if the matcher casts e to a string before comparison
Expect(e).Should(MatchError(e))
})
})
})
type mockErr string
func (m mockErr) Error() string { return string(m) }
-70
View File
@@ -4,8 +4,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/onsi/gomega/format"
)
@@ -42,32 +40,6 @@ func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (mess
return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath)
}
func formattedMessage(comparisonMessage string, failurePath []interface{}) string {
var diffMessage string
if len(failurePath) == 0 {
diffMessage = ""
} else {
diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath))
}
return fmt.Sprintf("%s%s", comparisonMessage, diffMessage)
}
func formattedFailurePath(failurePath []interface{}) string {
formattedPaths := []string{}
for i := len(failurePath) - 1; i >= 0; i-- {
switch p := failurePath[i].(type) {
case int:
formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p))
default:
if i != len(failurePath)-1 {
formattedPaths = append(formattedPaths, ".")
}
formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p))
}
}
return strings.Join(formattedPaths, "")
}
func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
actualString, ok := toString(actual)
if !ok {
@@ -91,45 +63,3 @@ func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatte
return abuf.String(), ebuf.String(), nil
}
func deepEqual(a interface{}, b interface{}) (bool, []interface{}) {
var errorPath []interface{}
if reflect.TypeOf(a) != reflect.TypeOf(b) {
return false, errorPath
}
switch a.(type) {
case []interface{}:
if len(a.([]interface{})) != len(b.([]interface{})) {
return false, errorPath
}
for i, v := range a.([]interface{}) {
elementEqual, keyPath := deepEqual(v, b.([]interface{})[i])
if !elementEqual {
return false, append(keyPath, i)
}
}
return true, errorPath
case map[string]interface{}:
if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) {
return false, errorPath
}
for k, v1 := range a.(map[string]interface{}) {
v2, ok := b.(map[string]interface{})[k]
if !ok {
return false, errorPath
}
elementEqual, keyPath := deepEqual(v1, v2)
if !elementEqual {
return false, append(keyPath, k)
}
}
return true, errorPath
default:
return a == b, errorPath
}
}
+38 -32
View File
@@ -1,6 +1,8 @@
package matchers_test
import (
"encoding/json"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/matchers"
@@ -9,25 +11,29 @@ import (
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}`))
Ω(`{
Expect("{}").Should(MatchJSON("{}"))
Expect(`{"a":1}`).Should(MatchJSON(`{"a":1}`))
Expect(`{
"a":1
}`).Should(MatchJSON(`{"a":1}`))
Ω(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`))
Ω(`{"a":1}`).ShouldNot(MatchJSON(`{"b":2, "a":1}`))
Expect(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`))
Expect(`{"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"}`))
Expect(`{"a":"a", "b":"b"}`).ShouldNot(MatchJSON(`{"a":"a", "b":"b", "c":"c"}`))
Expect(`{"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}`))
Expect(`{"a":null, "b":null}`).ShouldNot(MatchJSON(`{"c":"c", "d":"d"}`))
Expect(`{"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("{}"))
Expect([]byte("{}")).Should(MatchJSON([]byte("{}")))
Expect("{}").Should(MatchJSON([]byte("{}")))
Expect([]byte("{}")).Should(MatchJSON("{}"))
})
It("should work with json.RawMessage", func() {
Expect([]byte(`{"a": 1}`)).Should(MatchJSON(json.RawMessage(`{"a": 1}`)))
})
})
@@ -38,60 +44,60 @@ var _ = Describe("MatchJSONMatcher", func() {
subject.Match(actual)
failureMessage := subject.FailureMessage(`7`)
Ω(failureMessage).ToNot(ContainSubstring("first mismatched key"))
Expect(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]`))
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n <nil>: nil"))
})
})
})
+2 -1
View File
@@ -2,8 +2,9 @@ package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"regexp"
"github.com/onsi/gomega/format"
)
type MatchRegexpMatcher struct {
+8 -8
View File
@@ -9,36 +9,36 @@ import (
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]`))
Expect(" a2!bla").Should(MatchRegexp(`\d!`))
Expect(" 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`))
Expect(&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))
Expect(" 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())
Expect(success).Should(BeFalse())
Expect(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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
+3
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 {
+37 -30
View File
@@ -23,68 +23,75 @@ var _ = Describe("MatchXMLMatcher", func() {
)
Context("When passed stringifiables", func() {
It("matches documents regardless of the attribute order", func() {
a := `<a foo="bar" ka="boom"></a>`
b := `<a ka="boom" foo="bar"></a>`
Expect(b).Should(MatchXML(a))
Expect(a).Should(MatchXML(b))
})
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
Expect(sample_01).Should(MatchXML(sample_01)) // same XML
Expect(sample_01).Should(MatchXML(sample_02)) // same XML with blank lines
Expect(sample_01).Should(MatchXML(sample_03)) // same XML with different formatting
Expect(sample_01).ShouldNot(MatchXML(sample_04)) // same structures with different values
Expect(sample_01).ShouldNot(MatchXML(sample_05)) // different structures
Expect(sample_06).ShouldNot(MatchXML(sample_07)) // same xml names with different namespaces
Expect(sample_07).ShouldNot(MatchXML(sample_08)) // same structures with different values
Expect(sample_09).ShouldNot(MatchXML(sample_10)) // same structures with different attribute values
Expect(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)))
Expect([]byte(sample_01)).Should(MatchXML([]byte(sample_01)))
Expect([]byte(sample_01)).Should(MatchXML(sample_01))
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n <nil>: nil"))
})
})
})
+7 -5
View File
@@ -2,7 +2,6 @@ package matchers
import (
"fmt"
"reflect"
"strings"
"github.com/onsi/gomega/format"
@@ -10,7 +9,8 @@ import (
)
type MatchYAMLMatcher struct {
YAMLToMatch interface{}
YAMLToMatch interface{}
firstFailurePath []interface{}
}
func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) {
@@ -29,17 +29,19 @@ func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err er
return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err)
}
return reflect.DeepEqual(aval, eval), nil
var equal bool
equal, matcher.firstFailurePath = deepEqual(aval, eval)
return equal, nil
}
func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) {
actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
return format.Message(actualString, "to match YAML of", expectedString)
return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath)
}
func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) {
actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
return format.Message(actualString, "not to match YAML of", expectedString)
return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath)
}
func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
+12 -12
View File
@@ -10,36 +10,36 @@ 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())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(func(foo string) {})
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&PanicMatcher{}).Match(func() string { return "bar" })
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(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())
Expect(func() { panic("ack!") }).Should(Panic())
Expect(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())
Expect(func() { panic("ack!") }).ShouldNot(Panic())
})
Ω(failuresMessages).Should(ConsistOf(MatchRegexp("not to panic, but panicked with\\s*<string>: ack!")))
Expect(failuresMessages).Should(ConsistOf(MatchRegexp("not to panic, but panicked with\\s*<string>: ack!")))
})
})
})
+12 -6
View File
@@ -35,11 +35,6 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro
if argType.Kind() != reflect.Ptr {
return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s\nYou need to pass a pointer!", format.Object(actual, 1), format.Object(matcher.Arg, 1))
}
assignable := channelType.Elem().AssignableTo(argType.Elem())
if !assignable {
return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s", format.Object(actual, 1), format.Object(matcher.Arg, 1))
}
}
}
@@ -71,7 +66,18 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro
if didReceive {
if matcher.Arg != nil {
outValue := reflect.ValueOf(matcher.Arg)
reflect.Indirect(outValue).Set(value)
if value.Type().AssignableTo(outValue.Elem().Type()) {
outValue.Elem().Set(value)
return true, nil
}
if value.Type().Kind() == reflect.Interface && value.Elem().Type().AssignableTo(outValue.Elem().Type()) {
outValue.Elem().Set(value.Elem())
return true, nil
} else {
return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nType:\n%s\nTo:\n%s", format.Object(actual, 1), format.Object(value.Interface(), 1), format.Object(matcher.Arg, 1))
}
}
return true, nil
+71 -47
View File
@@ -20,17 +20,21 @@ func (j *jackie) DrunkenMaster() bool {
return true
}
type someError struct{ s string }
func (e *someError) Error() string { return e.s }
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())
Expect(channel).ShouldNot(Receive())
channel <- true
Ω(channel).Should(Receive())
Expect(channel).Should(Receive())
})
})
@@ -38,7 +42,7 @@ var _ = Describe("ReceiveMatcher", func() {
It("should succeed (eventually)", func() {
channel := make(chan bool)
Ω(channel).ShouldNot(Receive())
Expect(channel).ShouldNot(Receive())
go func() {
time.Sleep(10 * time.Millisecond)
@@ -51,19 +55,37 @@ var _ = Describe("ReceiveMatcher", func() {
})
Context("with a pointer argument", func() {
Context("of the correct type", func() {
Context("when the channel has an interface type", func() {
It("should write the value received on the channel to the pointer", func() {
channel := make(chan error, 1)
var value *someError
Ω(channel).ShouldNot(Receive(&value))
Ω(value).Should(BeZero())
channel <- &someError{"boooom!"}
Ω(channel).Should(Receive(&value))
Ω(value).Should(MatchError("boooom!"))
})
})
})
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())
Expect(channel).ShouldNot(Receive(&value))
Expect(value).Should(BeZero())
channel <- 17
Ω(channel).Should(Receive(&value))
Ω(value).Should(Equal(17))
Expect(channel).Should(Receive(&value))
Expect(value).Should(Equal(17))
})
})
@@ -74,16 +96,16 @@ var _ = Describe("ReceiveMatcher", func() {
stringChan <- "foo"
var s string
Ω(stringChan).Should(Receive(&s))
Ω(s).Should(Equal("foo"))
Expect(stringChan).Should(Receive(&s))
Expect(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}))
Expect(sliceChan).Should(Receive(&sl))
Expect(sl).Should(Equal([]bool{true, true, false}))
//channels of channels
chanChan := make(chan chan bool, 1)
@@ -91,8 +113,8 @@ var _ = Describe("ReceiveMatcher", func() {
chanChan <- c
var receivedC chan bool
Ω(chanChan).Should(Receive(&receivedC))
Ω(receivedC).Should(Equal(c))
Expect(chanChan).Should(Receive(&receivedC))
Expect(receivedC).Should(Equal(c))
//channels of interfaces
jackieChan := make(chan kungFuActor, 1)
@@ -100,24 +122,26 @@ var _ = Describe("ReceiveMatcher", func() {
jackieChan <- aJackie
var theJackie kungFuActor
Ω(jackieChan).Should(Receive(&theJackie))
Ω(theJackie).Should(Equal(aJackie))
Expect(jackieChan).Should(Receive(&theJackie))
Expect(theJackie).Should(Equal(aJackie))
})
})
Context("of the wrong type", func() {
It("should error", func() {
channel := make(chan int)
channel := make(chan int, 1)
channel <- 10
var incorrectType bool
success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
var notAPointer int
success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
@@ -126,17 +150,17 @@ var _ = Describe("ReceiveMatcher", func() {
It("should defer to the underlying matcher", func() {
intChannel := make(chan int, 1)
intChannel <- 3
Ω(intChannel).Should(Receive(Equal(3)))
Expect(intChannel).Should(Receive(Equal(3)))
intChannel <- 2
Ω(intChannel).ShouldNot(Receive(Equal(3)))
Expect(intChannel).ShouldNot(Receive(Equal(3)))
stringChannel := make(chan []string, 1)
stringChannel <- []string{"foo", "bar", "baz"}
Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo"))))
Expect(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo"))))
stringChannel <- []string{"foo", "bar", "baz"}
Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago"))))
Expect(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago"))))
})
It("should defer to the underlying matcher for the message", func() {
@@ -144,11 +168,11 @@ var _ = Describe("ReceiveMatcher", func() {
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`))
Expect(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`))
Expect(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+<int>: 3\s+not to equal\s+<int>: 3`))
})
It("should work just fine with Eventually", func() {
@@ -169,8 +193,8 @@ var _ = Describe("ReceiveMatcher", func() {
channel := make(chan int, 1)
channel <- 3
success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
@@ -178,8 +202,8 @@ var _ = Describe("ReceiveMatcher", func() {
It("should fail", func() {
channel := make(chan int, 1)
success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel)
Ω(success).Should(BeFalse())
Ω(err).ShouldNot(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).ShouldNot(HaveOccurred())
})
})
})
@@ -192,8 +216,8 @@ var _ = Describe("ReceiveMatcher", func() {
close(channel)
Ω(channel).Should(Receive())
Ω(channel).ShouldNot(Receive())
Expect(channel).Should(Receive())
Expect(channel).ShouldNot(Receive())
})
})
@@ -202,7 +226,7 @@ var _ = Describe("ReceiveMatcher", func() {
channel := make(chan bool)
close(channel)
Ω(channel).ShouldNot(Receive())
Expect(channel).ShouldNot(Receive())
})
})
})
@@ -215,8 +239,8 @@ var _ = Describe("ReceiveMatcher", func() {
writerChannel = channel
success, err := (&ReceiveMatcher{}).Match(writerChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
@@ -225,16 +249,16 @@ var _ = Describe("ReceiveMatcher", func() {
var nilChannel chan bool
success, err := (&ReceiveMatcher{}).Match(nilChannel)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&ReceiveMatcher{}).Match(nil)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
success, err = (&ReceiveMatcher{}).Match(3)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
@@ -244,14 +268,14 @@ var _ = Describe("ReceiveMatcher", 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."))
Expect(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"))
Expect(failures[0]).Should(ContainSubstring("<string>: hello"))
})
})
@@ -264,8 +288,8 @@ var _ = Describe("ReceiveMatcher", func() {
failures := InterceptGomegaFailures(func() {
Eventually(c).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
})
It("should bail early when passed a non-channel", func() {
@@ -273,8 +297,8 @@ var _ = Describe("ReceiveMatcher", func() {
failures := InterceptGomegaFailures(func() {
Eventually(3).Should(Receive())
})
Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Ω(failures).Should(HaveLen(1))
Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond))
Expect(failures).Should(HaveLen(1))
})
})
})
+92
View File
@@ -0,0 +1,92 @@
package matchers
import (
"fmt"
"reflect"
"strings"
)
func formattedMessage(comparisonMessage string, failurePath []interface{}) string {
var diffMessage string
if len(failurePath) == 0 {
diffMessage = ""
} else {
diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath))
}
return fmt.Sprintf("%s%s", comparisonMessage, diffMessage)
}
func formattedFailurePath(failurePath []interface{}) string {
formattedPaths := []string{}
for i := len(failurePath) - 1; i >= 0; i-- {
switch p := failurePath[i].(type) {
case int:
formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p))
default:
if i != len(failurePath)-1 {
formattedPaths = append(formattedPaths, ".")
}
formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p))
}
}
return strings.Join(formattedPaths, "")
}
func deepEqual(a interface{}, b interface{}) (bool, []interface{}) {
var errorPath []interface{}
if reflect.TypeOf(a) != reflect.TypeOf(b) {
return false, errorPath
}
switch a.(type) {
case []interface{}:
if len(a.([]interface{})) != len(b.([]interface{})) {
return false, errorPath
}
for i, v := range a.([]interface{}) {
elementEqual, keyPath := deepEqual(v, b.([]interface{})[i])
if !elementEqual {
return false, append(keyPath, i)
}
}
return true, errorPath
case map[interface{}]interface{}:
if len(a.(map[interface{}]interface{})) != len(b.(map[interface{}]interface{})) {
return false, errorPath
}
for k, v1 := range a.(map[interface{}]interface{}) {
v2, ok := b.(map[interface{}]interface{})[k]
if !ok {
return false, errorPath
}
elementEqual, keyPath := deepEqual(v1, v2)
if !elementEqual {
return false, append(keyPath, k)
}
}
return true, errorPath
case map[string]interface{}:
if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) {
return false, errorPath
}
for k, v1 := range a.(map[string]interface{}) {
v2, ok := b.(map[string]interface{})[k]
if !ok {
return false, errorPath
}
elementEqual, keyPath := deepEqual(v1, v2)
if !elementEqual {
return false, append(keyPath, k)
}
}
return true, errorPath
default:
return a == b, errorPath
}
}
+10 -10
View File
@@ -24,39 +24,39 @@ func Invalid() *AnyType {
var _ = Describe("Succeed", func() {
It("should succeed if the function succeeds", func() {
Ω(NotErroring()).Should(Succeed())
Expect(NotErroring()).Should(Succeed())
})
It("should succeed (in the negated) if the function errored", func() {
Ω(Erroring()).ShouldNot(Succeed())
Expect(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"))
Expect(success).Should(BeFalse())
Expect(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>: {}"))
Expect(success).Should(BeFalse())
Expect(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:]]+>: {}`)))
Expect(success).Should(BeFalse())
Expect(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())
Expect(err).ShouldNot(Succeed())
})
It("should succeed with nil pointers to types that conform to error interface", func() {
var err *CustomErr = nil
Ω(err).Should(Succeed())
Expect(err).Should(Succeed())
})
})
@@ -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]})
}
}
}
+6
View File
@@ -9,6 +9,7 @@ http://onsi.github.io/gomega/
package matchers
import (
"encoding/json"
"fmt"
"reflect"
)
@@ -133,6 +134,11 @@ func toString(a interface{}) (string, bool) {
return aStringer.String(), true
}
aJSONRawMessage, isJSONRawMessage := a.(json.RawMessage)
if isJSONRawMessage {
return string(aJSONRawMessage), true
}
return "", false
}
+10 -1
View File
@@ -1,7 +1,16 @@
package types
type TWithHelper interface {
Helper()
}
type GomegaFailHandler func(message string, callerSkip ...int)
type GomegaFailWrapper struct {
Fail GomegaFailHandler
TWithHelper TWithHelper
}
//A simple *testing.T interface wrapper
type GomegaTestingT interface {
Fatalf(format string, args ...interface{})
@@ -9,7 +18,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)