Repository navigation
Expand file tree
/
Copy pathengine_test.go
More file actions
305 lines (278 loc) · 11.6 KB
/
Copy pathengine_test.go
File metadata and controls
305 lines (278 loc) · 11.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
package redact
import (
_ "embed"
"errors"
"reflect"
"regexp"
"slices"
"testing"
"gopkg.in/yaml.v3"
)
//go:embed testdata/engine_configuration.yaml
var engineConfigurationData []byte
const engineConfigurationTestFixturePath = "testdata/engine_configuration.yaml"
type engineNameFixture struct {
Name string `yaml:"name"`
Value string `yaml:"value"`
Want engineName `yaml:"want"`
Error bool `yaml:"error"`
}
type engineConfigurationFixtures struct {
Engines []engineName `yaml:"engines"`
RequiredNames []string `yaml:"required_names"`
Cases []engineNameFixture `yaml:"cases"`
ResidueOnlyPattern string `yaml:"residue_only_pattern"`
Routing engineRoutingFixtures `yaml:"routing"`
JSONKeyRouting jsonKeyRoutingFixtures `yaml:"json_key_routing"`
}
type jsonKeyRoutingFixtures struct {
RequiredNames []string `yaml:"required_names"`
Cases []jsonKeyRoutingCase `yaml:"cases"`
}
type jsonKeyRoutingCase struct {
Name string `yaml:"name"`
JSON string `yaml:"json"`
Want string `yaml:"want"`
ProbeRule string `yaml:"probe_rule"`
Scans int `yaml:"scans"`
LastScan string `yaml:"last_scan"`
}
type engineRoutingFixtures struct {
Patterns []UserPattern `yaml:"patterns"`
XDGDataHome string `yaml:"xdg_data_home"`
RequiredNames []string `yaml:"required_names"`
Cases []engineRoutingCase `yaml:"cases"`
}
type engineRoutingCase struct {
Name string `yaml:"name"`
Rule string `yaml:"rule"`
Input string `yaml:"input"`
Output string `yaml:"output"`
ReplacementOverride string `yaml:"replacement_override"`
ExpectReplacement bool `yaml:"expect_replacement"`
}
func loadEngineConfigurationFixtures(t *testing.T) engineConfigurationFixtures {
t.Helper()
var fixtures engineConfigurationFixtures
if err := yaml.Unmarshal(engineConfigurationData, &fixtures); err != nil {
t.Fatal(err)
}
if err := requireFixtureNames(engineConfigurationTestFixturePath, "required_names", fixtures.RequiredNames, fixtureNames(fixtures.Cases, func(row engineNameFixture) string { return row.Name })); err != nil {
t.Fatal(err)
}
if fixtures.ResidueOnlyPattern == "" {
t.Fatal("restore the residue-only pattern in the engine configuration fixture to exercise compiler isolation")
}
if err := requireFixtureNames(engineConfigurationTestFixturePath, "routing/required_names", fixtures.Routing.RequiredNames, fixtureNames(fixtures.Routing.Cases, func(row engineRoutingCase) string { return row.Name })); err != nil {
t.Fatal(err)
}
if err := requireFixtureNames(engineConfigurationTestFixturePath, "json_key_routing/required_names", fixtures.JSONKeyRouting.RequiredNames, fixtureNames(fixtures.JSONKeyRouting.Cases, func(row jsonKeyRoutingCase) string { return row.Name })); err != nil {
t.Fatal(err)
}
if len(fixtures.Routing.Patterns) == 0 || fixtures.Routing.XDGDataHome == "" {
t.Fatal("restore configured patterns and XDG data home to exercise both routing sources")
}
return fixtures
}
func TestEngineIdentityRegistry(t *testing.T) {
fixtures := loadEngineConfigurationFixtures(t)
if got := AllEngines(); !slices.Equal(got, fixtures.Engines) {
t.Fatalf("AllEngines = %v, want ordered membership %v", got, fixtures.Engines)
}
names := AllEngines()
names[0] = "modified"
if !slices.Equal(AllEngines(), fixtures.Engines) {
t.Fatal("mutating AllEngines result changed the identity registry")
}
for _, row := range fixtures.Cases {
t.Run(row.Name, func(t *testing.T) {
got, err := NewEngineName(row.Value)
if (err != nil) != row.Error || got != row.Want {
t.Fatalf("NewEngineName(%q) = %q, %v; want %q, error=%v", row.Value, got, err, row.Want, row.Error)
}
})
}
}
func TestEngineIdentityReportsSelected(t *testing.T) {
if got, want := EngineIdentity(), selectEngine().Identity(); got != want {
t.Fatalf("EngineIdentity() = %q, want %q", got, want)
}
}
func TestEngineDefaultRemainsStdlib(t *testing.T) {
r, err := NewRedactor(Standard, nil, XDGPaths{})
if err != nil {
t.Fatal(err)
}
defaultRedactor := r.(*DefaultRedactor)
if selectEngine().Identity() != engineGoRegexp || defaultRedactor.patterns != nil {
t.Fatal("NewRedactor must reuse the original stdlib patterns by default")
}
if detector := NewResidueDetector().(*DefaultResidueDetector); detector.patterns != nil {
t.Fatal("NewResidueDetector must reuse the original stdlib patterns by default")
}
}
type rejectingEngine struct {
goRegexpEngine
err error
}
func (e rejectingEngine) Compile(string) (compiled, error) { return nil, e.err }
func TestEngineCompileFailureRefusesConstruction(t *testing.T) {
cause := errors.New("engine compiler unavailable")
e := rejectingEngine{err: cause}
if r, err := newRedactorWithEngine(e, Standard, nil, XDGPaths{}); r != nil || !errors.Is(err, cause) {
t.Fatalf("redactor = %v, %v; want no partial redactor and wrapped compiler error", r, err)
}
if p, err := newTitlePipelineWithEngine(e); p != nil || !errors.Is(err, cause) {
t.Fatalf("title pipeline = %v, %v; want no partial pipeline and wrapped compiler error", p, err)
}
if d, err := newResidueDetector(e); d != nil || !errors.Is(err, cause) {
t.Fatalf("residue detector = %v, %v; want no partial detector and wrapped compiler error", d, err)
}
}
type residueRejectingEngine struct {
goRegexpEngine
rejected string
err error
}
func (e residueRejectingEngine) Compile(pattern string) (compiled, error) {
if pattern == e.rejected {
return nil, e.err
}
return e.goRegexpEngine.Compile(pattern)
}
func TestEngineTitleCompilesOnlyTitleRules(t *testing.T) {
fixtures := loadEngineConfigurationFixtures(t)
pattern := regexp.MustCompile(fixtures.ResidueOnlyPattern)
original := ResidueRules
t.Cleanup(func() { ResidueRules = original })
ResidueRules = append(slices.Clone(ResidueRules), ResidueRule{ID: "residue_construction_probe", Pattern: pattern})
cause := errors.New("residue pattern refused")
e := residueRejectingEngine{rejected: pattern.String(), err: cause}
pipeline, err := newTitlePipelineWithEngine(e)
if err != nil {
t.Fatalf("title construction touched an unrelated residue pattern: %v", err)
}
if _, exists := pipeline.patterns[pattern]; exists {
t.Fatal("title pattern set contains an unrelated residue pattern")
}
// Positive control: the redactor really does include advisory residue rules.
if r, err := newRedactorWithEngine(e, Standard, nil, XDGPaths{}); r != nil || !errors.Is(err, cause) {
t.Fatalf("redactor = %v, %v; want refusal from the residue compiler", r, err)
}
}
// routingSpyEngine compiles real stdlib patterns and records calls per compiled
// entry, not per engine. Built-in scans cannot satisfy a configured/XDG check.
type routingSpyEngine struct{ goRegexpEngine }
func (e routingSpyEngine) Compile(pattern string) (compiled, error) {
p, err := e.goRegexpEngine.Compile(pattern)
if err != nil {
return nil, err
}
return &routingSpyPattern{compiled: p}, nil
}
type routingSpyPattern struct {
compiled
scans, replacements int
lastScan, lastReplace, lastReplacement string
}
func (p *routingSpyPattern) FindAllStringIndex(input string, n int) [][]int {
p.scans++
p.lastScan = input
return p.compiled.FindAllStringIndex(input, n)
}
func (p *routingSpyPattern) ReplaceAllString(input, replacement string) string {
p.replacements++
p.lastReplace, p.lastReplacement = input, replacement
return p.compiled.ReplaceAllString(input, replacement)
}
// Mutation checks: bypassing the compiled lookup in Detect fails each entry's
// scan assertion; bypassing it in back-reference replacement fails the rewrite
// assertions for both configured and generated rules, even with correct output.
// Ordinary XDG replacement is literal and deliberately invokes no engine rewrite.
func TestEngineConfiguredAndXDGRouting(t *testing.T) {
fixtures := loadEngineConfigurationFixtures(t).Routing
for _, row := range fixtures.Cases {
t.Run(row.Name, func(t *testing.T) {
redactor, err := newRedactorWithEngine(routingSpyEngine{}, Standard, fixtures.Patterns, XDGPaths{DataHome: fixtures.XDGDataHome})
if err != nil {
t.Fatal(err)
}
r := redactor.(*DefaultRedactor)
var target *Rule
for i := range r.userRules {
if r.userRules[i].ID == row.Rule {
target = &r.userRules[i]
break
}
}
if target == nil {
t.Fatalf("rule %q was not constructed; restore the fixture's configured/XDG source", row.Rule)
}
if row.ReplacementOverride != "" {
// Only this test's generated replacement changes. The generated
// pattern and normal production back-reference branch are intact.
target.Replacement = row.ReplacementOverride
}
spy, ok := r.patterns[target.Pattern].(*routingSpyPattern)
if !ok {
t.Fatalf("%s: no compiled spy entry; construction bypassed the injected engine", row.Rule)
}
matches := r.Detect(row.Input)
if len(matches) != 1 || matches[0].Rule != row.Rule {
t.Fatalf("Detect = %v; want exactly one %s match", matches, row.Rule)
}
if spy.scans != 1 || spy.lastScan != row.Input {
t.Fatalf("%s: Detect scans=%d input=%q; want one spy scan of %q", row.Rule, spy.scans, spy.lastScan, row.Input)
}
if got := r.Redact(row.Input, matches); got != row.Output {
t.Fatalf("Redact = %q, want %q", got, row.Output)
}
wantReplacements := 0
if row.ExpectReplacement {
wantReplacements = 1
}
if spy.scans != 1 || spy.replacements != wantReplacements {
t.Fatalf("%s: Redact scans=%d replacements=%d; want no rescan and %d spy replacements", row.Rule, spy.scans, spy.replacements, wantReplacements)
}
if got := r.RedactText(row.Input); got != row.Output {
t.Fatalf("RedactText = %q, want %q", got, row.Output)
}
if spy.scans != 2 || spy.lastScan != row.Input || spy.replacements != 2*wantReplacements {
t.Fatalf("%s: RedactText scans=%d replacements=%d; want two total scans and %d spy replacements", row.Rule, spy.scans, spy.replacements, 2*wantReplacements)
}
if row.ExpectReplacement && (spy.lastReplace != matches[0].MatchedText || spy.lastReplacement != target.Replacement) {
t.Fatalf("%s: spy rewrite input=%q replacement=%q; want matched text %q and rule replacement %q", row.Rule, spy.lastReplace, spy.lastReplacement, matches[0].MatchedText, target.Replacement)
}
})
}
}
// TestEngineJSONKeyRouting pins which scans RedactJSON makes for a string
// under an object key, and that each goes through the injected engine. The
// decision to replace a value whole reads the value with the same detection as
// text, so a bypass of the compiled lookup fails the scan counts here.
func TestEngineJSONKeyRouting(t *testing.T) {
for _, row := range loadEngineConfigurationFixtures(t).JSONKeyRouting.Cases {
t.Run(row.Name, func(t *testing.T) {
redactor, err := newRedactorWithEngine(routingSpyEngine{}, Standard, nil, XDGPaths{})
if err != nil {
t.Fatal(err)
}
r := redactor.(*DefaultRedactor)
rule := findRuleByID(row.ProbeRule)
if rule == nil {
t.Fatalf("probe rule %q is not compiled", row.ProbeRule)
}
spy, ok := r.patterns[rule.Pattern].(*routingSpyPattern)
if !ok {
t.Fatalf("%s: no compiled spy entry; construction bypassed the injected engine", row.ProbeRule)
}
got := r.RedactJSON(decodeJSONFixture(t, row.Name, row.JSON))
if want := decodeJSONFixture(t, row.Name, row.Want); !reflect.DeepEqual(got, want) {
t.Fatalf("RedactJSON(%s) = %#v, want %#v", row.JSON, got, want)
}
if spy.scans != row.Scans || spy.lastScan != row.LastScan {
t.Fatalf("%s: scans=%d last=%q; want %d scans, the last of %q", row.ProbeRule, spy.scans, spy.lastScan, row.Scans, row.LastScan)
}
})
}
}