build(deps): bump github.com/onsi/gomega from 1.15.0 to 1.24.2
Bumps [github.com/onsi/gomega](https://github.com/onsi/gomega) from 1.15.0 to 1.24.2. - [Release notes](https://github.com/onsi/gomega/releases) - [Changelog](https://github.com/onsi/gomega/blob/master/CHANGELOG.md) - [Commits](https://github.com/onsi/gomega/compare/v1.15.0...v1.24.2) --- updated-dependencies: - dependency-name: github.com/onsi/gomega dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
![49699333+dependabot[bot]@users.noreply.github.com](/assets/img/avatar_default.png)
committed by
Matthieu MOREL

parent
c5e81e3c05
commit
020b8db6ab
1
vendor/github.com/onsi/gomega/.gitignore
generated
vendored
1
vendor/github.com/onsi/gomega/.gitignore
generated
vendored
@ -3,3 +3,4 @@
|
||||
.
|
||||
.idea
|
||||
gomega.iml
|
||||
TODO.md
|
18
vendor/github.com/onsi/gomega/.travis.yml
generated
vendored
18
vendor/github.com/onsi/gomega/.travis.yml
generated
vendored
@ -1,18 +0,0 @@
|
||||
language: go
|
||||
arch:
|
||||
- amd64
|
||||
- ppc64le
|
||||
|
||||
go:
|
||||
- gotip
|
||||
- 1.16.x
|
||||
- 1.15.x
|
||||
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
|
||||
install: skip
|
||||
|
||||
script:
|
||||
- go mod tidy && git diff --exit-code go.mod go.sum
|
||||
- make test
|
211
vendor/github.com/onsi/gomega/CHANGELOG.md
generated
vendored
211
vendor/github.com/onsi/gomega/CHANGELOG.md
generated
vendored
@ -1,3 +1,214 @@
|
||||
## 1.24.2
|
||||
|
||||
### Fixes
|
||||
- Correctly handle assertion failure panics for eventually/consistnetly "g Gomega"s in a goroutine [78f1660]
|
||||
- docs:Fix typo "you an" -> "you can" (#607) [3187c1f]
|
||||
- fixes issue #600 (#606) [808d192]
|
||||
|
||||
### Maintenance
|
||||
- Bump golang.org/x/net from 0.2.0 to 0.4.0 (#611) [6ebc0bf]
|
||||
- Bump nokogiri from 1.13.9 to 1.13.10 in /docs (#612) [258cfc8]
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.5.0 to 2.5.1 (#609) [e6c3eb9]
|
||||
|
||||
## 1.24.1
|
||||
|
||||
### Fixes
|
||||
- maintain backward compatibility for Eventually and Consisntetly's signatures [4c7df5e]
|
||||
- fix small typo (#601) [ea0ebe6]
|
||||
|
||||
### Maintenance
|
||||
- Bump golang.org/x/net from 0.1.0 to 0.2.0 (#603) [1ba8372]
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.4.0 to 2.5.0 (#602) [f9426cb]
|
||||
- fix label-filter in test.yml [d795db6]
|
||||
- stop running flakey tests and rely on external network dependencies in CI [7133290]
|
||||
|
||||
## 1.24.0
|
||||
|
||||
### Features
|
||||
|
||||
Introducting [gcustom](https://onsi.github.io/gomega/#gcustom-a-convenient-mechanism-for-buildling-custom-matchers) - a convenient mechanism for building custom matchers.
|
||||
|
||||
This is an RC release for `gcustom`. The external API may be tweaked in response to feedback however it is expected to remain mostly stable.
|
||||
|
||||
### Maintenance
|
||||
|
||||
- Update BeComparableTo documentation [756eaa0]
|
||||
|
||||
## 1.23.0
|
||||
|
||||
### Features
|
||||
- Custom formatting on a per-type basis can be provided using `format.RegisterCustomFormatter()` -- see the docs [here](https://onsi.github.io/gomega/#adjusting-output)
|
||||
|
||||
- Substantial improvement have been made to `StopTrying()`:
|
||||
- Users can now use `StopTrying().Wrap(err)` to wrap errors and `StopTrying().Attach(description, object)` to attach arbitrary objects to the `StopTrying()` error
|
||||
- `StopTrying()` is now always interpreted as a failure. If you are an early adopter of `StopTrying()` you may need to change your code as the prior version would match against the returned value even if `StopTrying()` was returned. Going forward the `StopTrying()` api should remain stable.
|
||||
- `StopTrying()` and `StopTrying().Now()` can both be used in matchers - not just polled functions.
|
||||
|
||||
- `TryAgainAfter(duration)` is used like `StopTrying()` but instructs `Eventually` and `Consistently` that the poll should be tried again after the specified duration. This allows you to dynamically adjust the polling duration.
|
||||
|
||||
- `ctx` can now be passed-in as the first argument to `Eventually` and `Consistently`.
|
||||
|
||||
## Maintenance
|
||||
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.3.0 to 2.3.1 (#597) [afed901]
|
||||
- Bump nokogiri from 1.13.8 to 1.13.9 in /docs (#599) [7c691b3]
|
||||
- Bump github.com/google/go-cmp from 0.5.8 to 0.5.9 (#587) [ff22665]
|
||||
|
||||
## 1.22.1
|
||||
|
||||
## Fixes
|
||||
- When passed a context and no explicit timeout, Eventually will only timeout when the context is cancelled [e5105cf]
|
||||
- Allow StopTrying() to be wrapped [bf3cba9]
|
||||
|
||||
## Maintenance
|
||||
- bump to ginkgo v2.3.0 [c5d5c39]
|
||||
|
||||
## 1.22.0
|
||||
|
||||
### Features
|
||||
|
||||
Several improvements have been made to `Eventually` and `Consistently` in this and the most recent releases:
|
||||
|
||||
- Eventually and Consistently can take a context.Context [65c01bc]
|
||||
This enables integration with Ginkgo 2.3.0's interruptible nodes and node timeouts.
|
||||
- Eventually and Consistently that are passed a SpecContext can provide reports when an interrupt occurs [0d063c9]
|
||||
- Eventually/Consistently will forward an attached context to functions that ask for one [e2091c5]
|
||||
- Eventually/Consistently supports passing arguments to functions via WithArguments() [a2dc7c3]
|
||||
- Eventually and Consistently can now be stopped early with StopTrying(message) and StopTrying(message).Now() [52976bb]
|
||||
|
||||
These improvements are all documented in [Gomega's docs](https://onsi.github.io/gomega/#making-asynchronous-assertions)
|
||||
|
||||
## Fixes
|
||||
|
||||
## Maintenance
|
||||
|
||||
## 1.21.1
|
||||
|
||||
### Features
|
||||
- Eventually and Consistently that are passed a SpecContext can provide reports when an interrupt occurs [0d063c9]
|
||||
|
||||
## 1.21.0
|
||||
|
||||
### Features
|
||||
- Eventually and Consistently can take a context.Context [65c01bc]
|
||||
This enables integration with Ginkgo 2.3.0's interruptible nodes and node timeouts.
|
||||
- Introduces Eventually.Within.ProbeEvery with tests and documentation (#591) [f633800]
|
||||
- New BeKeyOf matcher with documentation and unit tests (#590) [fb586b3]
|
||||
|
||||
## Fixes
|
||||
- Cover the entire gmeasure suite with leak detection [8c54344]
|
||||
- Fix gmeasure leak [119d4ce]
|
||||
- Ignore new Ginkgo ProgressSignal goroutine in gleak [ba548e2]
|
||||
|
||||
## Maintenance
|
||||
|
||||
- Fixes crashes on newer Ruby 3 installations by upgrading github-pages gem dependency (#596) [12469a0]
|
||||
|
||||
|
||||
## 1.20.2
|
||||
|
||||
## Fixes
|
||||
- label specs that rely on remote access; bump timeout on short-circuit test to make it less flaky [35eeadf]
|
||||
- gexec: allow more headroom for SIGABRT-related unit tests (#581) [5b78f40]
|
||||
- Enable reading from a closed gbytes.Buffer (#575) [061fd26]
|
||||
|
||||
## Maintenance
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.1.5 to 2.1.6 (#583) [55d895b]
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.1.4 to 2.1.5 (#582) [346de7c]
|
||||
|
||||
## 1.20.1
|
||||
|
||||
## Fixes
|
||||
- fix false positive gleaks when using ginkgo -p (#577) [cb46517]
|
||||
- Fix typos in gomega_dsl.go (#569) [5f71ed2]
|
||||
- don't panic on Eventually(nil), fixing #555 (#567) [9d1186f]
|
||||
- vet optional description args in assertions, fixing #560 (#566) [8e37808]
|
||||
|
||||
## Maintenance
|
||||
- test: add new Go 1.19 to test matrix (#571) [40d7efe]
|
||||
- Bump tzinfo from 1.2.9 to 1.2.10 in /docs (#564) [5f26371]
|
||||
|
||||
## 1.20.0
|
||||
|
||||
## Features
|
||||
- New [`gleak`](https://onsi.github.io/gomega/#codegleakcode-finding-leaked-goroutines) experimental goroutine leak detection package! (#538) [85ba7bc]
|
||||
- New `BeComparableTo` matcher(#546) that uses `gocmp` to make comparisons [e77ea75]
|
||||
- New `HaveExistingField` matcher (#553) [fd130e1]
|
||||
- Document how to wrap Gomega (#539) [56714a4]
|
||||
|
||||
## Fixes
|
||||
- Support pointer receivers in HaveField; fixes #543 (#544) [8dab36e]
|
||||
|
||||
## Maintenance
|
||||
- Bump various dependencies:
|
||||
- Upgrade to yaml.v3 (#556) [f5a83b1]
|
||||
- Bump github/codeql-action from 1 to 2 (#549) [52f5adf]
|
||||
- Bump github.com/google/go-cmp from 0.5.7 to 0.5.8 (#551) [5f3942d]
|
||||
- Bump nokogiri from 1.13.4 to 1.13.6 in /docs (#554) [eb4b4c2]
|
||||
- Use latest ginkgo (#535) [1c29028]
|
||||
- Bump nokogiri from 1.13.3 to 1.13.4 in /docs (#541) [1ce84d5]
|
||||
- Bump actions/setup-go from 2 to 3 (#540) [755485e]
|
||||
- Bump nokogiri from 1.12.5 to 1.13.3 in /docs (#522) [4fbb0dc]
|
||||
- Bump actions/checkout from 2 to 3 (#526) [ac49202]
|
||||
|
||||
## 1.19.0
|
||||
|
||||
## Features
|
||||
- New [`HaveEach`](https://onsi.github.io/gomega/#haveeachelement-interface) matcher to ensure that each and every element in an `array`, `slice`, or `map` satisfies the passed in matcher. (#523) [9fc2ae2] (#524) [c8ba582]
|
||||
- Users can now wrap the `Gomega` interface to implement custom behavior on each assertion. (#521) [1f2e714]
|
||||
- [`ContainElement`](https://onsi.github.io/gomega/#containelementelement-interface) now accepts an additional pointer argument. Elements that satisfy the matcher are stored in the pointer enabling developers to easily add subsequent, more detailed, assertions against the matching element. (#527) [1a4e27f]
|
||||
|
||||
## Fixes
|
||||
- update RELEASING instructions to match ginkgo [0917cde]
|
||||
- Bump github.com/onsi/ginkgo/v2 from 2.0.0 to 2.1.3 (#519) [49ab4b0]
|
||||
- Fix CVE-2021-38561 (#534) [f1b4456]
|
||||
- Fix max number of samples in experiments on non-64-bit systems. (#528) [1c84497]
|
||||
- Remove dependency on ginkgo v1.16.4 (#530) [4dea8d5]
|
||||
- Fix for Go 1.18 (#532) [56d2a29]
|
||||
- Document precendence of timeouts (#533) [b607941]
|
||||
|
||||
## 1.18.1
|
||||
|
||||
## Fixes
|
||||
- Add pointer support to HaveField matcher (#495) [79e41a3]
|
||||
|
||||
## 1.18.0
|
||||
|
||||
## Features
|
||||
- Docs now live on the master branch in the docs folder which will make for easier PRs. The docs also use Ginkgo 2.0's new docs html/css/js. [2570272]
|
||||
- New HaveValue matcher can handle actuals that are either values (in which case they are passed on unscathed) or pointers (in which case they are indirected). [Docs here.](https://onsi.github.io/gomega/#working-with-values) (#485) [bdc087c]
|
||||
- Gmeasure has been declared GA [360db9d]
|
||||
|
||||
## Fixes
|
||||
- Gomega now uses ioutil for Go 1.15 and lower (#492) - official support is only for the most recent two major versions of Go but this will unblock users who need to stay on older unsupported versions of Go. [c29c1c0]
|
||||
|
||||
## Maintenace
|
||||
- Remove Travis workflow (#491) [72e6040]
|
||||
- Upgrade to Ginkgo 2.0.0 GA [f383637]
|
||||
- chore: fix description of HaveField matcher (#487) [2b4b2c0]
|
||||
- use tools.go to ensure Ginkgo cli dependencies are included [f58a52b]
|
||||
- remove dockerfile and simplify github actions to match ginkgo's actions [3f8160d]
|
||||
|
||||
## 1.17.0
|
||||
|
||||
### Features
|
||||
- Add HaveField matcher [3a26311]
|
||||
- add Error() assertions on the final error value of multi-return values (#480) [2f96943]
|
||||
- separate out offsets and timeouts (#478) [18a4723]
|
||||
- fix transformation error reporting (#479) [e001fab]
|
||||
- allow transform functions to report errors (#472) [bf93408]
|
||||
|
||||
### Fixes
|
||||
Stop using deprecated ioutil package (#467) [07f405d]
|
||||
|
||||
## 1.16.0
|
||||
|
||||
### Features
|
||||
- feat: HaveHTTPStatus multiple expected values (#465) [aa69f1b]
|
||||
- feat: HaveHTTPHeaderWithValue() matcher (#463) [dd83a96]
|
||||
- feat: HaveHTTPBody matcher (#462) [504e1f2]
|
||||
- feat: formatter for HTTP responses (#461) [e5b3157]
|
||||
|
||||
## 1.15.0
|
||||
|
||||
### Fixes
|
||||
|
1
vendor/github.com/onsi/gomega/Dockerfile
generated
vendored
1
vendor/github.com/onsi/gomega/Dockerfile
generated
vendored
@ -1 +0,0 @@
|
||||
FROM golang:1.15
|
33
vendor/github.com/onsi/gomega/Makefile
generated
vendored
33
vendor/github.com/onsi/gomega/Makefile
generated
vendored
@ -1,33 +0,0 @@
|
||||
###### Help ###################################################################
|
||||
|
||||
.DEFAULT_GOAL = help
|
||||
|
||||
.PHONY: help
|
||||
|
||||
help: ## list Makefile targets
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
|
||||
|
||||
###### Targets ################################################################
|
||||
|
||||
test: version download fmt vet ginkgo ## Runs all build, static analysis, and test steps
|
||||
|
||||
download: ## Download dependencies
|
||||
go mod download
|
||||
|
||||
vet: ## Run static code analysis
|
||||
go vet ./...
|
||||
|
||||
ginkgo: ## Run tests using Ginkgo
|
||||
go run github.com/onsi/ginkgo/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race
|
||||
|
||||
fmt: ## Checks that the code is formatted correcty
|
||||
@@if [ -n "$$(gofmt -s -e -l -d .)" ]; then \
|
||||
echo "gofmt check failed: run 'gofmt -s -e -l -w .'"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
docker_test: ## Run tests in a container via docker-compose
|
||||
docker-compose build test && docker-compose run --rm test make test
|
||||
|
||||
version: ## Display the version of Go
|
||||
@@go version
|
19
vendor/github.com/onsi/gomega/RELEASING.md
generated
vendored
19
vendor/github.com/onsi/gomega/RELEASING.md
generated
vendored
@ -1,12 +1,23 @@
|
||||
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
|
||||
- Use
|
||||
```bash
|
||||
LAST_VERSION=$(git tag --sort=version:refname | tail -n1)
|
||||
CHANGES=$(git log --pretty=format:'- %s [%h]' HEAD...$LAST_VERSION)
|
||||
echo -e "## NEXT\n\n$CHANGES\n\n### Features\n\n### Fixes\n\n### Maintenance\n\n$(cat CHANGELOG.md)" > CHANGELOG.md
|
||||
```
|
||||
to update the changelog
|
||||
- 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.
|
||||
1. Update GOMEGA_VERSION in `gomega_dsl.go`
|
||||
1. Commit, push, and release:
|
||||
```
|
||||
git commit -m "vM.m.p"
|
||||
git push
|
||||
gh release create "vM.m.p"
|
||||
git fetch --tags origin master
|
||||
```
|
10
vendor/github.com/onsi/gomega/docker-compose.yaml
generated
vendored
10
vendor/github.com/onsi/gomega/docker-compose.yaml
generated
vendored
@ -1,10 +0,0 @@
|
||||
version: '3.0'
|
||||
|
||||
services:
|
||||
test:
|
||||
build:
|
||||
dockerfile: Dockerfile
|
||||
context: .
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- ${PWD}:/app
|
78
vendor/github.com/onsi/gomega/format/format.go
generated
vendored
78
vendor/github.com/onsi/gomega/format/format.go
generated
vendored
@ -65,6 +65,52 @@ type GomegaStringer interface {
|
||||
GomegaString() string
|
||||
}
|
||||
|
||||
/*
|
||||
CustomFormatters can be registered with Gomega via RegisterCustomFormatter()
|
||||
Any value to be rendered by Gomega is passed to each registered CustomFormatters.
|
||||
The CustomFormatter signals that it will handle formatting the value by returning (formatted-string, true)
|
||||
If the CustomFormatter does not want to handle the object it should return ("", false)
|
||||
|
||||
Strings returned by CustomFormatters are not truncated
|
||||
*/
|
||||
type CustomFormatter func(value interface{}) (string, bool)
|
||||
type CustomFormatterKey uint
|
||||
|
||||
var customFormatterKey CustomFormatterKey = 1
|
||||
|
||||
type customFormatterKeyPair struct {
|
||||
CustomFormatter
|
||||
CustomFormatterKey
|
||||
}
|
||||
|
||||
/*
|
||||
RegisterCustomFormatter registers a CustomFormatter and returns a CustomFormatterKey
|
||||
|
||||
You can call UnregisterCustomFormatter with the returned key to unregister the associated CustomFormatter
|
||||
*/
|
||||
func RegisterCustomFormatter(customFormatter CustomFormatter) CustomFormatterKey {
|
||||
key := customFormatterKey
|
||||
customFormatterKey += 1
|
||||
customFormatters = append(customFormatters, customFormatterKeyPair{customFormatter, key})
|
||||
return key
|
||||
}
|
||||
|
||||
/*
|
||||
UnregisterCustomFormatter unregisters a previously registered CustomFormatter. You should pass in the key returned by RegisterCustomFormatter
|
||||
*/
|
||||
func UnregisterCustomFormatter(key CustomFormatterKey) {
|
||||
formatters := []customFormatterKeyPair{}
|
||||
for _, f := range customFormatters {
|
||||
if f.CustomFormatterKey == key {
|
||||
continue
|
||||
}
|
||||
formatters = append(formatters, f)
|
||||
}
|
||||
customFormatters = formatters
|
||||
}
|
||||
|
||||
var customFormatters = []customFormatterKeyPair{}
|
||||
|
||||
/*
|
||||
Generates a formatted matcher success/failure message of the form:
|
||||
|
||||
@ -219,17 +265,24 @@ func Object(object interface{}, indentation uint) string {
|
||||
IndentString takes a string and indents each line by the specified amount.
|
||||
*/
|
||||
func IndentString(s string, indentation uint) string {
|
||||
return indentString(s, indentation, true)
|
||||
}
|
||||
|
||||
func indentString(s string, indentation uint, indentFirstLine bool) string {
|
||||
result := &strings.Builder{}
|
||||
components := strings.Split(s, "\n")
|
||||
result := ""
|
||||
indent := strings.Repeat(Indent, int(indentation))
|
||||
for i, component := range components {
|
||||
result += indent + component
|
||||
if i > 0 || indentFirstLine {
|
||||
result.WriteString(indent)
|
||||
}
|
||||
result.WriteString(component)
|
||||
if i < len(components)-1 {
|
||||
result += "\n"
|
||||
result.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
return result.String()
|
||||
}
|
||||
|
||||
func formatType(v reflect.Value) string {
|
||||
@ -261,18 +314,27 @@ func formatValue(value reflect.Value, indentation uint) string {
|
||||
if value.CanInterface() {
|
||||
obj := value.Interface()
|
||||
|
||||
// if a CustomFormatter handles this values, we'll go with that
|
||||
for _, customFormatter := range customFormatters {
|
||||
formatted, handled := customFormatter.CustomFormatter(obj)
|
||||
// do not truncate a user-provided CustomFormatter()
|
||||
if handled {
|
||||
return indentString(formatted, indentation+1, false)
|
||||
}
|
||||
}
|
||||
|
||||
// GomegaStringer will take precedence to other representations and disregards UseStringerRepresentation
|
||||
if x, ok := obj.(GomegaStringer); ok {
|
||||
// do not truncate a user-defined GoMegaString() value
|
||||
return x.GomegaString()
|
||||
// do not truncate a user-defined GomegaString() value
|
||||
return indentString(x.GomegaString(), indentation+1, false)
|
||||
}
|
||||
|
||||
if UseStringerRepresentation {
|
||||
switch x := obj.(type) {
|
||||
case fmt.GoStringer:
|
||||
return truncateLongStrings(x.GoString())
|
||||
return indentString(truncateLongStrings(x.GoString()), indentation+1, false)
|
||||
case fmt.Stringer:
|
||||
return truncateLongStrings(x.String())
|
||||
return indentString(truncateLongStrings(x.String()), indentation+1, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
6
vendor/github.com/onsi/gomega/gbytes/buffer.go
generated
vendored
6
vendor/github.com/onsi/gomega/gbytes/buffer.go
generated
vendored
@ -87,17 +87,11 @@ func (b *Buffer) Write(p []byte) (n int, err error) {
|
||||
/*
|
||||
Read implements the io.Reader interface. It advances the
|
||||
cursor as it reads.
|
||||
|
||||
Returns an error if called after Close.
|
||||
*/
|
||||
func (b *Buffer) Read(d []byte) (int, error) {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
if b.closed {
|
||||
return 0, errors.New("attempt to read from closed buffer")
|
||||
}
|
||||
|
||||
if uint64(len(b.contents)) <= b.readCursor {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
19
vendor/github.com/onsi/gomega/gexec/build.go
generated
vendored
19
vendor/github.com/onsi/gomega/gexec/build.go
generated
vendored
@ -6,7 +6,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"go/build"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
@ -14,6 +13,8 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/onsi/gomega/internal/gutil"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -82,11 +83,11 @@ func CompileTest(packagePath string, args ...string) (compiledPath string, err e
|
||||
GetAndCompileTest is identical to CompileTest but `go get` the package before compiling tests.
|
||||
*/
|
||||
func GetAndCompileTest(packagePath string, args ...string) (compiledPath string, err error) {
|
||||
if err := getForTest(build.Default.GOPATH, packagePath, nil); err != nil {
|
||||
if err := getForTest(build.Default.GOPATH, packagePath, []string{"GO111MODULE=off"}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return doCompileTest(build.Default.GOPATH, packagePath, nil, args...)
|
||||
return doCompileTest(build.Default.GOPATH, packagePath, []string{"GO111MODULE=off"}, args...)
|
||||
}
|
||||
|
||||
/*
|
||||
@ -100,11 +101,11 @@ func CompileTestWithEnvironment(packagePath string, env []string, args ...string
|
||||
GetAndCompileTestWithEnvironment is identical to GetAndCompileTest but allows you to specify env vars to be set at build time.
|
||||
*/
|
||||
func GetAndCompileTestWithEnvironment(packagePath string, env []string, args ...string) (compiledPath string, err error) {
|
||||
if err := getForTest(build.Default.GOPATH, packagePath, env); err != nil {
|
||||
if err := getForTest(build.Default.GOPATH, packagePath, append(env, "GO111MODULE=off")); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return doCompileTest(build.Default.GOPATH, packagePath, env, args...)
|
||||
return doCompileTest(build.Default.GOPATH, packagePath, append(env, "GO111MODULE=off"), args...)
|
||||
}
|
||||
|
||||
/*
|
||||
@ -118,11 +119,11 @@ func CompileTestIn(gopath string, packagePath string, args ...string) (compiledP
|
||||
GetAndCompileTestIn is identical to GetAndCompileTest but allows you to specify a custom $GOPATH (the first argument).
|
||||
*/
|
||||
func GetAndCompileTestIn(gopath string, packagePath string, args ...string) (compiledPath string, err error) {
|
||||
if err := getForTest(gopath, packagePath, nil); err != nil {
|
||||
if err := getForTest(gopath, packagePath, []string{"GO111MODULE=off"}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return doCompileTest(gopath, packagePath, nil, args...)
|
||||
return doCompileTest(gopath, packagePath, []string{"GO111MODULE=off"}, args...)
|
||||
}
|
||||
|
||||
func isLocalPackage(packagePath string) bool {
|
||||
@ -222,11 +223,11 @@ func temporaryDirectory() (string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if tmpDir == "" {
|
||||
tmpDir, err = ioutil.TempDir("", "gexec_artifacts")
|
||||
tmpDir, err = gutil.MkdirTemp("", "gexec_artifacts")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return ioutil.TempDir(tmpDir, "g")
|
||||
return gutil.MkdirTemp(tmpDir, "g")
|
||||
}
|
||||
|
1
vendor/github.com/onsi/gomega/gexec/session.go
generated
vendored
1
vendor/github.com/onsi/gomega/gexec/session.go
generated
vendored
@ -121,7 +121,6 @@ To assert that the command has exited it is more convenient to use the Exit matc
|
||||
|
||||
When the process exits because it has received a particular signal, the exit code will be 128+signal-value
|
||||
(See http://www.tldp.org/LDP/abs/html/exitcodes.html and http://man7.org/linux/man-pages/man7/signal.7.html)
|
||||
|
||||
*/
|
||||
func (s *Session) ExitCode() int {
|
||||
s.lock.Lock()
|
||||
|
249
vendor/github.com/onsi/gomega/gomega_dsl.go
generated
vendored
249
vendor/github.com/onsi/gomega/gomega_dsl.go
generated
vendored
@ -22,7 +22,7 @@ import (
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
const GOMEGA_VERSION = "1.15.0"
|
||||
const GOMEGA_VERSION = "1.24.2"
|
||||
|
||||
const nilGomegaPanic = `You are trying to make an assertion, but haven't registered Gomega's fail handler.
|
||||
If you're using Ginkgo then you probably forgot to put your assertion in an It().
|
||||
@ -34,7 +34,7 @@ Depending on your vendoring solution you may be inadvertently importing gomega a
|
||||
// to abstract between the standard package-level function implementations
|
||||
// and alternatives like *WithT.
|
||||
//
|
||||
// The types in the top-level DSL have gotten a bit messy due to earlier depracations that avoid stuttering
|
||||
// The types in the top-level DSL have gotten a bit messy due to earlier deprecations that avoid stuttering
|
||||
// and due to an accidental use of a concrete type (*WithT) in an earlier release.
|
||||
//
|
||||
// As of 1.15 both the WithT and Ginkgo variants of Gomega are implemented by the same underlying object
|
||||
@ -52,7 +52,7 @@ var Default = Gomega(internal.NewGomega(internal.FetchDefaultDurationBundle()))
|
||||
// rich ecosystem of matchers without causing a test to fail. For example, to aggregate a series of potential failures
|
||||
// or for use in a non-test setting.
|
||||
func NewGomega(fail types.GomegaFailHandler) Gomega {
|
||||
return internal.NewGomega(Default.(*internal.Gomega).DurationBundle).ConfigureWithFailHandler(fail)
|
||||
return internal.NewGomega(internalGomega(Default).DurationBundle).ConfigureWithFailHandler(fail)
|
||||
}
|
||||
|
||||
// WithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage
|
||||
@ -69,17 +69,31 @@ type WithT = internal.Gomega
|
||||
// GomegaWithT is deprecated in favor of gomega.WithT, which does not stutter.
|
||||
type GomegaWithT = WithT
|
||||
|
||||
// NewWithT takes a *testing.T and returngs a `gomega.WithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with
|
||||
// inner is an interface that allows users to provide a wrapper around Default. The wrapper
|
||||
// must implement the inner interface and return either the original Default or the result of
|
||||
// a call to NewGomega().
|
||||
type inner interface {
|
||||
Inner() Gomega
|
||||
}
|
||||
|
||||
func internalGomega(g Gomega) *internal.Gomega {
|
||||
if v, ok := g.(inner); ok {
|
||||
return v.Inner().(*internal.Gomega)
|
||||
}
|
||||
return g.(*internal.Gomega)
|
||||
}
|
||||
|
||||
// NewWithT takes a *testing.T and returns a `gomega.WithT` 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 := gomega.NewWithT(t)
|
||||
// func TestFarmHasCow(t *testing.T) {
|
||||
// g := gomega.NewWithT(t)
|
||||
//
|
||||
// f := farm.New([]string{"Cow", "Horse"})
|
||||
// g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
|
||||
// }
|
||||
// f := farm.New([]string{"Cow", "Horse"})
|
||||
// g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
|
||||
// }
|
||||
func NewWithT(t types.GomegaTestingT) *WithT {
|
||||
return internal.NewGomega(Default.(*internal.Gomega).DurationBundle).ConfigureWithT(t)
|
||||
return internal.NewGomega(internalGomega(Default).DurationBundle).ConfigureWithT(t)
|
||||
}
|
||||
|
||||
// NewGomegaWithT is deprecated in favor of gomega.NewWithT, which does not stutter.
|
||||
@ -88,37 +102,37 @@ var NewGomegaWithT = NewWithT
|
||||
// RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails
|
||||
// the fail handler passed into RegisterFailHandler is called.
|
||||
func RegisterFailHandler(fail types.GomegaFailHandler) {
|
||||
Default.(*internal.Gomega).ConfigureWithFailHandler(fail)
|
||||
internalGomega(Default).ConfigureWithFailHandler(fail)
|
||||
}
|
||||
|
||||
// RegisterFailHandlerWithT is deprecated and will be removed in a future release.
|
||||
// users should use RegisterFailHandler, or RegisterTestingT
|
||||
func RegisterFailHandlerWithT(_ types.GomegaTestingT, fail types.GomegaFailHandler) {
|
||||
fmt.Println("RegisterFailHandlerWithT is deprecated. Please use RegisterFailHandler or RegisterTestingT instead.")
|
||||
Default.(*internal.Gomega).ConfigureWithFailHandler(fail)
|
||||
internalGomega(Default).ConfigureWithFailHandler(fail)
|
||||
}
|
||||
|
||||
// RegisterTestingT connects Gomega to Golang's XUnit style
|
||||
// Testing.T tests. It is now deprecated and you should use NewWithT() instead to get a fresh instance of Gomega for each test.
|
||||
func RegisterTestingT(t types.GomegaTestingT) {
|
||||
Default.(*internal.Gomega).ConfigureWithT(t)
|
||||
internalGomega(Default).ConfigureWithT(t)
|
||||
}
|
||||
|
||||
// InterceptGomegaFailures runs a given callback and returns an array of
|
||||
// failure messages generated by any Gomega assertions within the callback.
|
||||
// Exeuction continues after the first failure allowing users to collect all failures
|
||||
// Execution continues after the first failure allowing users to collect all failures
|
||||
// in the callback.
|
||||
//
|
||||
// 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 := Default.(*internal.Gomega).Fail
|
||||
originalHandler := internalGomega(Default).Fail
|
||||
failures := []string{}
|
||||
Default.(*internal.Gomega).Fail = func(message string, callerSkip ...int) {
|
||||
internalGomega(Default).Fail = func(message string, callerSkip ...int) {
|
||||
failures = append(failures, message)
|
||||
}
|
||||
defer func() {
|
||||
Default.(*internal.Gomega).Fail = originalHandler
|
||||
internalGomega(Default).Fail = originalHandler
|
||||
}()
|
||||
f()
|
||||
return failures
|
||||
@ -131,14 +145,14 @@ func InterceptGomegaFailures(f func()) []string {
|
||||
// does not register a failure with the FailHandler registered via RegisterFailHandler - it is up
|
||||
// to the user to decide what to do with the returned error
|
||||
func InterceptGomegaFailure(f func()) (err error) {
|
||||
originalHandler := Default.(*internal.Gomega).Fail
|
||||
Default.(*internal.Gomega).Fail = func(message string, callerSkip ...int) {
|
||||
originalHandler := internalGomega(Default).Fail
|
||||
internalGomega(Default).Fail = func(message string, callerSkip ...int) {
|
||||
err = errors.New(message)
|
||||
panic("stop execution")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
Default.(*internal.Gomega).Fail = originalHandler
|
||||
internalGomega(Default).Fail = originalHandler
|
||||
if e := recover(); e != nil {
|
||||
if err == nil {
|
||||
panic(e)
|
||||
@ -151,13 +165,14 @@ func InterceptGomegaFailure(f func()) (err error) {
|
||||
}
|
||||
|
||||
func ensureDefaultGomegaIsConfigured() {
|
||||
if !Default.(*internal.Gomega).IsConfigured() {
|
||||
if !internalGomega(Default).IsConfigured() {
|
||||
panic(nilGomegaPanic)
|
||||
}
|
||||
}
|
||||
|
||||
// Ω 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.
|
||||
@ -166,10 +181,13 @@ func ensureDefaultGomegaIsConfigured() {
|
||||
// a value and an error - a common patter in Go.
|
||||
//
|
||||
// For example, given a function with signature:
|
||||
// func MyAmazingThing() (int, error)
|
||||
//
|
||||
// func MyAmazingThing() (int, error)
|
||||
//
|
||||
// Then:
|
||||
// Ω(MyAmazingThing()).Should(Equal(3))
|
||||
//
|
||||
// Ω(MyAmazingThing()).Should(Equal(3))
|
||||
//
|
||||
// Will succeed only if `MyAmazingThing()` returns `(3, nil)`
|
||||
//
|
||||
// Ω and Expect are identical
|
||||
@ -179,7 +197,8 @@ func Ω(actual interface{}, extra ...interface{}) Assertion {
|
||||
}
|
||||
|
||||
// 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.
|
||||
@ -188,10 +207,13 @@ func Ω(actual interface{}, extra ...interface{}) Assertion {
|
||||
// a value and an error - a common patter in Go.
|
||||
//
|
||||
// For example, given a function with signature:
|
||||
// func MyAmazingThing() (int, error)
|
||||
//
|
||||
// func MyAmazingThing() (int, error)
|
||||
//
|
||||
// Then:
|
||||
// Expect(MyAmazingThing()).Should(Equal(3))
|
||||
//
|
||||
// Expect(MyAmazingThing()).Should(Equal(3))
|
||||
//
|
||||
// Will succeed only if `MyAmazingThing()` returns `(3, nil)`
|
||||
//
|
||||
// Expect and Ω are identical
|
||||
@ -201,10 +223,12 @@ func Expect(actual interface{}, extra ...interface{}) Assertion {
|
||||
}
|
||||
|
||||
// ExpectWithOffset wraps an actual value allowing assertions to be made on it:
|
||||
// ExpectWithOffset(1, "foo").To(Equal("foo"))
|
||||
//
|
||||
// ExpectWithOffset(1, "foo").To(Equal("foo"))
|
||||
//
|
||||
// Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument
|
||||
// that is used to modify the call-stack offset when computing line numbers.
|
||||
// that is used to modify the call-stack offset when computing line numbers. It is
|
||||
// the same as `Expect(...).WithOffset`.
|
||||
//
|
||||
// This is most useful in helper functions that make assertions. If you want Gomega's
|
||||
// error message to refer to the calling line in the test (as opposed to the line in the helper function)
|
||||
@ -218,7 +242,7 @@ func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Asse
|
||||
Eventually enables making assertions on asynchronous behavior.
|
||||
|
||||
Eventually checks that an assertion *eventually* passes. Eventually blocks when called and attempts an assertion periodically until it passes or a timeout occurs. Both the timeout and polling interval are configurable as optional arguments.
|
||||
The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds).
|
||||
The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds). In addition an optional context.Context can be passed in - Eventually will keep trying until either the timeout epxires or the context is cancelled, whichever comes first.
|
||||
|
||||
Eventually works with any Gomega compatible matcher and supports making assertions against three categories of actual value:
|
||||
|
||||
@ -226,15 +250,15 @@ Eventually works with any Gomega compatible matcher and supports making assertio
|
||||
|
||||
There are several examples of values that can change over time. These can be passed in to Eventually and will be passed to the matcher repeatedly until a match occurs. For example:
|
||||
|
||||
c := make(chan bool)
|
||||
go DoStuff(c)
|
||||
Eventually(c, "50ms").Should(BeClosed())
|
||||
c := make(chan bool)
|
||||
go DoStuff(c)
|
||||
Eventually(c, "50ms").Should(BeClosed())
|
||||
|
||||
will poll the channel repeatedly until it is closed. In this example `Eventually` will block until either the specified timeout of 50ms has elapsed or the channel is closed, whichever comes first.
|
||||
|
||||
Several Gomega libraries allow you to use Eventually in this way. For example, the gomega/gexec package allows you to block until a *gexec.Session exits successfuly via:
|
||||
Several Gomega libraries allow you to use Eventually in this way. For example, the gomega/gexec package allows you to block until a *gexec.Session exits successfully via:
|
||||
|
||||
Eventually(session).Should(gexec.Exit(0))
|
||||
Eventually(session).Should(gexec.Exit(0))
|
||||
|
||||
And the gomega/gbytes package allows you to monitor a streaming *gbytes.Buffer until a given string is seen:
|
||||
|
||||
@ -251,33 +275,57 @@ this will trigger Go's race detector as the goroutine polling via Eventually wil
|
||||
|
||||
**Category 2: Make Eventually assertions on functions**
|
||||
|
||||
Eventually can be passed functions that **take no arguments** and **return at least one value**. When configured this way, Eventually will poll the function repeatedly and pass the first returned value to the matcher.
|
||||
Eventually can be passed functions that **return at least one value**. When configured this way, Eventually will poll the function repeatedly and pass the first returned value to the matcher.
|
||||
|
||||
For example:
|
||||
|
||||
Eventually(func() int {
|
||||
return client.FetchCount()
|
||||
}).Should(BeNumerically(">=", 17))
|
||||
Eventually(func() int {
|
||||
return client.FetchCount()
|
||||
}).Should(BeNumerically(">=", 17))
|
||||
|
||||
will repeatedly poll client.FetchCount until the BeNumerically matcher is satisfied. (Note that this example could have been written as Eventually(client.FetchCount).Should(BeNumerically(">=", 17)))
|
||||
will repeatedly poll client.FetchCount until the BeNumerically matcher is satisfied. (Note that this example could have been written as Eventually(client.FetchCount).Should(BeNumerically(">=", 17)))
|
||||
|
||||
If multple values are returned by the function, Eventually will pass the first value to the matcher and require that all others are zero-valued. This allows you to pass Eventually a function that returns a value and an error - a common patternin Go.
|
||||
If multiple values are returned by the function, Eventually will pass the first value to the matcher and require that all others are zero-valued. This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go.
|
||||
|
||||
For example, consider a method that returns a value and an error:
|
||||
func FetchFromDB() (string, error)
|
||||
|
||||
func FetchFromDB() (string, error)
|
||||
|
||||
Then
|
||||
Eventually(FetchFromDB).Should(Equal("got it"))
|
||||
|
||||
Eventually(FetchFromDB).Should(Equal("got it"))
|
||||
|
||||
will pass only if and when the returned error is nil *and* the returned string satisfies the matcher.
|
||||
|
||||
It is important to note that the function passed into Eventually is invoked *synchronously* when polled. Eventually does not (in fact, it cannot) kill the function if it takes longer to return than Eventually's configured timeout. You should design your functions with this in mind.
|
||||
Eventually can also accept functions that take arguments, however you must provide those arguments using .WithArguments(). For example, consider a function that takes a user-id and makes a network request to fetch a full name:
|
||||
|
||||
func FetchFullName(userId int) (string, error)
|
||||
|
||||
You can poll this function like so:
|
||||
|
||||
Eventually(FetchFullName).WithArguments(1138).Should(Equal("Wookie"))
|
||||
|
||||
It is important to note that the function passed into Eventually is invoked *synchronously* when polled. Eventually does not (in fact, it cannot) kill the function if it takes longer to return than Eventually's configured timeout. A common practice here is to use a context. Here's an example that combines Ginkgo's spec timeout support with Eventually:
|
||||
|
||||
It("fetches the correct count", func(ctx SpecContext) {
|
||||
Eventually(ctx, func() int {
|
||||
return client.FetchCount(ctx, "/users")
|
||||
}).Should(BeNumerically(">=", 17))
|
||||
}, SpecTimeout(time.Second))
|
||||
|
||||
you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with paseed-in arguments as long as the context appears first. You can rewrite the above example as:
|
||||
|
||||
It("fetches the correct count", func(ctx SpecContext) {
|
||||
Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17))
|
||||
}, SpecTimeout(time.Second))
|
||||
|
||||
Either way the context passd to Eventually is also passed to the underlying funciton. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit.
|
||||
|
||||
**Category 3: Making assertions _in_ the function passed into Eventually**
|
||||
|
||||
When testing complex systems it can be valuable to assert that a _set_ of assertions passes Eventually. Eventually supports this by accepting functions that take a single Gomega argument and return zero or more values.
|
||||
|
||||
Here's an example that makes some asssertions and returns a value and error:
|
||||
Here's an example that makes some assertions and returns a value and error:
|
||||
|
||||
Eventually(func(g Gomega) (Widget, error) {
|
||||
ids, err := client.FetchIDs()
|
||||
@ -291,27 +339,52 @@ will pass only if all the assertions in the polled function pass and the return
|
||||
Eventually also supports a special case polling function that takes a single Gomega argument and returns no values. Eventually assumes such a function is making assertions and is designed to work with the Succeed matcher to validate that all assertions have passed.
|
||||
For example:
|
||||
|
||||
Eventually(func(g Gomega) {
|
||||
model, err := client.Find(1138)
|
||||
g.Expect(err).NotTo(HaveOccurred())
|
||||
g.Expect(model.Reticulate()).To(Succeed())
|
||||
g.Expect(model.IsReticulated()).To(BeTrue())
|
||||
g.Expect(model.Save()).To(Succeed())
|
||||
}).Should(Succeed())
|
||||
Eventually(func(g Gomega) {
|
||||
model, err := client.Find(1138)
|
||||
g.Expect(err).NotTo(HaveOccurred())
|
||||
g.Expect(model.Reticulate()).To(Succeed())
|
||||
g.Expect(model.IsReticulated()).To(BeTrue())
|
||||
g.Expect(model.Save()).To(Succeed())
|
||||
}).Should(Succeed())
|
||||
|
||||
will rerun the function until all assertions pass.
|
||||
|
||||
You can also pass additional arugments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example:
|
||||
|
||||
Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){
|
||||
tok, err := client.GetToken(ctx)
|
||||
g.Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
elements, err := client.Fetch(ctx, tok, path)
|
||||
g.Expect(err).NotTo(HaveOccurred())
|
||||
g.Expect(elements).To(ConsistOf(expected))
|
||||
}).WithContext(ctx).WithArguments("/names", "Joe", "Jane", "Sam").Should(Succeed())
|
||||
|
||||
Finally, in addition to passing timeouts and a context to Eventually you can be more explicit with Eventually's chaining configuration methods:
|
||||
|
||||
Eventually(..., "1s", "2s", ctx).Should(...)
|
||||
|
||||
is equivalent to
|
||||
|
||||
Eventually(...).WithTimeout(time.Second).WithPolling(2*time.Second).WithContext(ctx).Should(...)
|
||||
*/
|
||||
func Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion {
|
||||
func Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion {
|
||||
ensureDefaultGomegaIsConfigured()
|
||||
return Default.Eventually(actual, intervals...)
|
||||
return Default.Eventually(actualOrCtx, args...)
|
||||
}
|
||||
|
||||
// EventuallyWithOffset operates like Eventually but takes an additional
|
||||
// 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{}) AsyncAssertion {
|
||||
//
|
||||
// `EventuallyWithOffset` is the same as `Eventually(...).WithOffset`.
|
||||
//
|
||||
// `EventuallyWithOffset` specifying a timeout interval (and an optional polling interval) are
|
||||
// the same as `Eventually(...).WithOffset(...).WithTimeout` or
|
||||
// `Eventually(...).WithOffset(...).WithTimeout(...).WithPolling`.
|
||||
func EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion {
|
||||
ensureDefaultGomegaIsConfigured()
|
||||
return Default.EventuallyWithOffset(offset, actual, intervals...)
|
||||
return Default.EventuallyWithOffset(offset, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
/*
|
||||
@ -319,29 +392,75 @@ Consistently, like Eventually, enables making assertions on asynchronous behavio
|
||||
|
||||
Consistently blocks when called for a specified duration. During that duration Consistently repeatedly polls its matcher and ensures that it is satisfied. If the matcher is consistently satisfied, then Consistently will pass. Otherwise Consistently will fail.
|
||||
|
||||
Both the total waiting duration and the polling interval are configurable as optional arguments. The first optional arugment is the duration that Consistently will run for (defaults to 100ms), and the second argument is the polling interval (defaults to 10ms). As with Eventually, these intervals can be passed in as time.Duration, parsable duration strings or an integer or float number of seconds.
|
||||
Both the total waiting duration and the polling interval are configurable as optional arguments. The first optional argument is the duration that Consistently will run for (defaults to 100ms), and the second argument is the polling interval (defaults to 10ms). As with Eventually, these intervals can be passed in as time.Duration, parsable duration strings or an integer or float number of seconds. You can also pass in an optional context.Context - Consistently will exit early (with a failure) if the context is cancelled before the waiting duration expires.
|
||||
|
||||
Consistently accepts the same three categories of actual as Eventually, check the Eventually docs to learn more.
|
||||
|
||||
Consistently is useful in cases where you want to assert that something *does not happen* for a period of time. For example, you may want to assert that a goroutine does *not* send data down a channel. In this case you could write:
|
||||
|
||||
Consistently(channel, "200ms").ShouldNot(Receive())
|
||||
Consistently(channel, "200ms").ShouldNot(Receive())
|
||||
|
||||
This will block for 200 milliseconds and repeatedly check the channel and ensure nothing has been received.
|
||||
*/
|
||||
func Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
|
||||
func Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion {
|
||||
ensureDefaultGomegaIsConfigured()
|
||||
return Default.Consistently(actual, intervals...)
|
||||
return Default.Consistently(actualOrCtx, args...)
|
||||
}
|
||||
|
||||
// ConsistentlyWithOffset operates like Consistently but takes an additional
|
||||
// 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{}) AsyncAssertion {
|
||||
//
|
||||
// `ConsistentlyWithOffset` is the same as `Consistently(...).WithOffset` and
|
||||
// optional `WithTimeout` and `WithPolling`.
|
||||
func ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion {
|
||||
ensureDefaultGomegaIsConfigured()
|
||||
return Default.ConsistentlyWithOffset(offset, actual, intervals...)
|
||||
return Default.ConsistentlyWithOffset(offset, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
/*
|
||||
StopTrying can be used to signal to Eventually and Consistentlythat they should abort and stop trying. This always results in a failure of the assertion - and the failure message is the content of the StopTrying signal.
|
||||
|
||||
You can send the StopTrying signal by either returning StopTrying("message") as an error from your passed-in function _or_ by calling StopTrying("message").Now() to trigger a panic and end execution.
|
||||
|
||||
You can also wrap StopTrying around an error with `StopTrying("message").Wrap(err)` and can attach additional objects via `StopTrying("message").Attach("description", object). When rendered, the signal will include the wrapped error and any attached objects rendered using Gomega's default formatting.
|
||||
|
||||
Here are a couple of examples. This is how you might use StopTrying() as an error to signal that Eventually should stop:
|
||||
|
||||
playerIndex, numPlayers := 0, 11
|
||||
Eventually(func() (string, error) {
|
||||
if playerIndex == numPlayers {
|
||||
return "", StopTrying("no more players left")
|
||||
}
|
||||
name := client.FetchPlayer(playerIndex)
|
||||
playerIndex += 1
|
||||
return name, nil
|
||||
}).Should(Equal("Patrick Mahomes"))
|
||||
|
||||
And here's an example where `StopTrying().Now()` is called to halt execution immediately:
|
||||
|
||||
Eventually(func() []string {
|
||||
names, err := client.FetchAllPlayers()
|
||||
if err == client.IRRECOVERABLE_ERROR {
|
||||
StopTrying("Irrecoverable error occurred").Wrap(err).Now()
|
||||
}
|
||||
return names
|
||||
}).Should(ContainElement("Patrick Mahomes"))
|
||||
*/
|
||||
var StopTrying = internal.StopTrying
|
||||
|
||||
/*
|
||||
TryAgainAfter(<duration>) allows you to adjust the polling interval for the _next_ iteration of `Eventually` or `Consistently`. Like `StopTrying` you can either return `TryAgainAfter` as an error or trigger it immedieately with `.Now()`
|
||||
|
||||
When `TryAgainAfter(<duration>` is triggered `Eventually` and `Consistently` will wait for that duration. If a timeout occurs before the next poll is triggered both `Eventually` and `Consistently` will always fail with the content of the TryAgainAfter message. As with StopTrying you can `.Wrap()` and error and `.Attach()` additional objects to `TryAgainAfter`.
|
||||
*/
|
||||
var TryAgainAfter = internal.TryAgainAfter
|
||||
|
||||
/*
|
||||
PollingSignalError is the error returned by StopTrying() and TryAgainAfter()
|
||||
*/
|
||||
type PollingSignalError = internal.PollingSignalError
|
||||
|
||||
// SetDefaultEventuallyTimeout sets the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses.
|
||||
func SetDefaultEventuallyTimeout(t time.Duration) {
|
||||
Default.SetDefaultEventuallyTimeout(t)
|
||||
@ -375,8 +494,8 @@ func SetDefaultConsistentlyPollingInterval(t time.Duration) {
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.")
|
||||
// Consistently(myChannel).ShouldNot(Receive(), func() string { return "Nothing should have come down the pipe." })
|
||||
// Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.")
|
||||
// Consistently(myChannel).ShouldNot(Receive(), func() string { return "Nothing should have come down the pipe." })
|
||||
type AsyncAssertion = types.AsyncAssertion
|
||||
|
||||
// GomegaAsyncAssertion is deprecated in favor of AsyncAssertion, which does not stutter.
|
||||
@ -398,7 +517,7 @@ type GomegaAsyncAssertion = types.AsyncAssertion
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm)
|
||||
// Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm)
|
||||
type Assertion = types.Assertion
|
||||
|
||||
// GomegaAssertion is deprecated in favor of Assertion, which does not stutter.
|
||||
|
92
vendor/github.com/onsi/gomega/internal/assertion.go
generated
vendored
92
vendor/github.com/onsi/gomega/internal/assertion.go
generated
vendored
@ -4,48 +4,74 @@ import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
type Assertion struct {
|
||||
actualInput interface{}
|
||||
actuals []interface{} // actual value plus all extra values
|
||||
actualIndex int // value to pass to the matcher
|
||||
vet vetinari // the vet to call before calling Gomega matcher
|
||||
offset int
|
||||
extra []interface{}
|
||||
g *Gomega
|
||||
}
|
||||
|
||||
// ...obligatory discworld reference, as "vetineer" doesn't sound ... quite right.
|
||||
type vetinari func(assertion *Assertion, optionalDescription ...interface{}) bool
|
||||
|
||||
func NewAssertion(actualInput interface{}, g *Gomega, offset int, extra ...interface{}) *Assertion {
|
||||
return &Assertion{
|
||||
actualInput: actualInput,
|
||||
actuals: append([]interface{}{actualInput}, extra...),
|
||||
actualIndex: 0,
|
||||
vet: (*Assertion).vetActuals,
|
||||
offset: offset,
|
||||
extra: extra,
|
||||
g: g,
|
||||
}
|
||||
}
|
||||
|
||||
func (assertion *Assertion) WithOffset(offset int) types.Assertion {
|
||||
assertion.offset = offset
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *Assertion) Error() types.Assertion {
|
||||
return &Assertion{
|
||||
actuals: assertion.actuals,
|
||||
actualIndex: len(assertion.actuals) - 1,
|
||||
vet: (*Assertion).vetError,
|
||||
offset: assertion.offset,
|
||||
g: assertion.g,
|
||||
}
|
||||
}
|
||||
|
||||
func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
|
||||
vetOptionalDescription("Assertion", optionalDescription...)
|
||||
return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
vetOptionalDescription("Assertion", optionalDescription...)
|
||||
return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
|
||||
vetOptionalDescription("Assertion", optionalDescription...)
|
||||
return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
vetOptionalDescription("Assertion", optionalDescription...)
|
||||
return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
vetOptionalDescription("Assertion", optionalDescription...)
|
||||
return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) string {
|
||||
@ -61,7 +87,8 @@ func (assertion *Assertion) buildDescription(optionalDescription ...interface{})
|
||||
}
|
||||
|
||||
func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool {
|
||||
matches, err := matcher.Match(assertion.actualInput)
|
||||
actualInput := assertion.actuals[assertion.actualIndex]
|
||||
matches, err := matcher.Match(actualInput)
|
||||
assertion.g.THelper()
|
||||
if err != nil {
|
||||
description := assertion.buildDescription(optionalDescription...)
|
||||
@ -71,9 +98,9 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool
|
||||
if matches != desiredMatch {
|
||||
var message string
|
||||
if desiredMatch {
|
||||
message = matcher.FailureMessage(assertion.actualInput)
|
||||
message = matcher.FailureMessage(actualInput)
|
||||
} else {
|
||||
message = matcher.NegatedFailureMessage(assertion.actualInput)
|
||||
message = matcher.NegatedFailureMessage(actualInput)
|
||||
}
|
||||
description := assertion.buildDescription(optionalDescription...)
|
||||
assertion.g.Fail(description+message, 2+assertion.offset)
|
||||
@ -83,8 +110,11 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool
|
||||
return true
|
||||
}
|
||||
|
||||
func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool {
|
||||
success, message := vetExtras(assertion.extra)
|
||||
// vetActuals vets the actual values, with the (optional) exception of a
|
||||
// specific value, such as the first value in case non-error assertions, or the
|
||||
// last value in case of Error()-based assertions.
|
||||
func (assertion *Assertion) vetActuals(optionalDescription ...interface{}) bool {
|
||||
success, message := vetActuals(assertion.actuals, assertion.actualIndex)
|
||||
if success {
|
||||
return true
|
||||
}
|
||||
@ -95,12 +125,34 @@ func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func vetExtras(extras []interface{}) (bool, string) {
|
||||
for i, extra := range extras {
|
||||
if extra != nil {
|
||||
zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface()
|
||||
if !reflect.DeepEqual(zeroValue, extra) {
|
||||
message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra)
|
||||
// vetError vets the actual values, except for the final error value, in case
|
||||
// the final error value is non-zero. Otherwise, it doesn't vet the actual
|
||||
// values, as these are allowed to take on any values unless there is a non-zero
|
||||
// error value.
|
||||
func (assertion *Assertion) vetError(optionalDescription ...interface{}) bool {
|
||||
if err := assertion.actuals[assertion.actualIndex]; err != nil {
|
||||
// Go error result idiom: all other actual values must be zero values.
|
||||
return assertion.vetActuals(optionalDescription...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// vetActuals vets a slice of actual values, optionally skipping a particular
|
||||
// value slice element, such as the first or last value slice element.
|
||||
func vetActuals(actuals []interface{}, skipIndex int) (bool, string) {
|
||||
for i, actual := range actuals {
|
||||
if i == skipIndex {
|
||||
continue
|
||||
}
|
||||
if actual != nil {
|
||||
zeroValue := reflect.Zero(reflect.TypeOf(actual)).Interface()
|
||||
if !reflect.DeepEqual(zeroValue, actual) {
|
||||
var message string
|
||||
if err, ok := actual.(error); ok {
|
||||
message = fmt.Sprintf("Unexpected error: %s\n%s", err, format.Object(err, 1))
|
||||
} else {
|
||||
message = fmt.Sprintf("Unexpected non-nil/non-zero argument at index %d:\n\t<%T>: %#v", i, actual, actual)
|
||||
}
|
||||
return false, message
|
||||
}
|
||||
}
|
||||
|
465
vendor/github.com/onsi/gomega/internal/async_assertion.go
generated
vendored
465
vendor/github.com/onsi/gomega/internal/async_assertion.go
generated
vendored
@ -1,15 +1,36 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
var errInterface = reflect.TypeOf((*error)(nil)).Elem()
|
||||
var gomegaType = reflect.TypeOf((*types.Gomega)(nil)).Elem()
|
||||
var contextType = reflect.TypeOf(new(context.Context)).Elem()
|
||||
|
||||
type contextWithAttachProgressReporter interface {
|
||||
AttachProgressReporter(func() string) func()
|
||||
}
|
||||
|
||||
type asyncGomegaHaltExecutionError struct{}
|
||||
|
||||
func (a asyncGomegaHaltExecutionError) GinkgoRecoverShouldIgnoreThisPanic() {}
|
||||
func (a asyncGomegaHaltExecutionError) Error() string {
|
||||
return `An assertion has failed in a goroutine. You should call
|
||||
|
||||
defer GinkgoRecover()
|
||||
|
||||
at the top of the goroutine that caused this panic. This will allow Ginkgo and Gomega to correctly capture and manage this panic.`
|
||||
}
|
||||
|
||||
type AsyncAssertionType uint
|
||||
|
||||
const (
|
||||
@ -17,83 +38,92 @@ const (
|
||||
AsyncAssertionTypeConsistently
|
||||
)
|
||||
|
||||
func (at AsyncAssertionType) String() string {
|
||||
switch at {
|
||||
case AsyncAssertionTypeEventually:
|
||||
return "Eventually"
|
||||
case AsyncAssertionTypeConsistently:
|
||||
return "Consistently"
|
||||
}
|
||||
return "INVALID ASYNC ASSERTION TYPE"
|
||||
}
|
||||
|
||||
type AsyncAssertion struct {
|
||||
asyncType AsyncAssertionType
|
||||
|
||||
actualIsFunc bool
|
||||
actualValue interface{}
|
||||
actualFunc func() ([]reflect.Value, error)
|
||||
actualIsFunc bool
|
||||
actual interface{}
|
||||
argsToForward []interface{}
|
||||
|
||||
timeoutInterval time.Duration
|
||||
pollingInterval time.Duration
|
||||
ctx context.Context
|
||||
offset int
|
||||
g *Gomega
|
||||
}
|
||||
|
||||
func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput interface{}, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion {
|
||||
func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput interface{}, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, ctx context.Context, offset int) *AsyncAssertion {
|
||||
out := &AsyncAssertion{
|
||||
asyncType: asyncType,
|
||||
timeoutInterval: timeoutInterval,
|
||||
pollingInterval: pollingInterval,
|
||||
offset: offset,
|
||||
ctx: ctx,
|
||||
g: g,
|
||||
}
|
||||
|
||||
switch actualType := reflect.TypeOf(actualInput); {
|
||||
case actualType.Kind() != reflect.Func:
|
||||
out.actualValue = actualInput
|
||||
case actualType.NumIn() == 0 && actualType.NumOut() > 0:
|
||||
out.actual = actualInput
|
||||
if actualInput != nil && reflect.TypeOf(actualInput).Kind() == reflect.Func {
|
||||
out.actualIsFunc = true
|
||||
out.actualFunc = func() ([]reflect.Value, error) {
|
||||
return reflect.ValueOf(actualInput).Call([]reflect.Value{}), nil
|
||||
}
|
||||
case actualType.NumIn() == 1 && actualType.In(0).Implements(reflect.TypeOf((*types.Gomega)(nil)).Elem()):
|
||||
out.actualIsFunc = true
|
||||
out.actualFunc = func() (values []reflect.Value, err error) {
|
||||
var assertionFailure error
|
||||
assertionCapturingGomega := NewGomega(g.DurationBundle).ConfigureWithFailHandler(func(message string, callerSkip ...int) {
|
||||
skip := 0
|
||||
if len(callerSkip) > 0 {
|
||||
skip = callerSkip[0]
|
||||
}
|
||||
_, file, line, _ := runtime.Caller(skip + 1)
|
||||
assertionFailure = fmt.Errorf("Assertion in callback at %s:%d failed:\n%s", file, line, message)
|
||||
panic("stop execution")
|
||||
})
|
||||
|
||||
defer func() {
|
||||
if actualType.NumOut() == 0 {
|
||||
if assertionFailure == nil {
|
||||
values = []reflect.Value{reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())}
|
||||
} else {
|
||||
values = []reflect.Value{reflect.ValueOf(assertionFailure)}
|
||||
}
|
||||
} else {
|
||||
err = assertionFailure
|
||||
}
|
||||
if e := recover(); e != nil && assertionFailure == nil {
|
||||
panic(e)
|
||||
}
|
||||
}()
|
||||
|
||||
values = reflect.ValueOf(actualInput).Call([]reflect.Value{reflect.ValueOf(assertionCapturingGomega)})
|
||||
return
|
||||
}
|
||||
default:
|
||||
msg := fmt.Sprintf("The function passed to Gomega's async assertions should either take no arguments and return values, or take a single Gomega interface that it can use to make assertions within the body of the function. When taking a Gomega interface the function can optionally return values or return nothing. The function you passed takes %d arguments and returns %d values.", actualType.NumIn(), actualType.NumOut())
|
||||
g.Fail(msg, offset+4)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) WithOffset(offset int) types.AsyncAssertion {
|
||||
assertion.offset = offset
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) WithTimeout(interval time.Duration) types.AsyncAssertion {
|
||||
assertion.timeoutInterval = interval
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) WithPolling(interval time.Duration) types.AsyncAssertion {
|
||||
assertion.pollingInterval = interval
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) Within(timeout time.Duration) types.AsyncAssertion {
|
||||
assertion.timeoutInterval = timeout
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) ProbeEvery(interval time.Duration) types.AsyncAssertion {
|
||||
assertion.pollingInterval = interval
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) WithContext(ctx context.Context) types.AsyncAssertion {
|
||||
assertion.ctx = ctx
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) WithArguments(argsToForward ...interface{}) types.AsyncAssertion {
|
||||
assertion.argsToForward = argsToForward
|
||||
return assertion
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
vetOptionalDescription("Asynchronous assertion", optionalDescription...)
|
||||
return assertion.match(matcher, true, optionalDescription...)
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool {
|
||||
assertion.g.THelper()
|
||||
vetOptionalDescription("Asynchronous assertion", optionalDescription...)
|
||||
return assertion.match(matcher, false, optionalDescription...)
|
||||
}
|
||||
|
||||
@ -109,54 +139,238 @@ func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interfa
|
||||
return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n"
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) pollActual() (interface{}, error) {
|
||||
if !assertion.actualIsFunc {
|
||||
return assertion.actualValue, nil
|
||||
func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (interface{}, error) {
|
||||
if len(values) == 0 {
|
||||
return nil, fmt.Errorf("No values were returned by the function passed to Gomega")
|
||||
}
|
||||
|
||||
values, err := assertion.actualFunc()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extras := []interface{}{}
|
||||
for _, value := range values[1:] {
|
||||
extras = append(extras, value.Interface())
|
||||
}
|
||||
success, message := vetExtras(extras)
|
||||
if !success {
|
||||
return nil, errors.New(message)
|
||||
actual := values[0].Interface()
|
||||
if _, ok := AsPollingSignalError(actual); ok {
|
||||
return actual, actual.(error)
|
||||
}
|
||||
|
||||
return values[0].Interface(), nil
|
||||
var err error
|
||||
for i, extraValue := range values[1:] {
|
||||
extra := extraValue.Interface()
|
||||
if extra == nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := AsPollingSignalError(extra); ok {
|
||||
return actual, extra.(error)
|
||||
}
|
||||
extraType := reflect.TypeOf(extra)
|
||||
zero := reflect.Zero(extraType).Interface()
|
||||
if reflect.DeepEqual(extra, zero) {
|
||||
continue
|
||||
}
|
||||
if i == len(values)-2 && extraType.Implements(errInterface) {
|
||||
err = fmt.Errorf("function returned error: %w", extra.(error))
|
||||
}
|
||||
if err == nil {
|
||||
err = fmt.Errorf("Unexpected non-nil/non-zero return value at index %d:\n\t<%T>: %#v", i+1, extra, extra)
|
||||
}
|
||||
}
|
||||
|
||||
return actual, err
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) matcherMayChange(matcher types.GomegaMatcher, value interface{}) bool {
|
||||
if assertion.actualIsFunc {
|
||||
return true
|
||||
func (assertion *AsyncAssertion) invalidFunctionError(t reflect.Type) error {
|
||||
return fmt.Errorf(`The function passed to %s had an invalid signature of %s. Functions passed to %s must either:
|
||||
|
||||
(a) have return values or
|
||||
(b) take a Gomega interface as their first argument and use that Gomega instance to make assertions.
|
||||
|
||||
You can learn more at https://onsi.github.io/gomega/#eventually
|
||||
`, assertion.asyncType, t, assertion.asyncType)
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) noConfiguredContextForFunctionError() error {
|
||||
return fmt.Errorf(`The function passed to %s requested a context.Context, but no context has been provided. Please pass one in using %s().WithContext().
|
||||
|
||||
You can learn more at https://onsi.github.io/gomega/#eventually
|
||||
`, assertion.asyncType, assertion.asyncType)
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) argumentMismatchError(t reflect.Type, numProvided int) error {
|
||||
have := "have"
|
||||
if numProvided == 1 {
|
||||
have = "has"
|
||||
}
|
||||
return types.MatchMayChangeInTheFuture(matcher, value)
|
||||
return fmt.Errorf(`The function passed to %s has signature %s takes %d arguments but %d %s been provided. Please use %s().WithArguments() to pass the corect set of arguments.
|
||||
|
||||
You can learn more at https://onsi.github.io/gomega/#eventually
|
||||
`, assertion.asyncType, t, t.NumIn(), numProvided, have, assertion.asyncType)
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) buildActualPoller() (func() (interface{}, error), error) {
|
||||
if !assertion.actualIsFunc {
|
||||
return func() (interface{}, error) { return assertion.actual, nil }, nil
|
||||
}
|
||||
actualValue := reflect.ValueOf(assertion.actual)
|
||||
actualType := reflect.TypeOf(assertion.actual)
|
||||
numIn, numOut, isVariadic := actualType.NumIn(), actualType.NumOut(), actualType.IsVariadic()
|
||||
|
||||
if numIn == 0 && numOut == 0 {
|
||||
return nil, assertion.invalidFunctionError(actualType)
|
||||
}
|
||||
takesGomega, takesContext := false, false
|
||||
if numIn > 0 {
|
||||
takesGomega, takesContext = actualType.In(0).Implements(gomegaType), actualType.In(0).Implements(contextType)
|
||||
}
|
||||
if takesGomega && numIn > 1 && actualType.In(1).Implements(contextType) {
|
||||
takesContext = true
|
||||
}
|
||||
if takesContext && len(assertion.argsToForward) > 0 && reflect.TypeOf(assertion.argsToForward[0]).Implements(contextType) {
|
||||
takesContext = false
|
||||
}
|
||||
if !takesGomega && numOut == 0 {
|
||||
return nil, assertion.invalidFunctionError(actualType)
|
||||
}
|
||||
if takesContext && assertion.ctx == nil {
|
||||
return nil, assertion.noConfiguredContextForFunctionError()
|
||||
}
|
||||
|
||||
var assertionFailure error
|
||||
inValues := []reflect.Value{}
|
||||
if takesGomega {
|
||||
inValues = append(inValues, reflect.ValueOf(NewGomega(assertion.g.DurationBundle).ConfigureWithFailHandler(func(message string, callerSkip ...int) {
|
||||
skip := 0
|
||||
if len(callerSkip) > 0 {
|
||||
skip = callerSkip[0]
|
||||
}
|
||||
_, file, line, _ := runtime.Caller(skip + 1)
|
||||
assertionFailure = fmt.Errorf("Assertion in callback at %s:%d failed:\n%s", file, line, message)
|
||||
// we throw an asyncGomegaHaltExecutionError so that defer GinkgoRecover() can catch this error if the user makes an assertion in a goroutine
|
||||
panic(asyncGomegaHaltExecutionError{})
|
||||
})))
|
||||
}
|
||||
if takesContext {
|
||||
inValues = append(inValues, reflect.ValueOf(assertion.ctx))
|
||||
}
|
||||
for _, arg := range assertion.argsToForward {
|
||||
inValues = append(inValues, reflect.ValueOf(arg))
|
||||
}
|
||||
|
||||
if !isVariadic && numIn != len(inValues) {
|
||||
return nil, assertion.argumentMismatchError(actualType, len(inValues))
|
||||
} else if isVariadic && len(inValues) < numIn-1 {
|
||||
return nil, assertion.argumentMismatchError(actualType, len(inValues))
|
||||
}
|
||||
|
||||
return func() (actual interface{}, err error) {
|
||||
var values []reflect.Value
|
||||
assertionFailure = nil
|
||||
defer func() {
|
||||
if numOut == 0 && takesGomega {
|
||||
actual = assertionFailure
|
||||
} else {
|
||||
actual, err = assertion.processReturnValues(values)
|
||||
_, isAsyncError := AsPollingSignalError(err)
|
||||
if assertionFailure != nil && !isAsyncError {
|
||||
err = assertionFailure
|
||||
}
|
||||
}
|
||||
if e := recover(); e != nil {
|
||||
if _, isAsyncError := AsPollingSignalError(e); isAsyncError {
|
||||
err = e.(error)
|
||||
} else if assertionFailure == nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
}()
|
||||
values = actualValue.Call(inValues)
|
||||
return
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) afterTimeout() <-chan time.Time {
|
||||
if assertion.timeoutInterval >= 0 {
|
||||
return time.After(assertion.timeoutInterval)
|
||||
}
|
||||
|
||||
if assertion.asyncType == AsyncAssertionTypeConsistently {
|
||||
return time.After(assertion.g.DurationBundle.ConsistentlyDuration)
|
||||
} else {
|
||||
if assertion.ctx == nil {
|
||||
return time.After(assertion.g.DurationBundle.EventuallyTimeout)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) afterPolling() <-chan time.Time {
|
||||
if assertion.pollingInterval >= 0 {
|
||||
return time.After(assertion.pollingInterval)
|
||||
}
|
||||
if assertion.asyncType == AsyncAssertionTypeConsistently {
|
||||
return time.After(assertion.g.DurationBundle.ConsistentlyPollingInterval)
|
||||
} else {
|
||||
return time.After(assertion.g.DurationBundle.EventuallyPollingInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value interface{}) bool {
|
||||
if assertion.actualIsFunc || types.MatchMayChangeInTheFuture(matcher, value) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value interface{}) (matches bool, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
if _, isAsyncError := AsPollingSignalError(e); isAsyncError {
|
||||
err = e.(error)
|
||||
} else {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
matches, err = matcher.Match(value)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool {
|
||||
timer := time.Now()
|
||||
timeout := time.After(assertion.timeoutInterval)
|
||||
timeout := assertion.afterTimeout()
|
||||
lock := sync.Mutex{}
|
||||
|
||||
var matches bool
|
||||
var err error
|
||||
mayChange := true
|
||||
value, err := assertion.pollActual()
|
||||
if err == nil {
|
||||
mayChange = assertion.matcherMayChange(matcher, value)
|
||||
matches, err = matcher.Match(value)
|
||||
}
|
||||
var oracleMatcherSaysStop bool
|
||||
|
||||
assertion.g.THelper()
|
||||
|
||||
fail := func(preamble string) {
|
||||
errMsg := ""
|
||||
pollActual, err := assertion.buildActualPoller()
|
||||
if err != nil {
|
||||
assertion.g.Fail(err.Error(), 2+assertion.offset)
|
||||
return false
|
||||
}
|
||||
|
||||
value, err := pollActual()
|
||||
if err == nil {
|
||||
oracleMatcherSaysStop = assertion.matcherSaysStopTrying(matcher, value)
|
||||
matches, err = assertion.pollMatcher(matcher, value)
|
||||
}
|
||||
|
||||
messageGenerator := func() string {
|
||||
// can be called out of band by Ginkgo if the user requests a progress report
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
message := ""
|
||||
if err != nil {
|
||||
errMsg = "Error: " + err.Error()
|
||||
if pollingSignalErr, ok := AsPollingSignalError(err); ok && pollingSignalErr.IsStopTrying() {
|
||||
message = err.Error()
|
||||
for _, attachment := range pollingSignalErr.Attachments {
|
||||
message += fmt.Sprintf("\n%s:\n", attachment.Description)
|
||||
message += format.Object(attachment.Object, 1)
|
||||
}
|
||||
} else {
|
||||
message = "Error: " + err.Error() + "\n" + format.Object(err, 1)
|
||||
}
|
||||
} else {
|
||||
if desiredMatch {
|
||||
message = matcher.FailureMessage(value)
|
||||
@ -164,57 +378,90 @@ func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch
|
||||
message = matcher.NegatedFailureMessage(value)
|
||||
}
|
||||
}
|
||||
assertion.g.THelper()
|
||||
description := assertion.buildDescription(optionalDescription...)
|
||||
assertion.g.Fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset)
|
||||
return fmt.Sprintf("%s%s", description, message)
|
||||
}
|
||||
|
||||
if assertion.asyncType == AsyncAssertionTypeEventually {
|
||||
for {
|
||||
if err == nil && matches == desiredMatch {
|
||||
return true
|
||||
}
|
||||
fail := func(preamble string) {
|
||||
assertion.g.THelper()
|
||||
assertion.g.Fail(fmt.Sprintf("%s after %.3fs.\n%s", preamble, time.Since(timer).Seconds(), messageGenerator()), 3+assertion.offset)
|
||||
}
|
||||
|
||||
if !mayChange {
|
||||
fail("No future change is possible. Bailing out early")
|
||||
var contextDone <-chan struct{}
|
||||
if assertion.ctx != nil {
|
||||
contextDone = assertion.ctx.Done()
|
||||
if v, ok := assertion.ctx.Value("GINKGO_SPEC_CONTEXT").(contextWithAttachProgressReporter); ok {
|
||||
detach := v.AttachProgressReporter(messageGenerator)
|
||||
defer detach()
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
var nextPoll <-chan time.Time = nil
|
||||
var isTryAgainAfterError = false
|
||||
|
||||
if pollingSignalErr, ok := AsPollingSignalError(err); ok {
|
||||
if pollingSignalErr.IsStopTrying() {
|
||||
fail("Told to stop trying")
|
||||
return false
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(assertion.pollingInterval):
|
||||
value, err = assertion.pollActual()
|
||||
if err == nil {
|
||||
mayChange = assertion.matcherMayChange(matcher, value)
|
||||
matches, err = matcher.Match(value)
|
||||
}
|
||||
case <-timeout:
|
||||
fail("Timed out")
|
||||
return false
|
||||
if pollingSignalErr.IsTryAgainAfter() {
|
||||
nextPoll = time.After(pollingSignalErr.TryAgainDuration())
|
||||
isTryAgainAfterError = true
|
||||
}
|
||||
}
|
||||
} else if assertion.asyncType == AsyncAssertionTypeConsistently {
|
||||
for {
|
||||
if !(err == nil && matches == desiredMatch) {
|
||||
|
||||
if err == nil && matches == desiredMatch {
|
||||
if assertion.asyncType == AsyncAssertionTypeEventually {
|
||||
return true
|
||||
}
|
||||
} else if !isTryAgainAfterError {
|
||||
if assertion.asyncType == AsyncAssertionTypeConsistently {
|
||||
fail("Failed")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if !mayChange {
|
||||
if oracleMatcherSaysStop {
|
||||
if assertion.asyncType == AsyncAssertionTypeEventually {
|
||||
fail("No future change is possible. Bailing out early")
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(assertion.pollingInterval):
|
||||
value, err = assertion.pollActual()
|
||||
if err == nil {
|
||||
mayChange = assertion.matcherMayChange(matcher, value)
|
||||
matches, err = matcher.Match(value)
|
||||
if nextPoll == nil {
|
||||
nextPoll = assertion.afterPolling()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-nextPoll:
|
||||
v, e := pollActual()
|
||||
lock.Lock()
|
||||
value, err = v, e
|
||||
lock.Unlock()
|
||||
if err == nil {
|
||||
oracleMatcherSaysStop = assertion.matcherSaysStopTrying(matcher, value)
|
||||
m, e := assertion.pollMatcher(matcher, value)
|
||||
lock.Lock()
|
||||
matches, err = m, e
|
||||
lock.Unlock()
|
||||
}
|
||||
case <-contextDone:
|
||||
fail("Context was cancelled")
|
||||
return false
|
||||
case <-timeout:
|
||||
if assertion.asyncType == AsyncAssertionTypeEventually {
|
||||
fail("Timed out")
|
||||
return false
|
||||
} else {
|
||||
if isTryAgainAfterError {
|
||||
fail("Timed out while waiting on TryAgainAfter")
|
||||
return false
|
||||
}
|
||||
case <-timeout:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
16
vendor/github.com/onsi/gomega/internal/duration_bundle.go
generated
vendored
16
vendor/github.com/onsi/gomega/internal/duration_bundle.go
generated
vendored
@ -44,28 +44,28 @@ func durationFromEnv(key string, defaultDuration time.Duration) time.Duration {
|
||||
return duration
|
||||
}
|
||||
|
||||
func toDuration(input interface{}) time.Duration {
|
||||
func toDuration(input interface{}) (time.Duration, error) {
|
||||
duration, ok := input.(time.Duration)
|
||||
if ok {
|
||||
return duration
|
||||
return duration, nil
|
||||
}
|
||||
|
||||
value := reflect.ValueOf(input)
|
||||
kind := reflect.TypeOf(input).Kind()
|
||||
|
||||
if reflect.Int <= kind && kind <= reflect.Int64 {
|
||||
return time.Duration(value.Int()) * time.Second
|
||||
return time.Duration(value.Int()) * time.Second, nil
|
||||
} else if reflect.Uint <= kind && kind <= reflect.Uint64 {
|
||||
return time.Duration(value.Uint()) * time.Second
|
||||
return time.Duration(value.Uint()) * time.Second, nil
|
||||
} else if reflect.Float32 <= kind && kind <= reflect.Float64 {
|
||||
return time.Duration(value.Float() * float64(time.Second))
|
||||
return time.Duration(value.Float() * float64(time.Second)), nil
|
||||
} else if reflect.String == kind {
|
||||
duration, err := time.ParseDuration(value.String())
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("%#v is not a valid parsable duration string.", input))
|
||||
return 0, fmt.Errorf("%#v is not a valid parsable duration string: %w", input, err)
|
||||
}
|
||||
return duration
|
||||
return duration, nil
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("%v is not a valid interval. Must be time.Duration, parsable duration string or a number.", input))
|
||||
return 0, fmt.Errorf("%#v is not a valid interval. Must be a time.Duration, a parsable duration string, or a number.", input)
|
||||
}
|
||||
|
85
vendor/github.com/onsi/gomega/internal/gomega.go
generated
vendored
85
vendor/github.com/onsi/gomega/internal/gomega.go
generated
vendored
@ -1,6 +1,7 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/onsi/gomega/types"
|
||||
@ -39,50 +40,76 @@ func (g *Gomega) ConfigureWithT(t types.GomegaTestingT) *Gomega {
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *Gomega) Ω(atual interface{}, extra ...interface{}) types.Assertion {
|
||||
return g.ExpectWithOffset(0, atual, extra...)
|
||||
func (g *Gomega) Ω(actual interface{}, extra ...interface{}) types.Assertion {
|
||||
return g.ExpectWithOffset(0, actual, extra...)
|
||||
}
|
||||
|
||||
func (g *Gomega) Expect(atual interface{}, extra ...interface{}) types.Assertion {
|
||||
return g.ExpectWithOffset(0, atual, extra...)
|
||||
func (g *Gomega) Expect(actual interface{}, extra ...interface{}) types.Assertion {
|
||||
return g.ExpectWithOffset(0, actual, extra...)
|
||||
}
|
||||
|
||||
func (g *Gomega) ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) types.Assertion {
|
||||
return NewAssertion(actual, g, offset, extra...)
|
||||
}
|
||||
|
||||
func (g *Gomega) Eventually(actual interface{}, intervals ...interface{}) types.AsyncAssertion {
|
||||
return g.EventuallyWithOffset(0, actual, intervals...)
|
||||
func (g *Gomega) Eventually(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion {
|
||||
return g.makeAsyncAssertion(AsyncAssertionTypeEventually, 0, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
func (g *Gomega) EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) types.AsyncAssertion {
|
||||
timeoutInterval := g.DurationBundle.EventuallyTimeout
|
||||
pollingInterval := g.DurationBundle.EventuallyPollingInterval
|
||||
func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion {
|
||||
return g.makeAsyncAssertion(AsyncAssertionTypeEventually, offset, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
func (g *Gomega) Consistently(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion {
|
||||
return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, 0, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion {
|
||||
return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, offset, actualOrCtx, args...)
|
||||
}
|
||||
|
||||
func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion {
|
||||
baseOffset := 3
|
||||
timeoutInterval := -time.Duration(1)
|
||||
pollingInterval := -time.Duration(1)
|
||||
intervals := []interface{}{}
|
||||
var ctx context.Context
|
||||
|
||||
actual := actualOrCtx
|
||||
startingIndex := 0
|
||||
if _, isCtx := actualOrCtx.(context.Context); isCtx && len(args) > 0 {
|
||||
// the first argument is a context, we should accept it as the context _only if_ it is **not** the only argumnent **and** the second argument is not a parseable duration
|
||||
// this is due to an unfortunate ambiguity in early version of Gomega in which multi-type durations are allowed after the actual
|
||||
if _, err := toDuration(args[0]); err != nil {
|
||||
ctx = actualOrCtx.(context.Context)
|
||||
actual = args[0]
|
||||
startingIndex = 1
|
||||
}
|
||||
}
|
||||
|
||||
for _, arg := range args[startingIndex:] {
|
||||
switch v := arg.(type) {
|
||||
case context.Context:
|
||||
ctx = v
|
||||
default:
|
||||
intervals = append(intervals, arg)
|
||||
}
|
||||
}
|
||||
var err error
|
||||
if len(intervals) > 0 {
|
||||
timeoutInterval = toDuration(intervals[0])
|
||||
timeoutInterval, err = toDuration(intervals[0])
|
||||
if err != nil {
|
||||
g.Fail(err.Error(), offset+baseOffset)
|
||||
}
|
||||
}
|
||||
if len(intervals) > 1 {
|
||||
pollingInterval = toDuration(intervals[1])
|
||||
pollingInterval, err = toDuration(intervals[1])
|
||||
if err != nil {
|
||||
g.Fail(err.Error(), offset+baseOffset)
|
||||
}
|
||||
}
|
||||
|
||||
return NewAsyncAssertion(AsyncAssertionTypeEventually, actual, g, timeoutInterval, pollingInterval, offset)
|
||||
}
|
||||
|
||||
func (g *Gomega) Consistently(actual interface{}, intervals ...interface{}) types.AsyncAssertion {
|
||||
return g.ConsistentlyWithOffset(0, actual, intervals...)
|
||||
}
|
||||
|
||||
func (g *Gomega) ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) types.AsyncAssertion {
|
||||
timeoutInterval := g.DurationBundle.ConsistentlyDuration
|
||||
pollingInterval := g.DurationBundle.ConsistentlyPollingInterval
|
||||
if len(intervals) > 0 {
|
||||
timeoutInterval = toDuration(intervals[0])
|
||||
}
|
||||
if len(intervals) > 1 {
|
||||
pollingInterval = toDuration(intervals[1])
|
||||
}
|
||||
|
||||
return NewAsyncAssertion(AsyncAssertionTypeConsistently, actual, g, timeoutInterval, pollingInterval, offset)
|
||||
return NewAsyncAssertion(asyncAssertionType, actual, g, timeoutInterval, pollingInterval, ctx, offset)
|
||||
}
|
||||
|
||||
func (g *Gomega) SetDefaultEventuallyTimeout(t time.Duration) {
|
||||
|
48
vendor/github.com/onsi/gomega/internal/gutil/post_ioutil.go
generated
vendored
Normal file
48
vendor/github.com/onsi/gomega/internal/gutil/post_ioutil.go
generated
vendored
Normal file
@ -0,0 +1,48 @@
|
||||
//go:build go1.16
|
||||
// +build go1.16
|
||||
|
||||
// Package gutil is a replacement for ioutil, which should not be used in new
|
||||
// code as of Go 1.16. With Go 1.16 and higher, this implementation
|
||||
// uses the ioutil replacement functions in "io" and "os" with some
|
||||
// Gomega specifics. This means that we should not get deprecation warnings
|
||||
// for ioutil when they are added.
|
||||
package gutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func NopCloser(r io.Reader) io.ReadCloser {
|
||||
return io.NopCloser(r)
|
||||
}
|
||||
|
||||
func ReadAll(r io.Reader) ([]byte, error) {
|
||||
return io.ReadAll(r)
|
||||
}
|
||||
|
||||
func ReadDir(dirname string) ([]string, error) {
|
||||
entries, err := os.ReadDir(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, entry := range entries {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func ReadFile(filename string) ([]byte, error) {
|
||||
return os.ReadFile(filename)
|
||||
}
|
||||
|
||||
func MkdirTemp(dir, pattern string) (string, error) {
|
||||
return os.MkdirTemp(dir, pattern)
|
||||
}
|
||||
|
||||
func WriteFile(filename string, data []byte) error {
|
||||
return os.WriteFile(filename, data, 0644)
|
||||
}
|
47
vendor/github.com/onsi/gomega/internal/gutil/using_ioutil.go
generated
vendored
Normal file
47
vendor/github.com/onsi/gomega/internal/gutil/using_ioutil.go
generated
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
//go:build !go1.16
|
||||
// +build !go1.16
|
||||
|
||||
// Package gutil is a replacement for ioutil, which should not be used in new
|
||||
// code as of Go 1.16. With Go 1.15 and lower, this implementation
|
||||
// uses the ioutil functions, meaning that although Gomega is not officially
|
||||
// supported on these versions, it is still likely to work.
|
||||
package gutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func NopCloser(r io.Reader) io.ReadCloser {
|
||||
return ioutil.NopCloser(r)
|
||||
}
|
||||
|
||||
func ReadAll(r io.Reader) ([]byte, error) {
|
||||
return ioutil.ReadAll(r)
|
||||
}
|
||||
|
||||
func ReadDir(dirname string) ([]string, error) {
|
||||
files, err := ioutil.ReadDir(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, file := range files {
|
||||
names = append(names, file.Name())
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func ReadFile(filename string) ([]byte, error) {
|
||||
return ioutil.ReadFile(filename)
|
||||
}
|
||||
|
||||
func MkdirTemp(dir, pattern string) (string, error) {
|
||||
return ioutil.TempDir(dir, pattern)
|
||||
}
|
||||
|
||||
func WriteFile(filename string, data []byte) error {
|
||||
return ioutil.WriteFile(filename, data, 0644)
|
||||
}
|
106
vendor/github.com/onsi/gomega/internal/polling_signal_error.go
generated
vendored
Normal file
106
vendor/github.com/onsi/gomega/internal/polling_signal_error.go
generated
vendored
Normal file
@ -0,0 +1,106 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PollingSignalErrorType int
|
||||
|
||||
const (
|
||||
PollingSignalErrorTypeStopTrying PollingSignalErrorType = iota
|
||||
PollingSignalErrorTypeTryAgainAfter
|
||||
)
|
||||
|
||||
type PollingSignalError interface {
|
||||
error
|
||||
Wrap(err error) PollingSignalError
|
||||
Attach(description string, obj any) PollingSignalError
|
||||
Now()
|
||||
}
|
||||
|
||||
var StopTrying = func(message string) PollingSignalError {
|
||||
return &PollingSignalErrorImpl{
|
||||
message: message,
|
||||
pollingSignalErrorType: PollingSignalErrorTypeStopTrying,
|
||||
}
|
||||
}
|
||||
|
||||
var TryAgainAfter = func(duration time.Duration) PollingSignalError {
|
||||
return &PollingSignalErrorImpl{
|
||||
message: fmt.Sprintf("told to try again after %s", duration),
|
||||
duration: duration,
|
||||
pollingSignalErrorType: PollingSignalErrorTypeTryAgainAfter,
|
||||
}
|
||||
}
|
||||
|
||||
type PollingSignalErrorAttachment struct {
|
||||
Description string
|
||||
Object any
|
||||
}
|
||||
|
||||
type PollingSignalErrorImpl struct {
|
||||
message string
|
||||
wrappedErr error
|
||||
pollingSignalErrorType PollingSignalErrorType
|
||||
duration time.Duration
|
||||
Attachments []PollingSignalErrorAttachment
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) Wrap(err error) PollingSignalError {
|
||||
s.wrappedErr = err
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) Attach(description string, obj any) PollingSignalError {
|
||||
s.Attachments = append(s.Attachments, PollingSignalErrorAttachment{description, obj})
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) Error() string {
|
||||
if s.wrappedErr == nil {
|
||||
return s.message
|
||||
} else {
|
||||
return s.message + ": " + s.wrappedErr.Error()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) Unwrap() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.wrappedErr
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) Now() {
|
||||
panic(s)
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) IsStopTrying() bool {
|
||||
return s.pollingSignalErrorType == PollingSignalErrorTypeStopTrying
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) IsTryAgainAfter() bool {
|
||||
return s.pollingSignalErrorType == PollingSignalErrorTypeTryAgainAfter
|
||||
}
|
||||
|
||||
func (s *PollingSignalErrorImpl) TryAgainDuration() time.Duration {
|
||||
return s.duration
|
||||
}
|
||||
|
||||
func AsPollingSignalError(actual interface{}) (*PollingSignalErrorImpl, bool) {
|
||||
if actual == nil {
|
||||
return nil, false
|
||||
}
|
||||
if actualErr, ok := actual.(error); ok {
|
||||
var target *PollingSignalErrorImpl
|
||||
if errors.As(actualErr, &target) {
|
||||
return target, true
|
||||
} else {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
22
vendor/github.com/onsi/gomega/internal/vetoptdesc.go
generated
vendored
Normal file
22
vendor/github.com/onsi/gomega/internal/vetoptdesc.go
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
// vetOptionalDescription vets the optional description args: if it finds any
|
||||
// Gomega matcher at the beginning it panics. This allows for rendering Gomega
|
||||
// matchers as part of an optional Description, as long as they're not in the
|
||||
// first slot.
|
||||
func vetOptionalDescription(assertion string, optionalDescription ...interface{}) {
|
||||
if len(optionalDescription) == 0 {
|
||||
return
|
||||
}
|
||||
if _, isGomegaMatcher := optionalDescription[0].(types.GomegaMatcher); isGomegaMatcher {
|
||||
panic(fmt.Sprintf("%s has a GomegaMatcher as the first element of optionalDescription.\n\t"+
|
||||
"Do you mean to use And/Or/SatisfyAll/SatisfyAny to combine multiple matchers?",
|
||||
assertion))
|
||||
}
|
||||
}
|
555
vendor/github.com/onsi/gomega/matchers.go
generated
vendored
555
vendor/github.com/onsi/gomega/matchers.go
generated
vendored
@ -3,139 +3,158 @@ package gomega
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/onsi/gomega/matchers"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
//Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about
|
||||
//types when performing comparisons.
|
||||
//It is an error for both actual and expected to be nil. Use BeNil() instead.
|
||||
// Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about
|
||||
// types when performing comparisons.
|
||||
// It is an error for both actual and expected to be nil. Use BeNil() instead.
|
||||
func Equal(expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.EqualMatcher{
|
||||
Expected: expected,
|
||||
}
|
||||
}
|
||||
|
||||
//BeEquivalentTo is more lax than Equal, allowing equality between different types.
|
||||
//This is done by converting actual to have the type of expected before
|
||||
//attempting equality with reflect.DeepEqual.
|
||||
//It is an error for actual and expected to be nil. Use BeNil() instead.
|
||||
// BeEquivalentTo is more lax than Equal, allowing equality between different types.
|
||||
// This is done by converting actual to have the type of expected before
|
||||
// attempting equality with reflect.DeepEqual.
|
||||
// It is an error for actual and expected to be nil. Use BeNil() instead.
|
||||
func BeEquivalentTo(expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.BeEquivalentToMatcher{
|
||||
Expected: expected,
|
||||
}
|
||||
}
|
||||
|
||||
//BeIdenticalTo uses the == operator to compare actual with expected.
|
||||
//BeIdenticalTo is strict about types when performing comparisons.
|
||||
//It is an error for both actual and expected to be nil. Use BeNil() instead.
|
||||
// BeComparableTo uses gocmp.Equal from github.com/google/go-cmp (instead of reflect.DeepEqual) to perform a deep comparison.
|
||||
// You can pass cmp.Option as options.
|
||||
// It is an error for actual and expected to be nil. Use BeNil() instead.
|
||||
func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatcher {
|
||||
return &matchers.BeComparableToMatcher{
|
||||
Expected: expected,
|
||||
Options: opts,
|
||||
}
|
||||
}
|
||||
|
||||
// BeIdenticalTo uses the == operator to compare actual with expected.
|
||||
// BeIdenticalTo is strict about types when performing comparisons.
|
||||
// It is an error for both actual and expected to be nil. Use BeNil() instead.
|
||||
func BeIdenticalTo(expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.BeIdenticalToMatcher{
|
||||
Expected: expected,
|
||||
}
|
||||
}
|
||||
|
||||
//BeNil succeeds if actual is nil
|
||||
// BeNil succeeds if actual is nil
|
||||
func BeNil() types.GomegaMatcher {
|
||||
return &matchers.BeNilMatcher{}
|
||||
}
|
||||
|
||||
//BeTrue succeeds if actual is true
|
||||
// BeTrue succeeds if actual is true
|
||||
func BeTrue() types.GomegaMatcher {
|
||||
return &matchers.BeTrueMatcher{}
|
||||
}
|
||||
|
||||
//BeFalse succeeds if actual is false
|
||||
// BeFalse succeeds if actual is false
|
||||
func BeFalse() types.GomegaMatcher {
|
||||
return &matchers.BeFalseMatcher{}
|
||||
}
|
||||
|
||||
//HaveOccurred succeeds if actual is a non-nil error
|
||||
//The typical Go error checking pattern looks like:
|
||||
// err := SomethingThatMightFail()
|
||||
// Expect(err).ShouldNot(HaveOccurred())
|
||||
// HaveOccurred succeeds if actual is a non-nil error
|
||||
// The typical Go error checking pattern looks like:
|
||||
//
|
||||
// err := SomethingThatMightFail()
|
||||
// Expect(err).ShouldNot(HaveOccurred())
|
||||
func HaveOccurred() types.GomegaMatcher {
|
||||
return &matchers.HaveOccurredMatcher{}
|
||||
}
|
||||
|
||||
//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()
|
||||
// Expect(err).ShouldNot(HaveOccurred())
|
||||
// Succeed passes if actual is a nil error
|
||||
// Succeed is intended to be used with functions that return a single error value. Instead of
|
||||
//
|
||||
//You can write:
|
||||
// Expect(SomethingThatMightFail()).Should(Succeed())
|
||||
// err := SomethingThatMightFail()
|
||||
// Expect(err).ShouldNot(HaveOccurred())
|
||||
//
|
||||
//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.
|
||||
//This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass.
|
||||
// You can write:
|
||||
//
|
||||
// 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.
|
||||
// This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass.
|
||||
func Succeed() types.GomegaMatcher {
|
||||
return &matchers.SucceedMatcher{}
|
||||
}
|
||||
|
||||
//MatchError succeeds if actual is a non-nil error that matches the passed in string/error.
|
||||
// MatchError succeeds if actual is a non-nil error that matches the passed in string/error.
|
||||
//
|
||||
//These are valid use-cases:
|
||||
// Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error"
|
||||
// Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual)
|
||||
// These are valid use-cases:
|
||||
//
|
||||
//It is an error for err to be nil or an object that does not implement the Error interface
|
||||
// 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 {
|
||||
return &matchers.MatchErrorMatcher{
|
||||
Expected: expected,
|
||||
}
|
||||
}
|
||||
|
||||
//BeClosed succeeds if actual is a closed channel.
|
||||
//It is an error to pass a non-channel to BeClosed, it is also an error to pass nil
|
||||
// BeClosed succeeds if actual is a closed channel.
|
||||
// It is an error to pass a non-channel to BeClosed, it is also an error to pass nil
|
||||
//
|
||||
//In order to check whether or not the channel is closed, Gomega must try to read from the channel
|
||||
//(even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about
|
||||
//values coming down the channel.
|
||||
// In order to check whether or not the channel is closed, Gomega must try to read from the channel
|
||||
// (even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about
|
||||
// values coming down the channel.
|
||||
//
|
||||
//Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before
|
||||
//asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read).
|
||||
// Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before
|
||||
// asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read).
|
||||
//
|
||||
//Finally, as a corollary: it is an error to check whether or not a send-only channel is closed.
|
||||
// Finally, as a corollary: it is an error to check whether or not a send-only channel is closed.
|
||||
func BeClosed() types.GomegaMatcher {
|
||||
return &matchers.BeClosedMatcher{}
|
||||
}
|
||||
|
||||
//Receive succeeds if there is a value to be received on actual.
|
||||
//Actual must be a channel (and cannot be a send-only channel) -- anything else is an error.
|
||||
// Receive succeeds if there is a value to be received on actual.
|
||||
// Actual must be a channel (and cannot be a send-only channel) -- anything else is an error.
|
||||
//
|
||||
//Receive returns immediately and never blocks:
|
||||
// Receive returns immediately and never blocks:
|
||||
//
|
||||
//- If there is nothing on the channel `c` then Expect(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 Expect(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 Expect(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())
|
||||
// If you have a go-routine running in the background that will write to channel `c` you can:
|
||||
//
|
||||
//This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`)
|
||||
// Eventually(c).Should(Receive())
|
||||
//
|
||||
//A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`:
|
||||
// Consistently(c).ShouldNot(Receive())
|
||||
// This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`)
|
||||
//
|
||||
//You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:
|
||||
// Expect(c).Should(Receive(Equal("foo")))
|
||||
// A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`:
|
||||
//
|
||||
//When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.
|
||||
// Consistently(c).ShouldNot(Receive())
|
||||
//
|
||||
//Passing Receive a matcher is especially useful when paired with Eventually:
|
||||
// You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:
|
||||
//
|
||||
// Eventually(c).Should(Receive(ContainSubstring("bar")))
|
||||
// Expect(c).Should(Receive(Equal("foo")))
|
||||
//
|
||||
//will repeatedly attempt to pull values out of `c` until a value matching "bar" is received.
|
||||
// When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.
|
||||
//
|
||||
//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))
|
||||
// Expect(myThing.Sprocket).Should(Equal("foo"))
|
||||
// Expect(myThing.IsValid()).Should(BeTrue())
|
||||
// Passing Receive a matcher is especially useful when paired with Eventually:
|
||||
//
|
||||
// Eventually(c).Should(Receive(ContainSubstring("bar")))
|
||||
//
|
||||
// will repeatedly attempt to pull values out of `c` until a value matching "bar" is received.
|
||||
//
|
||||
// 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))
|
||||
// Expect(myThing.Sprocket).Should(Equal("foo"))
|
||||
// Expect(myThing.IsValid()).Should(BeTrue())
|
||||
func Receive(args ...interface{}) types.GomegaMatcher {
|
||||
var arg interface{}
|
||||
if len(args) > 0 {
|
||||
@ -147,27 +166,27 @@ func Receive(args ...interface{}) types.GomegaMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
//BeSent succeeds if a value can be sent to actual.
|
||||
//Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error.
|
||||
//In addition, actual must not be closed.
|
||||
// BeSent succeeds if a value can be sent to actual.
|
||||
// Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error.
|
||||
// In addition, actual must not be closed.
|
||||
//
|
||||
//BeSent never blocks:
|
||||
// BeSent never blocks:
|
||||
//
|
||||
//- 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 Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both 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 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.
|
||||
// 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.
|
||||
func BeSent(arg interface{}) types.GomegaMatcher {
|
||||
return &matchers.BeSentMatcher{
|
||||
Arg: arg,
|
||||
}
|
||||
}
|
||||
|
||||
//MatchRegexp succeeds if actual is a string or stringer that matches the
|
||||
//passed-in regexp. Optional arguments can be provided to construct a regexp
|
||||
//via fmt.Sprintf().
|
||||
// MatchRegexp succeeds if actual is a string or stringer that matches the
|
||||
// passed-in regexp. Optional arguments can be provided to construct a regexp
|
||||
// via fmt.Sprintf().
|
||||
func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.MatchRegexpMatcher{
|
||||
Regexp: regexp,
|
||||
@ -175,9 +194,9 @@ func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
//ContainSubstring succeeds if actual is a string or stringer that contains the
|
||||
//passed-in substring. Optional arguments can be provided to construct the substring
|
||||
//via fmt.Sprintf().
|
||||
// ContainSubstring succeeds if actual is a string or stringer that contains the
|
||||
// passed-in substring. Optional arguments can be provided to construct the substring
|
||||
// via fmt.Sprintf().
|
||||
func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.ContainSubstringMatcher{
|
||||
Substr: substr,
|
||||
@ -185,9 +204,9 @@ func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
//HavePrefix succeeds if actual is a string or stringer that contains the
|
||||
//passed-in string as a prefix. Optional arguments can be provided to construct
|
||||
//via fmt.Sprintf().
|
||||
// HavePrefix succeeds if actual is a string or stringer that contains the
|
||||
// passed-in string as a prefix. Optional arguments can be provided to construct
|
||||
// via fmt.Sprintf().
|
||||
func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.HavePrefixMatcher{
|
||||
Prefix: prefix,
|
||||
@ -195,9 +214,9 @@ func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
//HaveSuffix succeeds if actual is a string or stringer that contains the
|
||||
//passed-in string as a suffix. Optional arguments can be provided to construct
|
||||
//via fmt.Sprintf().
|
||||
// HaveSuffix succeeds if actual is a string or stringer that contains the
|
||||
// passed-in string as a suffix. Optional arguments can be provided to construct
|
||||
// via fmt.Sprintf().
|
||||
func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveSuffixMatcher{
|
||||
Suffix: suffix,
|
||||
@ -205,136 +224,177 @@ func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
//MatchJSON succeeds if actual is a string or stringer of JSON that matches
|
||||
//the expected JSON. The JSONs are decoded and the resulting objects are compared via
|
||||
//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
|
||||
// MatchJSON succeeds if actual is a string or stringer of JSON that matches
|
||||
// the expected JSON. The JSONs are decoded and the resulting objects are compared via
|
||||
// reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
|
||||
func MatchJSON(json interface{}) types.GomegaMatcher {
|
||||
return &matchers.MatchJSONMatcher{
|
||||
JSONToMatch: json,
|
||||
}
|
||||
}
|
||||
|
||||
//MatchXML succeeds if actual is a string or stringer of XML that matches
|
||||
//the expected XML. The XMLs are decoded and the resulting objects are compared via
|
||||
//reflect.DeepEqual so things like whitespaces shouldn't matter.
|
||||
// MatchXML succeeds if actual is a string or stringer of XML that matches
|
||||
// the expected XML. The XMLs are decoded and the resulting objects are compared via
|
||||
// reflect.DeepEqual so things like whitespaces shouldn't matter.
|
||||
func MatchXML(xml interface{}) types.GomegaMatcher {
|
||||
return &matchers.MatchXMLMatcher{
|
||||
XMLToMatch: xml,
|
||||
}
|
||||
}
|
||||
|
||||
//MatchYAML succeeds if actual is a string or stringer of YAML that matches
|
||||
//the expected YAML. The YAML's are decoded and the resulting objects are compared via
|
||||
//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
|
||||
// MatchYAML succeeds if actual is a string or stringer of YAML that matches
|
||||
// the expected YAML. The YAML's are decoded and the resulting objects are compared via
|
||||
// reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
|
||||
func MatchYAML(yaml interface{}) types.GomegaMatcher {
|
||||
return &matchers.MatchYAMLMatcher{
|
||||
YAMLToMatch: yaml,
|
||||
}
|
||||
}
|
||||
|
||||
//BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice.
|
||||
// BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice.
|
||||
func BeEmpty() types.GomegaMatcher {
|
||||
return &matchers.BeEmptyMatcher{}
|
||||
}
|
||||
|
||||
//HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice.
|
||||
// HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice.
|
||||
func HaveLen(count int) types.GomegaMatcher {
|
||||
return &matchers.HaveLenMatcher{
|
||||
Count: count,
|
||||
}
|
||||
}
|
||||
|
||||
//HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice.
|
||||
// HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice.
|
||||
func HaveCap(count int) types.GomegaMatcher {
|
||||
return &matchers.HaveCapMatcher{
|
||||
Count: count,
|
||||
}
|
||||
}
|
||||
|
||||
//BeZero succeeds if actual is the zero value for its type or if actual is nil.
|
||||
// BeZero succeeds if actual is the zero value for its type or if actual is nil.
|
||||
func BeZero() types.GomegaMatcher {
|
||||
return &matchers.BeZeroMatcher{}
|
||||
}
|
||||
|
||||
//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:
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))
|
||||
// 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:
|
||||
//
|
||||
//Actual must be an array, slice or map.
|
||||
//For maps, ContainElement searches through the map's values.
|
||||
func ContainElement(element interface{}) types.GomegaMatcher {
|
||||
// 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.
|
||||
//
|
||||
// If you want to have a copy of the matching element(s) found you can pass a
|
||||
// pointer to a variable of the appropriate type. If the variable isn't a slice
|
||||
// or map, then exactly one match will be expected and returned. If the variable
|
||||
// is a slice or map, then at least one match is expected and all matches will be
|
||||
// stored in the variable.
|
||||
//
|
||||
// var findings []string
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings)))
|
||||
func ContainElement(element interface{}, result ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.ContainElementMatcher{
|
||||
Element: element,
|
||||
Result: result,
|
||||
}
|
||||
}
|
||||
|
||||
//BeElementOf succeeds if actual is contained in the passed in elements.
|
||||
//BeElementOf() always uses Equal() to perform the match.
|
||||
//When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves
|
||||
//as the reverse of ContainElement() that operates with Equal() to perform the match.
|
||||
// Expect(2).Should(BeElementOf([]int{1, 2}))
|
||||
// Expect(2).Should(BeElementOf([2]int{1, 2}))
|
||||
//Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...):
|
||||
// Expect(2).Should(BeElementOf(1, 2))
|
||||
// BeElementOf succeeds if actual is contained in the passed in elements.
|
||||
// BeElementOf() always uses Equal() to perform the match.
|
||||
// When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves
|
||||
// as the reverse of ContainElement() that operates with Equal() to perform the match.
|
||||
//
|
||||
//Actual must be typed.
|
||||
// Expect(2).Should(BeElementOf([]int{1, 2}))
|
||||
// Expect(2).Should(BeElementOf([2]int{1, 2}))
|
||||
//
|
||||
// Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...):
|
||||
//
|
||||
// Expect(2).Should(BeElementOf(1, 2))
|
||||
//
|
||||
// Actual must be typed.
|
||||
func BeElementOf(elements ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.BeElementOfMatcher{
|
||||
Elements: elements,
|
||||
}
|
||||
}
|
||||
|
||||
//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:
|
||||
// BeKeyOf succeeds if actual is contained in the keys of the passed in map.
|
||||
// BeKeyOf() always uses Equal() to perform the match between actual and the map keys.
|
||||
//
|
||||
// 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")))
|
||||
// Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false}))
|
||||
func BeKeyOf(element interface{}) types.GomegaMatcher {
|
||||
return &matchers.BeKeyOfMatcher{
|
||||
Map: element,
|
||||
}
|
||||
}
|
||||
|
||||
// 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:
|
||||
//
|
||||
//Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.
|
||||
// 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")))
|
||||
//
|
||||
//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:
|
||||
// Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.
|
||||
//
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))
|
||||
// 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:
|
||||
//
|
||||
//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.
|
||||
// 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 {
|
||||
return &matchers.ConsistOfMatcher{
|
||||
Elements: elements,
|
||||
}
|
||||
}
|
||||
|
||||
//ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter.
|
||||
//By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
|
||||
// ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter.
|
||||
// By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
|
||||
//
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar"))
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo"))
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar"))
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo"))
|
||||
//
|
||||
//Actual must be an array, slice or map.
|
||||
//For maps, ContainElements searches through the map's values.
|
||||
// Actual must be an array, slice or map.
|
||||
// For maps, ContainElements searches through the map's values.
|
||||
func ContainElements(elements ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.ContainElementsMatcher{
|
||||
Elements: elements,
|
||||
}
|
||||
}
|
||||
|
||||
//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:
|
||||
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
|
||||
// HaveEach succeeds if actual solely contains elements that match the passed in element.
|
||||
// Please note that if actual is empty, HaveEach always will succeed.
|
||||
// By default HaveEach() uses Equal() to perform the match, however a
|
||||
// matcher can be passed in instead:
|
||||
//
|
||||
// Expect([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo")))
|
||||
//
|
||||
// Actual must be an array, slice or map.
|
||||
// For maps, HaveEach searches through the map's values.
|
||||
func HaveEach(element interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveEachMatcher{
|
||||
Element: element,
|
||||
}
|
||||
}
|
||||
|
||||
// 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:
|
||||
//
|
||||
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
|
||||
func HaveKey(key interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveKeyMatcher{
|
||||
Key: key,
|
||||
}
|
||||
}
|
||||
|
||||
//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:
|
||||
// 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"))
|
||||
// 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:
|
||||
//
|
||||
// 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,
|
||||
@ -342,17 +402,79 @@ 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 (float32, float64, uint8, etc...).
|
||||
// HaveField succeeds if actual is a struct and the value at the passed in field
|
||||
// matches the passed in matcher. By default HaveField used Equal() to perform the match,
|
||||
// however a matcher can be passed in in stead.
|
||||
//
|
||||
//There are six, self-explanatory, supported comparators:
|
||||
// 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))
|
||||
// The field must be a string that resolves to the name of a field in the struct. Structs can be traversed
|
||||
// using the '.' delimiter. If the field ends with '()' a method named field is assumed to exist on the struct and is invoked.
|
||||
// Such methods must take no arguments and return a single value:
|
||||
//
|
||||
// type Book struct {
|
||||
// Title string
|
||||
// Author Person
|
||||
// }
|
||||
// type Person struct {
|
||||
// FirstName string
|
||||
// LastName string
|
||||
// DOB time.Time
|
||||
// }
|
||||
// Expect(book).To(HaveField("Title", "Les Miserables"))
|
||||
// Expect(book).To(HaveField("Title", ContainSubstring("Les"))
|
||||
// Expect(book).To(HaveField("Author.FirstName", Equal("Victor"))
|
||||
// Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900))
|
||||
func HaveField(field string, expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveFieldMatcher{
|
||||
Field: field,
|
||||
Expected: expected,
|
||||
}
|
||||
}
|
||||
|
||||
// HaveExistingField succeeds if actual is a struct and the specified field
|
||||
// exists.
|
||||
//
|
||||
// HaveExistingField can be combined with HaveField in order to cover use cases
|
||||
// with optional fields. HaveField alone would trigger an error in such situations.
|
||||
//
|
||||
// Expect(MrHarmless).NotTo(And(HaveExistingField("Title"), HaveField("Title", "Supervillain")))
|
||||
func HaveExistingField(field string) types.GomegaMatcher {
|
||||
return &matchers.HaveExistingFieldMatcher{
|
||||
Field: field,
|
||||
}
|
||||
}
|
||||
|
||||
// HaveValue applies the given matcher to the value of actual, optionally and
|
||||
// repeatedly dereferencing pointers or taking the concrete value of interfaces.
|
||||
// Thus, the matcher will always be applied to non-pointer and non-interface
|
||||
// values only. HaveValue will fail with an error if a pointer or interface is
|
||||
// nil. It will also fail for more than 31 pointer or interface dereferences to
|
||||
// guard against mistakenly applying it to arbitrarily deep linked pointers.
|
||||
//
|
||||
// HaveValue differs from gstruct.PointTo in that it does not expect actual to
|
||||
// be a pointer (as gstruct.PointTo does) but instead also accepts non-pointer
|
||||
// and even interface values.
|
||||
//
|
||||
// actual := 42
|
||||
// Expect(actual).To(HaveValue(42))
|
||||
// Expect(&actual).To(HaveValue(42))
|
||||
func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher {
|
||||
return &matchers.HaveValueMatcher{
|
||||
Matcher: matcher,
|
||||
}
|
||||
}
|
||||
|
||||
// BeNumerically performs numerical assertions in a type-agnostic way.
|
||||
// Actual and expected should be numbers, though the specific type of
|
||||
// number is irrelevant (float32, float64, uint8, etc...).
|
||||
//
|
||||
// There are six, self-explanatory, supported comparators:
|
||||
//
|
||||
// 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,
|
||||
@ -360,10 +482,11 @@ 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
|
||||
// Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
|
||||
// Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
|
||||
// BeTemporally compares time.Time's like BeNumerically
|
||||
// Actual and expected must be time.Time. The comparators are the same as for BeNumerically
|
||||
//
|
||||
// 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,
|
||||
@ -372,113 +495,147 @@ 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.
|
||||
// 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 }{}))
|
||||
// BeAssignableToTypeOf succeeds if actual is assignable to the type of expected.
|
||||
// It will return an error when one of the values is nil.
|
||||
//
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
|
||||
//Panic succeeds if actual is a function that, when invoked, panics.
|
||||
//Actual must be a function that takes no arguments and returns no results.
|
||||
// Panic succeeds if actual is a function that, when invoked, panics.
|
||||
// Actual must be a function that takes no arguments and returns no results.
|
||||
func Panic() types.GomegaMatcher {
|
||||
return &matchers.PanicMatcher{}
|
||||
}
|
||||
|
||||
//PanicWith succeeds if actual is a function that, when invoked, panics with a specific value.
|
||||
//Actual must be a function that takes no arguments and returns no results.
|
||||
// PanicWith succeeds if actual is a function that, when invoked, panics with a specific value.
|
||||
// Actual must be a function that takes no arguments and returns no results.
|
||||
//
|
||||
//By default PanicWith uses Equal() to perform the match, however a
|
||||
//matcher can be passed in instead:
|
||||
// Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`)))
|
||||
// By default PanicWith uses Equal() to perform the match, however a
|
||||
// matcher can be passed in instead:
|
||||
//
|
||||
// Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`)))
|
||||
func PanicWith(expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.PanicMatcher{Expected: expected}
|
||||
}
|
||||
|
||||
//BeAnExistingFile succeeds if a file exists.
|
||||
//Actual must be a string representing the abs path to the file being checked.
|
||||
// BeAnExistingFile succeeds if a file exists.
|
||||
// Actual must be a string representing the abs path to the file being checked.
|
||||
func BeAnExistingFile() types.GomegaMatcher {
|
||||
return &matchers.BeAnExistingFileMatcher{}
|
||||
}
|
||||
|
||||
//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.
|
||||
// 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 if a file exists and is a directory.
|
||||
//Actual must be a string representing the abs path to the file being checked.
|
||||
// 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{}
|
||||
}
|
||||
|
||||
//HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches.
|
||||
//Actual must be either a *http.Response or *httptest.ResponseRecorder.
|
||||
//Expected must be either an int or a string.
|
||||
// Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200
|
||||
// Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found"
|
||||
func HaveHTTPStatus(expected interface{}) types.GomegaMatcher {
|
||||
// HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches.
|
||||
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
|
||||
// Expected must be either an int or a string.
|
||||
//
|
||||
// Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200
|
||||
// Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found"
|
||||
// Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent)) // asserts that resp.StatusCode == 200 || resp.StatusCode == 204
|
||||
func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveHTTPStatusMatcher{Expected: expected}
|
||||
}
|
||||
|
||||
//And succeeds only if all of the given matchers succeed.
|
||||
//The matchers are tried in order, and will fail-fast if one doesn't succeed.
|
||||
// Expect("hi").To(And(HaveLen(2), Equal("hi"))
|
||||
// HaveHTTPHeaderWithValue succeeds if the header is found and the value matches.
|
||||
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
|
||||
// Expected must be a string header name, followed by a header value which
|
||||
// can be a string, or another matcher.
|
||||
func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveHTTPHeaderWithValueMatcher{
|
||||
Header: header,
|
||||
Value: value,
|
||||
}
|
||||
}
|
||||
|
||||
// HaveHTTPBody matches if the body matches.
|
||||
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
|
||||
// Expected must be either a string, []byte, or other matcher
|
||||
func HaveHTTPBody(expected interface{}) types.GomegaMatcher {
|
||||
return &matchers.HaveHTTPBodyMatcher{Expected: expected}
|
||||
}
|
||||
|
||||
// And succeeds only if all of the given matchers succeed.
|
||||
// The matchers are tried in order, and will fail-fast if one doesn't succeed.
|
||||
//
|
||||
//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
// Expect("hi").To(And(HaveLen(2), Equal("hi"))
|
||||
//
|
||||
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
func And(ms ...types.GomegaMatcher) types.GomegaMatcher {
|
||||
return &matchers.AndMatcher{Matchers: ms}
|
||||
}
|
||||
|
||||
//SatisfyAll is an alias for And().
|
||||
// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
|
||||
// SatisfyAll is an alias for And().
|
||||
//
|
||||
// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
|
||||
func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher {
|
||||
return And(matchers...)
|
||||
}
|
||||
|
||||
//Or succeeds if any of the given matchers succeed.
|
||||
//The matchers are tried in order and will return immediately upon the first successful match.
|
||||
// Expect("hi").To(Or(HaveLen(3), HaveLen(2))
|
||||
// Or succeeds if any of the given matchers succeed.
|
||||
// The matchers are tried in order and will return immediately upon the first successful match.
|
||||
//
|
||||
//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
// Expect("hi").To(Or(HaveLen(3), HaveLen(2))
|
||||
//
|
||||
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
func Or(ms ...types.GomegaMatcher) types.GomegaMatcher {
|
||||
return &matchers.OrMatcher{Matchers: ms}
|
||||
}
|
||||
|
||||
//SatisfyAny is an alias for Or().
|
||||
// Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))
|
||||
// SatisfyAny is an alias for Or().
|
||||
//
|
||||
// Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))
|
||||
func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher {
|
||||
return Or(matchers...)
|
||||
}
|
||||
|
||||
//Not negates the given matcher; it succeeds if the given matcher fails.
|
||||
// Expect(1).To(Not(Equal(2))
|
||||
// Not negates the given matcher; it succeeds if the given matcher fails.
|
||||
//
|
||||
//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
// Expect(1).To(Not(Equal(2))
|
||||
//
|
||||
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
func Not(matcher types.GomegaMatcher) types.GomegaMatcher {
|
||||
return &matchers.NotMatcher{Matcher: matcher}
|
||||
}
|
||||
|
||||
//WithTransform applies the `transform` to the actual value and matches it against `matcher`.
|
||||
//The given transform must be a function of one parameter that returns one value.
|
||||
// var plus1 = func(i int) int { return i + 1 }
|
||||
// Expect(1).To(WithTransform(plus1, Equal(2))
|
||||
// WithTransform applies the `transform` to the actual value and matches it against `matcher`.
|
||||
// The given transform must be either a function of one parameter that returns one value or a
|
||||
// function of one parameter that returns two values, where the second value must be of the
|
||||
// error type.
|
||||
//
|
||||
//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
// var plus1 = func(i int) int { return i + 1 }
|
||||
// Expect(1).To(WithTransform(plus1, Equal(2))
|
||||
//
|
||||
// var failingplus1 = func(i int) (int, error) { return 42, "this does not compute" }
|
||||
// Expect(1).To(WithTransform(failingplus1, Equal(2)))
|
||||
//
|
||||
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
|
||||
func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher {
|
||||
return matchers.NewWithTransformMatcher(transform, matcher)
|
||||
}
|
||||
|
||||
//Satisfy matches the actual value against the `predicate` function.
|
||||
//The given predicate must be a function of one paramter that returns bool.
|
||||
// var isEven = func(i int) bool { return i%2 == 0 }
|
||||
// Expect(2).To(Satisfy(isEven))
|
||||
// Satisfy matches the actual value against the `predicate` function.
|
||||
// The given predicate must be a function of one paramter that returns bool.
|
||||
//
|
||||
// var isEven = func(i int) bool { return i%2 == 0 }
|
||||
// Expect(2).To(Satisfy(isEven))
|
||||
func Satisfy(predicate interface{}) types.GomegaMatcher {
|
||||
return matchers.NewSatisfyMatcher(predicate)
|
||||
}
|
||||
|
49
vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go
generated
vendored
Normal file
49
vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go
generated
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/onsi/gomega/format"
|
||||
)
|
||||
|
||||
type BeComparableToMatcher struct {
|
||||
Expected interface{}
|
||||
Options cmp.Options
|
||||
}
|
||||
|
||||
func (matcher *BeComparableToMatcher) Match(actual interface{}) (success bool, matchErr 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
|
||||
}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
success = false
|
||||
if err, ok := r.(error); ok {
|
||||
matchErr = err
|
||||
} else if errMsg, ok := r.(string); ok {
|
||||
matchErr = fmt.Errorf(errMsg)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return cmp.Equal(actual, matcher.Expected, matcher.Options...), nil
|
||||
}
|
||||
|
||||
func (matcher *BeComparableToMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
return cmp.Diff(matcher.Expected, actual, matcher.Options)
|
||||
}
|
||||
|
||||
func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "not to equal", matcher.Expected)
|
||||
}
|
45
vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go
generated
vendored
Normal file
45
vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go
generated
vendored
Normal file
@ -0,0 +1,45 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
)
|
||||
|
||||
type BeKeyOfMatcher struct {
|
||||
Map interface{}
|
||||
}
|
||||
|
||||
func (matcher *BeKeyOfMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
if !isMap(matcher.Map) {
|
||||
return false, fmt.Errorf("BeKeyOf matcher needs expected to be a map type")
|
||||
}
|
||||
|
||||
if reflect.TypeOf(actual) == nil {
|
||||
return false, fmt.Errorf("BeKeyOf matcher expects actual to be typed")
|
||||
}
|
||||
|
||||
var lastError error
|
||||
for _, key := range reflect.ValueOf(matcher.Map).MapKeys() {
|
||||
matcher := &EqualMatcher{Expected: key.Interface()}
|
||||
success, err := matcher.Match(actual)
|
||||
if err != nil {
|
||||
lastError = err
|
||||
continue
|
||||
}
|
||||
if success {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, lastError
|
||||
}
|
||||
|
||||
func (matcher *BeKeyOfMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "to be a key of", presentable(valuesOf(matcher.Map)))
|
||||
}
|
||||
|
||||
func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "not to be a key of", presentable(valuesOf(matcher.Map)))
|
||||
}
|
120
vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go
generated
vendored
120
vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go
generated
vendored
@ -3,6 +3,7 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
@ -11,6 +12,7 @@ import (
|
||||
|
||||
type ContainElementMatcher struct {
|
||||
Element interface{}
|
||||
Result []interface{}
|
||||
}
|
||||
|
||||
func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
@ -18,6 +20,49 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e
|
||||
return false, fmt.Errorf("ContainElement matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1))
|
||||
}
|
||||
|
||||
var actualT reflect.Type
|
||||
var result reflect.Value
|
||||
switch l := len(matcher.Result); {
|
||||
case l > 1:
|
||||
return false, errors.New("ContainElement matcher expects at most a single optional pointer to store its findings at")
|
||||
case l == 1:
|
||||
if reflect.ValueOf(matcher.Result[0]).Kind() != reflect.Ptr {
|
||||
return false, fmt.Errorf("ContainElement matcher expects a non-nil pointer to store its findings at. Got\n%s",
|
||||
format.Object(matcher.Result[0], 1))
|
||||
}
|
||||
actualT = reflect.TypeOf(actual)
|
||||
resultReference := matcher.Result[0]
|
||||
result = reflect.ValueOf(resultReference).Elem() // what ResultReference points to, to stash away our findings
|
||||
switch result.Kind() {
|
||||
case reflect.Array:
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
reflect.SliceOf(actualT.Elem()).String(), result.Type().String())
|
||||
case reflect.Slice:
|
||||
if !isArrayOrSlice(actual) {
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
reflect.MapOf(actualT.Key(), actualT.Elem()).String(), result.Type().String())
|
||||
}
|
||||
if !actualT.Elem().AssignableTo(result.Type().Elem()) {
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
actualT.String(), result.Type().String())
|
||||
}
|
||||
case reflect.Map:
|
||||
if !isMap(actual) {
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
actualT.String(), result.Type().String())
|
||||
}
|
||||
if !actualT.AssignableTo(result.Type()) {
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
actualT.String(), result.Type().String())
|
||||
}
|
||||
default:
|
||||
if !actualT.Elem().AssignableTo(result.Type()) {
|
||||
return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s",
|
||||
actualT.Elem().String(), result.Type().String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher)
|
||||
if !elementIsMatcher {
|
||||
elemMatcher = &EqualMatcher{Expected: matcher.Element}
|
||||
@ -25,30 +70,99 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e
|
||||
|
||||
value := reflect.ValueOf(actual)
|
||||
var valueAt func(int) interface{}
|
||||
|
||||
var getFindings func() reflect.Value
|
||||
var foundAt func(int)
|
||||
|
||||
if isMap(actual) {
|
||||
keys := value.MapKeys()
|
||||
valueAt = func(i int) interface{} {
|
||||
return value.MapIndex(keys[i]).Interface()
|
||||
}
|
||||
if result.Kind() != reflect.Invalid {
|
||||
fm := reflect.MakeMap(actualT)
|
||||
getFindings = func() reflect.Value {
|
||||
return fm
|
||||
}
|
||||
foundAt = func(i int) {
|
||||
fm.SetMapIndex(keys[i], value.MapIndex(keys[i]))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
valueAt = func(i int) interface{} {
|
||||
return value.Index(i).Interface()
|
||||
}
|
||||
if result.Kind() != reflect.Invalid {
|
||||
var f reflect.Value
|
||||
if result.Kind() == reflect.Slice {
|
||||
f = reflect.MakeSlice(result.Type(), 0, 0)
|
||||
} else {
|
||||
f = reflect.MakeSlice(reflect.SliceOf(result.Type()), 0, 0)
|
||||
}
|
||||
getFindings = func() reflect.Value {
|
||||
return f
|
||||
}
|
||||
foundAt = func(i int) {
|
||||
f = reflect.Append(f, value.Index(i))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var lastError error
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
success, err := elemMatcher.Match(valueAt(i))
|
||||
elem := valueAt(i)
|
||||
success, err := elemMatcher.Match(elem)
|
||||
if err != nil {
|
||||
lastError = err
|
||||
continue
|
||||
}
|
||||
if success {
|
||||
return true, nil
|
||||
if result.Kind() == reflect.Invalid {
|
||||
return true, nil
|
||||
}
|
||||
foundAt(i)
|
||||
}
|
||||
}
|
||||
|
||||
return false, lastError
|
||||
// when the expectation isn't interested in the findings except for success
|
||||
// or non-success, then we're done here and return the last matcher error
|
||||
// seen, if any, as well as non-success.
|
||||
if result.Kind() == reflect.Invalid {
|
||||
return false, lastError
|
||||
}
|
||||
|
||||
// pick up any findings the test is interested in as it specified a non-nil
|
||||
// result reference. However, the expection always is that there are at
|
||||
// least one or multiple findings. So, if a result is expected, but we had
|
||||
// no findings, then this is an error.
|
||||
findings := getFindings()
|
||||
if findings.Len() == 0 {
|
||||
return false, lastError
|
||||
}
|
||||
|
||||
// there's just a single finding and the result is neither a slice nor a map
|
||||
// (so it's a scalar): pick the one and only finding and return it in the
|
||||
// place the reference points to.
|
||||
if findings.Len() == 1 && !isArrayOrSlice(result.Interface()) && !isMap(result.Interface()) {
|
||||
if isMap(actual) {
|
||||
miter := findings.MapRange()
|
||||
miter.Next()
|
||||
result.Set(miter.Value())
|
||||
} else {
|
||||
result.Set(findings.Index(0))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// at least one or even multiple findings and a the result references a
|
||||
// slice or a map, so all we need to do is to store our findings where the
|
||||
// reference points to.
|
||||
if !findings.Type().AssignableTo(result.Type()) {
|
||||
return false, fmt.Errorf("ContainElement cannot return multiple findings. Need *%s, got *%s",
|
||||
findings.Type().String(), result.Type().String())
|
||||
}
|
||||
result.Set(findings)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
|
65
vendor/github.com/onsi/gomega/matchers/have_each_matcher.go
generated
vendored
Normal file
65
vendor/github.com/onsi/gomega/matchers/have_each_matcher.go
generated
vendored
Normal file
@ -0,0 +1,65 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
)
|
||||
|
||||
type HaveEachMatcher struct {
|
||||
Element interface{}
|
||||
}
|
||||
|
||||
func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
if !isArrayOrSlice(actual) && !isMap(actual) {
|
||||
return false, fmt.Errorf("HaveEach matcher expects an array/slice/map. Got:\n%s",
|
||||
format.Object(actual, 1))
|
||||
}
|
||||
|
||||
elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher)
|
||||
if !elementIsMatcher {
|
||||
elemMatcher = &EqualMatcher{Expected: matcher.Element}
|
||||
}
|
||||
|
||||
value := reflect.ValueOf(actual)
|
||||
if value.Len() == 0 {
|
||||
return false, fmt.Errorf("HaveEach matcher expects a non-empty array/slice/map. Got:\n%s",
|
||||
format.Object(actual, 1))
|
||||
}
|
||||
|
||||
var valueAt func(int) interface{}
|
||||
if isMap(actual) {
|
||||
keys := value.MapKeys()
|
||||
valueAt = func(i int) interface{} {
|
||||
return value.MapIndex(keys[i]).Interface()
|
||||
}
|
||||
} else {
|
||||
valueAt = func(i int) interface{} {
|
||||
return value.Index(i).Interface()
|
||||
}
|
||||
}
|
||||
|
||||
// if there are no elements, then HaveEach will match.
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
success, err := elemMatcher.Match(valueAt(i))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !success {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// FailureMessage returns a suitable failure message.
|
||||
func (matcher *HaveEachMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "to contain element matching", matcher.Element)
|
||||
}
|
||||
|
||||
// NegatedFailureMessage returns a suitable negated failure message.
|
||||
func (matcher *HaveEachMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "not to contain element matching", matcher.Element)
|
||||
}
|
36
vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go
generated
vendored
Normal file
36
vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go
generated
vendored
Normal file
@ -0,0 +1,36 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
)
|
||||
|
||||
type HaveExistingFieldMatcher struct {
|
||||
Field string
|
||||
}
|
||||
|
||||
func (matcher *HaveExistingFieldMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
// we don't care about the field's actual value, just about any error in
|
||||
// trying to find the field (or method).
|
||||
_, err = extractField(actual, matcher.Field, "HaveExistingField")
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
var mferr missingFieldError
|
||||
if errors.As(err, &mferr) {
|
||||
// missing field errors aren't errors in this context, but instead
|
||||
// unsuccessful matches.
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (matcher *HaveExistingFieldMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
return fmt.Sprintf("Expected\n%s\nto have field '%s'", format.Object(actual, 1), matcher.Field)
|
||||
}
|
||||
|
||||
func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
return fmt.Sprintf("Expected\n%s\nnot to have field '%s'", format.Object(actual, 1), matcher.Field)
|
||||
}
|
99
vendor/github.com/onsi/gomega/matchers/have_field.go
generated
vendored
Normal file
99
vendor/github.com/onsi/gomega/matchers/have_field.go
generated
vendored
Normal file
@ -0,0 +1,99 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
)
|
||||
|
||||
// missingFieldError represents a missing field extraction error that
|
||||
// HaveExistingFieldMatcher can ignore, as opposed to other, sever field
|
||||
// extraction errors, such as nil pointers, et cetera.
|
||||
type missingFieldError string
|
||||
|
||||
func (e missingFieldError) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
func extractField(actual interface{}, field string, matchername string) (interface{}, error) {
|
||||
fields := strings.SplitN(field, ".", 2)
|
||||
actualValue := reflect.ValueOf(actual)
|
||||
|
||||
if actualValue.Kind() == reflect.Ptr {
|
||||
actualValue = actualValue.Elem()
|
||||
}
|
||||
if actualValue == (reflect.Value{}) {
|
||||
return nil, fmt.Errorf("%s encountered nil while dereferencing a pointer of type %T.", matchername, actual)
|
||||
}
|
||||
|
||||
if actualValue.Kind() != reflect.Struct {
|
||||
return nil, fmt.Errorf("%s encountered:\n%s\nWhich is not a struct.", matchername, format.Object(actual, 1))
|
||||
}
|
||||
|
||||
var extractedValue reflect.Value
|
||||
|
||||
if strings.HasSuffix(fields[0], "()") {
|
||||
extractedValue = actualValue.MethodByName(strings.TrimSuffix(fields[0], "()"))
|
||||
if extractedValue == (reflect.Value{}) && actualValue.CanAddr() {
|
||||
extractedValue = actualValue.Addr().MethodByName(strings.TrimSuffix(fields[0], "()"))
|
||||
}
|
||||
if extractedValue == (reflect.Value{}) {
|
||||
return nil, missingFieldError(fmt.Sprintf("%s could not find method named '%s' in struct of type %T.", matchername, fields[0], actual))
|
||||
}
|
||||
t := extractedValue.Type()
|
||||
if t.NumIn() != 0 || t.NumOut() != 1 {
|
||||
return nil, fmt.Errorf("%s found an invalid method named '%s' in struct of type %T.\nMethods must take no arguments and return exactly one value.", matchername, fields[0], actual)
|
||||
}
|
||||
extractedValue = extractedValue.Call([]reflect.Value{})[0]
|
||||
} else {
|
||||
extractedValue = actualValue.FieldByName(fields[0])
|
||||
if extractedValue == (reflect.Value{}) {
|
||||
return nil, missingFieldError(fmt.Sprintf("%s could not find field named '%s' in struct:\n%s", matchername, fields[0], format.Object(actual, 1)))
|
||||
}
|
||||
}
|
||||
|
||||
if len(fields) == 1 {
|
||||
return extractedValue.Interface(), nil
|
||||
} else {
|
||||
return extractField(extractedValue.Interface(), fields[1], matchername)
|
||||
}
|
||||
}
|
||||
|
||||
type HaveFieldMatcher struct {
|
||||
Field string
|
||||
Expected interface{}
|
||||
|
||||
extractedField interface{}
|
||||
expectedMatcher omegaMatcher
|
||||
}
|
||||
|
||||
func (matcher *HaveFieldMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
matcher.extractedField, err = extractField(actual, matcher.Field, "HaveField")
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var isMatcher bool
|
||||
matcher.expectedMatcher, isMatcher = matcher.Expected.(omegaMatcher)
|
||||
if !isMatcher {
|
||||
matcher.expectedMatcher = &EqualMatcher{Expected: matcher.Expected}
|
||||
}
|
||||
|
||||
return matcher.expectedMatcher.Match(matcher.extractedField)
|
||||
}
|
||||
|
||||
func (matcher *HaveFieldMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
message = fmt.Sprintf("Value for field '%s' failed to satisfy matcher.\n", matcher.Field)
|
||||
message += matcher.expectedMatcher.FailureMessage(matcher.extractedField)
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
message = fmt.Sprintf("Value for field '%s' satisfied matcher, but should not have.\n", matcher.Field)
|
||||
message += matcher.expectedMatcher.NegatedFailureMessage(matcher.extractedField)
|
||||
|
||||
return message
|
||||
}
|
101
vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go
generated
vendored
Normal file
101
vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go
generated
vendored
Normal file
@ -0,0 +1,101 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/internal/gutil"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
type HaveHTTPBodyMatcher struct {
|
||||
Expected interface{}
|
||||
cachedBody []byte
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPBodyMatcher) Match(actual interface{}) (bool, error) {
|
||||
body, err := matcher.body(actual)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
switch e := matcher.Expected.(type) {
|
||||
case string:
|
||||
return (&EqualMatcher{Expected: e}).Match(string(body))
|
||||
case []byte:
|
||||
return (&EqualMatcher{Expected: e}).Match(body)
|
||||
case types.GomegaMatcher:
|
||||
return e.Match(body)
|
||||
default:
|
||||
return false, fmt.Errorf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1))
|
||||
}
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
body, err := matcher.body(actual)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("failed to read body: %s", err)
|
||||
}
|
||||
|
||||
switch e := matcher.Expected.(type) {
|
||||
case string:
|
||||
return (&EqualMatcher{Expected: e}).FailureMessage(string(body))
|
||||
case []byte:
|
||||
return (&EqualMatcher{Expected: e}).FailureMessage(body)
|
||||
case types.GomegaMatcher:
|
||||
return e.FailureMessage(body)
|
||||
default:
|
||||
return fmt.Sprintf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1))
|
||||
}
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
body, err := matcher.body(actual)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("failed to read body: %s", err)
|
||||
}
|
||||
|
||||
switch e := matcher.Expected.(type) {
|
||||
case string:
|
||||
return (&EqualMatcher{Expected: e}).NegatedFailureMessage(string(body))
|
||||
case []byte:
|
||||
return (&EqualMatcher{Expected: e}).NegatedFailureMessage(body)
|
||||
case types.GomegaMatcher:
|
||||
return e.NegatedFailureMessage(body)
|
||||
default:
|
||||
return fmt.Sprintf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1))
|
||||
}
|
||||
}
|
||||
|
||||
// body returns the body. It is cached because once we read it in Match()
|
||||
// the Reader is closed and it is not readable again in FailureMessage()
|
||||
// or NegatedFailureMessage()
|
||||
func (matcher *HaveHTTPBodyMatcher) body(actual interface{}) ([]byte, error) {
|
||||
if matcher.cachedBody != nil {
|
||||
return matcher.cachedBody, nil
|
||||
}
|
||||
|
||||
body := func(a *http.Response) ([]byte, error) {
|
||||
if a.Body != nil {
|
||||
defer a.Body.Close()
|
||||
var err error
|
||||
matcher.cachedBody, err = gutil.ReadAll(a.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading response body: %w", err)
|
||||
}
|
||||
}
|
||||
return matcher.cachedBody, nil
|
||||
}
|
||||
|
||||
switch a := actual.(type) {
|
||||
case *http.Response:
|
||||
return body(a)
|
||||
case *httptest.ResponseRecorder:
|
||||
return body(a.Result())
|
||||
default:
|
||||
return nil, fmt.Errorf("HaveHTTPBody matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1))
|
||||
}
|
||||
|
||||
}
|
81
vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go
generated
vendored
Normal file
81
vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go
generated
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
type HaveHTTPHeaderWithValueMatcher struct {
|
||||
Header string
|
||||
Value interface{}
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
headerValue, err := matcher.extractHeader(actual)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
headerMatcher, err := matcher.getSubMatcher()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return headerMatcher.Match(headerValue)
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual interface{}) string {
|
||||
headerValue, err := matcher.extractHeader(actual)
|
||||
if err != nil {
|
||||
panic(err) // protected by Match()
|
||||
}
|
||||
|
||||
headerMatcher, err := matcher.getSubMatcher()
|
||||
if err != nil {
|
||||
panic(err) // protected by Match()
|
||||
}
|
||||
|
||||
diff := format.IndentString(headerMatcher.FailureMessage(headerValue), 1)
|
||||
return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff)
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
headerValue, err := matcher.extractHeader(actual)
|
||||
if err != nil {
|
||||
panic(err) // protected by Match()
|
||||
}
|
||||
|
||||
headerMatcher, err := matcher.getSubMatcher()
|
||||
if err != nil {
|
||||
panic(err) // protected by Match()
|
||||
}
|
||||
|
||||
diff := format.IndentString(headerMatcher.NegatedFailureMessage(headerValue), 1)
|
||||
return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff)
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPHeaderWithValueMatcher) getSubMatcher() (types.GomegaMatcher, error) {
|
||||
switch m := matcher.Value.(type) {
|
||||
case string:
|
||||
return &EqualMatcher{Expected: matcher.Value}, nil
|
||||
case types.GomegaMatcher:
|
||||
return m, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("HaveHTTPHeaderWithValue matcher must be passed a string or a GomegaMatcher. Got:\n%s", format.Object(matcher.Value, 1))
|
||||
}
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual interface{}) (string, error) {
|
||||
switch r := actual.(type) {
|
||||
case *http.Response:
|
||||
return r.Header.Get(matcher.Header), nil
|
||||
case *httptest.ResponseRecorder:
|
||||
return r.Result().Header.Get(matcher.Header), nil
|
||||
default:
|
||||
return "", fmt.Errorf("HaveHTTPHeaderWithValue matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1))
|
||||
}
|
||||
}
|
72
vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go
generated
vendored
72
vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go
generated
vendored
@ -4,12 +4,15 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/internal/gutil"
|
||||
)
|
||||
|
||||
type HaveHTTPStatusMatcher struct {
|
||||
Expected interface{}
|
||||
Expected []interface{}
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, err error) {
|
||||
@ -23,20 +26,71 @@ func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, e
|
||||
return false, fmt.Errorf("HaveHTTPStatus matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1))
|
||||
}
|
||||
|
||||
switch e := matcher.Expected.(type) {
|
||||
case int:
|
||||
return resp.StatusCode == e, nil
|
||||
case string:
|
||||
return resp.Status == e, nil
|
||||
if len(matcher.Expected) == 0 {
|
||||
return false, fmt.Errorf("HaveHTTPStatus matcher must be passed an int or a string. Got nothing")
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("HaveHTTPStatus matcher must be passed an int or a string. Got:\n%s", format.Object(matcher.Expected, 1))
|
||||
for _, expected := range matcher.Expected {
|
||||
switch e := expected.(type) {
|
||||
case int:
|
||||
if resp.StatusCode == e {
|
||||
return true, nil
|
||||
}
|
||||
case string:
|
||||
if resp.Status == e {
|
||||
return true, nil
|
||||
}
|
||||
default:
|
||||
return false, fmt.Errorf("HaveHTTPStatus matcher must be passed int or string types. Got:\n%s", format.Object(expected, 1))
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "to have HTTP status", matcher.Expected)
|
||||
return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "to have HTTP status", matcher.expectedString())
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
||||
return format.Message(actual, "not to have HTTP status", matcher.Expected)
|
||||
return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "not to have HTTP status", matcher.expectedString())
|
||||
}
|
||||
|
||||
func (matcher *HaveHTTPStatusMatcher) expectedString() string {
|
||||
var lines []string
|
||||
for _, expected := range matcher.Expected {
|
||||
lines = append(lines, format.Object(expected, 1))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func formatHttpResponse(input interface{}) string {
|
||||
var resp *http.Response
|
||||
switch r := input.(type) {
|
||||
case *http.Response:
|
||||
resp = r
|
||||
case *httptest.ResponseRecorder:
|
||||
resp = r.Result()
|
||||
default:
|
||||
return "cannot format invalid HTTP response"
|
||||
}
|
||||
|
||||
body := "<nil>"
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
data, err := gutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
data = []byte("<error reading body>")
|
||||
}
|
||||
body = format.Object(string(data), 0)
|
||||
}
|
||||
|
||||
var s strings.Builder
|
||||
s.WriteString(fmt.Sprintf("%s<%s>: {\n", format.Indent, reflect.TypeOf(input)))
|
||||
s.WriteString(fmt.Sprintf("%s%sStatus: %s\n", format.Indent, format.Indent, format.Object(resp.Status, 0)))
|
||||
s.WriteString(fmt.Sprintf("%s%sStatusCode: %s\n", format.Indent, format.Indent, format.Object(resp.StatusCode, 0)))
|
||||
s.WriteString(fmt.Sprintf("%s%sBody: %s\n", format.Indent, format.Indent, body))
|
||||
s.WriteString(fmt.Sprintf("%s}", format.Indent))
|
||||
|
||||
return s.String()
|
||||
}
|
||||
|
54
vendor/github.com/onsi/gomega/matchers/have_value.go
generated
vendored
Normal file
54
vendor/github.com/onsi/gomega/matchers/have_value.go
generated
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
package matchers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"github.com/onsi/gomega/types"
|
||||
)
|
||||
|
||||
const maxIndirections = 31
|
||||
|
||||
type HaveValueMatcher struct {
|
||||
Matcher types.GomegaMatcher // the matcher to apply to the "resolved" actual value.
|
||||
resolvedActual interface{} // the ("resolved") value.
|
||||
}
|
||||
|
||||
func (m *HaveValueMatcher) Match(actual interface{}) (bool, error) {
|
||||
val := reflect.ValueOf(actual)
|
||||
for allowedIndirs := maxIndirections; allowedIndirs > 0; allowedIndirs-- {
|
||||
// return an error if value isn't valid. Please note that we cannot
|
||||
// check for nil here, as we might not deal with a pointer or interface
|
||||
// at this point.
|
||||
if !val.IsValid() {
|
||||
return false, errors.New(format.Message(
|
||||
actual, "not to be <nil>"))
|
||||
}
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr, reflect.Interface:
|
||||
// resolve pointers and interfaces to their values, then rinse and
|
||||
// repeat.
|
||||
if val.IsNil() {
|
||||
return false, errors.New(format.Message(
|
||||
actual, "not to be <nil>"))
|
||||
}
|
||||
val = val.Elem()
|
||||
continue
|
||||
default:
|
||||
// forward the final value to the specified matcher.
|
||||
m.resolvedActual = val.Interface()
|
||||
return m.Matcher.Match(m.resolvedActual)
|
||||
}
|
||||
}
|
||||
// too many indirections: extreme star gazing, indeed...?
|
||||
return false, errors.New(format.Message(actual, "too many indirections"))
|
||||
}
|
||||
|
||||
func (m *HaveValueMatcher) FailureMessage(_ interface{}) (message string) {
|
||||
return m.Matcher.FailureMessage(m.resolvedActual)
|
||||
}
|
||||
|
||||
func (m *HaveValueMatcher) NegatedFailureMessage(_ interface{}) (message string) {
|
||||
return m.Matcher.NegatedFailureMessage(m.resolvedActual)
|
||||
}
|
2
vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
generated
vendored
2
vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
generated
vendored
@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/onsi/gomega/format"
|
||||
"gopkg.in/yaml.v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type MatchYAMLMatcher struct {
|
||||
|
16
vendor/github.com/onsi/gomega/matchers/with_transform.go
generated
vendored
16
vendor/github.com/onsi/gomega/matchers/with_transform.go
generated
vendored
@ -9,7 +9,7 @@ import (
|
||||
|
||||
type WithTransformMatcher struct {
|
||||
// input
|
||||
Transform interface{} // must be a function of one parameter that returns one value
|
||||
Transform interface{} // must be a function of one parameter that returns one value and an optional error
|
||||
Matcher types.GomegaMatcher
|
||||
|
||||
// cached value
|
||||
@ -19,6 +19,9 @@ type WithTransformMatcher struct {
|
||||
transformedValue interface{}
|
||||
}
|
||||
|
||||
// reflect.Type for error
|
||||
var errorT = reflect.TypeOf((*error)(nil)).Elem()
|
||||
|
||||
func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher {
|
||||
if transform == nil {
|
||||
panic("transform function cannot be nil")
|
||||
@ -27,8 +30,10 @@ func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher)
|
||||
if txType.NumIn() != 1 {
|
||||
panic("transform function must have 1 argument")
|
||||
}
|
||||
if txType.NumOut() != 1 {
|
||||
panic("transform function must have 1 return value")
|
||||
if numout := txType.NumOut(); numout != 1 {
|
||||
if numout != 2 || !txType.Out(1).AssignableTo(errorT) {
|
||||
panic("transform function must either have 1 return value, or 1 return value plus 1 error value")
|
||||
}
|
||||
}
|
||||
|
||||
return &WithTransformMatcher{
|
||||
@ -57,6 +62,11 @@ func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) {
|
||||
// call the Transform function with `actual`
|
||||
fn := reflect.ValueOf(m.Transform)
|
||||
result := fn.Call([]reflect.Value{param})
|
||||
if len(result) == 2 {
|
||||
if !result[1].IsNil() {
|
||||
return false, fmt.Errorf("Transform function failed: %s", result[1].Interface().(error).Error())
|
||||
}
|
||||
}
|
||||
m.transformedValue = result[0].Interface() // expect exactly one value
|
||||
|
||||
return m.Matcher.Match(m.transformedValue)
|
||||
|
8
vendor/github.com/onsi/gomega/tools
generated
vendored
Normal file
8
vendor/github.com/onsi/gomega/tools
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
//go:build tools
|
||||
// +build tools
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "github.com/onsi/ginkgo/v2/ginkgo"
|
||||
)
|
27
vendor/github.com/onsi/gomega/types/types.go
generated
vendored
27
vendor/github.com/onsi/gomega/types/types.go
generated
vendored
@ -1,12 +1,13 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GomegaFailHandler func(message string, callerSkip ...int)
|
||||
|
||||
//A simple *testing.T interface wrapper
|
||||
// A simple *testing.T interface wrapper
|
||||
type GomegaTestingT interface {
|
||||
Helper()
|
||||
Fatalf(format string, args ...interface{})
|
||||
@ -18,11 +19,11 @@ type Gomega interface {
|
||||
Expect(actual interface{}, extra ...interface{}) Assertion
|
||||
ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion
|
||||
|
||||
Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion
|
||||
EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion
|
||||
Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion
|
||||
EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion
|
||||
|
||||
Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion
|
||||
ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion
|
||||
Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion
|
||||
ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion
|
||||
|
||||
SetDefaultEventuallyTimeout(time.Duration)
|
||||
SetDefaultEventuallyPollingInterval(time.Duration)
|
||||
@ -30,9 +31,9 @@ type Gomega interface {
|
||||
SetDefaultConsistentlyPollingInterval(time.Duration)
|
||||
}
|
||||
|
||||
//All Gomega matchers must implement the GomegaMatcher 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)
|
||||
@ -66,6 +67,14 @@ func MatchMayChangeInTheFuture(matcher GomegaMatcher, value interface{}) bool {
|
||||
type AsyncAssertion interface {
|
||||
Should(matcher GomegaMatcher, optionalDescription ...interface{}) bool
|
||||
ShouldNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool
|
||||
|
||||
WithOffset(offset int) AsyncAssertion
|
||||
WithTimeout(interval time.Duration) AsyncAssertion
|
||||
WithPolling(interval time.Duration) AsyncAssertion
|
||||
Within(timeout time.Duration) AsyncAssertion
|
||||
ProbeEvery(interval time.Duration) AsyncAssertion
|
||||
WithContext(ctx context.Context) AsyncAssertion
|
||||
WithArguments(argsToForward ...interface{}) AsyncAssertion
|
||||
}
|
||||
|
||||
// Assertions are returned by Ω and Expect and enable assertions against Gomega matchers
|
||||
@ -76,4 +85,8 @@ type Assertion interface {
|
||||
To(matcher GomegaMatcher, optionalDescription ...interface{}) bool
|
||||
ToNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool
|
||||
NotTo(matcher GomegaMatcher, optionalDescription ...interface{}) bool
|
||||
|
||||
WithOffset(offset int) Assertion
|
||||
|
||||
Error() Assertion
|
||||
}
|
||||
|
Reference in New Issue
Block a user