pax_global_header00006660000000000000000000000064147614100720014514gustar00rootroot0000000000000052 comment=9fab5b040ab866a661f058ff2711113bcddeecdc golang-gomega-1.36.2/000077500000000000000000000000001476141007200143115ustar00rootroot00000000000000golang-gomega-1.36.2/.github/000077500000000000000000000000001476141007200156515ustar00rootroot00000000000000golang-gomega-1.36.2/.github/FUNDING.yml000066400000000000000000000000171476141007200174640ustar00rootroot00000000000000github: [onsi] golang-gomega-1.36.2/.github/dependabot.yml000066400000000000000000000006271476141007200205060ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: bundler directory: "/docs" schedule: interval: daily time: '01:00' open-pull-requests-limit: 5 - package-ecosystem: gomod directory: "/" schedule: interval: daily time: '01:00' open-pull-requests-limit: 5 - package-ecosystem: github-actions directory: "/" schedule: interval: daily time: '01:00' open-pull-requests-limit: 5 golang-gomega-1.36.2/.github/workflows/000077500000000000000000000000001476141007200177065ustar00rootroot00000000000000golang-gomega-1.36.2/.github/workflows/codeql-analysis.yml000066400000000000000000000044751476141007200235330ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '39 17 * * 3' jobs: analyze: name: Analyze runs-on: ubuntu-latest strategy: fail-fast: false matrix: language: [ 'go', 'ruby' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 golang-gomega-1.36.2/.github/workflows/test.yml000066400000000000000000000013421476141007200214100ustar00rootroot00000000000000name: test on: [push, pull_request] jobs: mod: runs-on: ubuntu-latest name: Check modules steps: - uses: actions/setup-go@v5 with: go-version: 'oldstable' - uses: actions/checkout@v4 - run: go mod tidy && git diff --exit-code go.mod go.sum build: runs-on: ubuntu-latest strategy: matrix: version: [ 'oldstable', 'stable' ] name: Go ${{ matrix.version }} steps: - uses: actions/setup-go@v5 with: go-version: ${{ matrix.version }} - uses: actions/checkout@v4 - run: go vet ./... - run: go run github.com/onsi/ginkgo/v2/ginkgo -r --randomize-all --randomize-suites --race --trace --fail-on-pending --keep-going --label-filter="!network" golang-gomega-1.36.2/.gitignore000066400000000000000000000000601476141007200162750ustar00rootroot00000000000000.DS_Store *.test . .idea gomega.iml TODO .vscodegolang-gomega-1.36.2/CHANGELOG.md000066400000000000000000000730361476141007200161330ustar00rootroot00000000000000## 1.36.2 ### Maintenance - Bump google.golang.org/protobuf from 1.35.1 to 1.36.1 (#810) [9a7609d] - Bump golang.org/x/net from 0.30.0 to 0.33.0 (#807) [b6cb028] - Bump github.com/onsi/ginkgo/v2 from 2.20.1 to 2.22.1 (#808) [5756529] - Bump nokogiri from 1.16.3 to 1.16.5 in /docs (#757) [dabc12e] ## 1.36.1 ### Fixes - Fix https://github.com/onsi/gomega/issues/803 [1c6c112] - resolves onsi/gomega#696: make HaveField great on pointer receivers given only a non-addressable value [4feb9d7] ## 1.36.0 ### Features - new: make collection-related matchers Go 1.23 iterator aware [4c964c6] ### Maintenance - Replace min/max helpers with built-in min/max [ece6872] - Fix some typos in docs [8e924d7] ## 1.35.1 ### Fixes - Export EnforceDefaultTimeoutsWhenUsingContexts and DisableDefaultTimeoutsWhenUsingContext [ca36da1] ## 1.35.0 ### Features - You can now call `EnforceDefaultTimeoutsWhenUsingContexts()` to have `Eventually` honor the default timeout when passed a context. (prior to this you had to expclility add a timeout) [e4c4265] - You can call `StopTrying(message).Successfully()` to abort a `Consistently` early without failure [eeca931] ### Fixes - Stop memoizing the result of `HaveField` to avoid unexpected errors when used with async assertions. [3bdbc4e] ### Maintenance - Bump all dependencies [a05a416] ## 1.34.2 Require Go 1.22+ ### Maintenance - bump ginkgo as well [c59c6dc] - bump to go 1.22 - remove x/exp dependency [8158b99] ## 1.34.1 ### Maintenance - Use slices from exp/slices to keep golang 1.20 compat [5e71dcd] ## 1.34.0 ### Features - Add RoundTripper method to ghttp.Server [c549e0d] ### Fixes - fix incorrect handling of nil slices in HaveExactElements (fixes #771) [878940c] - issue_765 - fixed bug in Hopcroft-Karp algorithm [ebadb67] ### Maintenance - bump ginkgo [8af2ece] - Fix typo in docs [123a071] - Bump github.com/onsi/ginkgo/v2 from 2.17.2 to 2.17.3 (#756) [0e69083] - Bump google.golang.org/protobuf from 1.33.0 to 1.34.1 (#755) [2675796] - Bump golang.org/x/net from 0.24.0 to 0.25.0 (#754) [4160c0f] - Bump github-pages from 230 to 231 in /docs (#748) [892c303] ## 1.33.1 ### Fixes - fix confusing eventually docs [3a66379] ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.17.1 to 2.17.2 [e9bc35a] ## 1.33.0 ### Features `Receive` not accepts `Receive(, MATCHER>)`, allowing you to pick out a specific value on the channel that satisfies the provided matcher and is stored in the provided pointer. ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.15.0 to 2.17.1 (#745) [9999deb] - Bump github-pages from 229 to 230 in /docs (#735) [cb5ff21] - Bump golang.org/x/net from 0.20.0 to 0.23.0 (#746) [bac6596] ## 1.32.0 ### Maintenance - Migrate github.com/golang/protobuf to google.golang.org/protobuf [436a197] This release drops the deprecated github.com/golang/protobuf and adopts google.golang.org/protobuf. Care was taken to ensure the release is backwards compatible (thanks @jbduncan !). Please open an issue if you run into one. - chore: test with Go 1.22 (#733) [32ef35e] - Bump golang.org/x/net from 0.19.0 to 0.20.0 (#717) [a0d0387] - Bump github-pages and jekyll-feed in /docs (#732) [b71e477] - docs: fix typo and broken anchor link to gstruct [f460154] - docs: fix HaveEach matcher signature [a2862e4] ## 1.31.1 ### Fixes - Inverted arguments order of FailureMessage of BeComparableToMatcher [e0dd999] - Update test in case keeping msg is desired [ad1a367] ### Maintenance - Show how to import the format sub package [24e958d] - tidy up go.sum [26661b8] - bump dependencies [bde8f7a] ## 1.31.0 ### Features - Async assertions include context cancellation cause if present [121c37f] ### Maintenance - Bump minimum go version [dee1e3c] - docs: fix typo in example usage "occured" -> "occurred" [49005fe] - Bump actions/setup-go from 4 to 5 (#714) [f1c8757] - Bump github/codeql-action from 2 to 3 (#715) [9836e76] - Bump github.com/onsi/ginkgo/v2 from 2.13.0 to 2.13.2 (#713) [54726f0] - Bump golang.org/x/net from 0.17.0 to 0.19.0 (#711) [df97ecc] - docs: fix `HaveExactElement` typo (#712) [a672c86] ## 1.30.0 ### Features - BeTrueBecause and BeFalseBecause allow for better failure messages [4da4c7f] ### Maintenance - Bump actions/checkout from 3 to 4 (#694) [6ca6e97] - doc: fix type on gleak go doc [f1b8343] ## 1.29.0 ### Features - MatchError can now take an optional func(error) bool + description [2b39142] ## 1.28.1 ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.12.0 to 2.13.0 [635d196] - Bump github.com/google/go-cmp from 0.5.9 to 0.6.0 [14f8859] - Bump golang.org/x/net from 0.14.0 to 0.17.0 [d8a6508] - #703 doc(matchers): HaveEach() doc comment updated [2705bdb] - Minor typos (#699) [375648c] ## 1.28.0 ### Features - Add VerifyHost handler to ghttp (#698) [0b03b36] ### Fixes - Read Body for Newer Responses in HaveHTTPBodyMatcher (#686) [18d6673] ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.11.0 to 2.12.0 (#693) [55a33f3] - Typo in matchers.go (#691) [de68e8f] - Bump commonmarker from 0.23.9 to 0.23.10 in /docs (#690) [ab17f5e] - chore: update test matrix for Go 1.21 (#689) [5069017] - Bump golang.org/x/net from 0.12.0 to 0.14.0 (#688) [babe25f] ## 1.27.10 ### Fixes - fix: go 1.21 adding goroutine ID to creator+location (#685) [bdc7803] ## 1.27.9 ### Fixes - Prevent nil-dereference in format.Object for boxed nil error (#681) [3b31fc3] ### Maintenance - Bump golang.org/x/net from 0.11.0 to 0.12.0 (#679) [360849b] - chore: use String() instead of fmt.Sprintf (#678) [86f3659] - Bump golang.org/x/net from 0.10.0 to 0.11.0 (#674) [642ead0] - chore: unnecessary use of fmt.Sprintf (#677) [ceb9ca6] - Bump github.com/onsi/ginkgo/v2 from 2.10.0 to 2.11.0 (#675) [a2087d8] - docs: fix ContainSubstring references (#673) [fc9a89f] - Bump github.com/onsi/ginkgo/v2 from 2.9.7 to 2.10.0 (#671) [9076019] ## 1.27.8 ### Fixes - HaveExactElement should not call FailureMessage if a submatcher returned an error [096f392] ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.9.5 to 2.9.7 (#669) [8884bee] ## 1.27.7 ### Fixes - fix: gcustom.MakeMatcher accepts nil as actual value (#666) [57054d5] ### Maintenance - update gitignore [05c1bc6] - Bump github.com/onsi/ginkgo/v2 from 2.9.4 to 2.9.5 (#663) [7cadcf6] - Bump golang.org/x/net from 0.9.0 to 0.10.0 (#662) [b524839] - Bump github.com/onsi/ginkgo/v2 from 2.9.2 to 2.9.4 (#661) [5f44694] - Bump commonmarker from 0.23.8 to 0.23.9 in /docs (#657) [05dc99a] - Bump nokogiri from 1.14.1 to 1.14.3 in /docs (#658) [3a033d1] - Replace deprecated NewGomegaWithT with NewWithT (#659) [a19238f] - Bump golang.org/x/net from 0.8.0 to 0.9.0 (#656) [29ed041] - Bump actions/setup-go from 3 to 4 (#651) [11b2080] ## 1.27.6 ### Fixes - Allow collections matchers to work correctly when expected has nil elements [60e7cf3] ### Maintenance - updates MatchError godoc comment to also accept a Gomega matcher (#654) [67b869d] ## 1.27.5 ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.9.1 to 2.9.2 (#653) [a215021] - Bump github.com/go-task/slim-sprig (#652) [a26fed8] ## 1.27.4 ### Fixes - improve error formatting and remove duplication of error message in Eventually/Consistently [854f075] ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.9.0 to 2.9.1 (#650) [ccebd9b] ## 1.27.3 ### Fixes - format.Object now always includes err.Error() when passed an error [86d97ef] - Fix HaveExactElements to work inside ContainElement or other collection matchers (#648) [636757e] ### Maintenance - Bump github.com/golang/protobuf from 1.5.2 to 1.5.3 (#649) [cc16689] - Bump github.com/onsi/ginkgo/v2 from 2.8.4 to 2.9.0 (#646) [e783366] ## 1.27.2 ### Fixes - improve poll progress message when polling a consistently that has been passing [28a319b] ### Maintenance - bump ginkgo - remove tools.go hack as Ginkgo 2.8.2 automatically pulls in the cli dependencies [81443b3] ## 1.27.1 ### Maintenance - Bump golang.org/x/net from 0.6.0 to 0.7.0 (#640) [bc686cd] ## 1.27.0 ### Features - Add HaveExactElements matcher (#634) [9d50783] - update Gomega docs to discuss GinkgoHelper() [be32774] ### Maintenance - Bump github.com/onsi/ginkgo/v2 from 2.8.0 to 2.8.1 (#639) [296a68b] - Bump golang.org/x/net from 0.5.0 to 0.6.0 (#638) [c2b098b] - Bump github-pages from 227 to 228 in /docs (#636) [a9069ab] - test: update matrix for Go 1.20 (#635) [6bd25c8] - Bump github.com/onsi/ginkgo/v2 from 2.7.0 to 2.8.0 (#631) [5445f8b] - Bump webrick from 1.7.0 to 1.8.1 in /docs (#630) [03e93bb] - codeql: add ruby language (#626) [63c7d21] - dependabot: add bundler package-ecosystem for docs (#625) [d92f963] ## 1.26.0 ### Features - When a polled function returns an error, keep track of the actual and report on the matcher state of the last non-errored actual [21f3090] - improve eventually failure message output [c530fb3] ### Fixes - fix several documentation spelling issues [e2eff1f] ## 1.25.0 ### Features - add `MustPassRepeatedly(int)` to asyncAssertion (#619) [4509f72] - compare unwrapped errors using DeepEqual (#617) [aaeaa5d] ### Maintenance - Bump golang.org/x/net from 0.4.0 to 0.5.0 (#614) [c7cfea4] - Bump github.com/onsi/ginkgo/v2 from 2.6.1 to 2.7.0 (#615) [71b8adb] - Docs: Fix typo "MUltiple" -> "Multiple" (#616) [9351dda] - clean up go.sum [cd1dc1d] ## 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 The previous version (1.14.0) introduced a change to allow `Eventually` and `Consistently` to support functions that make assertions. This was accomplished by overriding the global fail handler when running the callbacks passed to `Eventually/Consistently` in order to capture any resulting errors. Issue #457 uncovered a flaw with this approach: when multiple `Eventually`s are running concurrently they race when overriding the singleton global fail handler. 1.15.0 resolves this by requiring users who want to make assertions in `Eventually/Consistently` call backs to explicitly pass in a function that takes a `Gomega` as an argument. The passed-in `Gomega` instance can be used to make assertions. Any failures will cause `Eventually` to retry the callback. This cleaner interface avoids the issue of swapping out globals but comes at the cost of changing the contract introduced in v1.14.0. As such 1.15.0 introduces a breaking change with respect to 1.14.0 - however we expect that adoption of this feature in 1.14.0 remains limited. In addition, 1.15.0 cleans up some of Gomega's internals. Most users shouldn't notice any differences stemming from the refactoring that was made. ## 1.14.0 ### Features - gmeasure.SamplingConfig now suppers a MinSamplingInterval [e94dbca] - Eventually and Consistently support functions that make assertions [2f04e6e] - Eventually and Consistently now allow their passed-in functions to make assertions. These assertions must pass or the function is considered to have failed and is retried. - Eventually and Consistently can now take functions with no return values. These implicitly return nil if they contain no failed assertion. Otherwise they return an error wrapping the first assertion failure. This allows these functions to be used with the Succeed() matcher. - Introduce InterceptGomegaFailure - an analogue to InterceptGomegaFailures - that captures the first assertion failure and halts execution in its passed-in callback. ### Fixes - Call Verify GHTTPWithGomega receiver funcs (#454) [496e6fd] - Build a binary with an expected name (#446) [7356360] ## 1.13.0 ### Features - gmeasure provides BETA support for benchmarking (#447) [8f2dfbf] - Set consistently and eventually defaults on init (#443) [12eb778] ## 1.12.0 ### Features - Add Satisfy() matcher (#437) [c548f31] - tweak truncation message [3360b8c] - Add format.GomegaStringer (#427) [cc80b6f] - Add Clear() method to gbytes.Buffer [c3c0920] ### Fixes - Fix error message in BeNumericallyMatcher (#432) [09c074a] - Bump github.com/onsi/ginkgo from 1.12.1 to 1.16.2 (#442) [e5f6ea0] - Bump github.com/golang/protobuf from 1.4.3 to 1.5.2 (#431) [adae3bf] - Bump golang.org/x/net (#441) [3275b35] ## 1.11.0 ### Features - feature: add index to gstruct element func (#419) [334e00d] - feat(gexec) Add CompileTest functions. Close #410 (#411) [47c613f] ### Fixes - Check more carefully for nils in WithTransform (#423) [3c60a15] - fix: typo in Makefile [b82522a] - Allow WithTransform function to accept a nil value (#422) [b75d2f2] - fix: print value type for interface{} containers (#409) [f08e2dc] - fix(BeElementOf): consistently flatten expected values [1fa9468] ## 1.10.5 ### Fixes - fix: collections matchers should display type of expectation (#408) [6b4eb5a] - fix(ContainElements): consistently flatten expected values [073b880] - fix(ConsistOf): consistently flatten expected values [7266efe] ## 1.10.4 ### Fixes - update golang net library to more recent version without vulnerability (#406) [817a8b9] - Correct spelling: alloted -> allotted (#403) [0bae715] - fix a panic in MessageWithDiff with long message (#402) [ea06b9b] ## 1.10.3 ### Fixes - updates golang/x/net to fix vulnerability detected by snyk (#394) [c479356] ## 1.10.2 ### Fixes - Add ExpectWithOffset, EventuallyWithOffset and ConsistentlyWithOffset to WithT (#391) [990941a] ## 1.10.1 ### Fixes - Update dependencies (#389) [9f5eecd] ## 1.10.0 ### Features - Add HaveHTTPStatusMatcher (#378) [f335c94] - Changed matcher for content-type in VerifyJSONRepresenting (#377) [6024f5b] - Make ghttp usable with x-unit style tests (#376) [c0be499] - Implement PanicWith matcher (#381) [f8032b4] ## 1.9.0 ### Features - Add ContainElements matcher (#370) [2f57380] - Output missing and extra elements in ConsistOf failure message [a31eda7] - Document method LargestMatching [7c5a280] ## 1.8.1 ### Fixes - Fix unexpected MatchError() behaviour (#375) [8ae7b2f] ## 1.8.0 ### Features - Allow optional description to be lazily evaluated function (#364) [bf64010] - Support wrapped errors (#359) [0a981cb] ## 1.7.1 ### Fixes - Bump go-yaml version to cover fixed ddos heuristic (#362) [95e431e] ## 1.7.0 ### Features - export format property variables (#347) [642e5ba] ### Fixes - minor fix in the documentation of ExpectWithOffset (#358) [beea727] ## 1.6.0 ### Features - Display special chars on error [41e1b26] - Add BeElementOf matcher [6a48b48] ### Fixes - Remove duplication in XML matcher tests [cc1a6cb] - Remove unnecessary conversions (#357) [7bf756a] - Fixed import order (#353) [2e3b965] - Added missing error handling in test (#355) [c98d3eb] - Simplify code (#356) [0001ed9] - Simplify code (#354) [0d9100e] - Fixed typos (#352) [3f647c4] - Add failure message tests to BeElementOf matcher [efe19c3] - Update go-testcov untested sections [37ee382] - Mark all uncovered files so go-testcov ./... works [53b150e] - Reenable gotip in travis [5c249dc] - Fix the typo of comment (#345) [f0e010e] - Optimize contain_element_matcher [abeb93d] ## 1.5.0 ### Features - Added MatchKeys matchers [8b909fc] ### Fixes and Minor Improvements - Add type aliases to remove stuttering [03b0461] - Don't run session_test.go on windows (#324) [5533ce8] ## 1.4.3 ### Fixes: - ensure file name and line numbers are correctly reported for XUnit [6fff58f] - Fixed matcher for content-type (#305) [69d9b43] ## 1.4.2 ### Fixes: - Add go.mod and go.sum files to define the gomega go module [f3de367, a085d30] - Work around go vet issue with Go v1.11 (#300) [40dd6ad] - Better output when using with go XUnit-style tests, fixes #255 (#297) [29a4b97] - Fix MatchJSON fail to parse json.RawMessage (#298) [ae19f1b] - show threshold in failure message of BeNumericallyMatcher (#293) [4bbecc8] ## 1.4.1 ### Fixes: - Update documentation formatting and examples (#289) [9be8410] - allow 'Receive' matcher to be used with concrete types (#286) [41673fd] - Fix data race in ghttp server (#283) [7ac6b01] - Travis badge should only show master [cc102ab] ## 1.4.0 ### Features - Make string pretty diff user configurable (#273) [eb112ce, 649b44d] ### Fixes - Use httputil.DumpRequest to pretty-print unhandled requests (#278) [a4ff0fc, b7d1a52] - fix typo floa32 > float32 (#272) [041ae3b, 6e33911] - Fix link to documentation on adding your own matchers (#270) [bb2c830, fcebc62] - Use setters and getters to avoid race condition (#262) [13057c3, a9c79f1] - Avoid sending a signal if the process is not alive (#259) [b8043e5, 4fc1762] - Improve message from AssignableToTypeOf when expected value is nil (#281) [9c1fb20] ## 1.3.0 Improvements: - The `Equal` matcher matches byte slices more performantly. - Improved how `MatchError` matches error strings. - `MatchXML` ignores the order of xml node attributes. - Improve support for XUnit style golang tests. ([#254](https://github.com/onsi/gomega/issues/254)) Bug Fixes: - Diff generation now handles multi-byte sequences correctly. - Multiple goroutines can now call `gexec.Build` concurrently. ## 1.2.0 Improvements: - Added `BeSent` which attempts to send a value down a channel and fails if the attempt blocks. Can be paired with `Eventually` to safely send a value down a channel with a timeout. - `Ω`, `Expect`, `Eventually`, and `Consistently` now immediately `panic` if there is no registered fail handler. This is always a mistake that can hide failing tests. - `Receive()` no longer errors when passed a closed channel, it's perfectly fine to attempt to read from a closed channel so Ω(c).Should(Receive()) always fails and Ω(c).ShoudlNot(Receive()) always passes with a closed channel. - Added `HavePrefix` and `HaveSuffix` matchers. - `ghttp` can now handle concurrent requests. - Added `Succeed` which allows one to write `Ω(MyFunction()).Should(Succeed())`. - Improved `ghttp`'s behavior around failing assertions and panics: - If a registered handler makes a failing assertion `ghttp` will return `500`. - If a registered handler panics, `ghttp` will return `500` *and* fail the test. This is new behavior that may cause existing code to break. This code is almost certainly incorrect and creating a false positive. - `ghttp` servers can take an `io.Writer`. `ghttp` will write a line to the writer when each request arrives. - Added `WithTransform` matcher to allow munging input data before feeding into the relevant matcher - Added boolean `And`, `Or`, and `Not` matchers to allow creating composite matchers - Added `gbytes.TimeoutCloser`, `gbytes.TimeoutReader`, and `gbytes.TimeoutWriter` - these are convenience wrappers that timeout if the underlying Closer/Reader/Writer does not return within the alloted time. - Added `gbytes.BufferReader` - this constructs a `gbytes.Buffer` that asynchronously reads the passed-in `io.Reader` into its buffer. Bug Fixes: - gexec: `session.Wait` now uses `EventuallyWithOffset` to get the right line number in the failure. - `ContainElement` no longer bails if a passed-in matcher errors. ## 1.0 (8/2/2014) No changes. Dropping "beta" from the version number. ## 1.0.0-beta (7/8/2014) Breaking Changes: - Changed OmegaMatcher interface. Instead of having `Match` return failure messages, two new methods `FailureMessage` and `NegatedFailureMessage` are called instead. - Moved and renamed OmegaFailHandler to types.GomegaFailHandler and OmegaMatcher to types.GomegaMatcher. Any references to OmegaMatcher in any custom matchers will need to be changed to point to types.GomegaMatcher New Test-Support Features: - `ghttp`: supports testing http clients - Provides a flexible fake http server - Provides a collection of chainable http handlers that perform assertions. - `gbytes`: supports making ordered assertions against streams of data - Provides a `gbytes.Buffer` - Provides a `Say` matcher to perform ordered assertions against output data - `gexec`: supports testing external processes - Provides support for building Go binaries - Wraps and starts `exec.Cmd` commands - Makes it easy to assert against stdout and stderr - Makes it easy to send signals and wait for processes to exit - Provides an `Exit` matcher to assert against exit code. DSL Changes: - `Eventually` and `Consistently` can accept `time.Duration` interval and polling inputs. - The default timeouts for `Eventually` and `Consistently` are now configurable. New Matchers: - `ConsistOf`: order-independent assertion against the elements of an array/slice or keys of a map. - `BeTemporally`: like `BeNumerically` but for `time.Time` - `HaveKeyWithValue`: asserts a map has a given key with the given value. Updated Matchers: - `Receive` matcher can take a matcher as an argument and passes only if the channel under test receives an objet that satisfies the passed-in matcher. - Matchers that implement `MatchMayChangeInTheFuture(actual interface{}) bool` can inform `Eventually` and/or `Consistently` when a match has no chance of changing status in the future. For example, `Receive` returns `false` when a channel is closed. Misc: - Start using semantic versioning - Start maintaining changelog Major refactor: - Pull out Gomega's internal to `internal` golang-gomega-1.36.2/CONTRIBUTING.md000066400000000000000000000016371476141007200165510ustar00rootroot00000000000000# Contributing to Gomega Your contributions to Gomega are essential for its long-term maintenance and improvement. To make a contribution: - Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code! - Ensure adequate test coverage: - Make sure to add appropriate unit tests - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR - Please run following linter locally `go vet ./...` and make sure output does not contain any warnings - Update the documentation. In addition to standard `godoc` comments Gomega has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. If you're a committer, check out RELEASING.md to learn how to cut a release. Thanks for supporting Gomega! golang-gomega-1.36.2/LICENSE000066400000000000000000000020461476141007200153200ustar00rootroot00000000000000Copyright (c) 2013-2014 Onsi Fakhouri Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-gomega-1.36.2/README.md000066400000000000000000000017151476141007200155740ustar00rootroot00000000000000![Gomega: Ginkgo's Preferred Matcher Library](http://onsi.github.io/gomega/images/gomega.png) [![test](https://github.com/onsi/gomega/actions/workflows/test.yml/badge.svg)](https://github.com/onsi/gomega/actions/workflows/test.yml) Jump straight to the [docs](http://onsi.github.io/gomega/) to learn about Gomega, including a list of [all available matchers](http://onsi.github.io/gomega/#provided-matchers). If you have a question, comment, bug report, feature request, etc. please open a GitHub issue. ## [Ginkgo](http://github.com/onsi/ginkgo): a BDD Testing Framework for Golang Learn more about Ginkgo [here](http://onsi.github.io/ginkgo/) ## Community Matchers A collection of community matchers is available on the [wiki](https://github.com/onsi/gomega/wiki). ## License Gomega is MIT-Licensed The `ConsistOf` matcher uses [goraph](https://github.com/amitkgupta/goraph) which is embedded in the source to simplify distribution. goraph has an MIT license. golang-gomega-1.36.2/RELEASING.md000066400000000000000000000015301476141007200161430ustar00rootroot00000000000000A Gomega release is a tagged sha and a GitHub release. To cut a release: 1. Ensure CHANGELOG.md is up to date. - 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) 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 ```golang-gomega-1.36.2/docs/000077500000000000000000000000001476141007200152415ustar00rootroot00000000000000golang-gomega-1.36.2/docs/.gitignore000066400000000000000000000000751476141007200172330ustar00rootroot00000000000000_site .sass-cache .jekyll-cache .jekyll-metadata vendor golang-gomega-1.36.2/docs/Gemfile000066400000000000000000000021761476141007200165420ustar00rootroot00000000000000source "https://rubygems.org" # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: # # bundle exec jekyll serve # # This will help ensure the proper Jekyll version is running. # Happy Jekylling! # gem "jekyll", "~> 4.2.1" # This is the default theme for new Jekyll sites. You may change this to anything you like. gem "minima", "~> 2.5" # If you want to use GitHub Pages, remove the "gem "jekyll"" above and # uncomment the line below. To upgrade, run `bundle update github-pages`. gem "github-pages", "~> 231", group: :jekyll_plugins # If you have any plugins, put them here! group :jekyll_plugins do gem "jekyll-feed", "~> 0.17" end gem "webrick" # Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem # and associated library. platforms :mingw, :x64_mingw, :mswin, :jruby do gem "tzinfo", "~> 1.2" gem "tzinfo-data" end # Performance-booster for watching directories on Windows gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin] golang-gomega-1.36.2/docs/Gemfile.lock000066400000000000000000000164471476141007200174770ustar00rootroot00000000000000GEM remote: https://rubygems.org/ specs: activesupport (6.0.6.1) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) zeitwerk (~> 2.2, >= 2.2.2) addressable (2.8.6) public_suffix (>= 2.0.2, < 6.0) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.12.2) colorator (1.1.0) commonmarker (0.23.10) concurrent-ruby (1.2.3) dnsruby (1.72.0) simpleidn (~> 0.2.1) em-websocket (0.5.3) eventmachine (>= 0.12.9) http_parser.rb (~> 0) ethon (0.16.0) ffi (>= 1.15.0) eventmachine (1.2.7) execjs (2.9.1) faraday (2.9.0) faraday-net_http (>= 2.0, < 3.2) faraday-net_http (3.1.0) net-http ffi (1.16.3) forwardable-extended (2.6.0) gemoji (4.1.0) github-pages (231) github-pages-health-check (= 1.18.2) jekyll (= 3.9.5) jekyll-avatar (= 0.8.0) jekyll-coffeescript (= 1.2.2) jekyll-commonmark-ghpages (= 0.4.0) jekyll-default-layout (= 0.1.5) jekyll-feed (= 0.17.0) jekyll-gist (= 1.5.0) jekyll-github-metadata (= 2.16.1) jekyll-include-cache (= 0.2.1) jekyll-mentions (= 1.6.0) jekyll-optional-front-matter (= 0.3.2) jekyll-paginate (= 1.1.0) jekyll-readme-index (= 0.3.0) jekyll-redirect-from (= 0.16.0) jekyll-relative-links (= 0.6.1) jekyll-remote-theme (= 0.4.3) jekyll-sass-converter (= 1.5.2) jekyll-seo-tag (= 2.8.0) jekyll-sitemap (= 1.4.0) jekyll-swiss (= 1.0.0) jekyll-theme-architect (= 0.2.0) jekyll-theme-cayman (= 0.2.0) jekyll-theme-dinky (= 0.2.0) jekyll-theme-hacker (= 0.2.0) jekyll-theme-leap-day (= 0.2.0) jekyll-theme-merlot (= 0.2.0) jekyll-theme-midnight (= 0.2.0) jekyll-theme-minimal (= 0.2.0) jekyll-theme-modernist (= 0.2.0) jekyll-theme-primer (= 0.6.0) jekyll-theme-slate (= 0.2.0) jekyll-theme-tactile (= 0.2.0) jekyll-theme-time-machine (= 0.2.0) jekyll-titles-from-headings (= 0.5.3) jemoji (= 0.13.0) kramdown (= 2.4.0) kramdown-parser-gfm (= 1.1.0) liquid (= 4.0.4) mercenary (~> 0.3) minima (= 2.5.1) nokogiri (>= 1.13.6, < 2.0) rouge (= 3.30.0) terminal-table (~> 1.4) github-pages-health-check (1.18.2) addressable (~> 2.3) dnsruby (~> 1.60) octokit (>= 4, < 8) public_suffix (>= 3.0, < 6.0) typhoeus (~> 1.3) html-pipeline (2.14.3) activesupport (>= 2) nokogiri (>= 1.4) http_parser.rb (0.8.0) i18n (1.14.4) concurrent-ruby (~> 1.0) jekyll (3.9.5) addressable (~> 2.4) colorator (~> 1.0) em-websocket (~> 0.5) i18n (>= 0.7, < 2) jekyll-sass-converter (~> 1.0) jekyll-watch (~> 2.0) kramdown (>= 1.17, < 3) liquid (~> 4.0) mercenary (~> 0.3.3) pathutil (~> 0.9) rouge (>= 1.7, < 4) safe_yaml (~> 1.0) jekyll-avatar (0.8.0) jekyll (>= 3.0, < 5.0) jekyll-coffeescript (1.2.2) coffee-script (~> 2.2) coffee-script-source (~> 1.12) jekyll-commonmark (1.4.0) commonmarker (~> 0.22) jekyll-commonmark-ghpages (0.4.0) commonmarker (~> 0.23.7) jekyll (~> 3.9.0) jekyll-commonmark (~> 1.4.0) rouge (>= 2.0, < 5.0) jekyll-default-layout (0.1.5) jekyll (>= 3.0, < 5.0) jekyll-feed (0.17.0) jekyll (>= 3.7, < 5.0) jekyll-gist (1.5.0) octokit (~> 4.2) jekyll-github-metadata (2.16.1) jekyll (>= 3.4, < 5.0) octokit (>= 4, < 7, != 4.4.0) jekyll-include-cache (0.2.1) jekyll (>= 3.7, < 5.0) jekyll-mentions (1.6.0) html-pipeline (~> 2.3) jekyll (>= 3.7, < 5.0) jekyll-optional-front-matter (0.3.2) jekyll (>= 3.0, < 5.0) jekyll-paginate (1.1.0) jekyll-readme-index (0.3.0) jekyll (>= 3.0, < 5.0) jekyll-redirect-from (0.16.0) jekyll (>= 3.3, < 5.0) jekyll-relative-links (0.6.1) jekyll (>= 3.3, < 5.0) jekyll-remote-theme (0.4.3) addressable (~> 2.0) jekyll (>= 3.5, < 5.0) jekyll-sass-converter (>= 1.0, <= 3.0.0, != 2.0.0) rubyzip (>= 1.3.0, < 3.0) jekyll-sass-converter (1.5.2) sass (~> 3.4) jekyll-seo-tag (2.8.0) jekyll (>= 3.8, < 5.0) jekyll-sitemap (1.4.0) jekyll (>= 3.7, < 5.0) jekyll-swiss (1.0.0) jekyll-theme-architect (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-cayman (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-dinky (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-hacker (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-leap-day (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-merlot (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-midnight (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-minimal (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-modernist (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-primer (0.6.0) jekyll (> 3.5, < 5.0) jekyll-github-metadata (~> 2.9) jekyll-seo-tag (~> 2.0) jekyll-theme-slate (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-tactile (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-theme-time-machine (0.2.0) jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-titles-from-headings (0.5.3) jekyll (>= 3.3, < 5.0) jekyll-watch (2.2.1) listen (~> 3.0) jemoji (0.13.0) gemoji (>= 3, < 5) html-pipeline (~> 2.2) jekyll (>= 3.0, < 5.0) kramdown (2.4.0) rexml kramdown-parser-gfm (1.1.0) kramdown (~> 2.0) liquid (4.0.4) listen (3.9.0) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) mercenary (0.3.6) minima (2.5.1) jekyll (>= 3.5, < 5.0) jekyll-feed (~> 0.9) jekyll-seo-tag (~> 2.1) minitest (5.22.3) net-http (0.4.1) uri nokogiri (1.16.5-x86_64-linux) racc (~> 1.4) octokit (4.25.1) faraday (>= 1, < 3) sawyer (~> 0.9) pathutil (0.16.2) forwardable-extended (~> 2.6) public_suffix (5.0.5) racc (1.7.3) rb-fsevent (0.11.2) rb-inotify (0.10.1) ffi (~> 1.0) rexml (3.2.6) rouge (3.30.0) rubyzip (2.3.2) safe_yaml (1.0.5) sass (3.7.4) sass-listen (~> 4.0.0) sass-listen (4.0.0) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) sawyer (0.9.2) addressable (>= 2.3.5) faraday (>= 0.17.3, < 3) simpleidn (0.2.1) unf (~> 0.1.4) terminal-table (1.8.0) unicode-display_width (~> 1.1, >= 1.1.1) thread_safe (0.3.6) typhoeus (1.4.1) ethon (>= 0.9.0) tzinfo (1.2.10) thread_safe (~> 0.1) unf (0.1.4) unf_ext unf_ext (0.0.9.1) unicode-display_width (1.8.0) uri (0.13.0) webrick (1.8.1) zeitwerk (2.6.13) PLATFORMS x86_64-linux DEPENDENCIES github-pages (~> 231) jekyll-feed (~> 0.17) minima (~> 2.5) tzinfo (~> 1.2) tzinfo-data wdm (~> 0.1.1) webrick BUNDLED WITH 2.3.22 golang-gomega-1.36.2/docs/_config.yml000066400000000000000000000002401476141007200173640ustar00rootroot00000000000000baseurl: "/gomega" # the subpath of your site, e.g. /blog # Build settings name: Gomega markdown: GFM highlighter: rouge lsi: false exclude: - "*.go"golang-gomega-1.36.2/docs/_layouts/000077500000000000000000000000001476141007200171005ustar00rootroot00000000000000golang-gomega-1.36.2/docs/_layouts/default.html000066400000000000000000000026121476141007200214130ustar00rootroot00000000000000
{{ content }}
golang-gomega-1.36.2/docs/css/000077500000000000000000000000001476141007200160315ustar00rootroot00000000000000golang-gomega-1.36.2/docs/css/layout.css000066400000000000000000000126501476141007200200640ustar00rootroot00000000000000:root { --max-width: 1024px; --header-height: 50px; --breakpoint: 640px; --gomega-blue: #2d6cad; --gomega-blue-darker: #0d5c8d; --gomega-blue-faint: #fafaff; } body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; margin: 0; } #header { background-color: var(--gomega-blue); color: #fff; border-bottom: solid 1px var(--gomega-blue-darker); } #left-background, #right-background { height: 100vh; background-color: var(--gomega-blue-faint); } #left-background { box-shadow: inset -2px 0 7px -5px var(--gomega-blue-darker); } #right-background { box-shadow: inset 2px 0 7px -5px var(--gomega-blue-darker); } #content { background-color: #fff; overflow-y: scroll; padding: 5px; padding-right:10px; } #sidebar { background-color: #fff; overflow-y: scroll; padding:5px; position:relative; font-size: 16px; } #mask { display:none; } img[alt="Ginkgo"] { max-width: 80%; max-height: 200px; display: block; margin-left: auto; margin-right: auto; } img[alt="Leakiee"] { max-width: 80%; max-height: 150px; display: block; float: right; } /* code styling */ .markdown-body div.highlight { margin-left: 20px; margin-right: 20px; border-radius: 10px; margin-bottom: 16px !important; max-width: 800px; border: solid 2px #f0f0f0; } .markdown-body .highlight pre, .markdown-body pre { background-color: transparent; } div.highlight.invalid { border: solid 2px #f0aaaa; background-color: #f0dddd; } /* sidebar items */ .sidebar-heading, .sidebar-item { display:block; text-decoration: none; color: #000; } .sidebar-heading { margin:5px 5px; padding:3px 0; } .sidebar-heading.active { font-weight:bold; color: var(--gomega-blue); } .sidebar-item { font-size: 0.8rem; margin: 5px 0 5px 10px; } .sidebar-item:nth-child(2n+1) { color:#555; } .sidebar-item.active { font-weight:bold; color: var(--gomega-blue); } .sidebar-section { overflow: hidden; max-height: 0; // transition: max-height 0.3s; } .sidebar-heading.active + .sidebar-section { max-height: 1000px; } /* header */ #header { display: flex; align-items: center; } .brand { font-size: 1.8rem; margin-left:10px; font-weight: bold; text-decoration: none; color: #fff; } .spacer { flex: 1; } .logo { max-height: 22px; margin: 0 5px; } a:last-of-type .logo { margin-right: 10px; } #disclosure { box-sizing: border-box; width: var(--header-height); height: var(--header-height); display: flex; flex-direction: column; align-items: center; justify-content: space-around; padding: 12px 0; cursor: pointer; } .hamburger-slice { width: calc(var(--header-height) - 20px); height: 2px; border-radius: 4px; background-color: #fff; } /* content styling */ #content h2 { border-bottom: none; } /* Desktop */ @media screen and (min-width: 640px) { #container { --sidebar-width: 200px; display: grid; grid-template-areas: "left-background header header right-background" "left-background sidebar content right-background"; grid-template-columns: 1fr var(--sidebar-width) minmax(calc(var(--breakpoint) - var(--sidebar-width)), var(--max-width)) 1fr; grid-template-rows: var(--header-height) auto; gap: 0; height:100vh; } #left-background { grid-area; left-background; } #right-background { grid-area; right-background; } #header { grid-area: header; } #sidebar { grid-area: sidebar; border-right: 5px solid #fff; } #content { grid-area: content; } #disclosure { display: none; } } /* Mobile */ @media screen and (max-width: 640px) { #container { --sidebar-width: 300px; display: grid; grid-template-areas: "header" "content"; grid-template-columns: 1fr; grid-template-rows: var(--header-height) auto; gap: 0; height:100vh; } #header { grid-area: header; } #content { grid-area: content; } #left-background { display: none; } #right-background { display: none; } #sidebar { position: fixed; width: var(--sidebar-width); top: var(--header-height); bottom: 0px; right: calc(-5px - var(--sidebar-width)); z-index:2; transition: right 0.3s; } #mask { background-color: rgba(0,0,0,0); position: fixed; width: 100vw; top: var(--header-height); bottom: 0px; left:0px; z-index:1; cursor: pointer; transition: background-color 0.3s; } #container.reveal-sidebar #sidebar { right: 0px; } #container.reveal-sidebar #mask { display:block; background-color: rgba(0,0,0,0.2); } .hamburger-slice { transition: transform 0.3s, opacity 0.1s; } #container .hamburger-slice:nth-child(1) { transform: rotate(0deg); transform-origin: top left; } #container .hamburger-slice:nth-child(2) { opacity: 100; } #container .hamburger-slice:nth-child(3) { transform: rotate(0deg); transform-origin: bottom left; } #container.reveal-sidebar .hamburger-slice:nth-child(1) { transform: rotate(35deg); } #container.reveal-sidebar .hamburger-slice:nth-child(2) { opacity: 0; } #container.reveal-sidebar .hamburger-slice:nth-child(3) { transform: rotate(-35deg); } } /* Print */ @media print { body { font-size: 10pt; margin: 0.25in; background-image: none; } #header { display: none; } #sidebar { display: none; } #left-background { display: none; } #right-background { display: none; } h2 { break-before: page; } .highlight { break-inside: avoid-page; } } golang-gomega-1.36.2/docs/css/primer-minimal.css000066400000000000000000000253661476141007200215010ustar00rootroot00000000000000.markdown-body { line-height: 1.5; word-wrap: break-word; } .markdown-body > * :first-child { margin-top: 0 !important; } .markdown-body > * :last-child { margin-bottom: 0 !important; } .markdown-body a { color: #000; text-decoration: underline; } .markdown-body a:visited { color: #333; text-decoration: underline; } .markdown-body .anchorjs-link { text-decoration: none; } .markdown-body .absent { color: #cb2431; } .markdown-body .anchor { float: left; padding-right: 4px; margin-left: -20px; line-height: 1; } .markdown-body .anchor:focus { outline: none; } .markdown-body p, .markdown-body blockquote, .markdown-body ul, .markdown-body ol, .markdown-body dl, .markdown-body table, .markdown-body pre { margin-top: 0; margin-bottom: 16px; } .markdown-body hr { height: 0.25em; padding: 0; margin: 24px 0; background-color: #e1e4e8; border: 0; } .markdown-body blockquote { padding: 0 1em; color: #6a737d; border-left: 0.25em solid #dfe2e5; } .markdown-body blockquote > :first-child { margin-top: 0; } .markdown-body blockquote > :last-child { margin-bottom: 0; } .markdown-body kbd { display: inline-block; padding: 3px 5px; font-size: 11px; line-height: 10px; color: #444d56; vertical-align: middle; background-color: #fafbfc; border: solid 1px #c6cbd1; border-bottom-color: #959da5; border-radius: 3px; box-shadow: inset 0 -1px 0 #959da5; } .markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; } .markdown-body h1 .octicon-link, .markdown-body h2 .octicon-link, .markdown-body h3 .octicon-link, .markdown-body h4 .octicon-link, .markdown-body h5 .octicon-link, .markdown-body h6 .octicon-link { color: #1b1f23; vertical-align: middle; visibility: hidden; } .markdown-body h1:hover .anchor, .markdown-body h2:hover .anchor, .markdown-body h3:hover .anchor, .markdown-body h4:hover .anchor, .markdown-body h5:hover .anchor, .markdown-body h6:hover .anchor { text-decoration: none; } .markdown-body h1:hover .anchor .octicon-link, .markdown-body h2:hover .anchor .octicon-link, .markdown-body h3:hover .anchor .octicon-link, .markdown-body h4:hover .anchor .octicon-link, .markdown-body h5:hover .anchor .octicon-link, .markdown-body h6:hover .anchor .octicon-link { visibility: visible; } .markdown-body h1 tt, .markdown-body h1 code, .markdown-body h2 tt, .markdown-body h2 code, .markdown-body h3 tt, .markdown-body h3 code, .markdown-body h4 tt, .markdown-body h4 code, .markdown-body h5 tt, .markdown-body h5 code, .markdown-body h6 tt, .markdown-body h6 code { font-size: inherit; } .markdown-body h1 { padding-bottom: 0.3em; font-size: 2em; border-bottom: 1px solid #eaecef; } .markdown-body h2 { padding-bottom: 0.3em; font-size: 1.5em; border-bottom: 1px solid #eaecef; } .markdown-body h3 { font-size: 1.25em; } .markdown-body h4 { font-size: 1em; } .markdown-body h5 { font-size: 0.875em; } .markdown-body h6 { font-size: 0.85em; color: #6a737d; } .markdown-body ul, .markdown-body ol { padding-left: 2em; } .markdown-body ul.no-list, .markdown-body ol.no-list { padding: 0; list-style-type: none; } .markdown-body ul ul, .markdown-body ul ol, .markdown-body ol ol, .markdown-body ol ul { margin-top: 0; margin-bottom: 0; } .markdown-body li { word-wrap: break-all; } .markdown-body li > p { margin-top: 16px; } .markdown-body li + li { margin-top: 0.25em; } .markdown-body dl { padding: 0; } .markdown-body dl dt { padding: 0; margin-top: 16px; font-size: 1em; font-style: italic; font-weight: 600; } .markdown-body dl dd { padding: 0 16px; margin-bottom: 16px; } .markdown-body table { display: block; width: 100%; overflow: auto; } .markdown-body table th { font-weight: 600; } .markdown-body table th, .markdown-body table td { padding: 6px 13px; border: 1px solid #dfe2e5; } .markdown-body table tr { background-color: #fff; border-top: 1px solid #c6cbd1; } .markdown-body table tr:nth-child(2n) { background-color: #f6f8fa; } .markdown-body table img { background-color: transparent; } .markdown-body img { max-width: 100%; box-sizing: content-box; background-color: #fff; } .markdown-body img[align=right] { padding-left: 20px; } .markdown-body img[align=left] { padding-right: 20px; } .markdown-body .emoji { max-width: none; vertical-align: text-top; background-color: transparent; } .markdown-body span.frame { display: block; overflow: hidden; } .markdown-body span.frame > span { display: block; float: left; width: auto; padding: 7px; margin: 13px 0 0; overflow: hidden; border: 1px solid #dfe2e5; } .markdown-body span.frame span img { display: block; float: left; } .markdown-body span.frame span span { display: block; padding: 5px 0 0; clear: both; color: #24292e; } .markdown-body span.align-center { display: block; overflow: hidden; clear: both; } .markdown-body span.align-center > span { display: block; margin: 13px auto 0; overflow: hidden; text-align: center; } .markdown-body span.align-center span img { margin: 0 auto; text-align: center; } .markdown-body span.align-right { display: block; overflow: hidden; clear: both; } .markdown-body span.align-right > span { display: block; margin: 13px 0 0; overflow: hidden; text-align: right; } .markdown-body span.align-right span img { margin: 0; text-align: right; } .markdown-body span.float-left { display: block; float: left; margin-right: 13px; overflow: hidden; } .markdown-body span.float-left span { margin: 13px 0 0; } .markdown-body span.float-right { display: block; float: right; margin-left: 13px; overflow: hidden; } .markdown-body span.float-right > span { display: block; margin: 13px auto 0; overflow: hidden; text-align: right; } .markdown-body code, .markdown-body tt { padding: 0.2em 0.4em; margin: 0; font-size: 85%; background-color: rgba(27, 31, 35, 0.05); border-radius: 3px; } .markdown-body code br, .markdown-body tt br { display: none; } .markdown-body del code { text-decoration: inherit; } .markdown-body pre { word-wrap: normal; } .markdown-body pre > code { padding: 0; margin: 0; font-size: 100%; word-break: normal; white-space: pre; background: transparent; border: 0; } .markdown-body .highlight { margin-bottom: 16px; } .markdown-body .highlight pre { margin-bottom: 0; word-break: normal; } .markdown-body .highlight pre, .markdown-body pre { padding: 16px; overflow: auto; font-size: 85%; line-height: 1.45; background-color: #f6f8fa; border-radius: 3px; } .markdown-body pre code, .markdown-body pre tt { display: inline; max-width: auto; padding: 0; margin: 0; overflow: visible; line-height: inherit; word-wrap: normal; background-color: transparent; border: 0; } .markdown-body .csv-data td, .markdown-body .csv-data th { padding: 5px; overflow: hidden; font-size: 12px; line-height: 1; text-align: left; white-space: nowrap; } .markdown-body .csv-data .blob-num { padding: 10px 8px 9px; text-align: right; background: #fff; border: 0; } .markdown-body .csv-data tr { border-top: 0; } .markdown-body .csv-data th { font-weight: 600; background: #f6f8fa; border-top: 0; } .highlight table td { padding: 5px; } .highlight table pre { margin: 0; } .highlight .cm { color: #999988; font-style: italic; } .highlight .cp { color: #999999; font-weight: bold; } .highlight .c1 { color: #999988; font-style: italic; } .highlight .cs { color: #999999; font-weight: bold; font-style: italic; } .highlight .c, .highlight .cd { color: #999988; font-style: italic; } .highlight .err { color: #a61717; background-color: #e3d2d2; } .highlight .gd { color: #000000; background-color: #ffdddd; } .highlight .ge { color: #000000; font-style: italic; } .highlight .gr { color: #aa0000; } .highlight .gh { color: #999999; } .highlight .gi { color: #000000; background-color: #ddffdd; } .highlight .go { color: #888888; } .highlight .gp { color: #555555; } .highlight .gs { font-weight: bold; } .highlight .gu { color: #aaaaaa; } .highlight .gt { color: #aa0000; } .highlight .kc { color: #000000; font-weight: bold; } .highlight .kd { color: #000000; font-weight: bold; } .highlight .kn { color: #000000; font-weight: bold; } .highlight .kp { color: #000000; font-weight: bold; } .highlight .kr { color: #000000; font-weight: bold; } .highlight .kt { color: #445588; font-weight: bold; } .highlight .k, .highlight .kv { color: #000000; font-weight: bold; } .highlight .mf { color: #009999; } .highlight .mh { color: #009999; } .highlight .il { color: #009999; } .highlight .mi { color: #009999; } .highlight .mo { color: #009999; } .highlight .m, .highlight .mb, .highlight .mx { color: #009999; } .highlight .sb { color: #d14; } .highlight .sc { color: #d14; } .highlight .sd { color: #d14; } .highlight .s2 { color: #d14; } .highlight .se { color: #d14; } .highlight .sh { color: #d14; } .highlight .si { color: #d14; } .highlight .sx { color: #d14; } .highlight .sr { color: #009926; } .highlight .s1 { color: #d14; } .highlight .ss { color: #990073; } .highlight .s { color: #d14; } .highlight .na { color: #008080; } .highlight .bp { color: #999999; } .highlight .nb { color: #0086B3; } .highlight .nc { color: #445588; font-weight: bold; } .highlight .no { color: #008080; } .highlight .nd { color: #3c5d5d; font-weight: bold; } .highlight .ni { color: #800080; } .highlight .ne { color: #990000; font-weight: bold; } .highlight .nf { color: #990000; font-weight: bold; } .highlight .nl { color: #990000; font-weight: bold; } .highlight .nn { color: #555555; } .highlight .nt { color: #000080; } .highlight .vc { color: #008080; } .highlight .vg { color: #008080; } .highlight .vi { color: #008080; } .highlight .nv { color: #008080; } .highlight .ow { color: #000000; font-weight: bold; } .highlight .o { color: #000000; font-weight: bold; } .highlight .w { color: #bbbbbb; } .highlight { background-color: #f8f8f8; }golang-gomega-1.36.2/docs/images/000077500000000000000000000000001476141007200165065ustar00rootroot00000000000000golang-gomega-1.36.2/docs/images/github.png000066400000000000000000000044321476141007200205010ustar00rootroot00000000000000PNG  IHDR@@iqtEXtSoftwareAdobe ImageReadyqe<$iTXtXML:com.adobe.xmp *NeCIDATxohUulY۪YmֵZz9!)ai0j %" "ϋ^+P ͡3ˢ5sV}s9wϋ<߿755"*$j}6P n2`\gG\^$SE, [% P^mஈ./s aff8>dQФlSgCnw@= PfIXGl ^/SI( l^ca 0| P` aQ>h+ 0x+QdhP!OG7@p,@{-iާ9G3~FQ)%mgKvC|?DZ~ ~OV1?7;yemb1 -1A]=`4lqߺV3t"@cg2N[cY rVm4" zBinu:'nUŶ*?ﵔF.t`B̫UI۟R$>a]Nd+y]ǃtz|rVv!G,[ |c*䱿}Gx? Y>uvN`ƭGK$;qkfAFn <8ٶ0!1xdipo;%!?±86WrDf^q8C81qڳ({0hï#.  #EN5!. 3*-\. oJiOfs}JvfN%YG5LGo]J: xMn#:ا TOZ&]/si}Ў!lhԡkW2 ~mU^vvOmz0}XYB_ -Bs_IENDB`golang-gomega-1.36.2/docs/images/go.png000066400000000000000000000124311476141007200176220ustar00rootroot00000000000000PNG  IHDRd!ZdrsRGBeXIfMM*V^(1fi|,,Pixelmator Pro 2.1.5Ϡd2021:10:14 11:28:55[ pHYs.#.#x?viTXtXML:com.adobe.xmp 207 100 3000000/10000 3000000/10000 1 2 Pixelmator Pro 2.1.5 2021-10-14T11:28:55-06:00 2021-10-14T11:31:18-06:00 ʸ,IDATx E{bKEiJ)[SQ-RCOVB[(AP{Ҋ% IŖDd|߼;3ウ7yܹs|+1p 8ǀc1p 8ǀc1p 8ǀc1p 8ǀc1@;Kz 455Fu*` X kn1G'eu*S{` >C߫%ςT 8BmM ,`!p\iR(Y%_.Za|ě$T:E8#2C?<f jNuYY ?2LVq i{$ev@qZ Ht1 y?jo" whߥ<4Nq(ʬWa8J?Z4; *c' f$DNI´ku[m]^&a_d_]HZԤ8΄2w5m6eM THى+-#w^-?i…KZh+sg-hf%)Yǀ^.j– @u h rw?<*)?G2GWi@ך&Z;L5+ )-hQ}Țǡ᫂tXNz %]^E[+<[gn]*!G+R<, l[ M7sx5?„8&E;,/o۲Gtڡj[M><]̱q qn`a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_b|t*#+Nkof^Xy bii)雈PqR/fi ZȣӺX䑜Z7SPs-5b;[@^d^Yr-r}M&pL32B&_ f'+Y9*=H nYk$vC,Ȣ©@^,VOlE!Ӕ1>dj̎?@d Nh\$+ P!`>HJbh8-+<w( >=|榪#K%ic p$t&ET0&?`Cя=;l>Fq< PNCј7]AWaE/g9 !>tΠ"M/~.>1胈3iash8FF+ZtgڲvJ8 ėǀc1p 8ǀc1p 8ǀc1p 8ǀc1p 8ǀc\  sIENDB`golang-gomega-1.36.2/docs/images/gomega.png000066400000000000000000001244161476141007200204630ustar00rootroot00000000000000PNG  IHDR ^TDsRGBeXIfMM*V^(1fi|HHPixelmator Pro 2.3.4 ^ pHYs  iTXtXML:com.adobe.xmp 350 1546 1 720000/10000 2 720000/10000 1 Pixelmator Pro 2.3.4 2022-01-17T14:21:54-07:00 5@IDATx]EM $BB@:$, " lEAEDD& {}߁6a+d߻w)yyeB @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ CQq 4 Aug#c}<&]_{?t.w.Η"}YyC @ @ 8EBSA0UQݤä[VZ+JΒNK_ @ @ P(H9c"0Tv##]_꣬VV4xDf @ @ P(H1b `[-_obSzR @ @@(Ď1GI*"ͳ}`poR'@ @ @@29Lz=lHw" @ @ / (ꃤWKm 3hgJI@ @ @++cQ<,=NN@ @ @!]|\@ 7v @ @ |A lkۤK@ @ @@j&OJm l5IR% @ @!※ S&`  @ @ CXyLJ[ @ @ @y$p~PJ_GK @ @ P91v)pܥ[K+!@ @ @ +ܤ8AbOjiO)@ @ @xc)riӁe @ @ @<%(? @ @ImW hZZH@ @ @@NKy$m:`|^s'M@ @ @%]LJQͽaE$ @ @$rbkrN @ @ @t`0k!^v" @ @ 1]9^sǯB @ @ k{+Җ9R^:=H @ @8vBiҾՙj}XiOR+.  @ @ (ⴁS>aA @ @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Нj0Z U;}ۋrt%!.F!aU1u}V*A<^\p.V:`!rc" nv>y%׫pjAD'˲`kK,d3,,˲ W5X:CBR$ȈrDֿAmY>OhCuR׍SS|TwhjQlg{N@aRh|C*zħ  *ک؁* ?ӻRKcgP?KyE INK{d $Y &cw؈␠ E'rDeK5Cd5ME\+q[isX .S$QZEDQquR;+Ymf-Wʧz먼Ot}oł#H;zwgB`MҪKkWg _.A /RΓJ_:Ӳ"Of(( x EzE6cAF']q@/VH}N2Wҽrˤj*̣DB Z#ysWvtˮ:?yR D䒑B@a`ΞC[f~!FFģQʶ4I|?Q`XCEF\g] q\?De3F93x)#zwdɈvEeEUYrlySg~/I2YFQC Wa-∾ 8ʋ]+aMB} sy>@-GH8<@Ψ=.S >$ =Eܡ^5iׇdA.>E]ܺG1ɇT$#r%˖Aș'4$"HwOszezȍ؋JĖ:LžY 5d(dFfmW ;⚛ֈ*.N[isg-4c%:&lSpO& (>B+w]Hx^]riܬUR*ْ"HqG m!OFX኿W'2IENDB`golang-gomega-1.36.2/docs/images/sponsor.png000066400000000000000000000052551476141007200207260ustar00rootroot00000000000000PNG  IHDR@@iqsRGBeXIfMM*V^(1fi|HHPixelmator Pro 2.1.5@@2021:10:14 11:22:28W pHYs  iTXtXML:com.adobe.xmp 2 720000/10000 1 720000/10000 64 64 Pixelmator Pro 2.1.5 2021-10-14T11:22:28-06:00 2021-10-14T11:31:52-06:00 s{IDATx[UycEeie&qLd'JQPDA*0,"aZD 3B-et~Q/v=kͷOf|.gk3dHG:tӁqjyk.=@A}q ցZ[fW`2Fa` Z* _gэK Da 讬/[AQxRBA !@Y"fTx)[ Rs:QV:@ކtpn{἖{[>ng(~(*^7v$G^wpKeWiǂU1I`&͡Mm!̄}f_h)pZAM3܈46vZ@5i bv ZEi@#E`M*ZA*O? ,"A,"}ʉiCv1.J; >oxdb2&5fs4,: `GomegaFailHandler` is defined in the `types` subpackage. ## Using Gomega with Golang's XUnit-style Tests Though Gomega is tailored to work best with Ginkgo it is easy to use Gomega with Golang's XUnit style tests. Here's how: To use Gomega with Golang's XUnit style tests: ```go func TestFarmHasCow(t *testing.T) { g := NewWithT(t) f := farm.New([]string{"Cow", "Horse"}) g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") } ``` `NewWithT(t)` wraps a `*testing.T` and returns a struct that supports `Expect`, `Eventually`, and `Consistently`. ## Making Assertions Gomega provides two notations for making assertions. These notations are functionally equivalent and their differences are purely aesthetic. - When you use the `Ω` notation, your assertions look like this: ```go Ω(ACTUAL).Should(Equal(EXPECTED)) Ω(ACTUAL).ShouldNot(Equal(EXPECTED)) ``` - When you use the `Expect` notation, your assertions look like this: ```go Expect(ACTUAL).To(Equal(EXPECTED)) Expect(ACTUAL).NotTo(Equal(EXPECTED)) Expect(ACTUAL).ToNot(Equal(EXPECTED)) ``` On OS X the `Ω` character should be easy to type, it is usually just option-z: `⌥z`. On the left hand side, you can pass anything you want in to `Ω` and `Expect` for `ACTUAL`. On the right hand side you must pass an object that satisfies the `GomegaMatcher` interface. Gomega's matchers (e.g. `Equal(EXPECTED)`) are simply functions that create and initialize an appropriate `GomegaMatcher` object. > Note that `Should` and `To` are just syntactic sugar and are functionally identical. Same is the case for `ToNot` and `NotTo`. > The `GomegaMatcher` interface is pretty simple and is discussed in the [custom matchers](#adding-your-own-matchers) section. It is defined in the `types` subpackage. ### Handling Errors It is a common pattern, in Golang, for functions and methods to return two things - a value and an error. For example: ```go func DoSomethingHard() (string, error) { ... } ``` To assert on the return value of such a method you might write a test that looks like this: ```go result, err := DoSomethingHard() Ω(err).ShouldNot(HaveOccurred()) Ω(result).Should(Equal("foo")) ``` Gomega streamlines this very common use case. Both `Ω` and `Expect` accept *multiple* arguments. The first argument is passed to the matcher, and the match only succeeds if *all* subsequent arguments are `nil` or zero-valued. With this, we can rewrite the above example as: ```go Ω(DoSomethingHard()).Should(Equal("foo")) ``` This will only pass if the return value of `DoSomethingHard()` is `("foo", nil)`. Additionally, if you call a function with a single `error` return value you can use the `Succeed` matcher to assert the function has returned without error. So for a function of the form: ```go func DoSomethingSimple() error { ... } ``` You can either write: ```go err := DoSomethingSimple() Ω(err).ShouldNot(HaveOccurred()) ``` Or you can write: ```go Ω(DoSomethingSimple()).Should(Succeed()) ``` > You should not use a function with multiple return values (like `DoSomethingHard`) with `Succeed`. Matchers are only passed the *first* value provided to `Ω`/`Expect`, the subsequent arguments are handled by `Ω` and `Expect` as outlined above. As a result of this behavior `Ω(DoSomethingHard()).ShouldNot(Succeed())` would never pass. Assertions about errors on functions with multiple return values can be made as follows (and in a lazy way when not asserting that all other return values are zero values): ```go _, _, _, err := MultipleReturnValuesFunc() Ω(err).Should(HaveOccurred()) ``` Alternatively, such error assertions on multi return value functions can be simplified by chaining `Error` to `Ω` and `Expect`. Doing so will additionally automatically assert that all return values, except for the trailing error return value, are in fact zero values: ```go Ω(MultipleReturnValuesFunc()).Error().Should(HaveOccurred()) ``` Similar, asserting that no error occurred is supported, too (where the other return values are allowed to take on any value): ```go Ω(MultipleReturnValuesFunc()).Error().ShouldNot(HaveOccurred()) ``` ### Annotating Assertions You can annotate any assertion by passing either a format string (and optional inputs to format) or a function of type `func() string` after the `GomegaMatcher`: ```go Ω(ACTUAL).Should(Equal(EXPECTED), "My annotation %d", foo) Ω(ACTUAL).ShouldNot(Equal(EXPECTED), "My annotation %d", foo) Expect(ACTUAL).To(Equal(EXPECTED), "My annotation %d", foo) Expect(ACTUAL).NotTo(Equal(EXPECTED), "My annotation %d", foo) Expect(ACTUAL).ToNot(Equal(EXPECTED), "My annotation %d", foo) Expect(ACTUAL).To(Equal(EXPECTED), func() string { return "My annotation" }) ``` If you pass a format string, the format string and inputs will be passed to `fmt.Sprintf(...)`. If you instead pass a function, the function will be lazily evaluated if the assertion fails. In both cases, if the assertion fails, Gomega will print your annotation alongside its standard failure message. This is useful in cases where the standard failure message lacks context. For example, if the following assertion fails: ```go Ω(SprocketsAreLeaky()).Should(BeFalse()) ``` Gomega will output: ``` Expected : true to be false ``` But this assertion: ```go Ω(SprocketsAreLeaky()).Should(BeFalse(), "Sprockets shouldn't leak") ``` Will offer the more helpful output: ``` Sprockets shouldn't leak Expected : true to be false ``` ### Adjusting Output When a failure occurs, Gomega prints out a recursive description of the objects involved in the failed assertion. This output can be very verbose, but Gomega's philosophy is to give as much output as possible to aid in identifying the root cause of a test failure. These recursive object renditions are performed by the `format` subpackage. Import the format subpackage in your test code: ```go import "github.com/onsi/gomega/format" ``` `format` provides some globally adjustable settings to tune Gomega's output: - `format.MaxLength = 4000`: Gomega will recursively traverse nested data structures as it produces output. If the length of this string representation is more than MaxLength, it will be truncated to MaxLength. To disable this behavior, set the MaxLength to `0`. - `format.MaxDepth = 10`: Gomega will recursively traverse nested data structures as it produces output. By default the maximum depth of this recursion is set to `10` you can adjust this to see deeper or shallower representations of objects. - Implementing `format.GomegaStringer`: If `GomegaStringer` interface is implemented on an object, Gomega will call `GomegaString` for an object's string representation. This is regardless of the `format.UseStringerRepresentation` value. Best practice to implement this interface is to implement it in a helper test file (e.g. `helper_test.go`) to avoid leaking it to your package's exported API. - `format.UseStringerRepresentation = false`: Gomega does *not* call `String` or `GoString` on objects that satisfy the `Stringer` and `GoStringer` interfaces. Oftentimes such representations, while more human readable, do not contain all the relevant information associated with an object thereby making it harder to understand why a test might be failing. If you'd rather see the output of `String` or `GoString` set this property to `true`. > For a tricky example of why `format.UseStringerRepresentation = false` is your friend, check out issue [#37](https://github.com/onsi/gomega/issues/37). - `format.PrintContextObjects = false`: Gomega by default will not print the content of objects satisfying the context.Context interface, due to too much output. If you want to enable displaying that content, set this property to `true`. If you want to use Gomega's recursive object description in your own code you can call into the `format` package directly: ```go fmt.Println(format.Object(theThingYouWantToPrint, 1)) ``` - `format.TruncatedDiff = true`: Gomega will truncate long strings and only show where they differ. You can set this to `false` if you want to see the full strings. You can also register your own custom formatter using `format.RegisterCustomFormatter(f)`. Custom formatters must be of type `type CustomFormatter func(value interface{}) (string, bool)`. Gomega will pass in any objects to be formatted to each registered custom formatter. A custom formatter signals that it will handle the passed-in object by returning a formatted string and `true`. If it does not handle the object it should return `"", false`. Strings returned by custom formatters will _not_ be truncated (though they may be truncated if the object being formatted is within another struct). Custom formatters take precedence of `GomegaStringer` and `format.UseStringerRepresentation`. `format.RegisterCustomFormatter` returns a key that can be used to unregister the custom formatter: ```go key := format.RegisterCustomFormatter(myFormatter) ... format.UnregisterCustomFormatter(key) ``` ## Making Asynchronous Assertions Gomega has support for making *asynchronous* assertions. There are two functions that provide this support: `Eventually` and `Consistently`. ### Eventually `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: ```go Eventually(ACTUAL, (TIMEOUT), (POLLING_INTERVAL), (context.Context)).Should(MATCHER) ``` 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 (e.g. "100ms") or `float64` (in which case they are interpreted as seconds). You can also provide a `context.Context` which - when cancelled - will instruct `Eventually` to stop and exit with a failure message. You are also allowed to pass in the `context.Context` _first_ as `Eventually(ctx, ACTUAL)`. > As with synchronous assertions, you can annotate asynchronous assertions by passing either a format string and optional inputs or a function of type `func() string` after the `GomegaMatcher`. Alternatively, the timeout and polling interval can also be specified by chaining `Within` and `ProbeEvery` or `WithTimeout` and `WithPolling` to `Eventually`: ```go Eventually(ACTUAL).WithTimeout(TIMEOUT).WithPolling(POLLING_INTERVAL).Should(MATCHER) Eventually(ACTUAL).Within(TIMEOUT).ProbeEvery(POLLING_INTERVAL).Should(MATCHER) ``` You can also configure the context in this way: ```go Eventually(ACTUAL).WithTimeout(TIMEOUT).WithPolling(POLLING_INTERVAL).WithContext(ctx).Should(MATCHER) ``` When no explicit timeout is provided, `Eventually` will use the default timeout. If both a context and a timeout are provided, `Eventually` will keep trying until either the context is cancelled or time runs out, whichever comes first. However if no explicit timeout is provided _and_ a context is provided, `Eventually` will not apply a timeout but will instead keep trying until the context is cancelled. This behavior is intentional in order to allow a single `context` to control the duration of a collection of `Eventually` assertions. To opt out of this behavior you can call the global `EnforceDefaultTimeoutsWhenUsingContexts()` configuration to force `Eventually` to apply a default timeout even when a context is provided. You can also ensure a number of consecutive pass before continuing with `MustPassRepeatedly`: ```go Eventually(ACTUAL).MustPassRepeatedly(NUMBER).Should(MATCHER) ``` Eventually works with any Gomega compatible matcher and supports making assertions against three categories of `ACTUAL` value: #### Category 1: Making `Eventually` assertions on values 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: ```go 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 successfully via: ```go 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: ```go Eventually(buffer).Should(gbytes.Say("hello there")) ``` In these examples, both `session` and `buffer` are designed to be thread-safe when polled by the `Exit` and `Say` matchers. This is not true in general of most raw values, so while it is tempting to do something like: ```go /* === INVALID === */ var s *string go mutateStringEventually(s) Eventually(s).Should(Equal("I've changed")) ``` this will trigger Go's race detector as the goroutine polling via Eventually will race over the value of `s` with the goroutine mutating the string. Similarly, something like `Eventually(slice).Should(HaveLen(N))` probably won't do what you think it should -- `Eventually` will be passed a pointer to the slice, yes, but if the slice is being `append`ed to (as in: `slice = append(slice, ...)`) Go will generate a new pointer and the pointer passed to `Eventually` will not contain the new elements. In both cases you should always pass `Eventually` a function that, when polled, returns the latest value of the object in question in a thread-safe way. #### Category 2: Making `Eventually` assertions on functions `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: ```go 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))` 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: ```go func FetchFromDB() (string, error) ``` Then ```go Eventually(FetchFromDB).Should(Equal("got it")) ``` will pass only if and when the returned error is `nil` *and* the returned string satisfies the matcher. Eventually can also accept functions that take arguments, however you must provide those arguments using `Eventually().WithArguments()`. For example, consider a function that takes a user-id and makes a network request to fetch a full name: ```go func FetchFullName(userId int) (string, error) ``` You can poll this function like so: ```go Eventually(FetchFullName).WithArguments(1138).Should(Equal("Wookie")) ``` `WithArguments()` supports multiple arguments as well as variadic arguments. 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. This is where using a `context.Context` can be helpful. Here is an example that leverages Gingko's support for interruptible nodes and spec timeouts: ```go It("fetches the correct count", func(ctx SpecContext) { Eventually(func() int { return client.FetchCount(ctx, "/users") }, ctx).Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) ``` now when the spec times out both the `client.FetchCount` function and `Eventually` will be signaled and told to exit. you can also use `Eventually().WithContext(ctx)` to provide the context. Since functions that take a context.Context as a first-argument are common in Go, `Eventually` supports automatically injecting the provided context into the function. This plays nicely with `WithArguments()` as well. You can rewrite the above example as: ```go It("fetches the correct count", func(ctx SpecContext) { Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) ``` now the `ctx` `SpecContext` is used both by `Eventually` and `client.FetchCount` and the `"/users"` argument is passed in after the `ctx` argument. The use of a context also allows you to specify a single timeout across a collection of `Eventually` assertions: ```go It("adds a few books and checks the count", func(ctx SpecContext) { intialCount := client.FetchCount(ctx, "/items") client.AddItem(ctx, "foo") client.AddItem(ctx, "bar") //note that there are several supported ways to pass in the context. All are equivalent: Eventually(ctx, client.FetchCount).WithArguments("/items").Should(BeNumerically("==", initialCount + 2)) Eventually(client.FetchItems).WithContext(ctx).Should(ContainElement("foo")) Eventually(client.FetchItems, ctx).Should(ContainElement("foo")) }, SpecTimeout(time.Second * 5)) ``` In addition, Gingko's `SpecContext` allows Gomega to tell Ginkgo about the status of a currently running `Eventually` whenever a Progress Report is generated. So, if a spec times out while running an `Eventually` Ginkgo will not only show you which `Eventually` was running when the timeout occurred, but will also include the failure the `Eventually` was hitting when the timeout occurred. #### 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 assertions and returns a value and error: ```go Eventually(func(g Gomega) (Widget, error) { ids, err := client.FetchIDs() g.Expect(err).NotTo(HaveOccurred()) g.Expect(ids).To(ContainElement(1138)) return client.FetchWidget(1138) }).Should(Equal(expectedWidget)) ``` will pass only if all the assertions in the polled function pass and the return value satisfied the matcher. Note that the assertions in the body of the polled function must be performed using the passed-in `g Gomega` object. If you use the global DSL expectations, `Eventually` will not intercept any failures and the test will fail. `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: ```go 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 arguments 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: ```go 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()) ``` ### Consistently `Consistently` checks that an assertion passes for a period of time. It does this by polling its argument repeatedly during the period. It fails if the matcher ever fails during that period. For example: ```go Consistently(func() []int { return thing.MemoryUsage() }).Should(BeNumerically("<", 10)) ``` `Consistently` will poll the passed in function repeatedly and check the return value against the `GomegaMatcher`. `Consistently` blocks and only returns when the desired duration has elapsed or if the matcher fails or if an (optional) passed-in context is cancelled. The default value for the wait-duration is 100 milliseconds. The default polling interval is 10 milliseconds. Like `Eventually`, you can change these values by passing them in just after your function: ```go Consistently(ACTUAL, (DURATION), (POLLING_INTERVAL), (context.Context)).Should(MATCHER) ``` As with `Eventually`, the duration parameters can be `time.Duration`s, string representations of a `time.Duration` (e.g. `"200ms"`) or `float64`s that are interpreted as seconds. Also as with `Eventually`, `Consistently` supports chaining `WithTimeout`, `WithPolling`, `WithContext` and `WithArguments` in the form of: ```go Consistently(ACTUAL).WithTimeout(DURATION).WithPolling(POLLING_INTERVAL).WithContext(ctx).WithArguments(...).Should(MATCHER) ``` `Consistently` tries to capture the notion that something "does not eventually" happen. A common use-case is to assert that no goroutine writes to a channel for a period of time. If you pass `Consistently` an argument that is not a function, it simply passes that argument to the matcher. So we can assert that: ```go Consistently(channel).ShouldNot(Receive()) ``` To assert that nothing gets sent to a channel. As with `Eventually`, you can also pass `Consistently` a function. In fact, `Consistently` works with the three categories of `ACTUAL` value outlined for `Eventually` in the section above. If `Consistently` is passed a `context.Context` it will exit if the context is cancelled - however it will always register the cancellation of the context as a failure. That is, the context is not used to control the duration of `Consistently` - that is always done by the `DURATION` parameter; instead, the context is used to allow `Consistently` to bail out early if it's time for the spec to finish up (e.g. a timeout has elapsed, or the user has sent an interrupt signal). When no explicit duration is provided, `Consistently` will use the default duration. Unlike `Eventually`, this behavior holds whether or not a context is provided. > Developers often try to use `runtime.Gosched()` to nudge background goroutines to run. This can lead to flaky tests as it is not deterministic that a given goroutine will run during the `Gosched`. `Consistently` is particularly handy in these cases: it polls for 100ms which is typically more than enough time for all your Goroutines to run. Yes, this is basically like putting a time.Sleep() in your tests... Sometimes, when making negative assertions in a concurrent world, that's the best you can do! ### Bailing Out Early - Polling Functions There are cases where you need to signal to `Eventually` and `Consistently` that they should stop trying. Gomega provides`StopTrying(message string)` to allow you to send that signal. There are two ways to use `StopTrying`. First, you can return `StopTrying` as an error. Consider, for example, the case where `Eventually` is searching through a set of possible queries with a server: ```go 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")) ``` Here we return a `StopTrying` error to tell `Eventually` that we've looked through all possible players and that it should stop. You can also call `StopTrying(...).Now()` to immediately end execution of the function. Consider, for example, the case of a client communicating with a server that experiences an irrevocable error: ```go Eventually(func() []string { names, err := client.FetchAllPlayers() if err == client.IRRECOVERABLE_ERROR { StopTrying("An irrecoverable error occurred").Now() } return names }).Should(ContainElement("Patrick Mahomes")) ``` calling `.Now()` will trigger a panic that will signal to `Eventually` that it should stop trying. You can also return `StopTrying()` errors and use `StopTrying().Now()` with `Consistently`. By default, both `Eventually` and `Consistently` treat the `StopTrying()` signal as a failure. The failure message will include the message passed in to `StopTrying()`. However, there are cases when you might want to short-circuit `Consistently` early without failing the test (e.g. you are using consistently to monitor the sideeffect of a goroutine and that goroutine has now ended. Once it ends there is no need to continue polling `Consistently`). In this case you can use `StopTrying(message).Successfully()` to signal that `Consistently` can end early without failing. For example: ``` Consistently(func() bool { select{ case err := <-done: //the process has ended if err != nil { return StopTrying("error occurred").Now() } StopTrying("success!).Successfully().Now() default: return GetCounts() } }).Should(BeNumerically("<", 10)) ``` Note that `StopTrying(message).Successfully()` is not intended for use with `Eventually`. `Eventually` *always* interprets `StopTrying` as a failure. You can add additional information to this failure message in a few ways. You can wrap an error via `StopTrying(message).Wrap(wrappedErr)` - now the output will read `: `. You can also attach arbitrary objects to `StopTrying()` via `StopTrying(message).Attach(description string, object any)`. Gomega will run the object through Gomega's standard formatting library to build a consistent representation for end users. You can attach multiple objects in this way and the output will look like: ``` Told to stop trying after : : : ``` ### Bailing Out Early - Matchers Just like functions being polled, matchers can also indicate if `Eventually`/`Consistently` should stop polling. Matchers implement a `Match` method with the following signature: ```go Match(actual interface{}) (success bool, err error) ``` If a matcher returns `StopTrying` for `error`, or calls `StopTrying(...).Now()`, `Eventually` and `Consistently` will stop polling and fail: `StopTrying` **always** signifies a failure. > Note: An alternative mechanism for having matchers bail out early is documented in the [custom matchers section below](#aborting-eventuallyconsistently). This mechanism, which entails implementing a `MatchMayChangeIntheFuture() bool` method, allows matchers to signify that no future change is possible out-of-band of the call to the matcher. ### Changing the Polling Interval Dynamically You typically configure the polling interval for `Eventually` and `Consistently` using the `.WithPolling()` or `.ProbeEvery()` chaining methods. Sometimes, however, a polled function or matcher might want to signal that a service is unavailable but should be tried again after a certain duration. You can signal this to both `Eventually` and `Consistently` using `TryAgainAfter()`. This error-signal operates like `StopTrying()`: you can return `TryAgainAfter()` as an error or throw a panic via `TryAgainAfter().Now()`. In either case, both `Eventually` and `Consistently` will wait for the specified duration before trying again. If a timeout occurs after the `TryAgainAfter` signal is sent but _before_ the next poll occurs both `Eventually` _and_ `Consistently` will always fail and print out the content of `TryAgainAfter`. The default message is `"told to try again after "` however, as with `StopTrying` you can use `.Wrap()` and `.Attach()` to wrap an error and attach additional objects to include in the message, respectively. ### Modifying Default Intervals By default, `Eventually` will poll every 10 milliseconds for up to 1 second and `Consistently` will monitor every 10 milliseconds for up to 100 milliseconds. You can modify these defaults across your test suite with: ```go SetDefaultEventuallyTimeout(t time.Duration) SetDefaultEventuallyPollingInterval(t time.Duration) SetDefaultConsistentlyDuration(t time.Duration) SetDefaultConsistentlyPollingInterval(t time.Duration) ``` You can also adjust these global timeouts by setting the `GOMEGA_DEFAULT_EVENTUALLY_TIMEOUT`, `GOMEGA_DEFAULT_EVENTUALLY_POLLING_INTERVAL`, `GOMEGA_DEFAULT_CONSISTENTLY_DURATION`, and `GOMEGA_DEFAULT_CONSISTENTLY_POLLING_INTERVAL` environment variables to a parseable duration string. The environment variables have a lower precedence than `SetDefault...()`. As discussed [above](#category-2-making-eventually-assertions-on-functions) `Eventually`s that are passed a `context` object without an explicit timeout will only stop polling when the context is cancelled. If you would like to enforce the default timeout when a context is provided you can call `EnforceDefaultTimeoutsWhenUsingContexts()` (to go back to the default behavior call `DisableDefaultTimeoutsWhenUsingContexts()`). You can also set the `GOMEGA_ENFORCE_DEFAULT_TIMEOUTS_WHEN_USING_CONTEXTS` environment variable to enforce the default timeout when a context is provided. ## Making Assertions in Helper Functions While writing [custom matchers](#adding-your-own-matchers) is an expressive way to make assertions against your code, it is often more convenient to write one-off helper functions like so: ```go var _ = Describe("Turbo-encabulator", func() { ... func assertTurboEncabulatorContains(components ...string) { teComponents, err := turboEncabulator.GetComponents() Expect(err).NotTo(HaveOccurred()) Expect(teComponents).To(HaveLen(components)) for _, component := range components { Expect(teComponents).To(ContainElement(component)) } } It("should have components", func() { assertTurboEncabulatorContains("semi-boloid slots", "grammeters") }) }) ``` This makes your tests more expressive and reduces boilerplate. However, when an assertion in the helper fails the line numbers provided by Gomega are unhelpful. Instead of pointing you to the line in your test that failed, they point you the line in the helper. To fix this, Ginkgo and Gomega provide two options. If you are on a recent version of Ginkgo you can register your helper with Ginkgo via `GinkgoHelper()`: ```go func assertTurboEncabulatorContains(components ...string) { GinkgoHelper() teComponents, err := turboEncabulator.GetComponents() Expect(err).NotTo(HaveOccurred()) Expect(teComponents).To(HaveLen(components)) for _, component := range components { Expect(teComponents).To(ContainElement(component)) } } ``` now, line numbers generated by Ginkgo will skip `assertTurboEncabulatorContains` and point to the calling site instead. `GinkgoHelper()` is the recommended way to solve this problem as it allows for straightforward nesting and reuse of helper functions. If, for some reason, you can't use `GinkgoHelper()` Gomega does provide an alternative: versions of `Expect`, `Eventually` and `Consistently` named `ExpectWithOffset`, `EventuallyWithOffset` and `ConsistentlyWithOffset` that allow you to specify an *offset* in the call stack. The offset is the first argument to these functions. With this, we can rewrite our helper as: ```go func assertTurboEncabulatorContains(components ...string) { teComponents, err := turboEncabulator.GetComponents() ExpectWithOffset(1, err).NotTo(HaveOccurred()) ExpectWithOffset(1, teComponents).To(HaveLen(components)) for _, component := range components { ExpectWithOffset(1, teComponents).To(ContainElement(component)) } } ``` Now, failed assertions will point to the correct call to the helper in the test. Alternatively, you can just use the baseline versions of `Expect`, `Eventually` and `Consistently` and combine them with `WithOffset`: ```go func assertTurboEncabulatorContains(components ...string) { teComponents, err := turboEncabulator.GetComponents() Expect(err).WithOffset(1).NotTo(HaveOccurred()) Expect(teComponents).WithOffset(1).To(HaveLen(components)) for _, component := range components { Expect(teComponents).WithOffset(1).To(ContainElement(component)) } } ``` Again, we recommend using `GinkgoHelper()` instead of `WithOffset(...)`. ## Provided Matchers Gomega comes with a bunch of `GomegaMatcher`s. They're all documented here. If there's one you'd like to see written either [send a pull request or open an issue](http://github.com/onsi/gomega). A number of community-supported matchers have appeared as well. A list is maintained on the Gomega [wiki](https://github.com/onsi/gomega/wiki). These docs only go over the positive assertion case (`Should`), the negative case (`ShouldNot`) is simply the negation of the positive case. They also use the `Ω` notation, but - as mentioned above - the `Expect` notation is equivalent. When using Go toolchain of version 1.23 or later, certain matchers as documented below become iterator-aware, handling iterator functions with `iter.Seq` and `iter.Seq2`-like signatures as collections in the same way as array/slice/map. ### Asserting Equivalence #### Equal(expected interface{}) ```go Ω(ACTUAL).Should(Equal(EXPECTED)) ``` uses [`reflect.DeepEqual`](http://golang.org/pkg/reflect#deepequal) to compare `ACTUAL` with `EXPECTED`. `reflect.DeepEqual` is awesome. It will use `==` when appropriate (e.g. when comparing primitives) but will recursively dig into maps, slices, arrays, and even your own structs to ensure deep equality. `reflect.DeepEqual`, however, is strict about comparing types. Both `ACTUAL` and `EXPECTED` *must* have the same type. If you want to compare across different types (e.g. if you've defined a type alias) you should use `BeEquivalentTo`. It is an error for both `ACTUAL` and `EXPECTED` to be nil, you should use `BeNil()` instead. When both `ACTUAL` and `EXPECTED` are a very long strings, it will attempt to pretty-print the diff and display exactly where they differ. > For asserting equality between numbers of different types, you'll want to use the [`BeNumerically()`](#benumericallycomparator-string-compareto-interface) matcher. #### BeComparableTo(expected interface{}, options ...cmp.Option) ```go Ω(ACTUAL).Should(BeComparableTo(EXPECTED, options ...cmp.Option)) ``` uses [`gocmp.Equal`](http://github.com/google/go-cmp) from `github.com/google/go-cmp` to compare `ACTUAL` with `EXPECTED`. This performs a deep object comparison like `reflect.DeepEqual` but offers a few additional configuration options. Learn more at the [go-cmp godocs](https://pkg.go.dev/github.com/google/go-cmp). #### BeEquivalentTo(expected interface{}) ```go Ω(ACTUAL).Should(BeEquivalentTo(EXPECTED)) ``` Like `Equal`, `BeEquivalentTo` uses `reflect.DeepEqual` to compare `ACTUAL` with `EXPECTED`. Unlike `Equal`, however, `BeEquivalentTo` will first convert `ACTUAL`'s type to that of `EXPECTED` before making the comparison with `reflect.DeepEqual`. This means that `BeEquivalentTo` will successfully match equivalent values of different types. This is particularly useful, for example, with type aliases: ```go type FoodSrce string Ω(FoodSrce("Cheeseboard Pizza") ).Should(Equal("Cheeseboard Pizza")) //will fail Ω(FoodSrce("Cheeseboard Pizza") ).Should(BeEquivalentTo("Cheeseboard Pizza")) //will pass ``` As with `Equal` it is an error for both `ACTUAL` and `EXPECTED` to be nil, you should use `BeNil()` instead. As a rule, you **should not** use `BeEquivalentTo` with numbers. Both of the following assertions are true: ```go Ω(5.1).Should(BeEquivalentTo(5)) Ω(5).ShouldNot(BeEquivalentTo(5.1)) ``` the first assertion passes because 5.1 will be cast to an integer and will get rounded down! Such false positives are terrible and should be avoided. Use [`BeNumerically()`](#benumericallycomparator-string-compareto-interface) to compare numbers instead. #### BeIdenticalTo(expected interface{}) ```go Ω(ACTUAL).Should(BeIdenticalTo(EXPECTED)) ``` Like `Equal`, `BeIdenticalTo` compares `ACTUAL` to `EXPECTED` for equality. Unlike `Equal`, however, it uses `==` to compare values. In practice, this means that primitive values like strings, integers and floats are identical to, as well as pointers to values. `BeIdenticalTo` is most useful when you want to assert that two pointers point to the exact same location in memory. As with `Equal` it is an error for both `ACTUAL` and `EXPECTED` to be nil, you should use `BeNil()` instead. #### BeAssignableToTypeOf(expected interface) ```go Ω(ACTUAL).Should(BeAssignableToTypeOf(EXPECTED interface)) ``` succeeds if `ACTUAL` is a type that can be assigned to a variable with the same type as `EXPECTED`. It is an error for either `ACTUAL` or `EXPECTED` to be `nil`. ### Asserting Presence #### BeNil() ```go Ω(ACTUAL).Should(BeNil()) ``` succeeds if `ACTUAL` is, in fact, `nil`. #### BeZero() ```go Ω(ACTUAL).Should(BeZero()) ``` succeeds if `ACTUAL` is the zero value for its type *or* if `ACTUAL` is `nil`. ### Asserting Truthiness #### BeTrue() ```go Ω(ACTUAL).Should(BeTrue()) ``` succeeds if `ACTUAL` is `bool` typed and has the value `true`. It is an error for `ACTUAL` to not be a `bool`. Since Gomega has no additional context about your assertion the failure messages are generally not particularly helpful. So it's generally recommended that you use `BeTrueBecause` instead. > Some matcher libraries have a notion of "truthiness" to assert that an object is present. Gomega is strict, and `BeTrue()` only works with `bool`s. You can use `Ω(ACTUAL).ShouldNot(BeZero())` or `Ω(ACTUAL).ShouldNot(BeNil())` to verify object presence. ### BeTrueBecause(reason) ```go Ω(ACTUAL).Should(BeTrueBecause(REASON, ARGS...)) ``` is just like `BeTrue()` but allows you to pass in a reason. This is a best practice as the default failure message is not particularly helpful. `fmt.Sprintf(REASON, ARGS...)` is used to render the reason. For example: ```go Ω(cow.JumpedOver(moon)).Should(BeTrueBecause("the cow should have jumped over the moon")) ``` #### BeFalse() ```go Ω(ACTUAL).Should(BeFalse()) ``` succeeds if `ACTUAL` is `bool` typed and has the value `false`. It is an error for `ACTUAL` to not be a `bool`. You should generally use `BeFalseBecause` instead to pas in a reason for a more helpful error message. ### BeFalseBecause(reason) ```go Ω(ACTUAL).Should(BeFalseBecause(REASON, ARGS...)) ``` is just like `BeFalse()` but allows you to pass in a reason. This is a best practice as the default failure message is not particularly helpful. `fmt.Sprintf(REASON, ARGS...)` is used to render the reason. ```go Ω(cow.JumpedOver(mars)).Should(BeFalseBecause("the cow should not have jumped over mars")) ``` ### Asserting on Errors #### HaveOccurred() ```go Ω(ACTUAL).Should(HaveOccurred()) ``` succeeds if `ACTUAL` is a non-nil `error`. Thus, the typical Go error checking pattern looks like: ```go err := SomethingThatMightFail() Ω(err).ShouldNot(HaveOccurred()) ``` #### Succeed() ```go Ω(ACTUAL).Should(Succeed()) ``` succeeds if `ACTUAL` is `nil`. The intended usage is ```go Ω(FUNCTION()).Should(Succeed()) ``` where `FUNCTION()` is a function call that returns an error-type as its *first or only* return value. See [Handling Errors](#handling-errors) for a more detailed discussion. #### MatchError(expected interface{}) ```go Ω(ACTUAL).Should(MatchError(EXPECTED, )) ``` succeeds if `ACTUAL` is a non-nil `error` that matches `EXPECTED`. `EXPECTED` must be one of the following: - A string, in which case the matcher asserts that `ACTUAL.Error() == EXPECTED` - An error (i.e. anything satisfying Go's `error` interface). In which case the matcher: - First checks if `errors.Is(ACTUAL, EXPECTED)` returns `true` - If not, it checks if `ACTUAL` or any of the errors it wraps (directly or indirectly) equals `EXPECTED` via `reflect.DeepEqual()`. - A matcher, in which case `ACTUAL.Error()` is tested against the matcher, for example `Expect(err).Should(MatchError(ContainSubstring("sprocket not found")))` will pass if `err.Error()` has the substring "sprocke tnot found" - A function with signature `func(error) bool`. The matcher then passes if `f(ACTUAL)` returns `true`. If using a function in this way you are required to pass a `FUNCTION_ERROR_DESCRIPTION` argument to `MatchError` that describes the function. This description is used in the failure message. For example: `Expect(err).To(MatchError(os.IsNotExist, "IsNotExist))` Any other type for `EXPECTED` is an error. It is also an error for `ACTUAL` to be nil. Note that `FUNCTION_ERROR_DESCRIPTION` is a description of the error function, if used. This is required when passing a function but is ignored in all other cases. ### Working with Channels #### BeClosed() ```go Ω(ACTUAL).Should(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. 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. #### Receive() ```go Ω(ACTUAL).Should(Receive(, )) ``` succeeds if there is a message 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*. It *never* blocks: - If there is nothing on the channel `c` then `Ω(c).Should(Receive())` will fail and `Ω(c).ShouldNot(Receive())` will pass. - If there is something on the channel `c` ready to be read, then `Ω(c).Should(Receive())` will pass and `Ω(c).ShouldNot(Receive())` will fail. - If the channel `c` is closed then `Ω(c).Should(Receive())` will fail and `Ω(c).ShouldNot(Receive())` will pass. If you have a go-routine running in the background that will write to channel `c`, for example: ```go go func() { time.Sleep(100 * time.Millisecond) c <- true }() ``` you can assert that `c` receives something (anything!) eventually: ```go Eventually(c).Should(Receive()) ``` This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`). 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`: ```go Consistently(c).ShouldNot(Receive()) ``` `Receive` also allows you to make assertions on the received object. You do this by passing `Receive` a matcher: ```go Eventually(c).Should(Receive(Equal("foo"))) ``` This assertion will only succeed if `c` receives an object *and* that object satisfies `Equal("foo")`. Note that `Eventually` will continually poll `c` until this condition is met. If there are objects coming down the channel that do not satisfy the passed in matcher, they will be pulled off and discarded until an object that *does* satisfy the matcher is received. In addition, there are occasions when you need to grab the object sent down the channel (e.g. to make several assertions against the object). To do this, you can ask the `Receive` matcher for the value passed to the channel by passing it a pointer to a variable of the appropriate type: ```go var receivedBagel Bagel Eventually(bagelChan).Should(Receive(&receivedBagel)) Ω(receivedBagel.Contents()).Should(ContainElement("cream cheese")) Ω(receivedBagel.Kind()).Should(Equal("sesame")) ``` Of course, this could have been written as `receivedBagel := <-bagelChan` - however using `Receive` makes it easy to avoid hanging the test suite should nothing ever come down the channel. The pointer can point to any variable whose type is assignable from the channel element type, or if the channel type is an interface and the underlying type is assignable to the pointer. Sometimes, you might need to *grab* the object that *matches* certain criteria: ```go var receivedBagel Bagel Eventually(bagelChan).Should(Receive(&receivedBagel, HaveField("Kind", "sesame"))) Ω(receivedBagel.Contents()).Should(ContainElement("cream cheese")) ``` Finally, `Receive` *never* blocks. `Eventually(c).Should(Receive())` repeatedly polls `c` in a non-blocking fashion. That means that you cannot use this pattern to verify that a *non-blocking send* has occurred on the channel - [more details at this GitHub issue](https://github.com/onsi/gomega/issues/82). #### BeSent(value interface{}) ```go Ω(ACTUAL).Should(BeSent(VALUE)) ``` attempts to send `VALUE` to the channel `ACTUAL` without blocking. It succeeds if this is possible. `ACTUAL` must be a channel (and cannot be a receive-only channel) that can be sent the type of the `VALUE` passed into `BeSent` -- anything else is an error. In addition, `ACTUAL` must not be closed. `BeSent` never blocks: - If the channel `c` is not ready to receive then `Ω(c).Should(BeSent("foo"))` will fail immediately. - If the channel `c` is eventually ready to receive then `Eventually(c).Should(BeSent("foo"))` will succeed... presuming the channel becomes ready to receive before `Eventually`'s timeout. - If the channel `c` is closed then `Ω(c).Should(BeSent("foo"))` and `Ω(c).ShouldNot(BeSent("foo"))` will both fail immediately. Of course, `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. ### Working with files #### BeAnExistingFile ```go Ω(ACTUAL).Should(BeAnExistingFile()) ``` succeeds if a file located at `ACTUAL` exists. `ACTUAL` must be a string representing the filepath. #### BeARegularFile ```go Ω(ACTUAL).Should(BeARegularFile()) ``` succeeds IFF a file located at `ACTUAL` exists and is a regular file. `ACTUAL` must be a string representing the filepath. #### BeADirectory ```go Ω(ACTUAL).Should(BeADirectory()) ``` succeeds IFF a file is located at `ACTUAL` exists and is a directory. `ACTUAL` must be a string representing the filepath. ### Working with Strings, JSON and YAML #### ContainSubstring(substr string, args ...interface{}) ```go Ω(ACTUAL).Should(ContainSubstring(STRING, ARGS...)) ``` succeeds if `ACTUAL` contains the substring generated by: ```go fmt.Sprintf(STRING, ARGS...) ``` `ACTUAL` must either be a `string`, `[]byte` or a `Stringer` (a type implementing the `String()` method). Any other input is an error. > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. #### HavePrefix(prefix string, args ...interface{}) ```go Ω(ACTUAL).Should(HavePrefix(STRING, ARGS...)) ``` succeeds if `ACTUAL` has the string prefix generated by: ```go fmt.Sprintf(STRING, ARGS...) ``` `ACTUAL` must either be a `string`, `[]byte` or a `Stringer` (a type implementing the `String()` method). Any other input is an error. > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. #### HaveSuffix(suffix string, args ...interface{}) ```go Ω(ACTUAL).Should(HaveSuffix(STRING, ARGS...)) ``` succeeds if `ACTUAL` has the string suffix generated by: ```go fmt.Sprintf(STRING, ARGS...) ``` `ACTUAL` must either be a `string`, `[]byte` or a `Stringer` (a type implementing the `String()` method). Any other input is an error. > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. #### MatchRegexp(regexp string, args ...interface{}) ```go Ω(ACTUAL).Should(MatchRegexp(STRING, ARGS...)) ``` succeeds if `ACTUAL` is matched by the regular expression string generated by: ```go fmt.Sprintf(STRING, ARGS...) ``` `ACTUAL` must either be a `string`, `[]byte` or a `Stringer` (a type implementing the `String()` method). Any other input is an error. It is also an error for the regular expression to fail to compile. > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. #### MatchJSON(json interface{}) ```go Ω(ACTUAL).Should(MatchJSON(EXPECTED)) ``` Both `ACTUAL` and `EXPECTED` must be a `string`, `[]byte` or a `Stringer`. `MatchJSON` succeeds if both `ACTUAL` and `EXPECTED` are JSON representations of the same object. This is verified by parsing both `ACTUAL` and `EXPECTED` and then asserting equality on the resulting objects with `reflect.DeepEqual`. By doing this `MatchJSON` avoids any issues related to white space, formatting, and key-ordering. It is an error for either `ACTUAL` or `EXPECTED` to be invalid JSON. In some cases it is useful to match two JSON strings while ignoring list order. For this you can use the community maintained [MatchUnorderedJSON](https://github.com/Benjamintf1/Expanded-Unmarshalled-Matchers) matcher. #### MatchXML(xml interface{}) ```go Ω(ACTUAL).Should(MatchXML(EXPECTED)) ``` Both `ACTUAL` and `EXPECTED` must be a `string`, `[]byte` or a `Stringer`. `MatchXML` succeeds if both `ACTUAL` and `EXPECTED` are XML representations of the same object. This is verified by parsing both `ACTUAL` and `EXPECTED` and then asserting equality on the resulting objects with `reflect.DeepEqual`. By doing this `MatchXML` avoids any issues related to white space or formatting. It is an error for either `ACTUAL` or `EXPECTED` to be invalid XML. #### MatchYAML(yaml interface{}) ```go Ω(ACTUAL).Should(MatchYAML(EXPECTED)) ``` Both `ACTUAL` and `EXPECTED` must be a `string`, `[]byte` or a `Stringer`. `MatchYAML` succeeds if both `ACTUAL` and `EXPECTED` are YAML representations of the same object. This is verified by parsing both `ACTUAL` and `EXPECTED` and then asserting equality on the resulting objects with `reflect.DeepEqual`. By doing this `MatchYAML` avoids any issues related to white space, formatting, and key-ordering. It is an error for either `ACTUAL` or `EXPECTED` to be invalid YAML. ### Working with Collections #### BeEmpty() ```go Ω(ACTUAL).Should(BeEmpty()) ``` succeeds if `ACTUAL` is, in fact, empty. `ACTUAL` must be of type `string`, `array`, `map`, `chan`, or `slice`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. It is an error for `ACTUAL` to have any other type. #### HaveLen(count int) ```go Ω(ACTUAL).Should(HaveLen(INT)) ``` succeeds if the length of `ACTUAL` is `INT`. `ACTUAL` must be of type `string`, `array`, `map`, `chan`, or `slice`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. It is an error for `ACTUAL` to have any other type. #### HaveCap(count int) ```go Ω(ACTUAL).Should(HaveCap(INT)) ``` succeeds if the capacity of `ACTUAL` is `INT`. `ACTUAL` must be of type `array`, `chan`, or `slice`. It is an error for it to have any other type. #### ContainElement(element interface{}) ```go Ω(ACTUAL).Should(ContainElement(ELEMENT)) ``` or ```go Ω(ACTUAL).Should(ContainElement(ELEMENT, )) ``` succeeds if `ACTUAL` contains an element that equals `ELEMENT`. `ACTUAL` must be an `array`, `slice`, or `map`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. It is an error for it to have any other type. For `map`s `ContainElement` searches through the map's values and not the keys. Similarly, for an iterator assignable to `iter.Seq2` `ContainElement` searches through the `v` elements of the produced (_, `v`) pairs. By default `ContainElement()` uses the `Equal()` matcher under the hood to assert equality between `ACTUAL`'s elements and `ELEMENT`. You can change this, however, by passing `ContainElement` a `GomegaMatcher`. For example, to check that a slice of strings has an element that matches a substring: ```go Ω([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) ``` In addition, there are occasions when you need to grab (all) matching contained elements, for instance, to make several assertions against the matching contained elements. To do this, you can ask the `ContainElement()` matcher for the matching contained elements by passing it a pointer to a variable of the appropriate type. If multiple matching contained elements are expected, then a pointer to either a slice or a map should be passed (but not a pointer to an array), otherwise a pointer to a scalar (non-slice, non-map): ```go var findings []string Ω([]string{"foo", "foobar", "bar"}).Should(ContainElement(ContainSubstring("foo"), &findings)) var finding string Ω([]string{"foo", "foobar", "bar"}).Should(ContainElement("foobar", &finding)) ``` The `ContainElement` matcher will fail with a descriptive error message in case of multiple matches when the pointer references a scalar type. In case of maps, the matching contained elements will be returned with their keys in the map referenced by the pointer. ```go var findings map[int]string Ω(map[int]string{ 1: "bar", 2: "foobar", 3: "foo", }).Should(ContainElement(ContainSubstring("foo"), &findings)) ``` In case of `iter.Seq` and `iter.Seq2`-like iterators, the matching contained elements can be returned in the slice referenced by the pointer. ```go it := func(yield func(string) bool) { for _, element := range []string{"foo", "bar", "baz"} { if !yield(element) { return } } } var findings []string Ω(it).Should(ContainElement(HasPrefix("ba"), &findings)) ``` Only in case of `iter.Seq2`-like iterators, the matching contained pairs can also be returned in the map referenced by the pointer. A (k, v) pair matches when it's "v" value matches. ```go it := func(yield func(int, string) bool) { for key, element := range []string{"foo", "bar", "baz"} { if !yield(key, element) { return } } } var findings map[int]string Ω(it).Should(ContainElement(HasPrefix("ba"), &findings)) ``` #### ContainElements(element ...interface{}) ```go Ω(ACTUAL).Should(ContainElements(ELEMENT1, ELEMENT2, ELEMENT3, ...)) ``` or ```go Ω(ACTUAL).Should(ContainElements([]SOME_TYPE{ELEMENT1, ELEMENT2, ELEMENT3, ...})) ``` succeeds if `ACTUAL` contains the elements passed into the matcher. 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: ```go Ω([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar")) Ω([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo")) ``` Actual must be an `array`, `slice` or `map`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. For maps, `ContainElements` matches against the `map`'s values. Similarly, for an iterator assignable to `iter.Seq2` `ContainElements` searches through the `v` elements of the produced (_, `v`) pairs. You typically pass variadic arguments to `ContainElements` (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 `ContainElements`: ```go Ω([]string{"Foo", "FooBar"}).Should(ContainElements([]string{"FooBar", "Foo"})) ``` Note that Go's type system does not allow you to write this as `ContainElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]interface{}` are different types - hence the need for this special rule. Starting with Go 1.23, you can also pass in an iterator assignable to `iter.Seq` (but not `iter.Seq2`) as the only element to `ConsistOf`. The difference between the `ContainElements` and `ConsistOf` matchers is that the latter is more restrictive because the `ConsistOf` matcher checks additionally that the `ACTUAL` elements and the elements passed into the matcher have the same length. #### BeElementOf(elements ...interface{}) ```go Ω(ACTUAL).Should(BeElementOf(ELEMENT1, ELEMENT2, ELEMENT3, ...)) ``` succeeds if `ACTUAL` equals one of the elements passed into the matcher. When a single element `ELEMENT` of type `array` or `slice` is passed into the matcher, `BeElementOf` succeeds if `ELEMENT` contains an element that equals `ACTUAL` (reverse of `ContainElement`). `BeElementOf` always uses the `Equal()` matcher under the hood to assert equality. #### BeKeyOf(m interface{}) ```go Ω(ACTUAL).Should(BeKeyOf(MAP)) ``` succeeds if `ACTUAL` equals one of the keys of `MAP`. It is an error for `MAP` to be of any type other than a map. `BeKeyOf` always uses the `Equal()` matcher under the hood to assert equality of `ACTUAL` with a map key. `BeKeyOf` can be used in situations where it is not possible to rewrite an assertion to use the more idiomatic `HaveKey`: one use is in combination with `ContainElement` doubling as a filter. For instance, the following example asserts that all expected specific sprockets are present in a larger list of sprockets: ```go var names = map[string]struct { detail string }{ "edgy_emil": {detail: "sprocket_project_A"}, "furious_freddy": {detail: "sprocket_project_B"}, } var canaries []Sprocket Expect(projects).To(ContainElement(HaveField("Name", BeKeyOf(names)), &canaries)) Expect(canaries).To(HaveLen(len(names))) ``` #### ConsistOf(element ...interface{}) ```go Ω(ACTUAL).Should(ConsistOf(ELEMENT1, ELEMENT2, ELEMENT3, ...)) ``` or ```go Ω(ACTUAL).Should(ConsistOf([]SOME_TYPE{ELEMENT1, ELEMENT2, ELEMENT3, ...})) ``` 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: ```go Ω([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) ``` Actual must be an `array`, `slice` or `map`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. For maps, `ConsistOf` matches against the `map`'s values. Similarly, for an iterator assignable to `iter.Seq2` `ContainElement` searches through the `v` elements of the produced (_, `v`) pairs. 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`: ```go Ω([]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. Starting with Go 1.23, you can also pass in an iterator assignable to `iter.Seq` (but not `iter.Seq2`) as the only element to `ConsistOf`. #### HaveExactElements(element ...interface{}) ```go Expect(ACTUAL).To(HaveExactElements(ELEMENT1, ELEMENT2, ELEMENT3, ...)) ``` or ```go Expect(ACTUAL).To(HaveExactElements([]SOME_TYPE{ELEMENT1, ELEMENT2, ELEMENT3, ...})) ``` succeeds if `ACTUAL` contains precisely the elements and ordering passed into the matchers. By default `HaveExactElements()` uses `Equal()` to match the elements, however custom matchers can be passed in instead. Here are some examples: ```go Expect([]string{"Foo", "FooBar"}).To(HaveExactElements("Foo", "FooBar")) Expect([]string{"Foo", "FooBar"}).To(HaveExactElements("Foo", ContainSubstring("Bar"))) Expect([]string{"Foo", "FooBar"}).To(HaveExactElements(ContainSubstring("Foo"), ContainSubstring("Foo"))) ``` `ACTUAL` must be an `array` or `slice`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` (but not `iter.Seq2`). You typically pass variadic arguments to `HaveExactElements` (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 `HaveExactElements`: ```go Expect([]string{"Foo", "FooBar"}).To(HaveExactElements([]string{"FooBar", "Foo"})) ``` Note that Go's type system does not allow you to write this as `HaveExactElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]interface{}` are different types - hence the need for this special rule. #### HaveEach(element interface{}) ```go Ω(ACTUAL).Should(HaveEach(ELEMENT)) ``` succeeds if `ACTUAL` solely consists of elements that equal `ELEMENT`. `ACTUAL` must be an `array`, `slice`, or `map`. For `map`s `HaveEach` searches through the map's values, not its keys. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq` or `iter.Seq2`. For `iter.Seq2` `HaveEach` searches through the `v` part of the yielded (_, `v`) pairs. In order to avoid ambiguity it is an error for `ACTUAL` to be an empty `array`, `slice`, or `map` (or a correctly typed `nil`) -- in these cases it cannot be decided if `HaveEach` should match, or should not match. If in your test it is acceptable for `ACTUAL` to be empty, you can use `Or(BeEmpty(), HaveEach(ELEMENT))` instead. Similar, an iterator not yielding any elements is also considered to be an error. By default `HaveEach()` uses the `Equal()` matcher under the hood to assert equality between `ACTUAL`'s elements and `ELEMENT`. You can change this, however, by passing `HaveEach` a `GomegaMatcher`. For example, to check that a slice of strings has an element that matches a substring: ```go Ω([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo"))) ``` #### HaveKey(key interface{}) ```go Ω(ACTUAL).Should(HaveKey(KEY)) ``` succeeds if `ACTUAL` is a map with a key that equals `KEY`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq2` and `HaveKey(KEY)` then succeeds if the iterator produces a (`KEY`, `_`) pair. It is an error for `ACTUAL` to have any other type than `map` or `iter.Seq2`. By default `HaveKey()` uses the `Equal()` matcher under the hood to assert equality between `ACTUAL`'s keys and `KEY`. You can change this, however, by passing `HaveKey` a `GomegaMatcher`. For example, to check that a map has a key that matches a regular expression: ```go Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) ``` #### HaveKeyWithValue(key interface{}, value interface{}) ```go Ω(ACTUAL).Should(HaveKeyWithValue(KEY, VALUE)) ``` succeeds if `ACTUAL` is a map with a key that equals `KEY` mapping to a value that equals `VALUE`. Starting with Go 1.23, `ACTUAL` can be also an iterator assignable to `iter.Seq2` and `HaveKeyWithValue(KEY)` then succeeds if the iterator produces a (`KEY`, `VALUE`) pair. It is an error for `ACTUAL` to have any other type than `map` or `iter.Seq2`. By default `HaveKeyWithValue()` uses the `Equal()` matcher under the hood to assert equality between `ACTUAL`'s keys and `KEY` and between the associated value and `VALUE`. You can change this, however, by passing `HaveKeyWithValue` a `GomegaMatcher` for either parameter. For example, to check that a map has a key that matches a regular expression and which is also associated with a value that passes some numerical threshold: ```go Ω(map[string]int{"Foo": 3, "BazFoo": 4}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), BeNumerically(">", 3))) ``` ### Working with Structs #### HaveField(field interface{}, value interface{}) ```go Ω(ACTUAL).Should(HaveField(FIELD, VALUE)) ``` succeeds if `ACTUAL` is a struct with a value that can be traversed via `FIELD` that equals `VALUE`. It is an error for `ACTUAL` to not be a `struct`. By default `HaveField()` uses the `Equal()` matcher under the hood to assert equality between the extracted value and `VALUE`. You can change this, however, by passing `HaveField` a `GomegaMatcher` for `VALUE`. `FIELD` allows you to access fields within the `ACTUAL` struct. Nested structs can be accessed using the `.` delimiter. `HaveField()` also allows you to invoke methods on the struct by adding a `()` suffix to the `FIELD` - these methods must take no arguments and return exactly one value. For example consider the following types: ```go type Book struct { Title string Author Person } type Person struct { Name string DOB time.Time } ``` and an instance book `var book = Book{...}` - you can use `HaveField` to make assertions like: ```go Ω(book).Should(HaveField("Title", "Les Miserables")) Ω(book).Should(HaveField("Title", ContainSubstring("Les Mis"))) Ω(book).Should(HaveField("Author.Name", "Victor Hugo")) Ω(book).Should(HaveField("Author.DOB.Year()", BeNumerically("<", 1900))) ``` `HaveField` can pair powerfully with a collection matcher like `ContainElement`. To assert that a list of books as at least one element with an author born in February you could write: ```go Ω(books).Should(ContainElement(HaveField("Author.DOB.Month()", Equal(2)))) ``` If you want to make lots of complex assertions against the fields of a struct take a look at the [`gstruct`package](#codegstructcode-testing-complex-data-types) documented below. #### HaveExistingField(field interface{}) While `HaveField()` considers a missing field to be an error (instead of non-success), combining it with `HaveExistingField()` allows `HaveField()` to be reused in test contexts other than assertions: for instance, as filters to [`ContainElement(ELEMENT, )`](#containelementelement-interface) or in detecting resource leaks (like leaked file descriptors). ```go Ω(ACTUAL).Should(HaveExistingField(FIELD)) ``` succeeds if `ACTUAL` is a struct with a field `FIELD`, regardless of this field's value. It is an error for `ACTUAL` to not be a `struct`. Like `HaveField()`, `HaveExistingField()` supports accessing nested structs using the `.` delimiter. Methods on the struct are invoked by adding a `()` suffix to the `FIELD` - these methods must take no arguments and return exactly one value. To assert a particular field value, but only if such a field exists in an `ACTUAL` struct, use the composing [`And`](#andmatchers-gomegamatcher) matcher: ```go Ω(ACTUAL).Should(And(HaveExistingField(FIELD), HaveField(FIELD, VALUE))) ``` ### Working with Numbers and Times #### BeNumerically(comparator string, compareTo ...interface{}) ```go Ω(ACTUAL).Should(BeNumerically(COMPARATOR_STRING, EXPECTED, )) ``` 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...). It is an error for `ACTUAL` or `EXPECTED` to not be a number. There are six supported comparators: - `Ω(ACTUAL).Should(BeNumerically("==", EXPECTED))`: asserts that `ACTUAL` and `EXPECTED` are numerically equal. - `Ω(ACTUAL).Should(BeNumerically("~", EXPECTED, ))`: asserts that `ACTUAL` and `EXPECTED` are within `` of one another. By default `` is `1e-8` but you can specify a custom value. - `Ω(ACTUAL).Should(BeNumerically(">", EXPECTED))`: asserts that `ACTUAL` is greater than `EXPECTED`. - `Ω(ACTUAL).Should(BeNumerically(">=", EXPECTED))`: asserts that `ACTUAL` is greater than or equal to `EXPECTED`. - `Ω(ACTUAL).Should(BeNumerically("<", EXPECTED))`: asserts that `ACTUAL` is less than `EXPECTED`. - `Ω(ACTUAL).Should(BeNumerically("<=", EXPECTED))`: asserts that `ACTUAL` is less than or equal to `EXPECTED`. Any other comparator is an error. #### BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) ```go Ω(ACTUAL).Should(BeTemporally(COMPARATOR_STRING, EXPECTED_TIME, )) ``` performs time-related assertions. `ACTUAL` must be a `time.Time`. There are six supported comparators: - `Ω(ACTUAL).Should(BeTemporally("==", EXPECTED_TIME))`: asserts that `ACTUAL` and `EXPECTED_TIME` are identical `time.Time`s. - `Ω(ACTUAL).Should(BeTemporally("~", EXPECTED_TIME, ))`: asserts that `ACTUAL` and `EXPECTED_TIME` are within `` of one another. By default `` is `time.Millisecond` but you can specify a custom value. - `Ω(ACTUAL).Should(BeTemporally(">", EXPECTED_TIME))`: asserts that `ACTUAL` is after `EXPECTED_TIME`. - `Ω(ACTUAL).Should(BeTemporally(">=", EXPECTED_TIME))`: asserts that `ACTUAL` is after or at `EXPECTED_TIME`. - `Ω(ACTUAL).Should(BeTemporally("<", EXPECTED_TIME))`: asserts that `ACTUAL` is before `EXPECTED_TIME`. - `Ω(ACTUAL).Should(BeTemporally("<=", EXPECTED_TIME))`: asserts that `ACTUAL` is before or at `EXPECTED_TIME`. Any other comparator is an error. ### Working with Values #### HaveValue(matcher types.GomegaMatcher) `HaveValue` applies `MATCHER` to the value that results from dereferencing `ACTUAL` in case of a pointer or an interface, or otherwise `ACTUAL` itself. Pointers and interfaces are dereferenced multiple times as necessary, with a limit of at most 31 dereferences. It will fail if the pointer value is `nil`: ```go Expect(ACTUAL).To(HaveValue(MATCHER)) ``` For instance: ```go i := 42 Expect(&i).To(HaveValue(Equal(42))) Expect(i).To(HaveValue(Equal(42))) ``` `HaveValue` can be used, for instance, in tests and custom matchers where the it doesn't matter (as opposed to `PointTo`) if a value first needs to be dereferenced or not. This is especially useful to custom matchers that are to be used in mixed contexts of pointers as well as non-pointers. Please note that negating the outcome of `HaveValue(nil)` won't suppress any error; for instance, in order to assert not having a specific value while still accepting `nil` the following matcher expression might be used: ```go Or(BeNil(), Not(HaveValue(...))) ``` ### Working with HTTP responses #### HaveHTTPStatus(expected interface{}) ```go Expect(ACTUAL).To(HaveHTTPStatus(EXPECTED, ...)) ``` 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 one or more `int` or `string` types. An `int` is compared to `StatusCode` and a `string` is compared to `Status`. The matcher succeeds if any of the `EXPECTED` values match. Here are some examples: - `Expect(resp).To(HaveHTTPStatus(http.StatusOK, http.StatusNoContext))`: asserts that `resp.StatusCode == 200` or `resp.StatusCode == 204` - `Expect(resp).To(HaveHTTPStatus("404 Not Found"))`: asserts that `resp.Status == "404 Not Found"`. #### HaveHTTPBody(expected interface{}) ```go Expect(ACTUAL).To(HaveHTTPBody(EXPECTED)) ``` Succeeds if the body of an HTTP Response matches. `ACTUAL` must be either a `*http.Response` or `*httptest.ResponseRecorder`. `EXPECTED` must be one of the following: - A `string` - A `[]byte` - A matcher, in which case the matcher will be called with the body as a `[]byte`. Here are some examples: - `Expect(resp).To(HaveHTTPBody("bar"))`: asserts that when `resp.Body` is read, it will equal `bar`. - `Expect(resp).To(HaveHTTPBody(MatchJSON("{\"some\":\"json\""))`: asserts that when `resp.Body` is read, the `MatchJSON` matches it to `{"some":"json"}`. Note that the body is an `io.ReadCloser` and the `HaveHTTPBody()` will read it and the close it. This means that subsequent attempts to read the body may have unexpected results. #### HaveHTTPHeaderWithValue(key string, value interface{}) ```go Expect(ACTUAL).To(HaveHTTPHeaderWithValue(KEY, VALUE)) ``` Succeeds if the HTTP Response has a matching header and value. `ACTUAL` must be either a `*http.Response` or `*httptest.ResponseRecorder`. `KEY` must be a `string`. It is passed to [`http.Header.Get(key string)`](https://pkg.go.dev/net/http#Header.Get), and will have the same behaviors regarding order of headers and capitalization. `VALUE` must be one of the following: - A `string` - A matcher, in which case the matcher will be called to match the value. Here are some examples: - `Expect(resp).To(HaveHTTPHeaderWithValue("Content-Type", "application/json"))`: asserts that the `Content-Type` header has exactly the value `application/json`. - `Expect(resp).To(HaveHTTPHeaderWithValue(ContainSubstring("json")))`: asserts that the `Content-Type` header contains the substring `json`. ### Asserting on Panics #### Panic() ```go Ω(ACTUAL).Should(Panic()) ``` succeeds if `ACTUAL` is a function that, when invoked, panics. `ACTUAL` must be a function that takes no arguments and returns no result -- any other type for `ACTUAL` is an error. #### PanicWith() ```go Ω(ACTUAL).Should(PanicWith(VALUE)) ``` succeeds if `ACTUAL` is a function that, when invoked, panics with a value of `VALUE`. `ACTUAL` must be a function that takes no arguments and returns no result -- any other type for `ACTUAL` is an error. By default `PanicWith()` uses the `Equal()` matcher under the hood to assert equality between `ACTUAL`'s panic value and `VALUE`. You can change this, however, by passing `PanicWith` a `GomegaMatcher`. For example, to check that the panic value matches a regular expression: ```go Ω(func() { panic("FooBarBaz") }).Should(PanicWith(MatchRegexp(`.+Baz$`))) ``` ### Composing Matchers You may form larger matcher expressions using the following operators: `And()`, `Or()`, `Not()` and `WithTransform()`. Note: `And()` and `Or()` can also be referred to as `SatisfyAll()` and `SatisfyAny()`, respectively. With these operators you can express multiple requirements in a single `Expect()` or `Eventually()` statement. For example: ```go Expect(number).To(SatisfyAll( BeNumerically(">", 0), BeNumerically("<", 10))) Expect(msg).To(SatisfyAny( Equal("Success"), MatchRegexp(`^Error .+$`))) ``` It can also provide a lightweight syntax to create new matcher types from existing ones. For example: ```go func BeBetween(min, max int) GomegaMatcher { return SatisfyAll( BeNumerically(">", min), BeNumerically("<", max)) } Ω(number).Should(BeBetween(0, 10)) ``` #### And(matchers ...GomegaMatcher) #### SatisfyAll(matchers ...GomegaMatcher) ```go Ω(ACTUAL).Should(And(MATCHER1, MATCHER2, ...)) ``` or ```go Ω(ACTUAL).Should(SatisfyAll(MATCHER1, MATCHER2, ...)) ``` succeeds if `ACTUAL` satisfies all of the specified matchers (similar to a logical AND). Tests the given matchers in order, returning immediately if one fails, without needing to test the remaining matchers. #### Or(matchers ...GomegaMatcher) #### SatisfyAny(matchers ...GomegaMatcher) ```go Ω(ACTUAL).Should(Or(MATCHER1, MATCHER2, ...)) ``` or ```go Ω(ACTUAL).Should(SatisfyAny(MATCHER1, MATCHER2, ...)) ``` succeeds if `ACTUAL` satisfies any of the specified matchers (similar to a logical OR). Tests the given matchers in order, returning immediately if one succeeds, without needing to test the remaining matchers. #### Not(matcher GomegaMatcher) ```go Ω(ACTUAL).Should(Not(MATCHER)) ``` succeeds if `ACTUAL` does **not** satisfy the specified matcher (similar to a logical NOT). #### WithTransform(transform interface{}, matcher GomegaMatcher) ```go Ω(ACTUAL).Should(WithTransform(TRANSFORM, MATCHER)) ``` succeeds if applying the `TRANSFORM` function to `ACTUAL` (i.e. the value of `TRANSFORM(ACTUAL)`) will satisfy the given `MATCHER`. For example: ```go GetColor := func(e Element) Color { return e.Color } Ω(element).Should(WithTransform(GetColor, Equal(BLUE))) ``` Or the same thing expressed by introducing a new, lightweight matcher: ```go // HaveColor returns a matcher that expects the element to have the given color. func HaveColor(c Color) GomegaMatcher { return WithTransform(func(e Element) Color { return e.Color }, Equal(c)) } Ω(element).Should(HaveColor(BLUE))) ``` `TRANSFORM` functions optionally can return an additional error value in case a transformation is not possible, avoiding the need to `panic`. Returning errors can be useful when using `WithTransform` to build lightweight matchers that accept different value types and that can gracefully fail when presented the wrong value type. As before, such a `TRANSFORM` expects a single actual value. But now it returns the transformed value together with an error value. This follows the common Go idiom to communicate errors via an explicit, separate return value. The following lightweight matcher expects to be used either on a `Sprocket` value or `*Sprocket` pointer. It gracefully fails when the actual value is something else. ```go // HaveSprocketName returns a matcher that expects the actual value to be // either a Sprocket or a *Sprocket, having the specified name. func HaveSprocketName(name string) GomegaMatcher { return WithTransform( func(actual interface{}) (string, error) { switch sprocket := actual.(type) { case *Sprocket: return Sprocket.Name, nil case Sprocket: return Sprocket.Name, nil default: return "", fmt.Errorf("HaveSprocketName expects a Sprocket or *Sprocket, but got %T", actual) } }, Equal(name)) } Ω(element).Should(HaveSprocketName("gomega"))) ``` #### Satisfy(predicate interface{}) ```go Ω(ACTUAL).Should(Satisfy(PREDICATE)) ``` succeeds if applying the `PREDICATE` function to `ACTUAL` (i.e. the value of `PREDICATE(ACTUAL)`) will return `true`. For example: ```go IsEven := func(i int) bool { return i%2==0 } Ω(number).Should(Satisfy(IsEven)) ``` ## Adding Your Own Matchers A matcher, in Gomega, is any type that satisfies the `GomegaMatcher` interface: ```go type GomegaMatcher interface { Match(actual interface{}) (success bool, err error) FailureMessage(actual interface{}) (message string) NegatedFailureMessage(actual interface{}) (message string) } ``` For the simplest cases, new matchers can be [created by composition](#composing-matchers). Please also take a look at the [Building Custom Matchers](https://onsi.github.io/ginkgo/#building-custom-matchers) section of the Ginkgo and Gomega patterns chapter in the Ginkgo docs for additional examples. In addition to composition, however, it is fairly straightforward to build domain-specific custom matchers. You can create new types that satisfy the `GomegaMatcher` interface *or* you can use the `gcustom` package to build matchers out of simple functions. Let's work through an example and illustrate both approaches. ### A Custom Matcher: RepresentJSONifiedObject(EXPECTED interface{}) Say you're working on a JSON API and you want to assert that your server returns the correct JSON representation. Rather than marshal/unmarshal JSON in your tests, you want to write an expressive matcher that checks that the received response is a JSON representation for the object in question. This is what the `RepresentJSONifiedObject` matcher could look like: ```go package json_response_matcher import ( "github.com/onsi/gomega/types" "encoding/json" "fmt" "net/http" "reflect" ) func RepresentJSONifiedObject(expected interface{}) types.GomegaMatcher { return &representJSONMatcher{ expected: expected, } } type representJSONMatcher struct { expected interface{} } func (matcher *representJSONMatcher) Match(actual interface{}) (success bool, err error) { response, ok := actual.(*http.Response) if !ok { return false, fmt.Errorf("RepresentJSONifiedObject matcher expects an http.Response") } pointerToObjectOfExpectedType := reflect.New(reflect.TypeOf(matcher.expected)).Interface() err = json.NewDecoder(response.Body).Decode(pointerToObjectOfExpectedType) if err != nil { return false, fmt.Errorf("Failed to decode JSON: %s", err.Error()) } decodedObject := reflect.ValueOf(pointerToObjectOfExpectedType).Elem().Interface() return reflect.DeepEqual(decodedObject, matcher.expected), nil } func (matcher *representJSONMatcher) FailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected\n\t%#v\nto contain the JSON representation of\n\t%#v", actual, matcher.expected) } func (matcher *representJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected\n\t%#v\nnot to contain the JSON representation of\n\t%#v", actual, matcher.expected) } ``` Let's break this down: - Most matchers have a constructor function that returns an instance of the matcher. In this case we've created `RepresentJSONifiedObject`. Where possible, your constructor function should take explicit types or interfaces. For our use case, however, we need to accept any possible expected type so `RepresentJSONifiedObject` takes an argument with the generic `interface{}` type. - The constructor function then initializes and returns an instance of our matcher: the `representJSONMatcher`. These rarely need to be exported outside of your matcher package. - The `representJSONMatcher` must satisfy the `GomegaMatcher` interface. It does this by implementing the `Match`, `FailureMessage`, and `NegatedFailureMessage` method: - If the `GomegaMatcher` receives invalid inputs `Match` returns a non-nil error explaining the problems with the input. This allows Gomega to fail the assertion whether the assertion is for the positive or negative case. - If the `actual` and `expected` values match, `Match` should return `true`. - Similarly, if the `actual` and `expected` values do not match, `Match` should return `false`. - If the `GomegaMatcher` was testing the `Should` case, and `Match` returned `false`, `FailureMessage` will be called to print a message explaining the failure. - Likewise, if the `GomegaMatcher` was testing the `ShouldNot` case, and `Match` returned `true`, `NegatedFailureMessage` will be called. - It is guaranteed that `FailureMessage` and `NegatedFailureMessage` will only be called *after* `Match`, so you can save off any state you need to compute the messages in `Match`. - Finally, it is common for matchers to make extensive use of the `reflect` library to interpret the generic inputs they receive. In this case, the `representJSONMatcher` goes through some `reflect` gymnastics to create a pointer to a new object with the same type as the `expected` object, read and decode JSON from `actual` into that pointer, and then deference the pointer and compare the result to the `expected` object. ### gcustom: A convenient mechanism for building custom matchers [`gcustom`](https://github.com/onsi/gomega/tree/master/gcustom) is a package that makes building custom matchers easy. Rather than define new types, you can simply provide `gcustom.MakeMatcher` with a function. The [godocs](https://pkg.go.dev/github.com/onsi/gomega/gcustom) for `gcustom` have all the details but here's how `RepresentJSONifiedObject` could be implemented with `gcustom`: ```go package json_response_matcher import ( "github.com/onsi/gomega/types" "github.com/onsi/gomega/gcustom" "encoding/json" "fmt" "net/http" "reflect" ) func RepresentJSONifiedObject(expected interface{}) types.GomegaMatcher { return gcustom.MakeMatcher(func(response *http.Response) (bool, err) { pointerToObjectOfExpectedType := reflect.New(reflect.TypeOf(matcher.expected)).Interface() err = json.NewDecoder(response.Body).Decode(pointerToObjectOfExpectedType) if err != nil { return false, fmt.Errorf("Failed to decode JSON: %w", err.Error()) } decodedObject := reflect.ValueOf(pointerToObjectOfExpectedType).Elem().Interface() return reflect.DeepEqual(decodedObject, matcher.expected), nil }).WithTemplate("Expected:\n{{.FormattedActual}}\n{{.To}} contain the JSON representation of\n{{format .Data 1}}").WithTemplateData(expected) } ``` The [`gcustom` godocs](https://pkg.go.dev/github.com/onsi/gomega/gcustom) go into much more detail but we can point out a few of the convenient features of `gcustom` here: - `gcustom` can take a matcher function that accepts a concrete type. In our case `func(response *https.Response) (bool, err)` - when this is done, the matcher built by `gcustom` takes care of all the type-checking for you and will only call your match function if an object of the correct type is asserted against. If you want to do your own type-checking (or want to build a matcher that works with multiple types) you can use `func(actual any) (bool, err)` instead. - Rather than implement different functions for the two different failure messages you can provide a single template. `gcustom` provides template variables to help you render the failure messages depending on positive failures vs negative failures. For example, the variable `{{.To}}` will render "to" for positive failures and "not to" for negative failures. - You can pass additional data to your template with `WithTemplateData()` - in this case we pass in the expected object so that the template can include it in the output. We do this with the expression `{{format .Data 1}}`. gcustom provides the `format` template function to render objects using Ginkgo's object formatting system (the `1` here denotes the level of indentation). `gcustom` also supports a simpler mechanism for generating messages: `.WithMessage()` simply takes a string and builds a canned message out of that string. You can also provide precompiled templates if you want to avoid the cost of compiling a template every time the matcher is called. ### Testing Custom Matchers Whether you create a new `representJSONMatcher` type, or use `gcustom` you might test drive this matcher while writing it using Ginkgo. Your test might look like: ```go package json_response_matcher_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "jsonresponsematcher" "bytes" "encoding/json" "io/ioutil" "net/http" "strings" "testing" ) func TestCustomMatcher(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Custom Matcher Suite") } type Book struct { Title string `json:"title"` Author string `json:"author"` } var _ = Describe("RepresentJSONified Object", func() { var ( book Book bookJSON []byte response *http.Response ) BeforeEach(func() { book = Book{ Title: "Les Miserables", Author: "Victor Hugo", } var err error bookJSON, err = json.Marshal(book) Ω(err).ShouldNot(HaveOccurred()) }) Context("when actual is not an http response", func() { It("should error", func() { _, err := RepresentJSONifiedObject(book).Match("not a response") Ω(err).Should(HaveOccurred()) }) }) Context("when actual is an http response", func() { BeforeEach(func() { response = &http.Response{} }) Context("with a body containing the JSON representation of actual", func() { BeforeEach(func() { response.ContentLength = int64(len(bookJSON)) response.Body = ioutil.NopCloser(bytes.NewBuffer(bookJSON)) }) It("should succeed", func() { Ω(response).Should(RepresentJSONifiedObject(book)) }) }) Context("with a body containing the JSON representation of something else", func() { BeforeEach(func() { reader := strings.NewReader(`{}`) response.ContentLength = int64(reader.Len()) response.Body = ioutil.NopCloser(reader) }) It("should fail", func() { Ω(response).ShouldNot(RepresentJSONifiedObject(book)) }) }) Context("with a body containing invalid JSON", func() { BeforeEach(func() { reader := strings.NewReader(`floop`) response.ContentLength = int64(reader.Len()) response.Body = ioutil.NopCloser(reader) }) It("should error", func() { _, err := RepresentJSONifiedObject(book).Match(response) Ω(err).Should(HaveOccurred()) }) }) }) }) ``` This also offers an example of what using the matcher would look like in your tests. Note that testing the cases when the matcher returns an error involves creating the matcher and invoking `Match` manually (instead of using an `Ω` or `Expect` assertion). ### Aborting Eventually/Consistently **Note: This section documents the `MatchMayChangeInTheFuture` method for aborting `Eventually`/`Consistently`. A more up-to-date approach that uses the `StopTrying` error is documented [earlier](#bailing-out-early--matchers).** There are sometimes instances where `Eventually` or `Consistently` should stop polling a matcher because the result of the match simply cannot change. For example, consider a test that looks like: ```go Eventually(myChannel).Should(Receive(Equal("bar"))) ``` `Eventually` will repeatedly invoke the `Receive` matcher against `myChannel` until the match succeeds. However, if the channel becomes *closed* there is *no way* for the match to ever succeed. Allowing `Eventually` to continue polling is inefficient and slows the test suite down. To get around this, a matcher can optionally implement: ```go MatchMayChangeInTheFuture(actual interface{}) bool ``` This is not part of the `GomegaMatcher` interface and, in general, most matchers do not need to implement `MatchMayChangeInTheFuture`. If implemented, however, `MatchMayChangeInTheFuture` will be called with the appropriate `actual` value by `Eventually` and `Consistently` *after* the call to `Match` during every polling interval. If `MatchMayChangeInTheFuture` returns `true`, `Eventually` and `Consistently` will continue polling. If, however, `MatchMayChangeInTheFuture` returns `false`, `Eventually` and `Consistently` will stop polling and either fail or pass as appropriate. If you'd like to look at a simple example of `MatchMayChangeInTheFuture` check out [`gexec`'s `Exit` matcher](https://github.com/onsi/gomega/tree/master/gexec/exit_matcher.go). Here, `MatchMayChangeInTheFuture` returns true if the `gexec.Session` under test has not exited yet, but returns false if it has. Because of this, if a process exits with status code 3, but an assertion is made of the form: ```go Eventually(session, 30).Should(gexec.Exit(0)) ``` `Eventually` will not block for 30 seconds but will return (and fail, correctly) as soon as the mismatched exit code arrives! > Note: `Eventually` and `Consistently` only exercise the `MatchMayChangeInTheFuture` method *if* they are passed a bare value. If they are passed functions to be polled it is not possible to guarantee that the return value of the function will not change between polling intervals. In this case, `MatchMayChangeInTheFuture` is not called and the polling continues until either a match is found or the timeout elapses. ### Contributing to Gomega Contributions are more than welcome. Either [open an issue](http://github.com/onsi/gomega/issues) for a matcher you'd like to see or, better yet, test drive the matcher and [send a pull request](https://github.com/onsi/gomega/pulls). When adding a new matcher please mimic the style use in Gomega's current matchers: you should use the `format` package to format your output, put the matcher and its tests in the `matchers` package, and the constructor in the `matchers.go` file in the top-level package. ## Extending Gomega The default Gomega can be wrapped by replacing it with an object that implements both the `gomega.Gomega` interface and the `inner` interface: ```go type inner interface { Inner() Gomega } ``` The `Inner()` method must return the actual `gomega.Default`. For Gomega to function properly your wrapper methods must call the same method on the real `gomega.Default` This allows you to wrap every Gomega method call (e.g. `Expect()`) with your own code across your test suite. You can use this to add random delays, additional logging, or just for tracking the number of `Expect()` calls made. ```go func init() { gomega.Default = &gomegaWrapper{ inner: gomega.Default, } } type gomegaWrapper struct { inner gomega.Gomega } func (g *gomegaWrapper) Inner() gomega.Gomega { return g.inner } func (g *gomegaWrapper) Ω(actual interface{}, extra ...interface{}) types.Assertion { // You now have an opportunity to add a random delay to help identify any timing // dependencies in your tests or can add additional logging. return g.inner.Ω(actual, extra...) } ... ``` ## `ghttp`: Testing HTTP Clients The `ghttp` package provides support for testing http *clients*. The typical pattern in Go for testing http clients entails spinning up an `httptest.Server` using the `net/http/httptest` package and attaching test-specific handlers that perform assertions. `ghttp` provides `ghttp.Server` - a wrapper around `httptest.Server` that allows you to easily build up a stack of test handlers. These handlers make assertions against the incoming request and return a pre-fabricated response. `ghttp` provides a number of prebuilt handlers that cover the most common assertions. You can combine these handlers to build out full-fledged assertions that test multiple aspects of the incoming requests. The goal of this documentation is to provide you with an adequate mental model to use `ghttp` correctly. For a full reference of all the available handlers and the various methods on `ghttp.Server` look at the [godoc](https://godoc.org/github.com/onsi/gomega/ghttp) documentation. ### Making assertions against an incoming request Let's start with a simple example. Say you are building an API client that provides a `FetchSprockets(category string)` method that makes an http request to a remote server to fetch sprockets of a given category. For now, let's not worry about the values returned by `FetchSprockets` but simply assert that the correct request was made. Here's the setup for our `ghttp`-based Ginkgo test: ```go Describe("The sprockets client", func() { var server *ghttp.Server var client *sprockets.Client BeforeEach(func() { server = ghttp.NewServer() client = sprockets.NewClient(server.URL()) }) AfterEach(func() { //shut down the server between tests server.Close() }) }) ``` Note that the server's URL is auto-generated and varies between test runs. Because of this, you must always inject the server URL into your client. Let's add a simple test that asserts that `FetchSprockets` hits the correct endpoint with the correct HTTP verb: ```go Describe("The sprockets client", func() { //...see above Describe("fetching sprockets", func() { BeforeEach(func() { server.AppendHandlers( ghttp.VerifyRequest("GET", "/sprockets"), ) }) It("should make a request to fetch sprockets", func() { client.FetchSprockets("") Ω(server.ReceivedRequests()).Should(HaveLen(1)) }) }) }) ``` Here we append a `VerifyRequest` handler to the `server` and call `client.FetchSprockets`. This call (assuming it's a blocking call) will make a round-trip to the test `server` before returning. The test `server` receives the request and passes it through the `VerifyRequest` handler which will validate that the request is a `GET` request hitting the `/sprockets` endpoint. If it's not, the test will fail. Note that the test can pass trivially if `client.FetchSprockets()` doesn't actually make a request. To guard against this you can assert that the `server` has actually received a request. All the requests received by the server are saved off and made available via `server.ReceivedRequests()`. We use this to assert that there should have been exactly one received requests. > Guarding against the trivial "false positive" case outlined above isn't really necessary. Just good practice when test *driving*. Let's add some more to our example. Let's make an assertion that `FetchSprockets` can request sprockets filtered by a particular category: ```go Describe("The sprockets client", func() { //...see above Describe("fetching sprockets", func() { BeforeEach(func() { server.AppendHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ) }) It("should make a request to fetch sprockets", func() { client.FetchSprockets("encabulators") Ω(server.ReceivedRequests()).Should(HaveLen(1)) }) }) }) ``` `ghttp.VerifyRequest` takes an optional third parameter that is matched against the request `URL`'s `RawQuery`. Let's extend the example some more. In addition to asserting that the request is a `GET` request to the correct endpoint with the correct query params, let's also assert that it includes the correct `BasicAuth` information and a correct custom header. Here's the complete example: ```go Describe("The sprockets client", func() { var ( server *ghttp.Server client *sprockets.Client username, password string ) BeforeEach(func() { username, password = "gopher", "tacoshell" server = ghttp.NewServer() client = sprockets.NewClient(server.URL(), username, password) }) AfterEach(func() { server.Close() }) Describe("fetching sprockets", func() { BeforeEach(func() { server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.VerifyBasicAuth(username, password), ghttp.VerifyHeader(http.Header{ "X-Sprocket-API-Version": []string{"1.0"}, }), ) ) }) It("should make a request to fetch sprockets", func() { client.FetchSprockets("encabulators") Ω(server.ReceivedRequests()).Should(HaveLen(1)) }) }) }) ``` This example *combines* multiple `ghttp` verify handlers using `ghttp.CombineHandlers`. Under the hood, this returns a new handler that wraps and invokes the three passed in verify handlers. The request sent by the client will pass through each of these verify handlers and must pass them all for the test to pass. Note that you can easily add your own verify handler into the mix. Just pass in a regular `http.HandlerFunc` and make assertions against the received request. > It's important to understand that you must pass `AppendHandlers` **one** handler *per* incoming request (see [below](#handling-multiple-requests)). In order to apply multiple handlers to a single request we must first combine them with `ghttp.CombineHandlers` and then pass that *one* wrapper handler in to `AppendHandlers`. ### Providing responses So far, we've only made assertions about the outgoing request. Clients are also responsible for parsing responses and returning valid data. Let's say that `FetchSprockets()` returns two things: a slice `[]Sprocket` and an `error`. Here's what a happy path test that asserts the correct data is returned might look like: ```go Describe("The sprockets client", func() { //... Describe("fetching sprockets", func() { BeforeEach(func() { server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.VerifyBasicAuth(username, password), ghttp.VerifyHeader(http.Header{ "X-Sprocket-API-Version": []string{"1.0"}, }), ghttp.RespondWith(http.StatusOK, `[ {"name": "entropic decoupler", "color": "red"}, {"name": "defragmenting ramjet", "color": "yellow"} ]`), ) ) }) It("should make a request to fetch sprockets", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(err).ShouldNot(HaveOccurred()) Ω(sprockets).Should(Equal([]Sprocket{ sprockets.Sprocket{Name: "entropic decoupler", Color: "red"}, sprockets.Sprocket{Name: "defragmenting ramjet", Color: "yellow"}, })) }) }) }) ``` We use `ghttp.RespondWith` to specify the response return by the server. In this case we're passing back a status code of `200` (`http.StatusOK`) and a pile of JSON. We then assert, in the test, that the client succeeds and returns the correct set of sprockets. The fact that details of the JSON encoding are bleeding into this test is somewhat unfortunate, and there's a lot of repetition going on. `ghttp` provides a `RespondWithJSONEncoded` handler that accepts an arbitrary object and JSON encodes it for you. Here's a cleaner test: ```go Describe("The sprockets client", func() { //... Describe("fetching sprockets", func() { var returnedSprockets []Sprocket BeforeEach(func() { returnedSprockets = []Sprocket{ sprockets.Sprocket{Name: "entropic decoupler", Color: "red"}, sprockets.Sprocket{Name: "defragmenting ramjet", Color: "yellow"}, } server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.VerifyBasicAuth(username, password), ghttp.VerifyHeader(http.Header{ "X-Sprocket-API-Version": []string{"1.0"}, }), ghttp.RespondWithJSONEncoded(http.StatusOK, returnedSprockets), ) ) }) It("should make a request to fetch sprockets", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(err).ShouldNot(HaveOccurred()) Ω(sprockets).Should(Equal(returnedSprockets)) }) }) }) ``` ### Testing different response scenarios Our test currently only handles the happy path where the server returns a `200`. We should also test a handful of sad paths. In particular, we'd like to return a `SprocketsErrorNotFound` error when the server `404`s and a `SprocketsErrorUnauthorized` error when the server returns a `401`. But how to do this without redefining our server handler three times? `ghttp` provides `RespondWithPtr` and `RespondWithJSONEncodedPtr` for just this use case. Both take *pointers* to status codes and respond bodies (objects for the `JSON` case). Here's the more complete test: ```go Describe("The sprockets client", func() { //... Describe("fetching sprockets", func() { var returnedSprockets []Sprocket var statusCode int BeforeEach(func() { returnedSprockets = []Sprocket{ sprockets.Sprocket{Name: "entropic decoupler", Color: "red"}, sprockets.Sprocket{Name: "defragmenting ramjet", Color: "yellow"}, } server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.VerifyBasicAuth(username, password), ghttp.VerifyHeader(http.Header{ "X-Sprocket-API-Version": []string{"1.0"}, }), ghttp.RespondWithJSONEncodedPtr(&statusCode, &returnedSprockets), ) ) }) Context("when the request succeeds", func() { BeforeEach(func() { statusCode = http.StatusOK }) It("should return the fetched sprockets without erroring", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(err).ShouldNot(HaveOccurred()) Ω(sprockets).Should(Equal(returnedSprockets)) }) }) Context("when the response is unauthorized", func() { BeforeEach(func() { statusCode = http.StatusUnauthorized }) It("should return the SprocketsErrorUnauthorized error", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(sprockets).Should(BeEmpty()) Ω(err).Should(MatchError(SprocketsErrorUnauthorized)) }) }) Context("when the response is not found", func() { BeforeEach(func() { statusCode = http.StatusNotFound }) It("should return the SprocketsErrorNotFound error", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(sprockets).Should(BeEmpty()) Ω(err).Should(MatchError(SprocketsErrorNotFound)) }) }) }) }) ``` In this way, the status code and returned value (not shown here) can be changed in sub-contexts without having to modify the original test setup. ### Handling multiple requests So far, we've only seen examples where one request is made per test. `ghttp` supports handling *multiple* requests too. `server.AppendHandlers` can be passed multiple handlers and these handlers are evaluated in order as requests come in. This can be helpful in cases where it is not possible (or desirable) to have calls to the client under test only generate *one* request. A common example is pagination. If the sprockets API is paginated it may be desirable for `FetchSprockets` to provide a simpler interface that simply fetches all available sprockets. Here's what a test might look like: ```go Describe("fetching sprockets from a paginated endpoint", func() { var returnedSprockets []Sprocket var firstResponse, secondResponse PaginatedResponse BeforeEach(func() { returnedSprockets = []Sprocket{ sprockets.Sprocket{Name: "entropic decoupler", Color: "red"}, sprockets.Sprocket{Name: "defragmenting ramjet", Color: "yellow"}, sprockets.Sprocket{Name: "parametric demuxer", Color: "blue"}, } firstResponse = sprockets.PaginatedResponse{ Sprockets: returnedSprockets[0:2], //first batch PaginationToken: "get-second-batch", //some opaque non-empty token } secondResponse = sprockets.PaginatedResponse{ Sprockets: returnedSprockets[2:], //second batch PaginationToken: "", //signifies the last batch } server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.RespondWithJSONEncoded(http.StatusOK, firstResponse), ), ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators&pagination-token=get-second-batch"), ghttp.RespondWithJSONEncoded(http.StatusOK, secondResponse), ), ) }) It("should fetch all the sprockets", func() { sprockets, err := client.FetchSprockets("encabulators") Ω(err).ShouldNot(HaveOccurred()) Ω(sprockets).Should(Equal(returnedSprockets)) }) }) ``` By default the `ghttp` server fails the test if the number of requests received exceeds the number of handlers registered, so this test ensures that the `client` stops sending requests after receiving the second (and final) set of paginated data. ### MUXing Routes to Handlers `AppendHandlers` allows you to make ordered assertions about incoming requests. This places a strong constraint on all incoming requests: namely that exactly the right requests have to arrive in exactly the right order and that no additional requests are allowed. One can take a different testing strategy, however. Instead of asserting that requests come in in a predefined order, you may which to build a test server that can handle arbitrarily many requests to a set of predefined routes. In fact, there may be some circumstances where you want to make ordered assertions on *some* requests (via `AppendHandlers`) but still support sending particular responses to *other* requests that may interleave the ordered assertions. `ghttp` supports these sorts of usecases via `server.RouteToHandler(method, path, handler)`. Let's cook up an example. Perhaps, instead of authenticating via basic auth our sprockets client logs in and fetches a token from the server when performing requests that require authentication. We could pepper our `AppendHandlers` calls with a handler that handles these requests (this is not a terrible idea, of course!) *or* we could set up a single route at the top of our tests. Here's what such a test might look like: ```go Describe("CRUDing sprockes", func() { BeforeEach(func() { server.RouteToHandler("POST", "/login", ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/login", "user=bob&password=password"), ghttp.RespondWith(http.StatusOK, "your-auth-token"), )) }) Context("GETting sprockets", func() { var returnedSprockets []Sprocket BeforeEach(func() { returnedSprockets = []Sprocket{ sprockets.Sprocket{Name: "entropic decoupler", Color: "red"}, sprockets.Sprocket{Name: "defragmenting ramjet", Color: "yellow"}, sprockets.Sprocket{Name: "parametric demuxer", Color: "blue"}, } server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"), ghttp.RespondWithJSONEncoded(http.StatusOK, returnedSprockets), ), ) }) It("should fetch all the sprockets", func() { sprockets, err := client.FetchSprockes("encabulators") Ω(err).ShouldNot(HaveOccurred()) Ω(sprockets).Should(Equal(returnedSprockets)) }) }) Context("POSTing sprockets", func() { var sprocketToSave Sprocket BeforeEach(func() { sprocketToSave = sprockets.Sprocket{Name: "endothermic penambulator", Color: "purple"} server.AppendHandlers( ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/sprocket", "token=your-auth-token"), ghttp.VerifyJSONRepresenting(sprocketToSave) ghttp.RespondWithJSONEncoded(http.StatusOK, nil), ), ) }) It("should save the sprocket", func() { err := client.SaveSprocket(sprocketToSave) Ω(err).ShouldNot(HaveOccurred()) }) }) }) ``` Here, saving a sprocket triggers authentication, which is handled by the registered `RouteToHandler` handler whereas fetching the list of sprockets does not. > `RouteToHandler` can take either a string as a route (as seen in this example) or a `regexp.Regexp`. ### Allowing unhandled requests By default, `ghttp`'s server marks the test as failed if a request is made for which there is no registered handler. It is sometimes useful to have a fake server that simply returns a fixed status code for all unhandled incoming requests. `ghttp` supports this: just call `server.SetAllowUnhandledRequests(true)` and `server.SetUnhandledRequestStatusCode(statusCode)`, passing whatever status code you'd like to return. In addition to returning the registered status code, `ghttp`'s server will also save all received requests. These can be accessed by calling `server.ReceivedRequests()`. This is useful for cases where you may want to make assertions against requests *after* they've been made. To bring it all together: there are three ways to instruct a `ghttp` server to handle requests: you can map routes to handlers using `RouteToHandler`, you can append handlers via `AppendHandlers`, and you can `SetAllowUnhandledRequests` and specify the status code by calling `SetUnhandledRequestStatusCode`. When a `ghttp` server receives a request it first checks against the set of handlers registered via `RouteToHandler` if there is no such handler it proceeds to pop an `AppendHandlers` handler off the stack, if the stack of ordered handlers is empty, it will check whether `GetAllowUnhandledRequests` returns `true` or `false`. If `false` the test fails. If `true`, a response is sent with whatever `GetUnhandledRequestStatusCode` returns. ### Using a RoundTripper to route requests to the test Server So far you have seen examples of using `server.URL()` to get the string URL of the test server. This is ok if you are testing code where you can pass the URL. In some cases you might need to pass a `http.Client` or similar. You can use `server.RoundTripper(nil)` to create a `http.RoundTripper` which will redirect requests to the test server. The method takes another `http.RoundTripper` to make the request to the test server, this allows chaining `http.Transports` or otherwise. If passed `nil`, then `http.DefaultTransport` is used to make the request. ```go Describe("The http client", func() { var server *ghttp.Server var httpClient *http.Client BeforeEach(func() { server = ghttp.NewServer() httpClient = &http.Client{Transport: server.RoundTripper(nil)} }) AfterEach(func() { //shut down the server between tests server.Close() }) }) ``` ## `gbytes`: Testing Streaming Buffers `gbytes` implements `gbytes.Buffer` - an `io.WriteCloser` that captures all input to an in-memory buffer. When used in concert with the `gbytes.Say` matcher, the `gbytes.Buffer` allows you make *ordered* assertions against streaming data. What follows is a contrived example. `gbytes` is best paired with [`gexec`](#gexec-testing-external-processes). Say you have an integration test that is streaming output from an external API. You can feed this stream into a `gbytes.Buffer` and make ordered assertions like so: ```go Describe("attach to the data stream", func() { var ( client *apiclient.Client buffer *gbytes.Buffer ) BeforeEach(func() { buffer = gbytes.NewBuffer() client := apiclient.New() go client.AttachToDataStream(buffer) }) It("should stream data", func() { Eventually(buffer).Should(gbytes.Say(`Attached to stream as client \d+`)) client.ReticulateSplines() Eventually(buffer).Should(gbytes.Say(`reticulating splines`)) client.EncabulateRetros(7) Eventually(buffer).Should(gbytes.Say(`encabulating 7 retros`)) }) }) ``` These assertions will only pass if the strings passed to `Say` (which are interpreted as regular expressions - make sure to escape characters appropriately!) appear in the buffer. An opaque read cursor (that you cannot access or modify) is fast-forwarded as successful assertions are made. So, for example: ```go Eventually(buffer).Should(gbytes.Say(`reticulating splines`)) Consistently(buffer).ShouldNot(gbytes.Say(`reticulating splines`)) ``` will (counterintuitively) pass. This allows you to write tests like: ```go client.ReticulateSplines() Eventually(buffer).Should(gbytes.Say(`reticulating splines`)) client.ReticulateSplines() Eventually(buffer).Should(gbytes.Say(`reticulating splines`)) ``` and ensure that the test is correctly asserting that `reticulating splines` appears *twice*. At any time, you can access the entire contents written to the buffer via `buffer.Contents()`. This includes *everything* ever written to the buffer regardless of the current position of the read cursor. ### Handling branches Sometimes (rarely!) you must write a test that must perform different actions depending on the output streamed to the buffer. This can be accomplished using `buffer.Detect`. Here's a contrived example: ```go func LoginIfNecessary() { client.Authorize() select { case <-buffer.Detect("You are not logged in"): client.Login() case <-buffer.Detect("Success"): return case <-time.After(time.Second): ginkgo.Fail("timed out waiting for output") } buffer.CancelDetects() } ``` `buffer.Detect` takes a string (interpreted as a regular expression) and returns a channel that will fire *once* if the requested string is detected. Upon detection, the buffer's opaque read cursor is fast-forwarded so subsequent uses of `gbytes.Say` will pick up from where the succeeding `Detect` left off. You *must* call `buffer.CancelDetects()` to clean up afterwards (`buffer` spawns one goroutine per call to `Detect`). ### Testing `io.Reader`s, `io.Writer`s, and `io.Closer`s Implementations of `io.Reader`, `io.Writer`, and `io.Closer` are expected to be blocking. This makes the following class of tests unsafe: ```go It("should read something", func() { p := make([]byte, 5) _, err := reader.Read(p) //unsafe! this could block forever Ω(err).ShouldNot(HaveOccurred()) Ω(p).Should(Equal([]byte("abcde"))) }) ``` It is safer to wrap `io.Reader`s, `io.Writer`s, and `io.Closer`s with explicit timeouts. You can do this with `gbytes.TimeoutReader`, `gbytes.TimeoutWriter`, and `gbytes.TimeoutCloser` like so: ```go It("should read something", func() { p := make([]byte, 5) _, err := gbytes.TimeoutReader(reader, time.Second).Read(p) Ω(err).ShouldNot(HaveOccurred()) Ω(p).Should(Equal([]byte("abcde"))) }) ``` The `gbytes` wrappers will return `gbytes.ErrTimeout` if a timeout occurs. In the case of `io.Reader`s you can leverage the `Say` matcher and the functionality of `gbytes.Buffer` by building a `gbytes.Buffer` that reads from the `io.Reader` asynchronously. You can do this with the `gbytes` package like so: ```go It("should read something", func() { Eventually(gbytes.BufferReader(reader)).Should(gbytes.Say("abcde")) }) ``` `gbytes.BufferReader` takes an `io.Reader` and returns a `gbytes.Buffer`. Under the hood an `io.Copy` goroutine is launched to copy data from the `io.Reader` into the `gbytes.Buffer`. The `gbytes.Buffer` is closed when the `io.Copy` completes. Because the `io.Copy` is launched asynchronously you *must* make assertions against the reader using `Eventually`. ## `gexec`: Testing External Processes `gexec` simplifies testing external processes. It can help you [compile go binaries](#compiling-external-binaries), [start external processes](#starting-external-processes), [send signals and wait for them to exit](#sending-signals-and-waiting-for-the-process-to-exit), make [assertions against the exit code](#asserting-against-exit-code), and stream output into `gbytes.Buffer`s to allow you [make assertions against output](#making-assertions-against-the-process-output). ### Compiling external binaries You use `gexec.Build()` to compile Go binaries. These are built using `go build` and are stored off in a temporary directory. You'll want to `gexec.CleanupBuildArtifacts()` when you're done with the test. A common pattern is to compile binaries once at the beginning of the test using `BeforeSuite` and to clean up once at the end of the test using `AfterSuite`: ```go var pathToSprocketCLI string BeforeSuite(func() { var err error pathToSprocketCLI, err = gexec.Build("github.com/spacely/sprockets") Ω(err).ShouldNot(HaveOccurred()) }) AfterSuite(func() { gexec.CleanupBuildArtifacts() }) ``` > By default, `gexec.Build` uses the GOPATH specified in your environment. You can also use `gexec.BuildIn(gopath string, packagePath string)` to specify a custom GOPATH for the build command. This is useful to, for example, build a binary against its vendored Go dependencies. > You can specify arbitrary environment variables for the build command – such as GOOS and GOARCH for building on other platforms – using `gexec.BuildWithEnvironment(packagePath string, envs []string)`. ### Starting external processes `gexec` provides a `Session` that wraps `exec.Cmd`. `Session` includes a number of features that will be explored in the next few sections. You create a `Session` by instructing `gexec` to start a command: ```go command := exec.Command(pathToSprocketCLI, "-api=127.0.0.1:8899") session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter) Ω(err).ShouldNot(HaveOccurred()) ``` `gexec.Start` calls `command.Start` for you and forwards the command's `stdout` and `stderr` to `io.Writer`s that you provide. In the code above, we pass in Ginkgo's `GinkgoWriter`. This makes working with external processes quite convenient: when a test passes no output is printed to screen, however if a test fails then any output generated by the command will be provided. > If you want to see all your output regardless of test status, just run `ginkgo` in verbose mode (`-v`) - now everything written to `GinkgoWriter` makes it onto the screen. ### Sending signals and waiting for the process to exit `gexec.Session` makes it easy to send signals to your started command: ```go session.Kill() //sends SIGKILL session.Interrupt() //sends SIGINT session.Terminate() //sends SIGTERM session.Signal(signal) //sends the passed in os.Signal signal ``` If the process has already exited these signal calls are no-ops. In addition to starting the wrapped command, `gexec.Session` also *monitors* the command until it exits. You can ask `gexec.Session` to `Wait` until the process exits: ```go session.Wait() ``` this will block until the session exits and will *fail* if it does not exit within the default `Eventually` timeout. You can override this timeout by specifying a custom one: ```go session.Wait(5 * time.Second) ``` > Though you can access the wrapped command using `session.Command` you should not attempt to `Wait` on it yourself. `gexec` has already called `Wait` in order to monitor your process for you. > Under the hood `session.Wait` simply uses `Eventually`. Since the signaling methods return the session you can chain calls together: ```go session.Terminate().Wait() ``` will send `SIGTERM` and then wait for the process to exit. ### Asserting against exit code Once a session has exited you can fetch its exit code with `session.ExitCode()`. You can subsequently make assertions against the exit code. A more idiomatic way to assert that a command has exited is to use the `gexec.Exit()` matcher: ```go Eventually(session).Should(Exit()) ``` Will verify that the `session` exits within `Eventually`'s default timeout. You can assert that the process exits with a specified exit code too: ```go Eventually(session).Should(Exit(0)) ``` > If the process has not exited yet, `session.ExitCode()` returns `-1` ### Making assertions against the process output In addition to streaming output to the passed in `io.Writer`s (the `GinkgoWriter` in our example above), `gexec.Start` attaches `gbytes.Buffer`s to the command's output streams. These are available on the `session` object via: ```go session.Out //a gbytes.Buffer connected to the command's stdout session.Err //a gbytes.Buffer connected to the command's stderr ``` This allows you to make assertions against the stream of output: ```go Eventually(session.Out).Should(gbytes.Say("hello [A-Za-z], nice to meet you")) Eventually(session.Err).Should(gbytes.Say("oops!")) ``` Since `gexec.Session` is a `gbytes.BufferProvider` that provides the `Out` buffer you can write assertions against `stdout` output like so: ```go Eventually(session).Should(gbytes.Say("hello [A-Za-z], nice to meet you")) ``` Using the `Say` matcher is convenient when making *ordered* assertions against a stream of data generated by a live process. Sometimes, however, all you need is to wait for the process to exit and then make assertions against the entire contents of its output. Since `Wait()` returns `session` you can wait for the process to exit, then grab all its stdout as a `[]byte` buffer with a simple one-liner: ```go Ω(session.Wait().Out.Contents()).Should(ContainSubstring("finished successfully")) ``` ### Signaling all processes `gexec` provides methods to track and send signals to all processes that it starts. ```go gexec.Kill() //sends SIGKILL to all processes gexec.Terminate() //sends SIGTERM to all processes gexec.Signal(int) //sends the passed in os.Signal signal to all the processes gexec.Interrupt() //sends SIGINT to all processes ``` If the any of the processes have already exited these signal calls are no-ops. `gexec` also provides methods to cleanup and wait for all the processes it started. ```go gexec.KillAndWait() gexec.TerminateAndWait() ``` You can specify a custom timeout by: ```go gexec.KillAndWait(5 * time.Second) gexec.TerminateAndWait(2 * time.Second) ``` The timeout is applied for each of the processes. It is considered good practice to ensure all of your processes have been killed before the end of the test suite. If you are using `ginkgo` you can use: ```go AfterSuite(func(){ gexec.KillAndWait() }) ``` Due to the global nature of these methods, keep in mind that signaling processes will affect all processes started by `gexec`, in any context. For example if these methods where used in an `AfterEach`, then processes started in `BeforeSuite` would also be signaled. ## `gstruct`: Testing Complex Data Types `gstruct` simplifies testing large and nested structs and slices. It is used for building up complex matchers that apply different tests to each field or element. ### Testing type `struct` `gstruct` provides the `FieldsMatcher` through the `MatchAllFields` and `MatchFields` functions for applying a separate matcher to each field of a struct: ```go actual := struct{ A int B bool C string }{5, true, "foo"} Expect(actual).To(MatchAllFields(Fields{ "A": BeNumerically("<", 10), "B": BeTrue(), "C": Equal("foo"), })) ``` `MatchAllFields` requires that every field is matched, and each matcher is mapped to a field. To match a subset or superset of a struct, you should use the `MatchFields` function with the `IgnoreExtras` and `IgnoreMissing` options. `IgnoreExtras` will ignore fields that don't map to a matcher, e.g. ```go Expect(actual).To(MatchFields(IgnoreExtras, Fields{ "A": BeNumerically("<", 10), "B": BeTrue(), // Ignore lack of "C" in the matcher. })) ``` `IgnoreMissing` will ignore matchers that don't map to a field, e.g. ```go Expect(actual).To(MatchFields(IgnoreMissing, Fields{ "A": BeNumerically("<", 10), "B": BeTrue(), "C": Equal("foo"), "D": Equal("bar"), // Ignored, since actual.D does not exist. })) ``` The options can be combined with the binary or: `IgnoreMissing|IgnoreExtras`. ### Testing type slice `gstruct` provides the `ElementsMatcher` through the `MatchAllElements` and `MatchElements` function for applying a separate matcher to each element, identified by an `Identifier` function: ```go actual := []string{ "A: foo bar baz", "B: once upon a time", "C: the end", } id := func(element interface{}) string { return string(element.(string)[0]) } Expect(actual).To(MatchAllElements(id, Elements{ "A": Not(BeZero()), "B": MatchRegexp("[A-Z]: [a-z ]+"), "C": ContainSubstring("end"), })) ``` `MatchAllElements` requires that there is a 1:1 mapping from every element to every matcher. To match a subset or superset of elements, you should use the `MatchElements` function with the `IgnoreExtras` and `IgnoreMissing` options. `IgnoreExtras` will ignore elements that don't map to a matcher, e.g. ```go Expect(actual).To(MatchElements(id, IgnoreExtras, Elements{ "A": Not(BeZero()), "B": MatchRegexp("[A-Z]: [a-z ]+"), // Ignore lack of "C" in the matcher. })) ``` `IgnoreMissing` will ignore matchers that don't map to an element, e.g. ```go Expect(actual).To(MatchElements(id, IgnoreMissing, Elements{ "A": Not(BeZero()), "B": MatchRegexp("[A-Z]: [a-z ]+"), "C": ContainSubstring("end"), "D": Equal("bar"), // Ignored, since actual.D does not exist. })) ``` You can also use the flag `AllowDuplicates` to permit multiple elements in your slice to map to a single key and matcher in your fields (this flag is not meaningful when applied to structs). ```go everyElementID := func(element interface{}) string { return "a constant" // Every element will map to the same key in this case; you can group them into multiple keys, however. } Expect(actual).To(MatchElements(everyElementID, AllowDuplicates, Elements{ "a constant": ContainSubstring(": "), // Because every element passes this test })) Expect(actual).NotTo(MatchElements(everyElementID, AllowDuplicates, Elements{ "a constant": ContainSubstring("foo bar baz"), // Only the first element passes this test })) ``` The options can be combined with the binary or: `IgnoreMissing|IgnoreExtras|AllowDuplicates`. Additionally, `gstruct` provides `MatchAllElementsWithIndex` and `MatchElementsWithIndex` function for applying a matcher with index to each element, identified by an `IdentifierWithIndex` function. A helper function is also included with `gstruct` called `IndexIdentity` that provides the functionality of the just using the index as your identifier as seen below. ```go actual := []string{ "A: foo bar baz", "B: once upon a time", "C: the end", } id := func(index int, _ interface{}) string { return strconv.Itoa(index) } Expect(actual).To(MatchAllElementsWithIndex(id, Elements{ "0": Not(BeZero()), "1": MatchRegexp("[A-Z]: [a-z ]+"), "2": ContainSubstring("end"), })) // IndexIdentity is a helper function equivalent to id in this example Expect(actual).To(MatchAllElementsWithIndex(IndexIdentity, Elements{ "0": Not(BeZero()), "1": MatchRegexp("[A-Z]: [a-z ]+"), "2": ContainSubstring("end"), })) ``` The `WithIndex` variants take the same options as the other functions. ### Testing type `map` All of the `*Fields` functions and types have a corresponding definitions `*Keys` which can perform analogous tests against map types: ```go actual := map[string]string{ "A": "correct", "B": "incorrect", } // fails, because `actual` includes the key B Expect(actual).To(MatchAllKeys(Keys{ "A": Equal("correct"), })) // passes Expect(actual).To(MatchAllKeys(Keys{ "A": Equal("correct"), "B": Equal("incorrect"), })) // passes Expect(actual).To(MatchKeys(IgnoreMissing, Keys{ "A": Equal("correct"), "B": Equal("incorrect"), "C": Equal("whatever"), // ignored, because `actual` doesn't have this key })) ``` ### Testing pointer values `gstruct` provides the `PointTo` function to apply a matcher to the value pointed-to. It will fail if the pointer value is `nil`: foo := 5 Expect(&foo).To(PointTo(Equal(5))) var bar *int Expect(bar).NotTo(PointTo(BeNil())) ### Putting it all together: testing complex structures The `gstruct` matchers are intended to be composable, and can be combined to apply fuzzy-matching to large and deeply nested structures. The additional `Ignore()` and `Reject()` matchers are provided for ignoring (always succeed) fields and elements, or rejecting (always fail) fields and elements. Example: ```go coreID := func(element interface{}) string { return strconv.Itoa(element.(CoreStats).Index) } Expect(actual).To(MatchAllFields(Fields{ "Name": Ignore(), "StartTime": BeTemporally(">=", time.Now().Add(-100 * time.Hour)), "CPU": PointTo(MatchAllFields(Fields{ "Time": BeTemporally(">=", time.Now().Add(-time.Hour)), "UsageNanoCores": BeNumerically("~", 1E9, 1E8), "UsageCoreNanoSeconds": BeNumerically(">", 1E6), "Cores": MatchElements(coreID, IgnoreExtras, Elements{ "0": MatchAllFields(Fields{ Index: Ignore(), "UsageNanoCores": BeNumerically("<", 1E9), "UsageCoreNanoSeconds": BeNumerically(">", 1E5), }), "1": MatchAllFields(Fields{ Index: Ignore(), "UsageNanoCores": BeNumerically("<", 1E9), "UsageCoreNanoSeconds": BeNumerically(">", 1E5), }), }), })), "Memory": PointTo(MatchAllFields(Fields{ "Time": BeTemporally(">=", time.Now().Add(-time.Hour)), "AvailableBytes": BeZero(), "UsageBytes": BeNumerically(">", 5E6), "WorkingSetBytes": BeNumerically(">", 5E6), "RSSBytes": BeNumerically("<", 1E9), "PageFaults": BeNumerically("~", 1000, 100), "MajorPageFaults": BeNumerically("~", 100, 50), })), "Rootfs": m.Ignore(), "Logs": m.Ignore(), })) ``` ## `gmeasure`: Benchmarking Code `gmeasure` provides support for measuring and recording benchmarks of your code and tests. It can be used as a simple standalone benchmarking framework, or as part of your code's test suite. `gmeasure` integrates cleanly with Ginkgo V2 to enable rich benchmarking of code alongside your tests. ### A Mental Model for `gmeasure` `gmeasure` is organized around the metaphor of `Experiment`s that can each record multiple `Measurement`s. To use `gmeasure` you create a `NewExperiment` and use the resulting `experiment` object to record values and durations. You can then print out the `experiment` to get a report of all measurements or access specific measurements and their statistical aggregates to perform comparisons and/or make assertions. An `experiment` can record _multiple_ `Measurement`s. Each `Measurement` has a `Name`, a `Type` (either `MeasurementTypeDuration` or `MeasurementTypeValue`), and a collection of recorded data points (of type `float64` for Value measurements and `time.Duration` for Duration measurements). In this way an experiment might describe a system or context being measured and can contain multiple measurements - one for each aspect of the system in question. `Experiment`s can either record values and durations that the user passes in directly. Or they can invoke callbacks and accept their return values as Value data points, or measure their runtimes to compute Duration data points. `Experiment`s can also _sample_ callbacks, calling them repeatedly to get an ensemble of data points. A `Measurement` is created when its first data point is recorded by an `Experiment`. Subsequent data points with the same measurement name are appended to the measurement: ```go experiment := gmeasure.NewExperiment("My Experiment") experiment.RecordDuration("runtime", 3*time.Second) //creates a new Measurement called "runtime" experiment.RecordDuration("runtime", 5*time.Second) //appends a data point to "runtime" ``` As described below, Measurements can be decorated with additional information. This includes information about the `Units` for the measurement, the `Precision` with which to render the measurement, and any `Style` to apply when rendering the measurement. Individual data points can also be decorated with an `Annotation` - an arbitrary string that is associated with that data point and gives it context. Decorations are applied as typed variadic arguments: ```go experiment := gmeasure.NewExperiment("My Experiment") // The first call to `RecordValue` for a measurement must set up any units, style, or precision decorations experiment.RecordValue("length", 3.141, gmeasure.Units("inches"), gmeasure.Style("{{blue}}"), gmeasure.Precision(2), gmeasure.Annotation("box A)")) // Subsequent calls can attach an annotation. In this call a new data-point of `2.71` is added to the `length` measurement with the annotation `box B`. experiment.RecordValue("length", 2.71, gmeasure.Annotation("box B")) ``` Once recorded, `Measurements` can be fetched from the `experiment` by name via `experiment.Get("name")`. The returned `Measurement` object includes all the data points. To get a statistical summary of the data points (that includes the min, max, median, mean, and standard deviation) call `measurement.Stats()` or `experiment.GetStats("name")`. These statistical summaries can also be rank-ordered with `RankStats()`. `gmeasure` is designed to integrate with Ginkgo. This is done by registering `Experiment`s, `Measurement`s and `Ranking`s as `ReportEntry`s via Ginkgo's `AddReportEntry`. This will cause Ginkgo to emit nicely formatted and styled summaries of each of these objects when generating the test report. Finally, `gmeasure` provides a mechanism to cache `Experiment`s to disk with a specified version number. This enables multiple use-cases. You can cache expensive experiments to avoid rerunning them while you iterate on other experiments. You can also compare experiments to cached experiments to explore whether changes in performance have been introduced to the codebase under test. `gmeasure` includes detailed [godoc documentation](https://pkg.go.dev/github.com/onsi/gomega/gmeasure) - this narrative documentation is intended to help you get started with `gmeasure`. ### Measuring Values `Experiment`s can record arbitrary `float64` values. You can do this by directly providing a `float64` via `experiment.RecordValue(measurementName string, value float64, decorators ...interface{})` or by providing a callback that returns a float64 via `experiment.MeasureValue(measurementName string, callback func() float64, decorators ...interface{})`. You can apply `Units`, `Style`, and `Precision` decorators to control the appearance of the `Measurement` when reports are generated. These decorators must be applied when the first data point is recorded but can be elided thereafter. You can also associate an `Annotation` decoration with any recorded data point. `Experiment`s are thread-safe so you can call `RecordValue` and `MeasureValue` from any goroutine. ### Measuring Durations `Experiment`s can record arbitrary `time.Duration` durations. You can do this by directly providing a `time.Duration` via `experiment.RecordDuration(measurementName string, duration time.Duration, decorators ...interface{})` or by providing a callback via `experiment.MeasureDuration(measurementName string, callback func(), decorators ...interface{})`. `gmeasure` will run the callback and measure how long it takes to complete. You can apply `Style` and `Precision` decorators to control the appearance of the `Measurement` when reports are generated. These decorators must be applied when the first data point is recorded but can be elided thereafter. You can also associate an `Annotation` decoration with any recorded data point. `Experiment`s are thread-safe so you can call `RecordDuration` and `MeasureDuration` from any goroutine. ### Sampling `Experiment`s support sampling callback functions repeatedly to build an ensemble of data points. All the sampling methods are configured by passing in a `SamplingConfig`: ```go type SamplingConfig struct { N int Duration time.Duration NumParallel int MinSamplingInterval time.Duration } ``` Setting `SamplingConfig.N` limits the total number of samples to perform to `N`. Setting `SamplingConfig.Duration` limits the total time spent sampling to `Duration`. At least one of these fields must be set. If both are set then `gmeasure` will `sample` until the first limiting condition is met. Setting `SamplingConfig.MinSamplingInterval` causes `gmeasure` to wait until at least `MinSamplingInterval` has elapsed between subsequent samples. By default, the `Experiment`'s sampling methods will run their callbacks serially within the calling goroutine. If `NumParallel` greater than `1`, however, the sampling methods will spin up `NumParallel` goroutines and farm the work among them. You cannot use `NumParallel` with `MinSamplingInterval`. The basic sampling method is `experiment.Sample(callback func(idx int), samplingConfig SamplingConfig)`. This will call the callback function repeatedly, passing in an `idx` counter that increments between each call. The sampling will end based on the conditions provided in `SamplingConfig`. Note that `experiment.Sample` is not explicitly associated with a measurement. You can use `experiment.Sample` whenever you want to repeatedly invoke a callback up to a limit of `N` and/or `Duration`. You can then record arbitrarily many value or duration measurements in the body of the callback. A common use-case, however, is to invoke a callback repeatedly to measure its duration or record its returned value and thereby generate an ensemble of data-points. This is supported via the `SampleX` family of methods built on top of `Sample`: ```go experiment.SampleValue(measurementName string, callback func(idx int) float64, samplingConfig SamplingConfig, decorations ...interface{}) experiment.SampleDuration(measurementName string, callback func(idx int), samplingConfig SamplingConfig, decorations ...interface{}) experiment.SampleAnnotatedValue(measurementName string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, decorations ...interface{}) experiment.SampleAnnotatedDuration(measurementName string, callback func(idx int) Annotation, samplingConfig SamplingConfig, decorations ...interface{}) ``` each of these will contribute data points to the `Measurement` with name `measurementName`. `SampleValue` records the `float64` values returned by its callback. `SampleDuration` times each invocation of its callback and records the measured duration. `SampleAnnotatedValue` and `SampleAnnotatedDuration` expect their callbacks to return `Annotation`s. These are attached to each generated data point. All these methods take the same decorators as their corresponding `RecordX` methods. ### Measuring Durations with `Stopwatch` In addition to `RecordDuration` and `MeasureDuration`, `gmeasure` also provides a `Stopwatch`-based abstraction for recording durations. To motivate `Stopwatch` consider the following example. Let's say we want to measure the end-to-end performance of a web-server. Here's the code we'd like to measure: ```go It("measures the end-to-end performance of the web-server", func() { model, err := client.Fetch("model-id-17") Expect(err).NotTo(HaveOccurred()) err = model.ReticulateSpines() Expect(err).NotTo(HaveOccurred()) Expect(client.Save(model)).To(Succeed()) reticulatedModels, err := client.List("reticulated-models") Expect(err).NotTo(HaveOccurred()) Expect(reticulatedModels).To(ContainElement(model)) }) ``` One approach would be to use `MeasureDuration`: ```go It("measures the end-to-end performance of the web-server", func() { experiment := gmeasure.NewExperiment("end-to-end web-server performance") AddReportEntry(experiment.Name, experiment) var model Model var err error experiment.MeasureDuration("fetch", func() { model, err = client.Fetch("model-id-17") }) Expect(err).NotTo(HaveOccurred()) err = model.ReticulateSpines() Expect(err).NotTo(HaveOccurred()) experiment.MeasureDuration("save", func() { Expect(client.Save(model)).To(Succeed()) }) var reticulatedModels []Models experiment.MeasureDuration("list", func() { reticulatedModels, err = client.List("reticulated-models") }) Expect(err).NotTo(HaveOccurred()) Expect(reticulatedModels).To(ContainElement(model)) }) ``` this... _works_. But all those closures and local variables make the test a bit harder to read. We can clean it up with a `Stopwatch`: ```go It("measures the end-to-end performance of the web-server", func() { experiment := gmeasure.NewExperiment("end-to-end web-server performance") AddReportEntry(experiment.Name, experiment) stopwatch := experiment.NewStopwatch() // start the stopwatch model, err := client.Fetch("model-id-17") stopwatch.Record("fetch") // record the amount of time elapsed and store it in a Measurement named fetch Expect(err).NotTo(HaveOccurred()) err = model.ReticulateSpines() Expect(err).NotTo(HaveOccurred()) stopwatch.Reset() // reset the stopwatch Expect(client.Save(model)).To(Succeed()) stopwatch.Record("save").Reset() // record the amount of time elapsed since the last Reset and store it in a Measurement named save, then reset the stopwatch reticulatedModels, err := client.List("reticulated-models") stopwatch.Record("list") Expect(err).NotTo(HaveOccurred()) Expect(reticulatedModels).To(ContainElement(model)) }) ``` that's now much cleaner and easier to reason about. If we wanted to sample the server's performance concurrently we could now simply wrap the relevant code in an `experiment.Sample`: ```go It("measures the end-to-end performance of the web-server", func() { experiment := gmeasure.NewExperiment("end-to-end web-server performance") AddReportEntry(experiment.Name, experiment) experiment.Sample(func(idx int) { defer GinkgoRecover() // necessary since these will launch as goroutines and contain assertions stopwatch := experiment.NewStopwatch() // we make a new stopwatch for each sample. Experiments are threadsafe, but Stopwatches are not. model, err := client.Fetch("model-id-17") stopwatch.Record("fetch") Expect(err).NotTo(HaveOccurred()) err = model.ReticulateSpines() Expect(err).NotTo(HaveOccurred()) stopwatch.Reset() Expect(client.Save(model)).To(Succeed()) stopwatch.Record("save").Reset() reticulatedModels, err := client.List("reticulated-models") stopwatch.Record("list") Expect(err).NotTo(HaveOccurred()) Expect(reticulatedModels).To(ContainElement(model)) }, gmeasure.SamplingConfig{N:100, Duration:time.Minute, NumParallel:8}) }) ``` Check out the [godoc documentation](https://pkg.go.dev/github.com/onsi/gomega/gmeasure#Stopwatch) for more details about `Stopwatch` including support for `Pause`ing and `Resume`ing the stopwatch. ### Stats and Rankings: Comparing Measurements Once you've recorded a few measurements you'll want to try to understand and interpret them. `gmeasure` allows you to quickly compute statistics for a given measurement. Consider the following example. Let's say we have two different ideas for how to implement a sorting algorithm and want to hone in on the algorithm with the shortest median runtime. We could run an experiment: ```go It("identifies the fastest algorithm", func() { experiment := gmeasure.NewExperiment("dueling algorithms") AddReportEntry(experiment.Name, experiment) experiment.SampleDuration("runtime: algorithm 1", func(_ int) { RunAlgorithm1() }, gmeasure.SamplingConfig{N:1000}) experiment.SampleDuration("runtime: algorithm 2", func(_ int) { RunAlgorithm2() }, gmeasure.SamplingConfig{N:1000}) }) ``` This will sample the two competing tables and print out a tabular representation of the resulting statistics. (Note - you don't need to use Ginkgo here, you could just use `gmeasure` in your code directly and then `fmt.Println` the `experiment` to get the tabular report). We could compare the tables by eye manually - or ask `gmeasure` to pick the winning algorithm for us: ```go It("identifies the fastest algorithm", func() { experiment := gmeasure.NewExperiment("dueling algorithms") AddReportEntry(experiment.Name, experiment) experiment.SampleDuration("runtime: algorithm 1", func(_ int) { RunAlgorithm1() }, gmeasure.SamplingConfig{N:1000}) experiment.SampleDuration("runtime: algorithm 2", func(_ int) { RunAlgorithm2() }, gmeasure.SamplingConfig{N:1000}) ranking := gmeasure.RankStats(gmeasure.LowerMedianIsBetter, experiment.GetStats("runtime: algorithm 1"), experiment.GetStats("runtime: algorithm 2")) AddReportEntry("Ranking", ranking) }) ``` This will now emit a ranking result that will highlight the winning algorithm (in this case, the algorithm with the lower Median). `RankStats` supports the following `RankingCriteria`: - `LowerMeanIsBetter` - `HigherMeanIsBetter` - `LowerMedianIsBetter` - `HigherMedianIsBetter` - `LowerMinIsBetter` - `HigherMinIsBetter` - `LowerMaxIsBetter` - `HigherMaxIsBetter` We can also inspect the statistics of the two algorithms programmatically. `experiment.GetStats` returns a `Stats` object that provides access to the following `Stat`s: - `StatMin` - the data point with the smallest value - `StatMax` - the data point with the highest values - `StatMedian` - the median data point - `StatMean` - the mean of all the data points - `StatStdDev` - the standard deviation of all the data points `Stats` can represent either Value Measurements or Duration Measurements. When inspecting a Value Measurement you can pull out the requested `Stat` (say, `StatMedian`) via `stats.ValueFor(StatMedian)` - this returns a `float64`. When inspecting Duration Measurements you can fetch `time.Duration` statistics via `stats.DurationFor(StatX)`. For either type you can fetch an appropriately formatted string representation of the stat via `stats.StringFor(StatX)`. You can also get a `float64` for either type by calling `stats.FloatFor(StatX)` (this simply returns a `float64(time.Duration)` for Duration Measurements and can be useful when you need to do some math with the stats). Going back to our dueling algorithms example. Lets say we find that Algorithm 2 is the winner with a median runtime of around 3 seconds - and we want to be alerted by a failing test should the winner ever change, or the median runtime vary substantially. We can do that by writing a few assertions: ```go It("identifies the fastest algorithm", func() { experiment := gmeasure.NewExperiment("dueling algorithms") AddReportEntry(experiment.Name, experiment) experiment.SampleDuration("runtime: algorithm 1", func(_ int) { RunAlgorithm1() }, gmeasure.SamplingConfig{N:1000}) experiment.SampleDuration("runtime: algorithm 2", func(_ int) { RunAlgorithm2() }, gmeasure.SamplingConfig{N:1000}) ranking := gmeasure.RankStats(gmeasure.LowerMedianIsBetter, experiment.GetStats("runtime: algorithm 1"), experiment.GetStats("runtime: algorithm 2")) AddReportEntry("Ranking", ranking) //assert that algorithm 2 is the winner Expect(ranking.Winner().MeasurementName).To(Equal("runtime: algorithm 2")) //assert that algorithm 2's median is within 0.5 seconds of 3 seconds Expect(experiment.GetStats("runtime: algorithm 2").DurationFor(gmeasure.StatMedian)).To(BeNumerically("~", 3*time.Second, 500*time.Millisecond)) }) ``` ### Formatting Experiment and Measurement Output `gmeasure` can produce formatted tabular output for `Experiment`s, `Measurement`s, and `Ranking`s. Each of these objects provides a `String()` method and a `ColorableString()` method. The `String()` method returns a string that does not include any styling tags whereas the `ColorableString()` method returns a string that includes Ginkgo's console styling tags (e.g. Ginkgo will render a string like `{{blue}}{{bold}}hello{{/}} there` as a bold blue "hello" followed by a default-styled " there"). `ColorableString()` is called for you automatically when you register any of these `gmeasure` objects as Ginkgo `ReportEntry`s. When printing out `Experiment`s, `gmeasure` will produce a table whose columns correspond to the key statistics provided by `gmeasure.Stats` and whose rows are the various `Measurement`s recorded by the `Experiment`. Users can also record and emit notes - contextual information about the experiment - by calling `experiment.RecordNote(note string)`. Each note will get its own row in the table. When printing out `Measurement`s, `gmeasure` will produce a table that includes _all_ the data points and annotations for the `Measurement`. When printing out `Ranking`s, `gmeasure` will produce a table similar to the `Experiment` table with the `Measurement`s sorted by `RankingCriteria`. Users can adjust a few aspects of `gmeasure`s output. This is done by providing decorators to the `Experiment` methods that record data points: - `Units(string)` - the `Units` decorator allows you to associate a set of units with a measurement. Subsequent renderings of the measurement's name will include the units in `[]` square brackets. - `Precision(int or time.Duration)` - the `Precision` decorator controls the rendering of numerical information. For Value Measurements an `int` is used to express the number of decimal points to print. For example `Precision(3)` will render values with `fmt.Sprintf("%.3f", value)`. For Duration Measurements a `time.Duration` is used to round durations before rendering them. For example `Precision(time.Second)` will render durations via `duration.Round(time.Second).String()`. - `Style(string)` - the `Style` decorator allows you to associate a Ginkgo console style to a measurement. The measurement's row will be rendered with this style. For example `Style("{{green}}")` will emit a green row. These formatting decorators **must** be applied to the _first_ data point recorded for a given Measurement (this is when the Measurement object is initialized and its style, precision, and units fields are populated). Just to get concrete here's a fleshed out example that uses all the things: ```go It("explores a complex object", func() { experiment := gmeasure.NewExperiment("exploring the encabulator") AddReportEntry(experiment.Name, experiment) experiment.RecordNote("Encabulation Properties") experiment.Sample(func(idx int) { stopwatch := experiment.NewStopwatch() encabulator.Encabulate() stopwatch.Record("Encabulate Runtime", gmeasure.Style("{{green}}"), gmeasure.Precision(time.Millisecond)) var m runtime.MemStats runtime.ReadMemStats(&m) experiment.RecordValue("Encabulate Memory Usage", float64(m.Alloc / 1024 / 1024), gmeasure.Style("{{red}}"), gmeasure.Precision(3), gmeasure.Units("MB"), gmeasure.Annotation(fmt.Sprintf("%d", idx))) }, gmeasure.SamplingConfig{N:1000, NumParallel:4}) experiment.RecordNote("Encabulation Teardown") experiment.MeasureDuration("Teardown Runtime", func() { encabulator.Teardown() }, gmeasure.Style("{{yellow}}")) memoryStats := experiment.GetStats("Encabulate Memory Usage") minMemory := memoryStats.ValueFor(gmeasure.StatMin) maxMemory := memoryStats.ValueFor(gmeasure.StatMax) Expect(maxMemory - minMemory).To(BeNumerically("<=", 10), "Should not see memory fluctuations exceeding 10 megabytes") }) ``` ### Ginkgo Integration The examples throughout this documentation have illustrated how `gmeasure` interoperates with Ginkgo. In short - you can emit output for `Experiment`, `Measurement`s, and `Ranking`s by registering them as Ginkgo `ReportEntry`s via `AddReportEntry()`. This simple connection point ensures that the output is appropriately formatted and associated with the spec in question. It also ensures that Ginkgo's machine readable reports will include appropriately encoded versions of these `gmeasure` objects. So, for example, `ginkgo --json-report=report.json` will include JSON encoded `Experiment`s in `report.json` if you remember to `AddReportEntry` the `Experiment`s. ### Caching Experiments `gmeasure` supports caching experiments to local disk. Experiments can be stored and retrieved from the cache by name and version number. Caching allows you to skip rerunning expensive experiments and versioned caching allows you to bust the cache by incrementing the version number. Under the hood, the cache is simply a set of files in a directory. Each file contains a JSON encoded header with the experiment's name and version number followed by the JSON-encoded experiment. The various cache methods are documented over at [pkg.go.dev](https://pkg.go.dev/github.com/onsi/gomega/gmeasure#ExperimentCache). Using an `ExperimentCache` with Ginkgo takes a little bit of wiring. Here's an example: ```go const EXPERIMENT_VERSION = 1 //bump this to bust the cache and recompute _all_ experiments Describe("some experiments", func() { var cache gmeasure.ExperimentCache var experiment *gmeasure.Experiment BeforeEach(func() { cache = gmeasure.NewExperimentCache("./gmeasure-cache") name := CurrentSpecReport().LeafNodeText // we use the text in each It block as the name of the experiment experiment = cache.Load(name, EXPERIMENT_VERSION) // we try to load the experiment from the cache if experiment != nil { // we have a cache hit - report on the experiment and skip this test. AddReportEntry(experiment) Skip("cached") } //we have a cache miss, make a new experiment and proceed with the test. experiment = gmeasure.NewExperiment(name) AddReportEntry(experiment) }) It("measures foo runtime", func() { experiment.SampleDuration("runtime", func() { //do stuff }, gmeasure.SamplingConfig{N:100}) }) It("measures bar runtime", func() { experiment.SampleDuration("runtime", func() { //do stuff }, gmeasure.SamplingConfig{N:100}) }) AfterEach(func() { // AfterEaches always run, even for tests that call `Skip`. So we make sure we aren't a skipped test then save the experiment to the cache if !CurrentSpecReport().State.Is(types.SpecStateSkipped) { cache.Save(experiment.Name, EXPERIMENT_VERSION, experiment) } }) }) ``` this test will load the experiment from the cache if it's available or run the experiment and store it in the cache if it is not. Incrementing `EXPERIMENT_VERSION` will force all experiments to rerun. Another usecase for `ExperimentCache` is to cache and commit experiments to source control for use as future baselines. Your code can assert that measurements are within a certain range of the stored baseline. For example: ```go Describe("server performance", func() { It("ensures a performance regression has not been introduced", func() { // make an experiment experiment := gmeasure.NewExperiment("performance regression test") AddReportEntry(experiment.Name, experiment) // measure the performance of one endpoint experiment.SampleDuration("fetching one", func() { model, err := client.Get("id-1") Expect(err).NotTo(HaveOccurred()) Expect(model.Id).To(Equal("id-1")) }, gmeasure.SamplingConfig{N:100}) // measure the performance of another endpoint experiment.SampleDuration("listing", func() { models, err := client.List() Expect(err).NotTo(HaveOccurred()) Expect(models).To(HaveLen(30)) }, gmeasure.SamplingConfig{N:100}) cache := gmeasure.NewExperimentCache("./gemasure-cache") baseline := cache.Load("performance regression test", 1) if baseline == nil { // this is the first run, let's store a baseline cache.Save("performacne regression test", 1, experiment) } else { for _, m := range []string{"fetching one", "listing"} { baselineStats := baseline.GetStats(m) currentStats := experiment.GetStats(m) //make sure the mean of the current performance measure is within one standard deviation of the baseline Expect(currentStats.DurationFor(gmeasure.StatMean)).To(BeNumerically("~", baselineStats.DurationFor(gmeasure.StatsMean), baselineStats.DurationFor(gmeasure.StatsStdDev)), m) } } }) }) ``` ## `gleak`: Finding Leaked Goroutines ![Leakiee](./images/leakiee.png) The `gleak` package provides support for goroutine leak detection. > **Please note:** gleak is an experimental new Gomega package. ### Basics Calling `Goroutines` returns information about all goroutines of a program at this moment. `Goroutines` typically gets invoked in the form of `Eventually(Goroutines).ShouldNot(...)`. Please note the missing `()` after `Goroutines`, as it must be called by `Eventually` and **not before it** with its results passed to `Eventually` only once. This does not preclude calling `Goroutines()`, such as for taking goroutines snapshots. Leaked goroutines are then detected by using `gleak`'s `HaveLeaked` matcher on the goroutines information. `HaveLeaked` checks the actual list of goroutines against a built-in list of well-known runtime and testing framework goroutines, as well as against any optionally additional goroutines specifications passed to `HaveLeaked`. Good, and thus "non-leaky", Goroutines can be identified in multiple ways: such as by the name of a topmost function on a goroutine stack or a snapshot of goroutine information taken before a test. Non-leaky goroutines can also be identified using basically any Gomega matcher, with `HaveField` or `WithTransform` being highly useful in test-specific situations. The `HaveLeaked` matcher _succeeds_ if it finds any goroutines that are neither in the integrated list of well-known goroutines nor in the optionally specified `HaveLeaked` arguments. In consequence, any _success_ of `HaveLeaked` actually is meant to be a _failure_, because of leaked goroutines. `HaveLeaked` is thus mostly used in combination with `ShouldNot` and `NotTo`/`ToNot`. ### Testing for Goroutine Leaks In its most simple form, just run a goroutine discovery with a leak check right _after_ each test in `AfterEach`: > **Important:** always use `Goroutines` and not `Goroutines()` in the call to > `Eventually`. This ensures that the goroutine discovery is correctly done > repeatedly as needed and not just a single time before calling `Eventually`. ```go AfterEach(func() { Eventually(Goroutines).ShouldNot(HaveLeaked()) }) ``` Using `Eventually` instead of `Ω`/`Expect` has the benefit of retrying the leak check periodically until there is no leak or until a timeout occurs. This ensures that goroutines that are (still) in the process of winding down can correctly terminate without triggering false positives. Please refer to the [`Eventually`](#eventually) section for details on how to change the timeout interval (which defaults to 1s) and the polling interval (which defaults to 10ms). Please note that this simplest form of goroutine leak test can cause false positives in situations where a test suite or dependency module uses additional goroutines. This simple form only looks at all goroutines _after_ a test has run and filters out all _well-known_ "non-leaky" goroutines, such as goroutines from Go's runtime and the testing frameworks (such as Go's own testing package and Gomega). ### Ginkgo -p In case you intend to run multiple package tests in parallel using `ginkgo -p ...`, you'll need to update any existing `BeforeSuite` or add new `BeforeSuite`s in each of your packages. Calling `gleak.IgnoreGinkgoParallelClient` at the beginning of `BeforeSuite` ensures that `gleak` updates its internal ignore list to ignore a background goroutine related to the communication between Ginkgo and the parallel packages under test. ```go var _ = BeforeSuite(func() { IgnoreGinkgoParallelClient() }) ``` ### Using Goroutine Snapshots in Leak Testing Often, it might be sufficient to cover for additional "non-leaky" goroutines by taking a "snapshot" of goroutines _before_ a test and then _afterwards_ use the snapshot to filter out the supposedly "non-leaky" goroutines. Using Ginkgo's v2 `DeferCleanup` this can be expressed in a compact manner and without the need for explicitly declaring a variable to carry the list of known goroutines over from `BeforeEach` to `AfterEach`. This keeps all things declared neatly in a single place. ```go BeforeEach(func() { goods := Goroutines() DeferCleanup(func() { Eventually(Goroutines).ShouldNot(HaveLeaked(goods)) }) }) ``` ### `HaveLeaked` Matcher ```go Eventually(ACTUAL).ShouldNot(HaveLeaked(NONLEAKY1, NONLEAKY2, NONLEAKY3, ...)) ``` causes a test to fail if `ACTUAL` after filtering out the well-known "good" (and non-leaky) goroutines of the Go runtime and test frameworks, as well as filtering out the additional non-leaky goroutines passed to the matcher, still results in one or more goroutines. The ordering of the goroutines does not matter. `HaveLeaked` always takes the built-in list of well-known good goroutines into consideration and this list can neither be overridden nor disabled. Additional known non-leaky goroutines `NONLEAKY1`, ... can be passed to `HaveLeaks` either in form of `GomegaMatcher`s or in shorthand notation: - `"foo.bar"` is shorthand for `IgnoringTopFunction("foo.bar")` and filters out any (non-leaky) goroutine with its topmost function on the backtrace stack having the exact name `foo.bar`. - `"foo.bar..."` is shorthand for `IgnoringTopFunction("foo.bar...")` and filters out any (non-leaky) goroutine with its topmost function on the backtrace stack beginning with the prefix `foo.bar.`; please notice the trailing `.` dot. - `"foo.bar [chan receive]"` is shorthand for `IgnoringTopFunction("foo.bar [chan receive]")` and filters out any (non-leaky) goroutine where its topmost function on the backtrace stack has the exact name `foo.bar` _and_ the goroutine is in a state beginning with `chan receive`. - `[]Goroutine` is shorthand for `IgnoringGoroutines()`: it filters out the specified goroutines, considering them to be non-leaky. The goroutines are identified by their [goroutine IDs](#goroutine-ids). - `IgnoringInBacktrace("foo.bar.baz")` filters out any (non-leaky) goroutine with `foo.bar.baz` _anywhere_ in its backtrace. - additionally, any other `GomegaMatcher` can be passed to `HaveLeaked()`, as long as this matcher can work on a passed-in actual value of type `Goroutine`. ### Goroutine Matchers The `gleak` packages comes with a set of predefined Goroutine matchers, to be used with `HaveLeaked`. If these matchers succeed (that is, they match on a certain `Goroutine`), then `HaveLeaked` considers the matched goroutine to be non-leaky. #### IgnoringTopFunction(topfname string) ```go Eventually(ACTUAL).ShouldNot(HaveLeaked(IgnoringTopFunction(TOPFNAME))) ``` In its most basic form, `IgnoringTopFunction` succeeds if `ACTUAL` contains a goroutine where the name of the topmost function on its call stack (backtrace) is `TOPFNAME`, causing `HaveLeaked` to filter out the matched goroutine as non-leaky. Different forms of `TOPFNAME` describe different goroutine matching criteria: - `"foo.bar"` matches only if a goroutine's topmost function has this exact name (ignoring any function parameters). - `"foo.bar..."` matches if a goroutine's topmost function name starts with the prefix `"foo.bar."`; it doesn't match `"foo.bar"` though. - `"foo.bar [state]"` matches if a goroutine's topmost function has this exact name and the goroutine's state begins with the specified state string. `ACTUAL` must be an array or slice of `Goroutine`s. #### IgnoringGoroutines(goroutines []Goroutine) ```go Eventually(ACTUAL).ShouldNot(HaveLeaked(IgnoringGoroutines(GOROUTINES))) ``` `IgnoringGoroutines` succeeds if `ACTUAL` contains one or more goroutines which are elements of `GOROUTINES`, causing `HaveLeaked` to filter out the matched goroutine(s) as non-leaky. `IgnoringGoroutines` compares goroutines by their `ID`s (see [Goroutine IDs](#gorotuine-ids) for background information). `ACTUAL` must be an array or slice of `Goroutine`s. #### IgnoringInBacktrace(fname string) ```go Eventually(Goroutines).ShouldNot(HaveLeaked(IgnoringInBacktrace(FNAME))) ``` `IgnoringInBacktrace` succeeds if `ACTUAL` contains a goroutine where `FNAME` is contained anywhere within its call stack (backtrace), causing `HaveLeaked` to filter out the matched goroutine as non-leaky. Please note that `IgnoringInBacktrace` uses a (somewhat lazy) `strings.Contains` to check for any occurrence of `FNAME` in backtraces. `ACTUAL` must be an array or slice of `Goroutine`s. #### IgnoringCreator(creatorname string) ```go Eventually(Goroutines).ShouldNot(HaveLeaked(IgnoringCreator(CREATORNAME))) ``` In its most basic form, `IgnoringCreator` succeeds if `ACTUAL` contains a goroutine where the name of the function creating the goroutine matches `CREATORNAME`, causing `HaveLeaked` to filter out the matched goroutine(s) as non-leaky. `IgnoringCreator` uses `==` for comparing the creator function name. Different forms of `CREATORNAME` describe different goroutine matching criteria: - `"foo.bar"` matches only if a goroutine's creator function has this exact name (ignoring any function parameters). - `"foo.bar..."` matches if a goroutine's creator function name starts with the prefix `"foo.bar."`; it doesn't match `"foo.bar"` though. ### Adjusting Leaky Goroutine Reporting When `HaveLeaked` finds leaked goroutines, `gleak` prints out a description of (only) the _leaked_ goroutines. This is different from panic output that contains backtraces of all goroutines. However, `noleak`'s goroutine dump deliberately is not subject to Gomega's usual object rendition controls, such as `format.MaxLength` (see also [Adjusting Output](#adjusting-output)). `noleak` will print leaked goroutine backtraces in a more compact form, with function calls and locations combined into single lines. Additionally, `noleak` defaults to reporting only the package plus file name and line number, but not the full file path. For instance: main.foo.func1() at foo/bar.go:123 Setting `noleak.ReportFilenameWithPath` to `true` will instead report full source code file paths: main.foo.func1() at /home/coolprojects/ohmyleak/mymodule/foo/bar.go:123 ### Well-Known Non-Leaky Goroutines The well-known good (and therefore "non-leaky") goroutines are identified by the names of the topmost functions on their stacks (backtraces): - signal handling: - `os/signal.signal_recv` and `os/signal.loop` (covering varying state), - as well as `runtime.ensureSigM`. - Go's built-in [`testing`](https://pkg.go.dev/testing) framework: - `testing.RunTests [chan receive]`, - `testing.(*T).Run [chan receive]`, - and `testing.(*T).Parallel [chan receive]`. - the [Ginkgo testing framework](https://onsi.github.io/ginkgo/): - `github.com/onsi/ginkgo/v2/internal.(*Suite).runNode` (including anonymous inner functions), - the anonymous inner functions of `github.com/onsi/ginkgo/v2/internal/interrupt_handler.(*InterruptHandler).registerForInterrupts`, - the creators `github.com/onsi/ginkgo/v2/internal.(*genericOutputInterceptor).ResumeIntercepting` and `github.com/onsi/ginkgo/v2/internal.(*genericOutputInterceptor).ResumeIntercepting...`, - the creator `github.com/onsi/ginkgo/v2/internal.RegisterForProgressSignal`, - and finally `github.com/onsi/ginkgo/internal/specrunner.(*SpecRunner).registerForInterrupts` (for v1 support). Additionally, any goroutines with `runtime.ReadTrace` in their backtrace stack are also considered to be non-leaky. ### Goroutine IDs In order to detect goroutine identities, we use what is generally termed "goroutine IDs". These IDs appear in runtime stack dumps ("backtrace"). But … are these goroutine IDs even unambiguous? What are their "guarantees", if there are any at all? First, Go's runtime code uses the identifier (and thus term) [`goid` for Goroutine IDs](https://github.com/golang/go/search?q=goidgen&unscoped_q=goidgen). Good to know in case you need to find your way around Go's runtime code. Now, based on [Go's `goid` runtime allocation code](https://github.com/golang/go/blob/release-branch.go1.18/src/runtime/proc.go#L4130), goroutine IDs never get reused – unless you manage to make the 64bit "master counter" of the Go runtime scheduler to wrap around. However, not all goroutine IDs up to the largest one currently seen might ever be used, because as an optimization goroutine IDs are always assigned to Go's "P" processors for assignment to newly created "G" goroutines in batches of 16. In consequence, there may be gaps and later goroutines might have lower goroutine IDs if they get created from a different P. Finally, there's [Scott Mansfield's blog post on Goroutine IDs](https://blog.sgmansfield.com/2015/12/goroutine-ids/). To sum up Scott's point of view: don't use goroutine IDs. He spells out good reasons for why you should not use them. Yet, logging, debugging and testing looks like a sane and solid exemption from his rule, not least `runtime.Stack` includes the `goids` for some reason. ### Credits The _Leakiee the gopher_ mascot clearly has been inspired by the Go gopher art work of [Renee French](http://reneefrench.blogspot.com/). The `gleak` package was heavily inspired by Uber's fine [goleak](https://github.com/uber-go/goleak) goroutine leak detector package. While `goleak` can be used with Gomega and Ginkgo in a very specific form, it unfortunately was never designed to be (optionally) used with a matcher library to unlock the full potential of reasoning about leaky goroutines. In fact, the crucial element of discovering goroutines is kept internal in `goleak`. In consequence, Gomega's `gleak` package uses its own goroutine discovery and is explicitly designed to perfectly blend in with Gomega (and Ginkgo). {% endraw %} golang-gomega-1.36.2/docs/js/000077500000000000000000000000001476141007200156555ustar00rootroot00000000000000golang-gomega-1.36.2/docs/js/docs.js000066400000000000000000000042561476141007200171520ustar00rootroot00000000000000(() => { let sidebar = document.getElementById("sidebar") let headings = document.querySelectorAll("#content h2,h3") let headingsLookup = {} let currentHeadingGroup = null let collapsibleGroup = null for (let heading of headings) { let el = document.createElement("a") el.href = `#${heading.id}` el.id = `${heading.id}-item` el.innerText = heading.innerText if (heading.tagName == "H2") { currentHeadingGroup = heading.id el.classList = "sidebar-heading" sidebar.appendChild(el) collapsibleGroup = document.createElement("div") collapsibleGroup.classList = "sidebar-section" sidebar.appendChild(collapsibleGroup) } else { el.classList = "sidebar-item" collapsibleGroup.appendChild(el) } headingsLookup[heading.id] = currentHeadingGroup } let ticking = false; document.getElementById("content").addEventListener("scroll", (e) => { if (!ticking) { window.requestAnimationFrame(function () { let viewportHeight = window.visualViewport.height; let winner = null; for (let heading of headings) { let rect = heading.getBoundingClientRect(); if (rect.top > viewportHeight) { break } winner = heading.id if (rect.top > 0) { break } } if (winner != null) { document.querySelectorAll("#sidebar .active").forEach(e => e.classList.remove("active")) document.getElementById(`${winner}-item`).classList.add("active") document.getElementById(`${headingsLookup[winner]}-item`).classList.add("active"); } ticking = false; }); ticking = true; } }) document.querySelector("img[alt=Gomega]").id = "top" document.querySelectorAll("div.highlight").forEach(el => { if (el.innerText.includes("/* === INVALID === */")) { el.classList.add("invalid") } }) document.getElementById("disclosure").addEventListener("click", (e) => { document.getElementById("container").classList.toggle("reveal-sidebar") }) document.getElementById("mask").addEventListener("click", (e) => { document.getElementById("container").classList.toggle("reveal-sidebar") }) })() golang-gomega-1.36.2/format/000077500000000000000000000000001476141007200156015ustar00rootroot00000000000000golang-gomega-1.36.2/format/format.go000066400000000000000000000350611476141007200174250ustar00rootroot00000000000000/* Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information. */ // untested sections: 4 package format import ( "context" "fmt" "reflect" "strconv" "strings" "time" ) // Use MaxDepth to set the maximum recursion depth when printing deeply nested objects var MaxDepth = uint(10) // MaxLength of the string representation of an object. // If MaxLength is set to 0, the Object will not be truncated. var MaxLength = 4000 /* By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output. Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead. Note that GoString and String don't always have all the information you need to understand why a test failed! */ var UseStringerRepresentation = false /* Print the content of context objects. By default it will be suppressed. Set PrintContextObjects = true to enable printing of the context internals. */ var PrintContextObjects = false // TruncatedDiff choose if we should display a truncated pretty diff or not var TruncatedDiff = true // TruncateThreshold (default 50) specifies the maximum length string to print in string comparison assertion error // messages. var TruncateThreshold uint = 50 // CharactersAroundMismatchToInclude (default 5) specifies how many contextual characters should be printed before and // after the first diff location in a truncated string assertion error message. var CharactersAroundMismatchToInclude uint = 5 var contextType = reflect.TypeOf((*context.Context)(nil)).Elem() var timeType = reflect.TypeOf(time.Time{}) // The default indentation string emitted by the format package var Indent = " " var longFormThreshold = 20 // GomegaStringer allows for custom formating of objects for gomega. type GomegaStringer interface { // GomegaString will be used to custom format an object. // It does not follow UseStringerRepresentation value and will always be called regardless. // It also ignores the MaxLength value. 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: Expected If expected is omitted, then the message looks like: Expected */ func Message(actual interface{}, message string, expected ...interface{}) string { if len(expected) == 0 { return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) } return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) } /* Generates a nicely formatted matcher success / failure message Much like Message(...), but it attempts to pretty print diffs in strings Expected : "...aaaaabaaaaa..." to equal | : "...aaaaazaaaaa..." */ func MessageWithDiff(actual, message, expected string) string { if TruncatedDiff && len(actual) >= int(TruncateThreshold) && len(expected) >= int(TruncateThreshold) { diffPoint := findFirstMismatch(actual, expected) formattedActual := truncateAndFormat(actual, diffPoint) formattedExpected := truncateAndFormat(expected, diffPoint) spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected) tabLength := 4 spaceFromMessageToActual := tabLength + len(": ") - len(message) paddingCount := spaceFromMessageToActual + spacesBeforeFormattedMismatch if paddingCount < 0 { return Message(formattedActual, message, formattedExpected) } padding := strings.Repeat(" ", paddingCount) + "|" return Message(formattedActual, message+padding, formattedExpected) } actual = escapedWithGoSyntax(actual) expected = escapedWithGoSyntax(expected) return Message(actual, message, expected) } func escapedWithGoSyntax(str string) string { withQuotes := fmt.Sprintf("%q", str) return withQuotes[1 : len(withQuotes)-1] } func truncateAndFormat(str string, index int) string { leftPadding := `...` rightPadding := `...` start := index - int(CharactersAroundMismatchToInclude) if start < 0 { start = 0 leftPadding = "" } // slice index must include the mis-matched character lengthOfMismatchedCharacter := 1 end := index + int(CharactersAroundMismatchToInclude) + lengthOfMismatchedCharacter if end > len(str) { end = len(str) rightPadding = "" } return fmt.Sprintf("\"%s\"", leftPadding+str[start:end]+rightPadding) } func findFirstMismatch(a, b string) int { aSlice := strings.Split(a, "") bSlice := strings.Split(b, "") for index, str := range aSlice { if index > len(bSlice)-1 { return index } if str != bSlice[index] { return index } } if len(b) > len(a) { return len(a) + 1 } return 0 } const truncateHelpText = ` Gomega truncated this representation as it exceeds 'format.MaxLength'. Consider having the object provide a custom 'GomegaStringer' representation or adjust the parameters in Gomega's 'format' package. Learn more here: https://onsi.github.io/gomega/#adjusting-output ` func truncateLongStrings(s string) string { if MaxLength > 0 && len(s) > MaxLength { var sb strings.Builder for i, r := range s { if i < MaxLength { sb.WriteRune(r) continue } break } sb.WriteString("...\n") sb.WriteString(truncateHelpText) return sb.String() } return s } /* Pretty prints the passed in object at the passed in indentation level. Object recurses into deeply nested objects emitting pretty-printed representations of their components. Modify format.MaxDepth to control how deep the recursion is allowed to go Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of recursing into the object. Set PrintContextObjects to true to print the content of objects implementing context.Context */ func Object(object interface{}, indentation uint) string { indent := strings.Repeat(Indent, int(indentation)) value := reflect.ValueOf(object) commonRepresentation := "" if err, ok := object.(error); ok && !isNilValue(value) { // isNilValue check needed here to avoid nil deref due to boxed nil commonRepresentation += "\n" + IndentString(err.Error(), indentation) + "\n" + indent } return fmt.Sprintf("%s<%s>: %s%s", indent, formatType(value), commonRepresentation, formatValue(value, indentation)) } /* 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") indent := strings.Repeat(Indent, int(indentation)) for i, component := range components { if i > 0 || indentFirstLine { result.WriteString(indent) } result.WriteString(component) if i < len(components)-1 { result.WriteString("\n") } } return result.String() } func formatType(v reflect.Value) string { switch v.Kind() { case reflect.Invalid: return "nil" case reflect.Chan: return fmt.Sprintf("%s | len:%d, cap:%d", v.Type(), v.Len(), v.Cap()) case reflect.Ptr: return fmt.Sprintf("%s | 0x%x", v.Type(), v.Pointer()) case reflect.Slice: return fmt.Sprintf("%s | len:%d, cap:%d", v.Type(), v.Len(), v.Cap()) case reflect.Map: return fmt.Sprintf("%s | len:%d", v.Type(), v.Len()) default: return v.Type().String() } } func formatValue(value reflect.Value, indentation uint) string { if indentation > MaxDepth { return "..." } if isNilValue(value) { return "nil" } 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 indentString(x.GomegaString(), indentation+1, false) } if UseStringerRepresentation { switch x := obj.(type) { case fmt.GoStringer: return indentString(truncateLongStrings(x.GoString()), indentation+1, false) case fmt.Stringer: return indentString(truncateLongStrings(x.String()), indentation+1, false) } } } if !PrintContextObjects { if value.Type().Implements(contextType) && indentation > 1 { return "" } } switch value.Kind() { case reflect.Bool: return fmt.Sprintf("%v", value.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return fmt.Sprintf("%v", value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return fmt.Sprintf("%v", value.Uint()) case reflect.Uintptr: return fmt.Sprintf("0x%x", value.Uint()) case reflect.Float32, reflect.Float64: return fmt.Sprintf("%v", value.Float()) case reflect.Complex64, reflect.Complex128: return fmt.Sprintf("%v", value.Complex()) case reflect.Chan: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Func: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Ptr: return formatValue(value.Elem(), indentation) case reflect.Slice: return truncateLongStrings(formatSlice(value, indentation)) case reflect.String: return truncateLongStrings(formatString(value.String(), indentation)) case reflect.Array: return truncateLongStrings(formatSlice(value, indentation)) case reflect.Map: return truncateLongStrings(formatMap(value, indentation)) case reflect.Struct: if value.Type() == timeType && value.CanInterface() { t, _ := value.Interface().(time.Time) return t.Format(time.RFC3339Nano) } return truncateLongStrings(formatStruct(value, indentation)) case reflect.Interface: return formatInterface(value, indentation) default: if value.CanInterface() { return truncateLongStrings(fmt.Sprintf("%#v", value.Interface())) } return truncateLongStrings(fmt.Sprintf("%#v", value)) } } func formatString(object interface{}, indentation uint) string { if indentation == 1 { s := fmt.Sprintf("%s", object) components := strings.Split(s, "\n") result := "" for i, component := range components { if i == 0 { result += component } else { result += Indent + component } if i < len(components)-1 { result += "\n" } } return result } else { return fmt.Sprintf("%q", object) } } func formatSlice(v reflect.Value, indentation uint) string { if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && isPrintableString(string(v.Bytes())) { return formatString(v.Bytes(), indentation) } l := v.Len() result := make([]string, l) longest := 0 for i := 0; i < l; i++ { result[i] = formatValue(v.Index(i), indentation+1) if len(result[i]) > longest { longest = len(result[i]) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("[%s]", strings.Join(result, ", ")) } func formatMap(v reflect.Value, indentation uint) string { l := v.Len() result := make([]string, l) longest := 0 for i, key := range v.MapKeys() { value := v.MapIndex(key) result[i] = fmt.Sprintf("%s: %s", formatValue(key, indentation+1), formatValue(value, indentation+1)) if len(result[i]) > longest { longest = len(result[i]) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("{%s}", strings.Join(result, ", ")) } func formatStruct(v reflect.Value, indentation uint) string { t := v.Type() l := v.NumField() result := []string{} longest := 0 for i := 0; i < l; i++ { structField := t.Field(i) fieldEntry := v.Field(i) representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1)) result = append(result, representation) if len(representation) > longest { longest = len(representation) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("{%s}", strings.Join(result, ", ")) } func formatInterface(v reflect.Value, indentation uint) string { return fmt.Sprintf("<%s>%s", formatType(v.Elem()), formatValue(v.Elem(), indentation)) } func isNilValue(a reflect.Value) bool { switch a.Kind() { case reflect.Invalid: return true case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return a.IsNil() } return false } /* Returns true when the string is entirely made of printable runes, false otherwise. */ func isPrintableString(str string) bool { for _, runeValue := range str { if !strconv.IsPrint(runeValue) { return false } } return true } golang-gomega-1.36.2/format/format_suite_test.go000066400000000000000000000003021476141007200216630ustar00rootroot00000000000000package format_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "testing" ) func TestFormat(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Format Suite") } golang-gomega-1.36.2/format/format_test.go000066400000000000000000000735721476141007200204750ustar00rootroot00000000000000package format_test import ( "context" "fmt" "strings" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) //recursive struct const truncateHelpText = ` Gomega truncated this representation as it exceeds 'format.MaxLength'. Consider having the object provide a custom 'GomegaStringer' representation or adjust the parameters in Gomega's 'format' package. Learn more here: https://onsi.github.io/gomega/#adjusting-output ` type StringAlias string type ByteAlias []byte type IntAlias int type AStruct struct { Exported string } type SimpleStruct struct { Name string Enumeration int Veritas bool Data []byte secret uint32 } type ComplexStruct struct { Strings []string SimpleThings []*SimpleStruct DataMaps map[int]ByteAlias } type SecretiveStruct struct { boolValue bool intValue int uintValue uint uintptrValue uintptr floatValue float32 complexValue complex64 chanValue chan bool funcValue func() pointerValue *int sliceValue []string byteSliceValue []byte stringValue string arrValue [3]int byteArrValue [3]byte mapValue map[string]int structValue AStruct interfaceValue interface{} } type CustomFormatted struct { Data string Count int } type NotCustomFormatted struct { Data string Count int } type CustomError struct { Details string } var _ error = &CustomError{} func (c *CustomError) Error() string { return c.Details } func customFormatter(obj interface{}) (string, bool) { cf, ok := obj.(CustomFormatted) if !ok { return "", false } return fmt.Sprintf("%s (%d)", cf.Data, cf.Count), true } type GoStringer struct { } func (g GoStringer) GoString() string { return "go-string" } func (g GoStringer) String() string { return "string" } type Stringer struct { } func (g Stringer) String() string { return "string" } type gomegaStringer struct { } func (g gomegaStringer) GomegaString() string { return "gomegastring" } type gomegaStringerLong struct { } func (g gomegaStringerLong) GomegaString() string { return strings.Repeat("s", MaxLength*2) } type gomegaStringerMultiline struct { } func (g gomegaStringerMultiline) GomegaString() string { return "A\nB\nC" } var _ = Describe("Format", func() { match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { if len(args) > 0 { valueRepresentation = fmt.Sprintf(valueRepresentation, args...) } return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) } matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { if len(args) > 0 { valueRepresentation = fmt.Sprintf(valueRepresentation, args...) } return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) } hashMatchingRegexp := func(entries ...string) string { entriesSwitch := "(" + strings.Join(entries, "|") + ")" arr := make([]string, len(entries)) for i := range arr { arr[i] = entriesSwitch } return "{\\s*" + strings.Join(arr, ",\\s* ") + ",?\\s*}" } Describe("Message", func() { Context("with only an actual value", func() { BeforeEach(func() { MaxLength = 4000 }) It("should print out an indented formatted representation of the value and the message", func() { Expect(Message(3, "to be three.")).Should(Equal("Expected\n : 3\nto be three.")) }) It("should print out an indented formatted representation of the value and the message, and trucate it when too long", func() { tooLong := strings.Repeat("s", MaxLength+1) tooLongResult := strings.Repeat("s", MaxLength) + "...\n" + truncateHelpText Expect(Message(tooLong, "to be truncated")).Should(Equal("Expected\n : " + tooLongResult + "\nto be truncated")) }) It("should print out an indented formatted representation of the value and the message, and not trucate it when MaxLength = 0", func() { MaxLength = 0 tooLong := strings.Repeat("s", MaxLength+1) Expect(Message(tooLong, "to be truncated")).Should(Equal("Expected\n : " + tooLong + "\nto be truncated")) }) }) Context("with an actual and an expected value", func() { It("should print out an indented formatted representatino of both values, and the message", func() { Expect(Message(3, "to equal", 4)).Should(Equal("Expected\n : 3\nto equal\n : 4")) }) }) }) Describe("MessageWithDiff", func() { It("shows the exact point where two long strings differ", func() { stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedLongStringFailureMessage)) }) It("truncates the start of long strings that differ only at their end", func() { stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedStartStringFailureMessage)) }) It("truncates the start of long strings that differ only in length", func() { smallString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" largeString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(largeString, "to equal", smallString)).Should(Equal(expectedTruncatedStartSizeFailureMessage)) Expect(MessageWithDiff(smallString, "to equal", largeString)).Should(Equal(expectedTruncatedStartSizeSwappedFailureMessage)) }) It("truncates the end of long strings that differ only at their start", func() { stringWithB := "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stringWithZ := "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedEndStringFailureMessage)) }) It("handles multi-byte sequences correctly", func() { stringA := "• abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1" stringB := "• abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" Expect(MessageWithDiff(stringA, "to equal", stringB)).Should(Equal(expectedTruncatedMultiByteFailureMessage)) }) It("prints special characters", func() { stringA := "\n" stringB := "something_else" Expect(MessageWithDiff(stringA, "to equal", stringB)).Should(Equal(expectedSpecialCharacterFailureMessage)) }) It("handles negative padding length", func() { stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" longMessage := "to equal very long message" Expect(MessageWithDiff(stringWithB, longMessage, stringWithZ)).Should(Equal(expectedDiffLongMessage)) }) Context("With truncated diff disabled", func() { BeforeEach(func() { TruncatedDiff = false }) AfterEach(func() { TruncatedDiff = true }) It("should show the full diff", func() { stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedFullFailureDiff)) }) }) Context("With alternate diff lengths", func() { initialValue := TruncateThreshold // 50 by default BeforeEach(func() { TruncateThreshold = 10000 }) AfterEach(func() { TruncateThreshold = initialValue }) It("should show the full diff when truncate threshold is increased beyond length of strings", func() { stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedFullFailureDiff)) }) }) Context("with alternative number of characters to include around mismatch", func() { initialValue := CharactersAroundMismatchToInclude // 5 by default BeforeEach(func() { CharactersAroundMismatchToInclude = 10 }) AfterEach(func() { CharactersAroundMismatchToInclude = initialValue }) It("it shows more characters around a line length mismatch", func() { smallString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" largeString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Expect(MessageWithDiff(largeString, "to equal", smallString)).Should(Equal(expectedTruncatedStartSizeFailureMessageExtraDiff)) Expect(MessageWithDiff(smallString, "to equal", largeString)).Should(Equal(expectedTruncatedStartSizeSwappedFailureMessageExtraDiff)) }) }) Describe("At extremes of configurable values", func() { Context("with zero-length threshold", func() { initialValue := TruncateThreshold // 50 by default BeforeEach(func() { TruncateThreshold = 0 }) AfterEach(func() { TruncateThreshold = initialValue }) It("should show the full diff when truncate threshold is increased beyond length of strings", func() { stringWithB := "aba" stringWithZ := "aza" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedDiffSmallThreshold)) }) }) Context("with zero characters around mismatch", func() { initialValue := CharactersAroundMismatchToInclude // 5 by default BeforeEach(func() { CharactersAroundMismatchToInclude = 0 }) AfterEach(func() { CharactersAroundMismatchToInclude = initialValue }) It("", func() { stringWithB := "aba" stringWithZ := "aza" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedDiffZeroMismatch)) }) }) Context("with zero-length threshold and zero characters around mismatch", func() { initialCharactersAroundMismatch := CharactersAroundMismatchToInclude initialTruncateThreshold := TruncateThreshold BeforeEach(func() { CharactersAroundMismatchToInclude = 0 TruncateThreshold = 0 }) AfterEach(func() { CharactersAroundMismatchToInclude = initialCharactersAroundMismatch TruncateThreshold = initialTruncateThreshold }) It("", func() { stringWithB := "aba" stringWithZ := "aza" Expect(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedDiffSmallThresholdZeroMismatch)) }) }) }) }) Describe("IndentString", func() { It("should indent the string", func() { Expect(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz")) }) }) Describe("Object", func() { Describe("formatting boolean values", func() { It("should give the type and format values correctly", func() { Expect(Object(true, 1)).Should(match("bool", "true")) Expect(Object(false, 1)).Should(match("bool", "false")) }) }) Describe("formatting numbers", func() { It("should give the type and format values correctly", func() { Expect(Object(int(3), 1)).Should(match("int", "3")) Expect(Object(int8(3), 1)).Should(match("int8", "3")) Expect(Object(int16(3), 1)).Should(match("int16", "3")) Expect(Object(int32(3), 1)).Should(match("int32", "3")) Expect(Object(int64(3), 1)).Should(match("int64", "3")) Expect(Object(uint(3), 1)).Should(match("uint", "3")) Expect(Object(uint8(3), 1)).Should(match("uint8", "3")) Expect(Object(uint16(3), 1)).Should(match("uint16", "3")) Expect(Object(uint32(3), 1)).Should(match("uint32", "3")) Expect(Object(uint64(3), 1)).Should(match("uint64", "3")) }) It("should handle uintptr differently", func() { Expect(Object(uintptr(3), 1)).Should(match("uintptr", "0x3")) }) }) Describe("formatting channels", func() { It("should give the type and format values correctly", func() { c := make(chan<- bool, 3) c <- true c <- false Expect(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c)) }) }) Describe("formatting strings", func() { It("should give the type and format values correctly", func() { s := "a\nb\nc" Expect(Object(s, 1)).Should(match("string", `a b c`)) }) }) Describe("formatting []byte slices", func() { When("the slice is made of printable bytes", func() { It("should present it as string", func() { b := []byte("a b c") Expect(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a b c`)) }) }) When("the slice contains non-printable bytes", func() { It("should present it as slice", func() { b := []byte("a b c\n\x01\x02\x03\xff\x1bH") Expect(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:12, cap:\d+`, `\[97, 32, 98, 32, 99, 10, 1, 2, 3, 255, 27, 72\]`)) }) }) }) Describe("formatting functions", func() { It("should give the type and format values correctly", func() { f := func(a string, b []int) ([]byte, error) { return []byte("abc"), nil } Expect(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f)) }) }) Describe("formatting pointers", func() { It("should give the type and dereference the value to format it correctly", func() { a := 3 Expect(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3")) }) When("there are pointers to pointers...", func() { It("should recursively deference the pointer until it gets to a value", func() { a := 3 var b *int var c **int var d ***int b = &a c = &b d = &c Expect(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3")) }) }) When("the pointer points to nil", func() { It("should say nil and not explode", func() { var a *AStruct Expect(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) }) }) }) Describe("formatting arrays", func() { It("should give the type and format values correctly", func() { w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"} Expect(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`)) }) Context("with byte arrays", func() { It("should give the type and format values correctly", func() { w := [3]byte{17, 28, 19} Expect(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`)) }) }) }) Describe("formatting slices", func() { It("should include the length and capacity in the type information", func() { s := make([]bool, 3, 4) Expect(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]")) }) When("the slice contains long entries", func() { It("should format the entries with newlines", func() { w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"} expected := `[ "Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg", ]` Expect(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected)) }) }) }) Describe("formatting maps", func() { It("should include the length in the type information", func() { m := make(map[int]bool, 5) m[3] = true m[4] = false Expect(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false"))) }) When("the slice contains long entries", func() { It("should format the entries with newlines", func() { m := map[string][]byte{} m["Josiah Edward Bartlet"] = []byte("Martin Sheen") m["Toby Ziegler"] = []byte("Richard Schiff") m["CJ Cregg"] = []byte("Allison Janney") expected := `{ ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), }` Expect(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected)) }) }) }) Describe("formatting structs", func() { It("should include the struct name and the field names", func() { s := SimpleStruct{ Name: "Oswald", Enumeration: 17, Veritas: true, Data: []byte("datum"), secret: 1983, } Expect(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`)) }) When("the struct contains long entries", func() { It("should format the entries with new lines", func() { s := &SimpleStruct{ Name: "Mithrandir Gandalf Greyhame", Enumeration: 2021, Veritas: true, Data: []byte("wizard"), secret: 3, } Expect(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{ Name: "Mithrandir Gandalf Greyhame", Enumeration: 2021, Veritas: true, Data: "wizard", secret: 3, }`)) }) }) }) Describe("formatting nil values", func() { It("should print out nil", func() { Expect(Object(nil, 1)).Should(match("nil", "nil")) var typedNil *AStruct Expect(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) var c chan<- bool Expect(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil")) var s []string Expect(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil")) var m map[string]bool Expect(Object(m, 1)).Should(match("map[string]bool | len:0", "nil")) }) }) Describe("formatting aliased types", func() { It("should print out the correct alias type", func() { Expect(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`)) Expect(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`)) Expect(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3")) }) }) Describe("handling nested things", func() { It("should produce a correctly nested representation", func() { s := ComplexStruct{ Strings: []string{"lots", "of", "short", "strings"}, SimpleThings: []*SimpleStruct{ {"short", 7, true, []byte("succinct"), 17}, {"something longer", 427, true, []byte("designed to wrap around nicely"), 30}, }, DataMaps: map[int]ByteAlias{ 17: ByteAlias("some substantially longer chunks of data"), 1138: ByteAlias("that should make things wrap"), }, } expected := `{ Strings: \["lots", "of", "short", "strings"\], SimpleThings: \[ {Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17}, { Name: "something longer", Enumeration: 427, Veritas: true, Data: "designed to wrap around nicely", secret: 30, }, \], DataMaps: { (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), }, }` Expect(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected)) }) }) Describe("formatting nested interface{} types", func() { It("should print out the types of the container and value", func() { Expect(Object([]interface{}{"foo"}, 1)). To(match("[]interface {} | len:1, cap:1", `["foo"]`)) Expect(Object(map[string]interface{}{"foo": true}, 1)). To(match("map[string]interface {} | len:1", `{"foo": true}`)) Expect(Object(struct{ A interface{} }{A: 1}, 1)). To(match("struct { A interface {} }", "{A: 1}")) v := struct{ A interface{} }{A: struct{ B string }{B: "foo"}} Expect(Object(v, 1)).To(match(`struct { A interface {} }`, `{ A: {B: "foo"}, }`)) }) }) Describe("formatting times", func() { It("should format time as RFC3339", func() { t := time.Date(2016, 10, 31, 9, 57, 23, 12345, time.UTC) Expect(Object(t, 1)).Should(match("time.Time", `2016-10-31T09:57:23.000012345Z`)) }) }) Describe("formatting errors", func() { It("should include the error() representation", func() { err := fmt.Errorf("whoops: %w", fmt.Errorf("welp: %w", fmt.Errorf("ruh roh"))) Expect(Object(err, 1)).Should(MatchRegexp(` \<\*fmt\.wrapError \| 0x[0-9a-f]*\>\: whoops\: welp\: ruh roh \{ msg\: "whoops\: welp\: ruh roh", err\: \<\*fmt.wrapError \| 0x[0-9a-f]*\>\{ msg\: "welp\: ruh roh", err\: \<\*errors.errorString \| 0x[0-9a-f]*\>\{s\: "ruh roh"\}, \}, \}`)) }) It("should not panic if the error is a boxed nil", func() { var err *CustomError Expect(Object(err, 1)).Should(Equal(" <*format_test.CustomError | 0x0>: nil")) }) }) }) Describe("Handling unexported fields in structs", func() { It("should handle all the various types correctly", func() { a := int(5) s := SecretiveStruct{ boolValue: true, intValue: 3, uintValue: 4, uintptrValue: 5, floatValue: 6.0, complexValue: complex(5.0, 3.0), chanValue: make(chan bool, 2), funcValue: func() {}, pointerValue: &a, sliceValue: []string{"string", "slice"}, byteSliceValue: []byte("bytes"), stringValue: "a string", arrValue: [3]int{11, 12, 13}, byteArrValue: [3]byte{17, 20, 32}, mapValue: map[string]int{"a key": 20, "b key": 30}, structValue: AStruct{"exported"}, interfaceValue: map[string]int{"a key": 17}, } expected := fmt.Sprintf(`{ boolValue: true, intValue: 3, uintValue: 4, uintptrValue: 0x5, floatValue: 6, complexValue: \(5\+3i\), chanValue: %p, funcValue: %p, pointerValue: 5, sliceValue: \["string", "slice"\], byteSliceValue: "bytes", stringValue: "a string", arrValue: \[11, 12, 13\], byteArrValue: \[17, 20, 32\], mapValue: %s, structValue: {Exported: "exported"}, interfaceValue: {"a key": 17}, }`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`)) Expect(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected)) }) }) Describe("Handling interfaces", func() { It("should unpack the interface", func() { outerHash := map[string]interface{}{} innerHash := map[string]int{} innerHash["inner"] = 3 outerHash["integer"] = 2 outerHash["map"] = innerHash expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`) Expect(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected)) }) }) Describe("Handling recursive things", func() { It("should not go crazy...", func() { m := map[string]interface{}{} m["integer"] = 2 m["map"] = m Expect(Object(m, 1)).Should(ContainSubstring("...")) }) It("really should not go crazy...", func() { type complexKey struct { Value map[interface{}]int } complexObject := complexKey{} complexObject.Value = make(map[interface{}]int) complexObject.Value[&complexObject] = 2 Expect(Object(complexObject, 1)).Should(ContainSubstring("...")) }) }) Describe("When instructed to use the Stringer representation", func() { BeforeEach(func() { UseStringerRepresentation = true }) AfterEach(func() { UseStringerRepresentation = false }) When("passed a GoStringer", func() { It("should use what GoString() returns", func() { Expect(Object(GoStringer{}, 1)).Should(ContainSubstring(": go-string")) }) }) When("passed a stringer", func() { It("should use what String() returns", func() { Expect(Object(Stringer{}, 1)).Should(ContainSubstring(": string")) }) }) When("passed a GomegaStringer", func() { It("should use what GomegaString() returns", func() { Expect(Object(gomegaStringer{}, 1)).Should(ContainSubstring(": gomegastring")) UseStringerRepresentation = false Expect(Object(gomegaStringer{}, 1)).Should(ContainSubstring(": gomegastring")) }) It("should use what GomegaString() returns, disregarding MaxLength", func() { Expect(Object(gomegaStringerLong{}, 1)).Should(Equal(" : " + strings.Repeat("s", MaxLength*2))) UseStringerRepresentation = false Expect(Object(gomegaStringerLong{}, 1)).Should(Equal(" : " + strings.Repeat("s", MaxLength*2))) }) It("should indent what the GomegaString() returns", func() { Expect(Object(gomegaStringerMultiline{}, 1)).Should(Equal(" : A\n B\n C")) }) }) Describe("when used with a registered CustomFormatter", func() { It("pases objects through the custom formatter and uses the returned format, if handled", func() { cf := CustomFormatted{"bob", 17} ncf := NotCustomFormatted{"bob", 17} Expect(Object(cf, 0)).To(Equal(": {Data: bob, Count: 17}")) Expect(Object(ncf, 0)).To(Equal(": {Data: bob, Count: 17}")) key := RegisterCustomFormatter(customFormatter) Expect(Object(cf, 0)).To(Equal(": bob (17)")) Expect(Object(ncf, 0)).To(Equal(": {Data: bob, Count: 17}")) UnregisterCustomFormatter(key) Expect(Object(cf, 0)).To(Equal(": {Data: bob, Count: 17}")) Expect(Object(ncf, 0)).To(Equal(": {Data: bob, Count: 17}")) }) It("indents CustomFormatter output correctly", func() { cf := CustomFormatted{"hey\nbob", 17} DeferCleanup(UnregisterCustomFormatter, RegisterCustomFormatter(func(value interface{}) (string, bool) { cf, ok := value.(CustomFormatted) if !ok { return "", false } return fmt.Sprintf("The Data:\n%s\nThe Count:%d", cf.Data, cf.Count), true })) Ω(Object(cf, 1)).Should(Equal(" : The Data:\n hey\n bob\n The Count:17")) type Wrapped struct { MyObject CustomFormatted OuterCount int } wrapped := Wrapped{ MyObject: cf, OuterCount: 10, } Ω(Object(wrapped, 1)).Should(Equal(" : {\n MyObject: The Data:\n hey\n bob\n The Count:17,\n OuterCount: 10,\n }")) }) }) }) Describe("Printing a context.Context field", func() { type structWithContext struct { Context context.Context Value string } objWithContext := structWithContext{Value: "some-value", Context: context.TODO()} It("Suppresses the content by default", func() { Expect(Object(objWithContext, 1)).Should(ContainSubstring("")) }) It("Doesn't suppress the context if it's the object being printed", func() { Expect(Object(context.TODO(), 1)).ShouldNot(MatchRegexp("^.*$")) }) Context("PrintContextObjects is set", func() { BeforeEach(func() { PrintContextObjects = true }) AfterEach(func() { PrintContextObjects = false }) It("Prints the context", func() { Expect(Object(objWithContext, 1)).ShouldNot(ContainSubstring("")) }) }) }) }) var expectedLongStringFailureMessage = strings.TrimSpace(` Expected : "...aaaaabaaaaa..." to equal | : "...aaaaazaaaaa..." `) var expectedTruncatedEndStringFailureMessage = strings.TrimSpace(` Expected : "baaaaa..." to equal | : "zaaaaa..." `) var expectedTruncatedStartStringFailureMessage = strings.TrimSpace(` Expected : "...aaaaab" to equal | : "...aaaaaz" `) var expectedTruncatedStartSizeFailureMessage = strings.TrimSpace(` Expected : "...aaaaaa" to equal | : "...aaaaa" `) var expectedTruncatedStartSizeFailureMessageExtraDiff = strings.TrimSpace(` Expected : "...aaaaaaaaaaa" to equal | : "...aaaaaaaaaa" `) var expectedTruncatedStartSizeSwappedFailureMessage = strings.TrimSpace(` Expected : "...aaaa" to equal | : "...aaaaa" `) var expectedTruncatedStartSizeSwappedFailureMessageExtraDiff = strings.TrimSpace(` Expected : "...aaaaaaaaa" to equal | : "...aaaaaaaaaa" `) var expectedTruncatedMultiByteFailureMessage = strings.TrimSpace(` Expected : "...tuvwxyz1" to equal | : "...tuvwxyz" `) var expectedFullFailureDiff = strings.TrimSpace(` Expected : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa to equal : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa `) var expectedSpecialCharacterFailureMessage = strings.TrimSpace(` Expected : \n to equal : something_else `) var expectedDiffSmallThreshold = strings.TrimSpace(` Expected : "aba" to equal | : "aza" `) var expectedDiffZeroMismatch = strings.TrimSpace(` Expected : aba to equal : aza `) var expectedDiffSmallThresholdZeroMismatch = strings.TrimSpace(` Expected : "...b..." to equal | : "...z..." `) var expectedDiffLongMessage = strings.TrimSpace(` Expected : "...aaaaabaaaaa..." to equal very long message : "...aaaaazaaaaa..." `) golang-gomega-1.36.2/gbytes/000077500000000000000000000000001476141007200156065ustar00rootroot00000000000000golang-gomega-1.36.2/gbytes/buffer.go000066400000000000000000000132721476141007200174130ustar00rootroot00000000000000/* Package gbytes provides a buffer that supports incrementally detecting input. You use gbytes.Buffer with the gbytes.Say matcher. When Say finds a match, it fastforwards the buffer's read cursor to the end of that match. Subsequent matches against the buffer will only operate against data that appears *after* the read cursor. The read cursor is an opaque implementation detail that you cannot access. You should use the Say matcher to sift through the buffer. You can always access the entire buffer's contents with Contents(). */ package gbytes import ( "errors" "fmt" "io" "regexp" "sync" "time" ) /* gbytes.Buffer implements an io.Writer and can be used with the gbytes.Say matcher. You should only use a gbytes.Buffer in test code. It stores all writes in an in-memory buffer - behavior that is inappropriate for production code! */ type Buffer struct { contents []byte readCursor uint64 lock *sync.Mutex detectCloser chan interface{} closed bool } /* NewBuffer returns a new gbytes.Buffer */ func NewBuffer() *Buffer { return &Buffer{ lock: &sync.Mutex{}, } } /* BufferWithBytes returns a new gbytes.Buffer seeded with the passed in bytes */ func BufferWithBytes(bytes []byte) *Buffer { return &Buffer{ lock: &sync.Mutex{}, contents: bytes, } } /* BufferReader returns a new gbytes.Buffer that wraps a reader. The reader's contents are read into the Buffer via io.Copy */ func BufferReader(reader io.Reader) *Buffer { b := &Buffer{ lock: &sync.Mutex{}, } go func() { io.Copy(b, reader) b.Close() }() return b } /* Write implements the io.Writer interface */ func (b *Buffer) Write(p []byte) (n int, err error) { b.lock.Lock() defer b.lock.Unlock() if b.closed { return 0, errors.New("attempt to write to closed buffer") } b.contents = append(b.contents, p...) return len(p), nil } /* Read implements the io.Reader interface. It advances the cursor as it reads. */ func (b *Buffer) Read(d []byte) (int, error) { b.lock.Lock() defer b.lock.Unlock() if uint64(len(b.contents)) <= b.readCursor { return 0, io.EOF } n := copy(d, b.contents[b.readCursor:]) b.readCursor += uint64(n) return n, nil } /* Clear clears out the buffer's contents */ func (b *Buffer) Clear() error { b.lock.Lock() defer b.lock.Unlock() if b.closed { return errors.New("attempt to clear closed buffer") } b.contents = []byte{} b.readCursor = 0 return nil } /* Close signifies that the buffer will no longer be written to */ func (b *Buffer) Close() error { b.lock.Lock() defer b.lock.Unlock() b.closed = true return nil } /* Closed returns true if the buffer has been closed */ func (b *Buffer) Closed() bool { b.lock.Lock() defer b.lock.Unlock() return b.closed } /* Contents returns all data ever written to the buffer. */ func (b *Buffer) Contents() []byte { b.lock.Lock() defer b.lock.Unlock() contents := make([]byte, len(b.contents)) copy(contents, b.contents) return contents } /* Detect takes a regular expression and returns a channel. The channel will receive true the first time data matching the regular expression is written to the buffer. The channel is subsequently closed and the buffer's read-cursor is fast-forwarded to just after the matching region. You typically don't need to use Detect and should use the ghttp.Say matcher instead. Detect is useful, however, in cases where your code must be branch and handle different outputs written to the buffer. For example, consider a buffer hooked up to the stdout of a client library. You may (or may not, depending on state outside of your control) need to authenticate the client library. You could do something like: select { case <-buffer.Detect("You are not logged in"): //log in case <-buffer.Detect("Success"): //carry on case <-time.After(time.Second): //welp } buffer.CancelDetects() You should always call CancelDetects after using Detect. This will close any channels that have not detected and clean up the goroutines that were spawned to support them. Finally, you can pass detect a format string followed by variadic arguments. This will construct the regexp using fmt.Sprintf. */ func (b *Buffer) Detect(desired string, args ...interface{}) chan bool { formattedRegexp := desired if len(args) > 0 { formattedRegexp = fmt.Sprintf(desired, args...) } re := regexp.MustCompile(formattedRegexp) b.lock.Lock() defer b.lock.Unlock() if b.detectCloser == nil { b.detectCloser = make(chan interface{}) } closer := b.detectCloser response := make(chan bool) go func() { ticker := time.NewTicker(10 * time.Millisecond) defer ticker.Stop() defer close(response) for { select { case <-ticker.C: b.lock.Lock() data, cursor := b.contents[b.readCursor:], b.readCursor loc := re.FindIndex(data) b.lock.Unlock() if loc != nil { response <- true b.lock.Lock() newCursorPosition := cursor + uint64(loc[1]) if newCursorPosition >= b.readCursor { b.readCursor = newCursorPosition } b.lock.Unlock() return } case <-closer: return } } }() return response } /* CancelDetects cancels any pending detects and cleans up their goroutines. You should always call this when you're done with a set of Detect channels. */ func (b *Buffer) CancelDetects() { b.lock.Lock() defer b.lock.Unlock() close(b.detectCloser) b.detectCloser = nil } func (b *Buffer) didSay(re *regexp.Regexp) (bool, []byte) { b.lock.Lock() defer b.lock.Unlock() unreadBytes := b.contents[b.readCursor:] copyOfUnreadBytes := make([]byte, len(unreadBytes)) copy(copyOfUnreadBytes, unreadBytes) loc := re.FindIndex(unreadBytes) if loc != nil { b.readCursor += uint64(loc[1]) return true, copyOfUnreadBytes } return false, copyOfUnreadBytes } golang-gomega-1.36.2/gbytes/buffer_test.go000066400000000000000000000133761476141007200204570ustar00rootroot00000000000000package gbytes_test import ( "io" "time" . "github.com/onsi/gomega/gbytes" "bytes" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type SlowReader struct { R io.Reader D time.Duration } func (s SlowReader) Read(p []byte) (int, error) { time.Sleep(s.D) return s.R.Read(p) } var _ = Describe("Buffer", func() { var buffer *Buffer BeforeEach(func() { buffer = NewBuffer() }) Describe("dumping the entire contents of the buffer", func() { It("should return everything that's been written", func() { buffer.Write([]byte("abc")) buffer.Write([]byte("def")) Expect(buffer.Contents()).Should(Equal([]byte("abcdef"))) Expect(buffer).Should(Say("bcd")) Expect(buffer.Contents()).Should(Equal([]byte("abcdef"))) }) }) Describe("creating a buffer with bytes", func() { It("should create the buffer with the cursor set to the beginning", func() { buffer := BufferWithBytes([]byte("abcdef")) Expect(buffer.Contents()).Should(Equal([]byte("abcdef"))) Expect(buffer).Should(Say("abc")) Expect(buffer).ShouldNot(Say("abc")) Expect(buffer).Should(Say("def")) }) }) Describe("creating a buffer that wraps a reader", func() { Context("for a well-behaved reader", func() { It("should buffer the contents of the reader", func() { reader := bytes.NewBuffer([]byte("abcdef")) buffer := BufferReader(reader) Eventually(buffer).Should(Say("abc")) Expect(buffer).ShouldNot(Say("abc")) Eventually(buffer).Should(Say("def")) Eventually(buffer.Closed).Should(BeTrue()) }) }) Context("for a slow reader", func() { It("should allow Eventually to time out", func() { slowReader := SlowReader{ R: bytes.NewBuffer([]byte("abcdef")), D: time.Second, } buffer := BufferReader(slowReader) failures := InterceptGomegaFailures(func() { Eventually(buffer, 100*time.Millisecond).Should(Say("abc")) }) Expect(failures).ShouldNot(BeEmpty()) fastReader := SlowReader{ R: bytes.NewBuffer([]byte("abcdef")), D: time.Millisecond, } buffer = BufferReader(fastReader) Eventually(buffer, 100*time.Millisecond).Should(Say("abc")) Eventually(buffer.Closed).Should(BeTrue()) }) }) }) Describe("reading from a buffer", func() { It("should read the current contents of the buffer", func() { buffer := BufferWithBytes([]byte("abcde")) dest := make([]byte, 3) n, err := buffer.Read(dest) Expect(err).ShouldNot(HaveOccurred()) Expect(n).Should(Equal(3)) Expect(string(dest)).Should(Equal("abc")) dest = make([]byte, 3) n, err = buffer.Read(dest) Expect(err).ShouldNot(HaveOccurred()) Expect(n).Should(Equal(2)) Expect(string(dest[:n])).Should(Equal("de")) n, err = buffer.Read(dest) Expect(err).Should(Equal(io.EOF)) Expect(n).Should(Equal(0)) }) }) Describe("detecting regular expressions", func() { It("should fire the appropriate channel when the passed in pattern matches, then close it", func() { go func() { time.Sleep(10 * time.Millisecond) buffer.Write([]byte("abcde")) }() A := buffer.Detect("%s", "a.c") B := buffer.Detect("def") var gotIt bool select { case gotIt = <-A: case <-B: Fail("should not have gotten here") case <-time.After(time.Second): Fail("timed out waiting for detection") } Expect(gotIt).Should(BeTrue()) Eventually(A).Should(BeClosed()) buffer.Write([]byte("f")) Eventually(B).Should(Receive()) Eventually(B).Should(BeClosed()) }) It("should fast-forward the buffer upon detection", func() { buffer.Write([]byte("abcde")) select { case <-buffer.Detect("abc"): case <-time.After(time.Second): Fail("timed out waiting for detection") } Expect(buffer).ShouldNot(Say("abc")) Expect(buffer).Should(Say("de")) }) It("should only fast-forward the buffer when the channel is read, and only if doing so would not rewind it", func() { buffer.Write([]byte("abcde")) A := buffer.Detect("abc") time.Sleep(20 * time.Millisecond) //give the goroutine a chance to detect and write to the channel Expect(buffer).Should(Say("abcd")) select { case <-A: case <-time.After(time.Second): Fail("timed out waiting for detection") } Expect(buffer).ShouldNot(Say("d")) Expect(buffer).Should(Say("e")) Eventually(A).Should(BeClosed()) }) It("should be possible to cancel a detection", func() { A := buffer.Detect("abc") B := buffer.Detect("def") buffer.CancelDetects() buffer.Write([]byte("abcdef")) Eventually(A).Should(BeClosed()) Eventually(B).Should(BeClosed()) Expect(buffer).Should(Say("bcde")) select { case <-buffer.Detect("f"): case <-time.After(time.Second): Fail("timed out waiting for detection") } }) }) Describe("clearing the buffer", func() { It("should clear out the contents of the buffer", func() { buffer.Write([]byte("abc")) Expect(buffer).To(Say("ab")) Expect(buffer.Clear()).To(Succeed()) Expect(buffer).NotTo(Say("c")) Expect(buffer.Contents()).To(BeEmpty()) buffer.Write([]byte("123")) Expect(buffer).To(Say("123")) Expect(buffer.Contents()).To(Equal([]byte("123"))) }) It("should error when the buffer is closed", func() { buffer.Write([]byte("abc")) buffer.Close() err := buffer.Clear() Expect(err).To(HaveOccurred()) }) }) Describe("closing the buffer", func() { It("should error when further write attempts are made", func() { _, err := buffer.Write([]byte("abc")) Expect(err).ShouldNot(HaveOccurred()) buffer.Close() _, err = buffer.Write([]byte("def")) Expect(err).Should(HaveOccurred()) Expect(buffer.Contents()).Should(Equal([]byte("abc"))) }) It("should be closed", func() { Expect(buffer.Closed()).Should(BeFalse()) buffer.Close() Expect(buffer.Closed()).Should(BeTrue()) }) }) }) golang-gomega-1.36.2/gbytes/gbuffer_suite_test.go000066400000000000000000000003021476141007200220200ustar00rootroot00000000000000package gbytes_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "testing" ) func TestGbytes(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Gbytes Suite") } golang-gomega-1.36.2/gbytes/io_wrappers.go000066400000000000000000000037311476141007200204730ustar00rootroot00000000000000package gbytes import ( "errors" "io" "time" ) // ErrTimeout is returned by TimeoutCloser, TimeoutReader, and TimeoutWriter when the underlying Closer/Reader/Writer does not return within the specified timeout var ErrTimeout = errors.New("timeout occurred") // TimeoutCloser returns an io.Closer that wraps the passed-in io.Closer. If the underlying Closer fails to close within the allotted timeout ErrTimeout is returned. func TimeoutCloser(c io.Closer, timeout time.Duration) io.Closer { return timeoutReaderWriterCloser{c: c, d: timeout} } // TimeoutReader returns an io.Reader that wraps the passed-in io.Reader. If the underlying Reader fails to read within the allotted timeout ErrTimeout is returned. func TimeoutReader(r io.Reader, timeout time.Duration) io.Reader { return timeoutReaderWriterCloser{r: r, d: timeout} } // TimeoutWriter returns an io.Writer that wraps the passed-in io.Writer. If the underlying Writer fails to write within the allotted timeout ErrTimeout is returned. func TimeoutWriter(w io.Writer, timeout time.Duration) io.Writer { return timeoutReaderWriterCloser{w: w, d: timeout} } type timeoutReaderWriterCloser struct { c io.Closer w io.Writer r io.Reader d time.Duration } func (t timeoutReaderWriterCloser) Close() error { done := make(chan struct{}) var err error go func() { err = t.c.Close() close(done) }() select { case <-done: return err case <-time.After(t.d): return ErrTimeout } } func (t timeoutReaderWriterCloser) Read(p []byte) (int, error) { done := make(chan struct{}) var n int var err error go func() { n, err = t.r.Read(p) close(done) }() select { case <-done: return n, err case <-time.After(t.d): return 0, ErrTimeout } } func (t timeoutReaderWriterCloser) Write(p []byte) (int, error) { done := make(chan struct{}) var n int var err error go func() { n, err = t.w.Write(p) close(done) }() select { case <-done: return n, err case <-time.After(t.d): return 0, ErrTimeout } } golang-gomega-1.36.2/gbytes/io_wrappers_test.go000066400000000000000000000076321476141007200215360ustar00rootroot00000000000000package gbytes_test import ( "fmt" "io" "time" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type FakeCloser struct { err error duration time.Duration } func (f FakeCloser) Close() error { time.Sleep(f.duration) return f.err } type FakeReader struct { err error duration time.Duration } func (f FakeReader) Read(p []byte) (int, error) { time.Sleep(f.duration) if f.err != nil { return 0, f.err } for i := 0; i < len(p); i++ { p[i] = 'a' } return len(p), nil } type FakeWriter struct { err error duration time.Duration } func (f FakeWriter) Write(p []byte) (int, error) { time.Sleep(f.duration) if f.err != nil { return 0, f.err } return len(p), nil } var _ = Describe("Io Wrappers", func() { Describe("TimeoutCloser", func() { var innerCloser io.Closer var timeoutCloser io.Closer JustBeforeEach(func() { timeoutCloser = TimeoutCloser(innerCloser, 20*time.Millisecond) }) When("the underlying Closer closes with no error", func() { BeforeEach(func() { innerCloser = FakeCloser{} }) It("returns with no error", func() { Expect(timeoutCloser.Close()).Should(Succeed()) }) }) When("the underlying Closer closes with an error", func() { BeforeEach(func() { innerCloser = FakeCloser{err: fmt.Errorf("boom")} }) It("returns the error", func() { Expect(timeoutCloser.Close()).Should(MatchError("boom")) }) }) When("the underlying Closer hangs", func() { BeforeEach(func() { innerCloser = FakeCloser{ err: fmt.Errorf("boom"), duration: time.Hour, } }) It("returns ErrTimeout", func() { Expect(timeoutCloser.Close()).Should(MatchError(ErrTimeout)) }) }) }) Describe("TimeoutReader", func() { var innerReader io.Reader var timeoutReader io.Reader JustBeforeEach(func() { timeoutReader = TimeoutReader(innerReader, 20*time.Millisecond) }) When("the underlying Reader returns no error", func() { BeforeEach(func() { innerReader = FakeReader{} }) It("returns with no error", func() { p := make([]byte, 5) n, err := timeoutReader.Read(p) Expect(n).Should(Equal(5)) Expect(err).ShouldNot(HaveOccurred()) Expect(p).Should(Equal([]byte("aaaaa"))) }) }) When("the underlying Reader returns an error", func() { BeforeEach(func() { innerReader = FakeReader{err: fmt.Errorf("boom")} }) It("returns the error", func() { p := make([]byte, 5) _, err := timeoutReader.Read(p) Expect(err).Should(MatchError("boom")) }) }) When("the underlying Reader hangs", func() { BeforeEach(func() { innerReader = FakeReader{err: fmt.Errorf("boom"), duration: time.Hour} }) It("returns ErrTimeout", func() { p := make([]byte, 5) _, err := timeoutReader.Read(p) Expect(err).Should(MatchError(ErrTimeout)) }) }) }) Describe("TimeoutWriter", func() { var innerWriter io.Writer var timeoutWriter io.Writer JustBeforeEach(func() { timeoutWriter = TimeoutWriter(innerWriter, 20*time.Millisecond) }) When("the underlying Writer returns no error", func() { BeforeEach(func() { innerWriter = FakeWriter{} }) It("returns with no error", func() { n, err := timeoutWriter.Write([]byte("aaaaa")) Expect(n).Should(Equal(5)) Expect(err).ShouldNot(HaveOccurred()) }) }) When("the underlying Writer returns an error", func() { BeforeEach(func() { innerWriter = FakeWriter{err: fmt.Errorf("boom")} }) It("returns the error", func() { _, err := timeoutWriter.Write([]byte("aaaaa")) Expect(err).Should(MatchError("boom")) }) }) When("the underlying Writer hangs", func() { BeforeEach(func() { innerWriter = FakeWriter{err: fmt.Errorf("boom"), duration: time.Hour} }) It("returns ErrTimeout", func() { _, err := timeoutWriter.Write([]byte("aaaaa")) Expect(err).Should(MatchError(ErrTimeout)) }) }) }) }) golang-gomega-1.36.2/gbytes/say_matcher.go000066400000000000000000000053761476141007200204470ustar00rootroot00000000000000// untested sections: 1 package gbytes import ( "fmt" "regexp" "github.com/onsi/gomega/format" ) //Objects satisfying the BufferProvider can be used with the Say matcher. type BufferProvider interface { Buffer() *Buffer } /* Say is a Gomega matcher that operates on gbytes.Buffers: Expect(buffer).Should(Say("something")) will succeed if the unread portion of the buffer matches the regular expression "something". When Say succeeds, it fast forwards the gbytes.Buffer's read cursor to just after the successful match. Thus, subsequent calls to Say will only match against the unread portion of the buffer Say pairs very well with Eventually. To assert that a buffer eventually receives data matching "[123]-star" within 3 seconds you can: Eventually(buffer, 3).Should(Say("[123]-star")) Ditto with consistently. To assert that a buffer does not receive data matching "never-see-this" for 1 second you can: Consistently(buffer, 1).ShouldNot(Say("never-see-this")) In addition to bytes.Buffers, Say can operate on objects that implement the gbytes.BufferProvider interface. In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer() If the buffer is closed, the Say matcher will tell Eventually to abort. */ func Say(expected string, args ...interface{}) *sayMatcher { if len(args) > 0 { expected = fmt.Sprintf(expected, args...) } return &sayMatcher{ re: regexp.MustCompile(expected), } } type sayMatcher struct { re *regexp.Regexp receivedSayings []byte } func (m *sayMatcher) buffer(actual interface{}) (*Buffer, bool) { var buffer *Buffer switch x := actual.(type) { case *Buffer: buffer = x case BufferProvider: buffer = x.Buffer() default: return nil, false } return buffer, true } func (m *sayMatcher) Match(actual interface{}) (success bool, err error) { buffer, ok := m.buffer(actual) if !ok { return false, fmt.Errorf("Say must be passed a *gbytes.Buffer or BufferProvider. Got:\n%s", format.Object(actual, 1)) } didSay, sayings := buffer.didSay(m.re) m.receivedSayings = sayings return didSay, nil } func (m *sayMatcher) FailureMessage(actual interface{}) (message string) { return fmt.Sprintf( "Got stuck at:\n%s\nWaiting for:\n%s", format.IndentString(string(m.receivedSayings), 1), format.IndentString(m.re.String(), 1), ) } func (m *sayMatcher) NegatedFailureMessage(actual interface{}) (message string) { return fmt.Sprintf( "Saw:\n%s\nWhich matches the unexpected:\n%s", format.IndentString(string(m.receivedSayings), 1), format.IndentString(m.re.String(), 1), ) } func (m *sayMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { switch x := actual.(type) { case *Buffer: return !x.Closed() case BufferProvider: return !x.Buffer().Closed() default: return true } } golang-gomega-1.36.2/gbytes/say_matcher_test.go000066400000000000000000000100511476141007200214700ustar00rootroot00000000000000package gbytes_test import ( "time" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type speaker struct { buffer *Buffer } func (s *speaker) Buffer() *Buffer { return s.buffer } var _ = Describe("SayMatcher", func() { var buffer *Buffer BeforeEach(func() { buffer = NewBuffer() buffer.Write([]byte("abc")) }) When("actual is not a gexec Buffer, or a BufferProvider", func() { It("should error", func() { failures := InterceptGomegaFailures(func() { Expect("foo").Should(Say("foo")) }) Expect(failures[0]).Should(ContainSubstring("*gbytes.Buffer")) }) }) When("a match is found", func() { It("should succeed", func() { Expect(buffer).Should(Say("abc")) }) It("should support printf-like formatting", func() { Expect(buffer).Should(Say("a%sc", "b")) }) It("should match literal %", func() { buffer.Write([]byte("%")) Expect(buffer).Should(Say("abc%")) }) It("should use a regular expression", func() { Expect(buffer).Should(Say("a.c")) }) It("should fastforward the buffer", func() { buffer.Write([]byte("def")) Expect(buffer).Should(Say("abcd")) Expect(buffer).Should(Say("ef")) Expect(buffer).ShouldNot(Say("[a-z]")) }) }) When("no match is found", func() { It("should not error", func() { Expect(buffer).ShouldNot(Say("def")) }) When("the buffer is closed", func() { BeforeEach(func() { buffer.Close() }) It("should abort an eventually", func() { t := time.Now() failures := InterceptGomegaFailures(func() { Eventually(buffer).Should(Say("def")) }) Eventually(buffer).ShouldNot(Say("def")) Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) Expect(failures).Should(HaveLen(1)) t = time.Now() Eventually(buffer).Should(Say("abc")) Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) }) It("should abort a consistently", func() { t := time.Now() Consistently(buffer, 2.0).ShouldNot(Say("def")) Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) }) It("should not error with a synchronous matcher", func() { Expect(buffer).ShouldNot(Say("def")) Expect(buffer).Should(Say("abc")) }) }) }) When("a positive match fails", func() { It("should report where it got stuck", func() { Expect(buffer).Should(Say("abc")) buffer.Write([]byte("def")) failures := InterceptGomegaFailures(func() { Expect(buffer).Should(Say("abc")) }) Expect(failures[0]).Should(ContainSubstring("Got stuck at:")) Expect(failures[0]).Should(ContainSubstring("def")) }) }) When("a negative match fails", func() { It("should report where it got stuck", func() { failures := InterceptGomegaFailures(func() { Expect(buffer).ShouldNot(Say("abc")) }) Expect(failures[0]).Should(ContainSubstring("Saw:")) Expect(failures[0]).Should(ContainSubstring("Which matches the unexpected:")) Expect(failures[0]).Should(ContainSubstring("abc")) }) }) When("a match is not found", func() { It("should not fastforward the buffer", func() { Expect(buffer).ShouldNot(Say("def")) Expect(buffer).Should(Say("abc")) }) }) Context("a nice real-life example", func() { It("should behave well", func() { Expect(buffer).Should(Say("abc")) go func() { time.Sleep(10 * time.Millisecond) buffer.Write([]byte("def")) }() Expect(buffer).ShouldNot(Say("def")) Eventually(buffer).Should(Say("def")) }) }) When("actual is a BufferProvider", func() { It("should use actual's buffer", func() { s := &speaker{ buffer: NewBuffer(), } Expect(s).ShouldNot(Say("abc")) s.Buffer().Write([]byte("abc")) Expect(s).Should(Say("abc")) }) It("should abort an eventually", func() { s := &speaker{ buffer: NewBuffer(), } s.buffer.Close() t := time.Now() failures := InterceptGomegaFailures(func() { Eventually(s).Should(Say("def")) }) Expect(failures).Should(HaveLen(1)) Expect(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) }) }) }) golang-gomega-1.36.2/gcustom/000077500000000000000000000000001476141007200157725ustar00rootroot00000000000000golang-gomega-1.36.2/gcustom/gcustom_suite_test.go000066400000000000000000000003051476141007200222500ustar00rootroot00000000000000package gcustom_test import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestGcustom(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Gcustom Suite") } golang-gomega-1.36.2/gcustom/make_matcher.go000066400000000000000000000241651476141007200207510ustar00rootroot00000000000000/* package gcustom provides a simple mechanism for creating custom Gomega matchers */ package gcustom import ( "fmt" "reflect" "strings" "text/template" "github.com/onsi/gomega/format" ) var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() var errInterface = reflect.TypeOf((*error)(nil)).Elem() var defaultTemplate = template.Must(ParseTemplate("{{if .Failure}}Custom matcher failed for:{{else}}Custom matcher succeeded (but was expected to fail) for:{{end}}\n{{.FormattedActual}}")) func formatObject(object any, indent ...uint) string { indentation := uint(0) if len(indent) > 0 { indentation = indent[0] } return format.Object(object, indentation) } /* ParseTemplate allows you to precompile templates for MakeMatcher's custom matchers. Use ParseTemplate if you are concerned about performance and would like to avoid repeatedly parsing failure message templates. The data made available to the template is documented in the WithTemplate() method of CustomGomegaMatcher. Once parsed you can pass the template in either as an argument to MakeMatcher(matchFunc,