forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner_test.go
498 lines (440 loc) · 11.9 KB
/
runner_test.go
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package tester_test
import (
"context"
"testing"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/cover"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/tester"
"github.com/open-policy-agent/opa/topdown"
"github.com/open-policy-agent/opa/types"
"github.com/open-policy-agent/opa/util/test"
)
func TestRunner_EnableFailureLine(t *testing.T) {
ctx := context.Background()
files := map[string]string{
"/a_test.rego": `package foo
test_a {
true
false
true
}
test_b {
false
true
}
test_c {
input.x = 1 # indexer understands this
}`,
}
tests := map[[2]string]struct {
wantErr bool
wantFail bool
FailRow int
}{
{"data.foo", "test_a"}: {false, true, 4},
{"data.foo", "test_b"}: {false, true, 8},
{"data.foo", "test_c"}: {false, true, 0},
}
test.WithTempFS(files, func(d string) {
paths := []string{d}
modules, store, err := tester.Load(paths, nil)
if err != nil {
t.Fatal(err)
}
ch, err := tester.NewRunner().EnableFailureLine(true).SetStore(store).Run(ctx, modules)
if err != nil {
t.Fatal(err)
}
var rs []*tester.Result
for r := range ch {
rs = append(rs, r)
}
seen := map[[2]string]struct{}{}
for i := range rs {
k := [2]string{rs[i].Package, rs[i].Name}
seen[k] = struct{}{}
exp, ok := tests[k]
if !ok {
t.Errorf("Unexpected result for %v", k)
} else if exp.wantErr != (rs[i].Error != nil) || exp.wantFail != rs[i].Fail {
t.Errorf("Expected %v for %v but got: %v", exp, k, rs[i])
} else if exp.FailRow != 0 {
if rs[i].FailedAt == nil || rs[i].FailedAt.Location == nil {
t.Errorf("Failed line not set")
} else if rs[i].FailedAt.Location.Row != exp.FailRow {
t.Errorf("Expected Failed Line %v but got: %v", exp.FailRow, rs[i].FailedAt.Location.Row)
}
} else if rs[i].FailedAt != nil {
t.Errorf("Failed line set, but expected not set.")
}
}
// This makes sure all tests were executed
for k := range tests {
if _, ok := seen[k]; !ok {
t.Errorf("Expected result for %v", k)
}
}
})
}
func TestRun(t *testing.T) {
testRun(t, testRunConfig{})
}
func TestRunBenchmark(t *testing.T) {
testRun(t, testRunConfig{bench: true})
}
func TestRunWithCoverage(t *testing.T) {
cov := cover.New()
modules := testRun(t, testRunConfig{coverTracer: cov})
report := cov.Report(modules)
if len(report.Files) != len(modules) {
t.Errorf("Expected %d files in coverage report, got %d", len(modules), len(report.Files))
}
if report.Coverage == 0 {
t.Error("Expected test coverage")
}
}
type expectedTestResult struct {
wantErr bool
wantFail bool
}
type testRunConfig struct {
bench bool
filter string
coverTracer topdown.QueryTracer
}
type expectedTestResults map[[2]string]expectedTestResult
func testRun(t *testing.T, conf testRunConfig) map[string]*ast.Module {
files := map[string]string{
"/a.rego": `package foo
allow { true }
`,
"/a_test.rego": `package foo
test_pass { allow }
non_test { true }
test_fail { not allow }
test_fail_non_bool = 100
test_err { conflict }
conflict = true
conflict = false
test_duplicate { false }
test_duplicate { true }
test_duplicate { true }
`,
"/b_test.rego": `package bar
test_duplicate { true }`,
}
tests := expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
{"data.foo", "test_fail"}: {false, true},
{"data.foo", "test_fail_non_bool"}: {false, true},
{"data.foo", "test_duplicate"}: {false, true},
{"data.foo", "test_duplicate#01"}: {false, false},
{"data.foo", "test_duplicate#02"}: {false, false},
{"data.foo", "test_err"}: {true, false},
{"data.bar", "test_duplicate"}: {false, false},
}
var modules map[string]*ast.Module
test.WithTempFS(files, func(d string) {
var rs []*tester.Result
rs, modules = doTestRunWithTmpDir(t, d, conf)
validateTestResults(t, tests, rs, conf)
})
return modules
}
func doTestRunWithTmpDir(t *testing.T, dir string, conf testRunConfig) ([]*tester.Result, map[string]*ast.Module) {
t.Helper()
ctx := context.Background()
paths := []string{dir}
modules, store, err := tester.Load(paths, nil)
if err != nil {
t.Fatal(err)
}
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)
runner := tester.NewRunner().
SetStore(store).
SetModules(modules).
Filter(conf.filter).
SetTimeout(60 * time.Second).
SetCoverageQueryTracer(conf.coverTracer)
var ch chan *tester.Result
if conf.bench {
ch, err = runner.RunBenchmarks(ctx, txn, tester.BenchmarkOptions{})
} else {
ch, err = runner.RunTests(ctx, txn)
}
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
var rs []*tester.Result
for r := range ch {
rs = append(rs, r)
}
return rs, modules
}
func validateTestResults(t *testing.T, tests expectedTestResults, rs []*tester.Result, conf testRunConfig) {
t.Helper()
seen := map[[2]string]struct{}{}
for i := range rs {
k := [2]string{rs[i].Package, rs[i].Name}
seen[k] = struct{}{}
exp, ok := tests[k]
if !ok {
t.Errorf("Unexpected result for %v", k)
} else if exp.wantErr != (rs[i].Error != nil) || exp.wantFail != rs[i].Fail {
t.Errorf("Expected %+v for %v but got: %v", exp, k, rs[i])
} else {
// Test passed
if conf.bench && rs[i].BenchmarkResult == nil {
t.Errorf("Expected BenchmarkResult for test %v, got nil", k)
} else if !conf.bench && rs[i].BenchmarkResult != nil {
t.Errorf("Unexpected BenchmarkResult for test %v, expected nil", k)
}
}
}
for k := range tests {
if _, ok := seen[k]; !ok {
t.Errorf("Expected result for %v", k)
}
}
}
func TestRunWithFilterRegex(t *testing.T) {
files := map[string]string{
"/a.rego": `package foo
allow { true }
`,
"/a_test.rego": `package foo
test_pass { allow }
non_test { true }
test_fail { not allow }
test_fail_non_bool = 100
test_err { conflict }
conflict = true
conflict = false
test_duplicate { false }
test_duplicate { true }
test_duplicate { true }
`,
"/b_test.rego": `package bar
test_duplicate { true }`,
}
cases := []struct {
note string
regex string
tests expectedTestResults
}{
{
note: "all tests match",
regex: ".*",
tests: expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
{"data.foo", "test_fail"}: {false, true},
{"data.foo", "test_fail_non_bool"}: {false, true},
{"data.foo", "test_duplicate"}: {false, true},
{"data.foo", "test_duplicate#01"}: {false, false},
{"data.foo", "test_duplicate#02"}: {false, false},
{"data.foo", "test_err"}: {true, false},
{"data.bar", "test_duplicate"}: {false, false},
},
},
{
note: "no filter",
regex: "",
tests: expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
{"data.foo", "test_fail"}: {false, true},
{"data.foo", "test_fail_non_bool"}: {false, true},
{"data.foo", "test_duplicate"}: {false, true},
{"data.foo", "test_duplicate#01"}: {false, false},
{"data.foo", "test_duplicate#02"}: {false, false},
{"data.foo", "test_err"}: {true, false},
{"data.bar", "test_duplicate"}: {false, false},
},
},
{
note: "no tests match",
regex: "^$",
tests: nil,
},
{
note: "single package name",
regex: "bar",
tests: expectedTestResults{
{"data.bar", "test_duplicate"}: {false, false},
},
},
{
note: "single package explicit",
regex: "data.bar.test_duplicate",
tests: expectedTestResults{
{"data.bar", "test_duplicate"}: {false, false},
},
},
{
note: "single test ",
regex: "test_pass",
tests: expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
},
},
{
note: "single test explicit",
regex: "data.foo.test_pass",
tests: expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
},
},
{
note: "wildcards",
regex: "^.*foo.*_fail.*$",
tests: expectedTestResults{
{"data.foo", "test_fail"}: {false, true},
{"data.foo", "test_fail_non_bool"}: {false, true},
},
},
{
note: "mixed",
regex: "(bar|data.foo.test_pass)",
tests: expectedTestResults{
{"data.foo", "test_pass"}: {false, false},
{"data.bar", "test_duplicate"}: {false, false},
},
},
{
note: "case insensitive",
regex: "(?i)DATA.BAR",
tests: expectedTestResults{
{"data.bar", "test_duplicate"}: {false, false},
},
},
}
test.WithTempFS(files, func(d string) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
conf := testRunConfig{filter: tc.regex}
rs, _ := doTestRunWithTmpDir(t, d, conf)
validateTestResults(t, tc.tests, rs, conf)
})
}
})
}
func TestRunnerCancel(t *testing.T) {
testCancel(t, false)
}
func TestRunnerCancelBenchmark(t *testing.T) {
testCancel(t, true)
}
func testCancel(t *testing.T, bench bool) {
registerSleepBuiltin()
ctx, cancel := context.WithCancel(context.Background())
module := `package foo
test_1 { test.sleep("100ms") }
test_2 { true }`
files := map[string]string{
"/a_test.rego": module,
}
test.WithTempFS(files, func(d string) {
paths := []string{d}
modules, store, err := tester.Load(paths, nil)
if err != nil {
t.Fatal(err)
}
txn := storage.NewTransactionOrDie(ctx, store)
runner := tester.NewRunner().SetStore(store).SetModules(modules)
// Everything below uses a canceled context..
cancel()
var ch chan *tester.Result
if bench {
ch, err = runner.RunBenchmarks(ctx, txn, tester.BenchmarkOptions{})
} else {
ch, err = runner.RunTests(ctx, txn)
}
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
var results []*tester.Result
for r := range ch {
results = append(results, r)
}
if len(results) != 1 {
t.Fatalf("Expected only a single test result, got: %d", len(results))
}
if !topdown.IsCancel(results[0].Error) {
t.Fatalf("Expected cancel error for first test but got: %v", results[0].Error)
}
})
}
func TestRunnerTimeout(t *testing.T) {
testTimeout(t, false)
}
func TestRunnerTimeoutBenchmark(t *testing.T) {
testTimeout(t, true)
}
func testTimeout(t *testing.T, bench bool) {
registerSleepBuiltin()
ctx := context.Background()
files := map[string]string{
"/a_test.rego": `package foo
test_1 { test.sleep("100ms") }
# 1ms is low enough for a single test to pass,
# but long enough for benchmark to timeout
test_2 { test.sleep("1ms") }`,
}
test.WithTempFS(files, func(d string) {
paths := []string{d}
modules, store, err := tester.Load(paths, nil)
if err != nil {
t.Fatal(err)
}
duration, err := time.ParseDuration("15ms")
if err != nil {
t.Fatal(err)
}
txn := storage.NewTransactionOrDie(ctx, store)
runner := tester.NewRunner().SetTimeout(duration).SetStore(store).SetModules(modules)
var ch chan *tester.Result
if bench {
ch, err = runner.RunBenchmarks(ctx, txn, tester.BenchmarkOptions{})
} else {
ch, err = runner.RunTests(ctx, txn)
}
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
var results []*tester.Result
for r := range ch {
results = append(results, r)
}
if !topdown.IsCancel(results[0].Error) {
t.Fatalf("Expected cancel error for first test but got: %v", results[0].Error)
}
if bench {
if !topdown.IsCancel(results[1].Error) {
t.Fatalf("Expected cancel error for second test but got: %v", results[1].Error)
}
} else {
if topdown.IsCancel(results[1].Error) {
t.Fatalf("Expected no error for second test, but it timed out")
}
}
})
}
func registerSleepBuiltin() {
ast.RegisterBuiltin(&ast.Builtin{
Name: "test.sleep",
Decl: types.NewFunction(
types.Args(types.S),
types.NewNull(),
),
})
topdown.RegisterFunctionalBuiltin1("test.sleep", func(a ast.Value) (ast.Value, error) {
d, _ := time.ParseDuration(string(a.(ast.String)))
time.Sleep(d)
return ast.Null{}, nil
})
}