Debian Codegraph @

README.md

raw symbols SCIP
1 # check
2
3 [![License MIT](https://img.shields.io/badge/license-MIT-royalblue.svg)](LICENSE)
4 [![Go version](https://img.shields.io/github/go-mod/go-version/powerman/check?color=blue)](https://go.dev/)
5 [![Test](https://img.shields.io/github/actions/workflow/status/powerman/check/test.yml?label=test)](https://github.com/powerman/check/actions/workflows/test.yml)
6 [![Coverage Status](https://raw.githubusercontent.com/powerman/check/gh-badges/coverage.svg)](https://github.com/powerman/check/actions/workflows/test.yml)
7 [![Release](https://img.shields.io/github/v/release/powerman/check?color=blue)](https://github.com/powerman/check/releases/latest)
8 [![Go Reference](https://pkg.go.dev/badge/github.com/powerman/check.svg)](https://pkg.go.dev/github.com/powerman/check)
9
10 ![Linux | amd64 arm64 armv7 ppc64le s390x riscv64](https://img.shields.io/badge/Linux-amd64%20arm64%20armv7%20ppc64le%20s390x%20riscv64-royalblue)
11 ![macOS | amd64 arm64](https://img.shields.io/badge/macOS-amd64%20arm64-royalblue)
12 ![Windows | amd64 arm64](https://img.shields.io/badge/Windows-amd64%20arm64-royalblue)
13
14 Helpers to complement Go [testing](https://pkg.go.dev/testing) package.
15
16 Write tests with ease and fun!
17
18 ## Rationale
19
20 Plain Go tests force a choice between two extremes:
21 verbose `if got != want { t.Fatalf(...) }` boilerplate for every comparison,
22 or reaching for a heavier test framework
23 that replaces `go test` with its own runner and vocabulary.
24 This project avoids both:
25
26 - It never introduces a new concept - no suites, no custom runner, no dot-import.
27 Every wrapped value is still a real `*testing.T`/`*testing.B`/`*testing.F` underneath,
28 so `tt.Run`, `tt.Parallel`, `t.Log`, `t.Cleanup`
29 and everything else you already know keep working exactly as before.
30 - Checkers already know what "nil", "equal" or "contains" means for the type you handed them,
31 so you rarely write the type-specific comparison yourself: `t.Nil(err)` handles
32 typed-nil pointers correctly (see the `Nil` doc comment for the classic gotcha),
33 `t.Len(v, 3)` works the same for a map, slice, string, channel or array,
34 `t.Err(err, io.EOF)` unwraps and compares by value instead of just by chain membership.
35 - A failed check prints a full, readable dump of both values plus a text diff,
36 so `t.DeepEqual(got, want)` on a whole struct/slice/map actually shows you what's wrong,
37 instead of the `got X, want Y` you'd hand-roll around `==`.
38 See [Failure Output](#failure-output) below.
39 - `check.Must()`/`check.New()` let you pick, per test,
40 whether a failed check should stop the test (`testify/require`-like)
41 or just record the failure and continue (`testify/assert`-like),
42 without importing two different packages for that.
43 - `check.TestMain` adds a per-test and grand-total pass/fail/todo counter to every run,
44 so you get a sense of overall test health beyond individual PASS/FAIL lines -
45 see the `checks:` lines in [Failure Output](#failure-output).
46
47 > [!NOTE]
48 >
49 > The first `check` commit dates back to December 2017 —
50 > a time when [testify](https://github.com/stretchr/testify)
51 > had seen no activity for five months, with 40+ pull requests piling up
52 > and the organization's domain parked for sale
53 > ([issue #526](https://github.com/stretchr/testify/issues/526)).
54 > testify has since recovered, but `check` was born from the uncertainty
55 > of that period and took a different approach from the start.
56
57 ## Features
58
59 - Zero required external dependencies.
60 Protobuf/gRPC comparison support pulls its (much heavier) dependencies in
61 only if you opt into the [companion submodules](#protobuf-grpc-support).
62 - Compelling output from failed tests:
63 - Very easy-to-read dumps for expected and actual values.
64 - Same text diff you loved in testify.
65 - Statistics with amount of passed/failed checks.
66 - Colored output in terminal.
67 - 100% compatible with testing package - check package just provides convenient wrappers
68 for `*testing.T`/`*testing.B`/`*testing.F` methods without an unusual execution flow
69 (see [Non-goals](#non-goals)).
70 - All checks you may ever need! :)
71 - Very easy to add your own check functions.
72 - Concise, handy and consistent API, without dot-import!
73
74 ## Quickstart
75
76 Wrap each (including subtests) `*testing.T`/`*testing.B`/`*testing.F`
77 using `check.Must()` and write tests as usually with testing package.
78 Call new methods provided by this package to have more clean/concise test code
79 and cool dump/diff.
80
81 `check.Must()` is the recommended default: it stops the test on the first failed check
82 (like `testify/require`). Use `check.New()` instead for the softer,
83 `testify/assert`-like behavior where a failed check doesn't stop the test.
84
85 > [!NOTE]
86 >
87 > Call `tb.Run()`/`tb.Parallel()` on the original `*testing.T`/`*testing.B`
88 > before wrapping it with `check.Must()`/`check.New()` —
89 > these two aren't available on the wrapped value
90 > (this also satisfies the `paralleltest` linter):
91
92 ```go
93 import "github.com/powerman/check"
94
95 func TestSomething(tt *testing.T) {
96 tt.Parallel()
97 t := check.Must(tt)
98 t.Equal(2, 2)
99 t.Log("You can use new t just like usual *testing.T")
100 tt.Run("Subtests/Parallel example", func(tt *testing.T) {
101 tt.Parallel()
102 t := check.Must(tt)
103 t.NotEqual(2, 3, "should not be 3!")
104 obj, err := NewObj()
105 if t.Nil(err) {
106 t.Match(obj.field, `^\d+$`)
107 }
108 })
109 }
110 ```
111
112 To get optional statistics about executed checkers add:
113
114 ```go
115 func TestMain(m *testing.M) { check.TestMain(m) }
116 ```
117
118 See the [package examples](https://pkg.go.dev/github.com/powerman/check#pkg-examples)
119 for more runnable snippets: table-driven subtests, soft checks with `New`, `TODO`,
120 custom `Should` checkers, `Err`/`ErrIs`/`ErrAs`/`Match` side by side, and `MergeContext`.
121
122 ### Legacy `check.T()`
123
124 `check.T(tt *testing.T) *check.C` is the original, soft-mode by default constructor
125 kept for backward compatibility - `*check.C` behaves exactly like it always did,
126 including direct access to the wrapped `*testing.T` via its `T` field.
127 New code should prefer `check.New()`/`check.Must()`.
128
129 ## Installation
130
131 ```sh
132 go get github.com/powerman/check
133 ```
134
135 ## Failure Output
136
137 Here's what a failed `DeepEqual` looks like (from `testdata/demo/demo_test.go`,
138 run with `go test -tags demo -v ./testdata/demo/`).
139 Only `Total` actually differs - `ID`, `Customer` and `Items` match -
140 so `Diff` singles out the one line that's wrong
141 instead of making you eyeball two full dumps for what changed.
142 The `checks:` lines at the end are `check.TestMain`'s pass/fail/todo counters
143 (one passing `Equal` plus this failing `DeepEqual`):
144
145 ```text
146 === RUN TestDemoFailure
147 demo_test.go:41: order total should match after checkout
148 Checker: DeepEqual
149 Expected: (demo.Order) {
150 ID: (string) (len=3) "A-1",
151 Customer: (string) (len=3) "Ann",
152 Total: (int) 40,
153 Items: ([]string) (len=2) {
154 (string) (len=3) "pen",
155 (string) (len=3) "cup"
156 }
157 }
158 Actual: (demo.Order) {
159 ID: (string) (len=3) "A-1",
160 Customer: (string) (len=3) "Ann",
161 Total: (int) 42,
162 Items: ([]string) (len=2) {
163 (string) (len=3) "pen",
164 (string) (len=3) "cup"
165 }
166 }
167
168 Diff:
169 --- Expected
170 +++ Actual
171 @@ -3,3 +3,3 @@
172 Customer: (string) (len=3) "Ann",
173 - Total: (int) 40,
174 + Total: (int) 42,
175 Items: ([]string) (len=2) {
176
177 --- FAIL: TestDemoFailure (0.00s)
178 checks: 1 passed 1 failed TestDemoFailure
179 checks: 1 passed 0 todo 1 failed (total)
180 ```
181
182 With a color terminal (see `doc.go` for the `FORCE_COLOR`/`NO_COLOR` environment variables)
183 the same failure looks like this:
184
185 ![Colored failure output](.github/assets/demo-failure.png)
186
187 ## Custom Checkers
188
189 You can extend `DeepEqual`/`NotDeepEqual` and `Err`/`NotErr`
190 with custom comparison logic via `RegisterEqualChecker` and `RegisterErrChecker`.
191
192 - This package enables [validator](https://github.com/go-playground/validator)
193 `FieldError` and `[]FieldError` comparison by `Namespace()`+`Tag()`
194 via `check.Err`/`check.NotErr`.
195
196 ### Protobuf / gRPC Support
197
198 Protobuf message comparison and gRPC status error comparison have been extracted
199 into separate modules to keep the core dependency-light:
200
201 - **[checkproto](https://github.com/powerman/checkproto)** — enables
202 `proto.Equal` via `check.DeepEqual`/`check.NotDeepEqual` for protobuf messages.
203 - **[checkgrpc](https://github.com/powerman/checkgrpc)** — enables
204 gRPC status comparison via `check.Err`/`check.NotErr`.
205 It also imports checkproto, so a single blank import covers both.
206
207 Usage: just add a blank import in your test file or `TestMain`:
208
209 ```go
210 import _ "github.com/powerman/checkgrpc"
211 ```
212
213 ## Comparison
214
215 A few honest notes on how check compares to other assertion libraries,
216 so you can pick the right one instead of the one you found first.
217
218 ### vs [testify](https://github.com/stretchr/testify)
219
220 testify's `assert`/`require` packages solve the same problem:
221 convenience wrappers around `*testing.T` with a soft/hard mode split,
222 and (via `assert.New(t)`/`require.New(t)`) a method-style API too,
223 so that's not a real difference. Where check does differ:
224
225 - Argument order: check and go-quicktest/qt put the actual value first,
226 matching `if got != want` (`t.Equal(got, want)`)
227 and the `got = %v, want %v` shape of Go's own idiomatic test failure messages.
228 testify and shoenig/test put the expected value first instead
229 (`assert.Equal(t, want, got)`, `must.Eq(t, want, got)`),
230 which only really makes sense if you're already used to it:
231 `got` is usually a separate variable set by calling the code under test,
232 often on its own long line, while `want` is often a short literal written inline -
233 `want, got` order buries the value to check at the end of the call.
234 - Dump + diff is the default failure output, not an opt-in - you don't need
235 `assert.EqualExportedValues` or a separate diff helper to get a readable struct comparison.
236 - No suite package, no mock package - check stays a pure assertion/checker library.
237 Use `testify/mock` (or anything else) alongside it if you need mocks.
238
239 A few UX differences side by side:
240
241 - Error is nil: `t.Nil(err)` vs `assert.NoError(t, err)` or `assert.Nil(t, err)` -
242 two names for one idea.
243 - Error unwraps to & value-equals a sentinel/custom error: `t.Err(err, io.EOF)` vs
244 no direct equivalent - `assert.ErrorIs` only checks chain membership,
245 not value equality of a freshly-constructed error.
246 - Length of a map/slice/string/channel: `t.Len(v, 3)` vs `assert.Len(t, v, 3)`,
247 but `len == 0` needs the separate `assert.Empty`/`NotEmpty`.
248
249 check does not cover 100% of testify's `assert`/`require` surface.
250 Beyond `Eventually`/`Never` and the HTTP handler helpers
251 (deliberately left out, see [Non-goals](#non-goals)),
252 testify's `IsIncreasing`/`IsDecreasing`/`IsNonIncreasing`/`IsNonDecreasing`
253 (sequence monotonicity) and `YAMLEq` have no check equivalent - not deliberately,
254 just not needed yet. (Open an issue if you need them.)
255 Everything else (`Same`, `EqualValues`, `Positive`, `Negative`, ...)
256 is one line via an existing checker
257 (`t.Equal` already compares pointers by identity, `t.Greater(x, 0)` covers `Positive`).
258
259 ### vs [go-quicktest/qt](https://github.com/go-quicktest/qt) and [shoenig/test](https://github.com/shoenig/test)
260
261 go-quicktest/qt and shoenig/test are newer, generics-first libraries:
262 `qt.Assert(t, got, qt.Equals(want))` and `must.Eq(t, want, got)`
263 are package-level generic functions, so a type mistake (comparing `int` to `int32`)
264 is often a compile error instead of a runtime panic or failed check.
265
266 In practice that payoff is smaller than it sounds: a type mistake fails the test either way,
267 the only question is whether you see it as a `go build`/`go vet` error
268 before running `go test` (qt/shoenig/test) or as a panic/failed check while it runs (check) -
269 not whether it's caught.
270 check is deliberately not generic for a more concrete reason:
271 part of its convenience only works with `any`
272 (`Match` accepts string/`[]byte`/error/`fmt.Stringer`; `Equal` special-cases `time.Time`),
273 and Go doesn't yet support generic methods,
274 so a generic `check.TB` isn't possible without splitting the API into free functions.
275 Pick qt or shoenig/test if you want compile-time typed assertions as package functions;
276 pick check if you want a method-style API and check's dump/diff by default.
277
278 ### vs [gotest.tools/v3](https://github.com/gotestyourself/gotest.tools)
279
280 `gotest.tools/v3/assert` is close in spirit
281 (wraps `*testing.T`-style helpers, diffs with `go-cmp`)
282 but keeps the package-function shape
283 (`assert.Equal(t, x, y)`, `assert.DeepEqual(t, x, y, opts...)`)
284 and leans on go-cmp's option system for custom comparisons,
285 where check uses a small `RegisterEqualChecker`/`RegisterErrChecker` registry instead.
286 If you already rely on go-cmp's options (unexported fields, custom comparers, ...),
287 it plugs into check just as easily: register it once with
288 `check.RegisterEqualChecker(func(a, b any) (bool, bool) { return cmp.Equal(a, b), true })`
289 to make it check's default, or call it ad hoc with `t.True(cmp.Equal(got, want))`
290 (no dump/diff for that one call, but full access to go-cmp's own options).
291
292 ## Non-goals
293
294 - No BDD/suites - check stays inside `go test`, `t.Run` and `t.Parallel`;
295 see [Rationale](#rationale).
296 - No `Eventually`/`Never` polling helpers - Go's `testing/synctest`
297 covers that class of test better (deterministic virtual time, no flaky sleeps).
298 - No HTTP handler assertions (testify's `HTTPSuccess`/`HTTPRedirect`/`HTTPBodyContains`/...) -
299 `net/http/httptest` plus check's own checkers already cover that ground, e.g.
300 `t.Match(rec.Body.String(), pattern)` or `t.Equal(rec.Code, http.StatusOK)`.
301 - No mocking - pair check with whatever mocking library you already use.
302
303 ## TODO
304
305 - Questionable:
306 - [ ] Provide a way to force binary dump for utf8.Valid `string`/`[]byte`?
307 - [ ] Count skipped tests (will have to overload `Skip`, `Skipf`, `SkipNow`)?
308 - Complicated:
309 - [ ] Show line of source_test.go with failed test.