/
runner.go
627 lines (538 loc) · 16.9 KB
/
runner.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// 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 contains utilities for executing Rego tests.
package tester
import (
"bytes"
"context"
"fmt"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
wasm_errors "github.com/open-policy-agent/opa/internal/wasm/sdk/opa/errors"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/storage/inmem"
"github.com/open-policy-agent/opa/topdown"
)
// TestPrefix declares the prefix for all test rules.
const TestPrefix = "test_"
// SkipTestPrefix declares the prefix for tests that should be skipped.
const SkipTestPrefix = "todo_test_"
// Run executes all test cases found under files in path.
func Run(ctx context.Context, paths ...string) ([]*Result, error) {
return RunWithFilter(ctx, nil, paths...)
}
// RunWithFilter executes all test cases found under files in path. The filter
// will be applied to exclude files that should not be included.
func RunWithFilter(ctx context.Context, filter loader.Filter, paths ...string) ([]*Result, error) {
modules, store, err := Load(paths, nil)
if err != nil {
return nil, err
}
ch, err := NewRunner().SetStore(store).Run(ctx, modules)
if err != nil {
return nil, err
}
result := []*Result{}
for r := range ch {
result = append(result, r)
}
return result, nil
}
// Result represents a single test case result.
type Result struct {
Location *ast.Location `json:"location"`
Package string `json:"package"`
Name string `json:"name"`
Fail bool `json:"fail,omitempty"`
Error error `json:"error,omitempty"`
Skip bool `json:"skip,omitempty"`
Duration time.Duration `json:"duration"`
Trace []*topdown.Event `json:"trace,omitempty"`
Output []byte `json:"output,omitempty"`
FailedAt *ast.Expr `json:"failed_at,omitempty"`
BenchmarkResult *testing.BenchmarkResult `json:"benchmark_result,omitempty"`
}
func newResult(loc *ast.Location, pkg, name string, duration time.Duration, trace []*topdown.Event, output []byte) *Result {
return &Result{
Location: loc,
Package: pkg,
Name: name,
Duration: duration,
Trace: trace,
Output: output,
}
}
// Pass returns true if the test case passed.
func (r Result) Pass() bool {
return !r.Fail && !r.Skip && r.Error == nil
}
func (r *Result) String() string {
if r.Skip {
return fmt.Sprintf("%v.%v: %v", r.Package, r.Name, r.outcome())
}
return fmt.Sprintf("%v.%v: %v (%v)", r.Package, r.Name, r.outcome(), r.Duration)
}
func (r *Result) outcome() string {
if r.Pass() {
return "PASS"
}
if r.Fail {
return "FAIL"
}
if r.Skip {
return "SKIPPED"
}
return "ERROR"
}
// BenchmarkOptions defines options specific to benchmarking tests
type BenchmarkOptions struct {
ReportAllocations bool
}
// Runner implements simple test discovery and execution.
type Runner struct {
compiler *ast.Compiler
store storage.Store
cover topdown.QueryTracer
trace bool
enablePrintStatements bool
runtime *ast.Term
timeout time.Duration
modules map[string]*ast.Module
bundles map[string]*bundle.Bundle
filter string
target string // target type (wasm, rego, etc.)
customBuiltins []*Builtin
}
// NewRunner returns a new runner.
func NewRunner() *Runner {
return &Runner{
timeout: 5 * time.Second,
}
}
// SetCompiler sets the compiler used by the runner.
func (r *Runner) SetCompiler(compiler *ast.Compiler) *Runner {
r.compiler = compiler
return r
}
type Builtin struct {
Decl *ast.Builtin
Func func(*rego.Rego)
}
func (r *Runner) AddCustomBuiltins(builtinsList []*Builtin) *Runner {
r.customBuiltins = builtinsList
return r
}
// SetStore sets the store to execute tests over.
func (r *Runner) SetStore(store storage.Store) *Runner {
r.store = store
return r
}
// SetCoverageTracer sets the tracer to use to compute coverage.
// Deprecated: Use SetCoverageQueryTracer instead.
func (r *Runner) SetCoverageTracer(tracer topdown.Tracer) *Runner {
if tracer == nil {
return r
}
if qt, ok := tracer.(topdown.QueryTracer); ok {
r.cover = qt
} else {
r.cover = topdown.WrapLegacyTracer(tracer)
}
r.trace = false
return r
}
// SetCoverageQueryTracer sets the tracer to use to compute coverage.
func (r *Runner) SetCoverageQueryTracer(tracer topdown.QueryTracer) *Runner {
if tracer == nil {
return r
}
r.cover = tracer
r.trace = false
return r
}
// CapturePrintOutput captures print() call outputs during evaluation and
// includes the output in test results.
func (r *Runner) CapturePrintOutput(yes bool) *Runner {
r.enablePrintStatements = yes
return r
}
// EnableTracing enables tracing of evaluation and includes traces in results.
// Tracing is currently mutually exclusive with coverage.
func (r *Runner) EnableTracing(yes bool) *Runner {
r.trace = yes
if r.trace {
r.cover = nil
}
return r
}
// SetRuntime sets runtime information to expose to the evaluation engine.
func (r *Runner) SetRuntime(term *ast.Term) *Runner {
r.runtime = term
return r
}
// SetTimeout sets the timeout for the individual test cases
func (r *Runner) SetTimeout(timout time.Duration) *Runner {
r.timeout = timout
return r
}
// SetModules will add modules to the Runner which will be compiled then used
// for discovering and evaluating tests.
func (r *Runner) SetModules(modules map[string]*ast.Module) *Runner {
r.modules = modules
return r
}
// SetBundles will add bundles to the Runner which will be compiled then used
// for discovering and evaluating tests.
func (r *Runner) SetBundles(bundles map[string]*bundle.Bundle) *Runner {
r.bundles = bundles
return r
}
// Filter will set a test name regex filter for the test runner. Only test
// cases which match the filter will be run.
func (r *Runner) Filter(regex string) *Runner {
r.filter = regex
return r
}
// Target sets the output target type to use.
func (r *Runner) Target(target string) *Runner {
r.target = target
return r
}
func getFailedAtFromTrace(bufFailureLineTracer *topdown.BufferTracer) *ast.Expr {
events := *bufFailureLineTracer
const SecondToLast = 2
eventsLen := len(events)
for i, opFail := eventsLen-1, 0; i >= 0; i-- {
if events[i].Op == topdown.FailOp {
opFail++
}
if opFail == SecondToLast {
return events[i].Node.(*ast.Expr)
}
}
return nil
}
// Run executes all tests contained in supplied modules.
// Deprecated: Use RunTests and the Runner#SetModules or Runner#SetBundles
// helpers instead. This will NOT use the modules or bundles set on the Runner.
func (r *Runner) Run(ctx context.Context, modules map[string]*ast.Module) (ch chan *Result, err error) {
return r.SetModules(modules).RunTests(ctx, nil)
}
// RunTests executes tests found in either modules or bundles loaded on the runner.
func (r *Runner) RunTests(ctx context.Context, txn storage.Transaction) (ch chan *Result, err error) {
return r.runTests(ctx, txn, true, r.runTest)
}
// RunBenchmarks executes tests similar to tester.Runner#RunTests but will repeat
// a number of times to get stable performance metrics.
func (r *Runner) RunBenchmarks(ctx context.Context, txn storage.Transaction, options BenchmarkOptions) (ch chan *Result, err error) {
return r.runTests(ctx, txn, false, func(ctx context.Context, txn storage.Transaction, module *ast.Module, rule *ast.Rule) (result *Result, b bool) {
return r.runBenchmark(ctx, txn, module, rule, options)
})
}
type run func(context.Context, storage.Transaction, *ast.Module, *ast.Rule) (*Result, bool)
func (r *Runner) runTests(ctx context.Context, txn storage.Transaction, enablePrintStatements bool, runFunc run) (chan *Result, error) {
var testRegex *regexp.Regexp
var err error
if r.filter != "" {
testRegex, err = regexp.Compile(r.filter)
if err != nil {
return nil, err
}
}
if r.compiler == nil {
capabilities := ast.CapabilitiesForThisVersion()
// Add custom builtins declarations to compiler
for _, builtin := range r.customBuiltins {
capabilities.Builtins = append(capabilities.Builtins, builtin.Decl)
}
r.compiler = ast.NewCompiler().
WithCapabilities(capabilities).
WithEnablePrintStatements(enablePrintStatements)
}
// rewrite duplicate test_* rule names as we compile modules
r.compiler.WithStageAfter("RewriteRuleHeadRefs", ast.CompilerStageDefinition{
Name: "RewriteDuplicateTestNames",
MetricName: "rewrite_duplicate_test_names",
Stage: rewriteDuplicateTestNames,
})
if r.store == nil {
r.store = inmem.NewWithOpts(inmem.OptRoundTripOnWrite(false))
}
if r.bundles != nil && len(r.bundles) > 0 {
if txn == nil {
return nil, fmt.Errorf("unable to activate bundles: storage transaction is nil")
}
// Activate the bundle(s) to get their info and policies into the store
// the actual compiled policies will overwritten later..
opts := &bundle.ActivateOpts{
Ctx: ctx,
Store: r.store,
Txn: txn,
Compiler: r.compiler,
Metrics: metrics.New(),
Bundles: r.bundles,
}
err = bundle.Activate(opts)
if err != nil {
return nil, err
}
// Aggregate the bundle modules with other ones provided
if r.modules == nil {
r.modules = map[string]*ast.Module{}
}
for path, b := range r.bundles {
for name, mod := range b.ParsedModules(path) {
r.modules[name] = mod
}
}
}
if len(r.modules) > 0 {
if r.compiler.Compile(r.modules); r.compiler.Failed() {
return nil, r.compiler.Errors
}
}
filenames := make([]string, 0, len(r.compiler.Modules))
for name := range r.compiler.Modules {
filenames = append(filenames, name)
}
sort.Strings(filenames)
ch := make(chan *Result)
go func() {
defer close(ch)
for _, name := range filenames {
module := r.compiler.Modules[name]
for _, rule := range module.Rules {
if !r.shouldRun(rule, testRegex) {
continue
}
tr, stop := func() (*Result, bool) {
runCtx, cancel := context.WithTimeout(ctx, r.timeout)
defer cancel()
return runFunc(runCtx, txn, module, rule)
}()
ch <- tr
if stop {
return
}
}
}
}()
return ch, nil
}
func (r *Runner) shouldRun(rule *ast.Rule, testRegex *regexp.Regexp) bool {
ruleName := ruleName(rule.Head)
// All tests must have the right prefix
if !strings.HasPrefix(ruleName, TestPrefix) && !strings.HasPrefix(ruleName, SkipTestPrefix) {
return false
}
// Even with the prefix it needs to pass the regex (if applicable)
fullName := rule.Ref().String()
if testRegex != nil && !testRegex.MatchString(fullName) {
return false
}
return true
}
// rewriteDuplicateTestNames will rewrite duplicate test names to have a numbered suffix.
// This uses a global "count" of each to ensure compiling more than once as new modules
// are added can't introduce duplicates again.
func rewriteDuplicateTestNames(compiler *ast.Compiler) *ast.Error {
count := map[string]int{}
for _, mod := range compiler.Modules {
for _, rule := range mod.Rules {
name := ruleName(rule.Head)
if !strings.HasPrefix(name, TestPrefix) {
continue
}
key := rule.Ref().String()
if k, ok := count[key]; ok {
ref := rule.Head.Ref()
newName := fmt.Sprintf("%s#%02d", name, k)
if len(ref) == 1 {
ref[0] = ast.VarTerm(newName)
} else {
ref[len(ref)-1] = ast.StringTerm(newName)
}
rule.Head.SetRef(ref)
}
count[key]++
}
}
return nil
}
// ruleName is a helper to be used when checking if a function
// (a) is a test, or
// (b) needs to be skipped
// -- it'll resolve `p.q.r` to `r`. For representing results, we'll
// use rule.Head.Ref()
func ruleName(h *ast.Head) string {
ref := h.Ref()
switch last := ref[len(ref)-1].Value.(type) {
case ast.Var:
return string(last)
case ast.String:
return string(last)
default:
return ""
}
}
func (r *Runner) runTest(ctx context.Context, txn storage.Transaction, mod *ast.Module, rule *ast.Rule) (*Result, bool) {
var bufferTracer *topdown.BufferTracer
var bufFailureLineTracer *topdown.BufferTracer
var tracer topdown.QueryTracer
if r.cover != nil {
tracer = r.cover
} else if r.trace {
bufferTracer = topdown.NewBufferTracer()
tracer = bufferTracer
}
ruleName := ruleName(rule.Head)
if strings.HasPrefix(ruleName, SkipTestPrefix) { // TODO(sr): add test
tr := newResult(rule.Loc(), mod.Package.Path.String(), rule.Head.Ref().String(), 0*time.Second, nil, nil)
tr.Skip = true
return tr, false
}
printbuf := bytes.NewBuffer(nil)
rg := rego.New(
rego.Store(r.store),
rego.Transaction(txn),
rego.Compiler(r.compiler),
rego.Query(rule.Path().String()),
rego.QueryTracer(tracer),
rego.Runtime(r.runtime),
rego.Target(r.target),
rego.PrintHook(topdown.NewPrintHook(printbuf)),
)
// Register custom builtins on rego instance
for _, v := range r.customBuiltins {
v.Func(rg)
}
t0 := time.Now()
rs, err := rg.Eval(ctx)
dt := time.Since(t0)
var trace []*topdown.Event
if bufferTracer != nil {
trace = *bufferTracer
}
tr := newResult(rule.Loc(), mod.Package.Path.String(), rule.Head.Ref().String(), dt, trace, printbuf.Bytes())
tr.Error = err
var stop bool
if err != nil {
if topdown.IsCancel(err) || wasm_errors.IsCancel(err) {
stop = ctx.Err() != context.DeadlineExceeded
}
} else if len(rs) == 0 {
tr.Fail = true
if bufFailureLineTracer != nil {
tr.FailedAt = getFailedAtFromTrace(bufFailureLineTracer)
}
} else if b, ok := rs[0].Expressions[0].Value.(bool); !ok || !b {
tr.Fail = true
}
return tr, stop
}
func (r *Runner) runBenchmark(ctx context.Context, txn storage.Transaction, mod *ast.Module, rule *ast.Rule, options BenchmarkOptions) (*Result, bool) {
tr := &Result{
Location: rule.Loc(),
Package: mod.Package.Path.String(),
Name: rule.Head.Ref().String(), // TODO(sr): test
}
var stop bool
t0 := time.Now()
br := testing.Benchmark(func(b *testing.B) {
pq, err := rego.New(
rego.Store(r.store),
rego.Transaction(txn),
rego.Compiler(r.compiler),
rego.Query(rule.Path().String()),
rego.Runtime(r.runtime),
rego.Target(r.target),
).PrepareForEval(ctx)
if err != nil {
tr.Fail = true
b.Fatalf("Unexpected error: %s", err)
}
m := metrics.New()
// Track memory allocations
if options.ReportAllocations {
b.ReportAllocs()
}
// Don't count setup in the benchmark time, only evaluation time
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Start the timer (might already be started, but that's ok)
b.StartTimer()
rs, err := pq.Eval(
ctx,
rego.EvalTransaction(txn),
rego.EvalMetrics(m),
)
// Stop the timer so we don't count any of the error handling time
b.StopTimer()
if err != nil {
tr.Error = err
if topdown.IsCancel(err) && !(ctx.Err() == context.DeadlineExceeded) {
stop = true
}
b.Fatalf("Unexpected error: %s", err)
} else if len(rs) == 0 {
tr.Fail = true
b.Fatal("Expected boolean result, got `undefined`")
} else if pass, ok := rs[0].Expressions[0].Value.(bool); !ok || !pass {
tr.Fail = true
b.Fatal("Expected test to evaluate as true, got false")
}
}
for k, v := range m.All() {
fv := float64(v.(int64)) / float64(b.N)
b.ReportMetric(fv, k+"/op")
}
})
tr.Duration = time.Since(t0)
tr.BenchmarkResult = &br
return tr, stop
}
// Load returns modules and an in-memory store for running tests.
func Load(args []string, filter loader.Filter) (map[string]*ast.Module, storage.Store, error) {
loaded, err := loader.NewFileLoader().Filtered(args, filter)
if err != nil {
return nil, nil, err
}
store := inmem.NewFromObject(loaded.Documents)
modules := map[string]*ast.Module{}
ctx := context.Background()
err = storage.Txn(ctx, store, storage.WriteParams, func(txn storage.Transaction) error {
for _, loadedModule := range loaded.Modules {
modules[loadedModule.Name] = loadedModule.Parsed
// Add the policies to the store to ensure that any future bundle
// activations will preserve them and re-compile the module with
// the bundle modules.
err := store.UpsertPolicy(ctx, txn, loadedModule.Name, loadedModule.Raw)
if err != nil {
return err
}
}
return nil
})
return modules, store, err
}
// LoadBundles will load the given args as bundles, either tarball or directory is OK.
func LoadBundles(args []string, filter loader.Filter) (map[string]*bundle.Bundle, error) {
bundles := map[string]*bundle.Bundle{}
for _, bundleDir := range args {
b, err := loader.NewFileLoader().WithSkipBundleVerification(true).AsBundle(bundleDir)
if err != nil {
return nil, fmt.Errorf("unable to load bundle %s: %s", bundleDir, err)
}
bundles[bundleDir] = b
}
return bundles, nil
}