-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors_test.go
More file actions
364 lines (349 loc) · 13.6 KB
/
errors_test.go
File metadata and controls
364 lines (349 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Copyright 2026 AxonOps Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// errors_test.go pins the contract of the package-level sentinel errors:
//
// - errors.Is wrap-identity: fmt.Errorf("%w", ErrX) is discoverable
// as ErrX via errors.Is (the canonical Go discrimination pattern).
// - Each sentinel carries a distinct message — no two sentinels alias
// to the same Error() string.
// - Each message starts with the "fuzzymatch: " package prefix per
// .claude/skills/go-coding-standards.
// - Each message body (after the prefix) is lowercase and carries no
// trailing punctuation per the same standard.
// - Each sentinel is distinguishable from every other via errors.Is
// (pairwise distinct as values).
//
// Stdlib testing only — no testify in root.
package fuzzymatch_test
import (
"errors"
"fmt"
"strings"
"testing"
"unicode"
"unicode/utf8"
"github.com/axonops/fuzzymatch"
)
// sentinelCases enumerates every sentinel exported from errors.go so
// the table-driven tests below stay in sync with the source as new
// sentinels are added (later phases extend this list).
//
// Order is not load-bearing — the tests iterate the slice.
func sentinelCases() []struct {
name string
err error
} {
return []struct {
name string
err error
}{
{"ErrInvalidAlgoID", fuzzymatch.ErrInvalidAlgoID},
{"ErrInvalidInnerAlgo", fuzzymatch.ErrInvalidInnerAlgo},
{"ErrInvalidQGramSize", fuzzymatch.ErrInvalidQGramSize},
{"ErrInvalidTverskyParam", fuzzymatch.ErrInvalidTverskyParam},
// Phase 8 sentinels — Scorer construction surface.
{"ErrEmptyScorer", fuzzymatch.ErrEmptyScorer},
{"ErrInvalidWeight", fuzzymatch.ErrInvalidWeight},
{"ErrInvalidThreshold", fuzzymatch.ErrInvalidThreshold},
{"ErrMissingThreshold", fuzzymatch.ErrMissingThreshold},
// Phase 8.5 sentinels — typed-panic value for library bugs.
{"ErrInternalInvariantViolated", fuzzymatch.ErrInternalInvariantViolated},
// Phase 8.5 R2 sentinel — Smith-Waterman-Gotoh parameter guard.
{"ErrInvalidSWGParam", fuzzymatch.ErrInvalidSWGParam},
// Phase 10 sentinels — Extract / ExtractOne validation surface
// per 10-CONTEXT.md §1 D-04 + §2 D-12 + §3 D-13 + §3 D-14.
{"ErrInvalidCutoff", fuzzymatch.ErrInvalidCutoff},
{"ErrInvalidLimit", fuzzymatch.ErrInvalidLimit},
{"ErrInvalidChoice", fuzzymatch.ErrInvalidChoice},
{"ErrMissingScorer", fuzzymatch.ErrMissingScorer},
{"ErrConflictingScorer", fuzzymatch.ErrConflictingScorer},
}
}
// TestSentinels_Identity asserts errors.Is(sentinel, sentinel) is true
// for each Phase 8 Scorer sentinel and that the canonical message
// strings match the contract pinned in CONTEXT.md §2 / PATTERNS.md.
// This is the Phase 8 plan 08-01 acceptance gate for the four new
// Scorer-construction sentinels.
func TestSentinels_Identity(t *testing.T) {
cases := []struct {
name string
err error
message string
}{
{
name: "ErrEmptyScorer",
err: fuzzymatch.ErrEmptyScorer,
message: "fuzzymatch: scorer has no algorithms (pass at least one WithAlgorithm option or use DefaultScorer)",
},
{
name: "ErrInvalidWeight",
err: fuzzymatch.ErrInvalidWeight,
message: "fuzzymatch: invalid algorithm weight (must be > 0)",
},
{
name: "ErrInvalidThreshold",
err: fuzzymatch.ErrInvalidThreshold,
message: "fuzzymatch: invalid threshold (must be in [0.0, 1.0])",
},
{
name: "ErrMissingThreshold",
err: fuzzymatch.ErrMissingThreshold,
message: "fuzzymatch: scorer threshold required (pass WithThreshold or use DefaultScorer)",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if c.err == nil {
t.Fatalf("%s is nil — Phase 8 sentinel missing from errors.go", c.name)
}
if !errors.Is(c.err, c.err) {
t.Errorf("errors.Is(%s, %s) = false; want true (sentinel identity)", c.name, c.name)
}
if got := c.err.Error(); got != c.message {
t.Errorf("%s.Error() = %q; want %q", c.name, got, c.message)
}
const prefix = "fuzzymatch: "
if !strings.HasPrefix(c.err.Error(), prefix) {
t.Errorf("%s.Error() = %q; must begin with %q", c.name, c.err.Error(), prefix)
}
})
}
}
// TestSentinels_WrapIdentity asserts each sentinel survives one level
// of fmt.Errorf("%w") wrapping discoverable by errors.Is. This is the
// canonical Go pattern for sentinel discrimination across layers.
func TestSentinels_WrapIdentity(t *testing.T) {
for _, c := range sentinelCases() {
t.Run(c.name, func(t *testing.T) {
if c.err == nil {
t.Fatalf("%s: sentinel is nil — exported var missing from errors.go", c.name)
}
wrapped := fmt.Errorf("scorer: %w", c.err)
if !errors.Is(wrapped, c.err) {
t.Errorf("errors.Is(fmt.Errorf(\"scorer: %%w\", %s), %s) = false; want true", c.name, c.name)
}
})
}
}
// TestSentinels_DistinctMessages asserts no two sentinels share the
// same Error() string. Two sentinels with the same message would be
// indistinguishable from a log-grep perspective even though errors.Is
// would still distinguish them.
func TestSentinels_DistinctMessages(t *testing.T) {
cases := sentinelCases()
// Map check, internal — output isn't a slice/map, so the
// no-map-iteration rule doesn't apply (test internals are exempt).
seen := make(map[string]string, len(cases))
for _, c := range cases {
msg := c.err.Error()
if prev, dup := seen[msg]; dup {
t.Errorf("%s.Error() = %q duplicates %s.Error()", c.name, msg, prev)
}
seen[msg] = c.name
}
if len(seen) != len(cases) {
t.Errorf("distinct message count = %d; want %d", len(seen), len(cases))
}
}
// TestSentinels_StartWithPackagePrefix asserts every sentinel message
// begins with the "fuzzymatch: " prefix so that wrapper composition
// produces readable error chains.
func TestSentinels_StartWithPackagePrefix(t *testing.T) {
const prefix = "fuzzymatch: "
for _, c := range sentinelCases() {
t.Run(c.name, func(t *testing.T) {
msg := c.err.Error()
if !strings.HasPrefix(msg, prefix) {
t.Errorf("%s.Error() = %q; must begin with %q", c.name, msg, prefix)
}
})
}
}
// TestSentinels_LowercaseAndNoTrailingPunctuation asserts every
// sentinel's body text (after the "fuzzymatch: " prefix) starts with a
// lowercase rune and carries no trailing punctuation ('.', '!', or
// '?'). This matches the Go convention codified in
// .claude/skills/go-coding-standards/SKILL.md ("Error strings:
// lowercase, no punctuation") which constrains the FIRST-rune
// capitalisation only — embedded identifier names (e.g.
// "WithAlgorithm", "DefaultScorer") inside parenthesised remediation
// hints are permitted because they refer to public API symbols and
// disambiguate the actionable next step for the consumer.
func TestSentinels_LowercaseAndNoTrailingPunctuation(t *testing.T) {
const prefix = "fuzzymatch: "
for _, c := range sentinelCases() {
t.Run(c.name, func(t *testing.T) {
msg := c.err.Error()
body := strings.TrimPrefix(msg, prefix)
if body == msg {
// Already failed in TestSentinels_StartWithPackagePrefix; nothing more to do here.
return
}
// Trailing punctuation check: '.', '!', '?' all disallowed.
if last := body[len(body)-1]; last == '.' || last == '!' || last == '?' {
t.Errorf("%s.Error() = %q has trailing punctuation %q", c.name, msg, string(last))
}
// First-rune lowercase gate. Per Effective Go's error-string
// convention, the message is concatenable into other
// contexts — capitalising the FIRST word would produce
// awkward compositions ("scorer: Invalid weight"). Embedded
// identifier names later in the message are referencing
// public Go symbols and are permitted (and required for
// disambiguation of remediation hints). Inspect only the
// first rune via utf8.DecodeRuneInString rather than a
// for-range loop with `break` (linter-friendly).
if r, _ := utf8.DecodeRuneInString(body); unicode.IsUpper(r) {
t.Errorf("%s.Error() body %q starts with uppercase rune %q (only embedded identifier names may be capitalised)", c.name, body, string(r))
}
})
}
}
// TestSentinels_AreDistinctAsValues asserts pairwise distinctness via
// errors.Is. This catches the regression where a future refactor
// might accidentally alias two sentinels to the same errors.New value
// (e.g. `ErrInvalidInnerAlgo = ErrInvalidAlgoID`).
func TestSentinels_AreDistinctAsValues(t *testing.T) {
cases := sentinelCases()
for i, a := range cases {
for j, b := range cases {
if i == j {
continue
}
if errors.Is(a.err, b.err) {
t.Errorf("errors.Is(%s, %s) = true; sentinels must be pairwise distinct", a.name, b.name)
}
}
}
}
// TestSentinels_NotNil asserts every sentinel is initialised (non-nil).
// This is a belt-and-braces gate against a future refactor accidentally
// declaring a sentinel without assigning it (`var ErrX error` instead
// of `var ErrX = errors.New(...)`).
func TestSentinels_NotNil(t *testing.T) {
for _, c := range sentinelCases() {
t.Run(c.name, func(t *testing.T) {
if c.err == nil {
t.Errorf("%s is nil — must be initialised via errors.New", c.name)
}
})
}
}
// extractSentinelCases enumerates the five Phase 10 Extract /
// ExtractOne validation sentinels per 10-CONTEXT.md §1 D-04 + §2 D-12
// + §3 D-13 + §3 D-14. The plan 10-01 acceptance gate is that every
// sentinel has a distinct identity (errors.Is is reflexive on the
// sentinel and rejects every other sentinel), the "fuzzymatch: "
// prefix is preserved, and the canonical message strings match the
// declarations in errors.go.
func extractSentinelCases() []struct {
name string
err error
message string
} {
return []struct {
name string
err error
message string
}{
{
name: "ErrInvalidCutoff",
err: fuzzymatch.ErrInvalidCutoff,
message: "fuzzymatch: invalid cutoff (must be finite, in [0.0, 1.0])",
},
{
name: "ErrInvalidLimit",
err: fuzzymatch.ErrInvalidLimit,
message: "fuzzymatch: invalid limit (must be non-negative; 0 means unlimited)",
},
{
name: "ErrInvalidChoice",
err: fuzzymatch.ErrInvalidChoice,
message: "fuzzymatch: invalid choice (empty Name)",
},
{
name: "ErrMissingScorer",
err: fuzzymatch.ErrMissingScorer,
message: "fuzzymatch: missing scoring option (pass WithScorer or WithAlgorithmID to Extract)",
},
{
name: "ErrConflictingScorer",
err: fuzzymatch.ErrConflictingScorer,
message: "fuzzymatch: conflicting scoring options (Extract accepts WithScorer or WithAlgorithmID but not both)",
},
}
}
// TestExtractSentinels_Distinct asserts every Phase 10 Extract sentinel
// is reflexively errors.Is-equal to itself and pairwise distinct from
// every other Extract sentinel. Five identities + C(5,2) = 10 distinct
// pairs. The canonical-message gate also confirms the
// "fuzzymatch: " prefix is preserved on each.
func TestExtractSentinels_Distinct(t *testing.T) {
cases := extractSentinelCases()
const prefix = "fuzzymatch: "
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if c.err == nil {
t.Fatalf("%s is nil — Phase 10 sentinel missing from errors.go", c.name)
}
if !errors.Is(c.err, c.err) {
t.Errorf("errors.Is(%s, %s) = false; want true (sentinel identity)", c.name, c.name)
}
if got := c.err.Error(); got != c.message {
t.Errorf("%s.Error() = %q; want %q (canonical message)", c.name, got, c.message)
}
if !strings.HasPrefix(c.err.Error(), prefix) {
t.Errorf("%s.Error() = %q; must begin with %q", c.name, c.err.Error(), prefix)
}
})
}
// Pairwise distinctness — guards against accidental aliasing
// (e.g. `var ErrInvalidCutoff = ErrInvalidThreshold` slip).
for i, a := range cases {
for j, b := range cases {
if i == j {
continue
}
if errors.Is(a.err, b.err) {
t.Errorf("errors.Is(%s, %s) = true; Phase 10 sentinels must be pairwise distinct", a.name, b.name)
}
}
}
}
// TestExtractSentinels_JoinDiscrimination asserts the errors.Join
// collect-all behaviour documented in ErrInvalidChoice's godoc. Go
// 1.20+ errors.Is walks Unwrap() []error so a joined error wrapping
// multiple offending-index errors still discriminates as
// ErrInvalidChoice. Plan 10-03's Choice.Name validation surface
// produces exactly this shape (per Phase 9 D-03 precedent applied to
// Phase 10 D-14).
func TestExtractSentinels_JoinDiscrimination(t *testing.T) {
t.Parallel()
// Simulate the plan 10-03 collect-all idiom: two offending
// indices, each wrapping ErrInvalidChoice with a context string
// citing the offending index.
e1 := fmt.Errorf("invalid choice at index %d: empty name: %w", 0, fuzzymatch.ErrInvalidChoice)
e2 := fmt.Errorf("invalid choice at index %d: empty name: %w", 3, fuzzymatch.ErrInvalidChoice)
joined := errors.Join(e1, e2)
if joined == nil {
t.Fatal("errors.Join(e1, e2) returned nil; expected non-nil joined error")
}
if !errors.Is(joined, fuzzymatch.ErrInvalidChoice) {
t.Errorf("errors.Is(joined, ErrInvalidChoice) = false; expected true via Go 1.20+ Unwrap() []error walking")
}
// Sanity: the joined error must NOT spuriously match another
// Phase 10 sentinel.
if errors.Is(joined, fuzzymatch.ErrInvalidCutoff) {
t.Error("errors.Is(joined, ErrInvalidCutoff) = true; joined ErrInvalidChoice chain must not spuriously match other sentinels")
}
}