build: bump Go version requirement to 1.24 (#7839)

Go 1.23 is no longer supported as per Go release policy.

Changes:

- Use Go v1.24.6 as the project SDK requirement
- Apply lint fixes for Go 1.24
- Fix "non-constant format string in call" issues as seen in CI.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
This commit is contained in:
Ville Vesilehto
2025-08-24 10:02:09 +03:00
committed by GitHub
parent e04cf20432
commit f77322b3fb
100 changed files with 879 additions and 940 deletions
+3 -4
View File
@@ -5,7 +5,6 @@
package bundle
import (
"context"
"fmt"
"strings"
"testing"
@@ -17,7 +16,7 @@ import (
)
func TestHasRootsOverlap(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
cases := []struct {
note string
@@ -181,7 +180,7 @@ func TestActivate_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
compiler := ast.NewCompiler().WithDefaultRegoVersion(ast.RegoV0CompatV1)
@@ -329,7 +328,7 @@ func TestDeactivate_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
+1 -2
View File
@@ -8,7 +8,6 @@ package cmd
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"maps"
@@ -1793,7 +1792,7 @@ func TestResetExprLocations(t *testing.T) {
q contains 1
q contains 2
`)).Partial(context.Background())
`)).Partial(t.Context())
if err != nil {
t.Fatal(err)
+7 -7
View File
@@ -301,7 +301,7 @@ main contains "hello" if {
testLogger := loggingtest.New()
params.Logger = testLogger
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
go func(expectedErrors []string) {
err := runExecWithContext(ctx, params)
@@ -531,7 +531,7 @@ main contains "hello" if {
testLogger := loggingtest.New()
params.Logger = testLogger
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
go func(expectedErrors []string) {
err := runExecWithContext(ctx, params)
@@ -891,7 +891,7 @@ main contains "hello" if {
testLogger := loggingtest.New()
params.Logger = testLogger
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
go func() {
err := runExecWithContext(ctx, params)
@@ -950,7 +950,7 @@ func TestInvalidConfig(t *testing.T) {
params.Fail = true
params.FailDefined = true
err := exec.Exec(context.TODO(), nil, params)
err := exec.Exec(t.Context(), nil, params)
if err == nil || err.Error() != "specify --fail or --fail-defined but not both" {
t.Fatalf("Expected error '%s' but got '%s'", "specify --fail or --fail-defined but not both", err.Error())
}
@@ -963,7 +963,7 @@ func TestInvalidConfigAllThree(t *testing.T) {
params.FailDefined = true
params.FailNonEmpty = true
err := exec.Exec(context.TODO(), nil, params)
err := exec.Exec(t.Context(), nil, params)
if err == nil || err.Error() != "specify --fail or --fail-defined but not both" {
t.Fatalf("Expected error '%s' but got '%s'", "specify --fail or --fail-defined but not both", err.Error())
}
@@ -975,7 +975,7 @@ func TestInvalidConfigNonEmptyAndFail(t *testing.T) {
params.FailNonEmpty = true
params.Fail = true
err := exec.Exec(context.TODO(), nil, params)
err := exec.Exec(t.Context(), nil, params)
if err == nil || err.Error() != "specify --fail-non-empty or --fail but not both" {
t.Fatalf("Expected error '%s' but got '%s'", "specify --fail-non-empty or --fail but not both", err.Error())
}
@@ -987,7 +987,7 @@ func TestInvalidConfigNonEmptyAndFailDefined(t *testing.T) {
params.FailNonEmpty = true
params.FailDefined = true
err := exec.Exec(context.TODO(), nil, params)
err := exec.Exec(t.Context(), nil, params)
if err == nil || err.Error() != "specify --fail-non-empty or --fail-defined but not both" {
t.Fatalf("Expected error '%s' but got '%s'", "specify --fail-non-empty or --fail-defined but not both", err.Error())
}
+1 -2
View File
@@ -2,7 +2,6 @@ package exec
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
@@ -227,7 +226,7 @@ func TestExec(t *testing.T) {
params.Paths = append(params.Paths, dir+"/files/")
}
ctx := context.Background()
ctx := t.Context()
opa, _ := sdk.New(ctx, sdk.Options{
Config: bytes.NewReader([]byte{}),
Logger: logging.NewNoOpLogger(),
+2 -2
View File
@@ -34,7 +34,7 @@ func TestJsonReporter_Close(t *testing.T) {
func TestJsonReporter_StoreDecision(t *testing.T) {
testString := "test"
ctx := context.TODO()
ctx := t.Context()
tcs := []struct {
Name string
Path string
@@ -142,7 +142,7 @@ func TestJsonReporter_ReportFailure(t *testing.T) {
for _, tc := range tcs {
t.Run(tc.Name, func(t *testing.T) {
wr := bytes.NewBuffer([]byte{})
ctx := context.Background()
ctx := t.Context()
j := jsonReporter{
w: wr,
buf: []result{},
+10 -10
View File
@@ -24,7 +24,7 @@ import (
func TestRunServerBase(t *testing.T) {
params := newTestRunParams()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
rt, err := initRuntime(ctx, params, nil, false)
if err != nil {
@@ -57,7 +57,7 @@ func TestRunServerBaseListenOnLocalhost(t *testing.T) {
params := newTestRunParams()
params.rt.V1Compatible = true
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
rt, err := initRuntime(ctx, params, nil, true)
if err != nil {
@@ -98,7 +98,7 @@ func TestRunServerBaseListenOnLocalhost(t *testing.T) {
func TestRunServerWithDiagnosticAddr(t *testing.T) {
params := newTestRunParams()
params.rt.DiagnosticAddrs = &[]string{"localhost:0"}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
rt, err := initRuntime(ctx, params, nil, false)
if err != nil {
@@ -141,7 +141,7 @@ func TestInitRuntimeVerifyNonBundle(t *testing.T) {
params.pubKey = "secret"
params.serverMode = false
_, err := initRuntime(context.Background(), params, nil, false)
_, err := initRuntime(t.Context(), params, nil, false)
if err == nil {
t.Fatal("Expected error but got nil")
}
@@ -175,7 +175,7 @@ func TestInitRuntimeCipherSuites(t *testing.T) {
params.cipherSuites = tc.cipherSuites
}
rt, err := initRuntime(context.Background(), params, nil, false)
rt, err := initRuntime(t.Context(), params, nil, false)
fmt.Println(err)
if !tc.expErr && err != nil {
@@ -219,7 +219,7 @@ func TestInitRuntimeSkipKnownSchemaCheck(t *testing.T) {
t.Fatal(err)
}
_, err = initRuntime(context.Background(), params, []string{rootDir}, false)
_, err = initRuntime(t.Context(), params, []string{rootDir}, false)
if err == nil {
t.Fatal("Expected error but got nil")
}
@@ -230,7 +230,7 @@ func TestInitRuntimeSkipKnownSchemaCheck(t *testing.T) {
// skip type checking for known input schemas
params.skipKnownSchemaCheck = true
_, err = initRuntime(context.Background(), params, []string{rootDir}, false)
_, err = initRuntime(t.Context(), params, []string{rootDir}, false)
if err != nil {
t.Fatal(err)
}
@@ -282,7 +282,7 @@ func TestRunServerUploadPolicy(t *testing.T) {
for i, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
params := newTestRunParams()
params.rt.V0Compatible = tc.v0Compatible
@@ -345,7 +345,7 @@ func TestRunServerCheckLogTimestampFormat(t *testing.T) {
}
func checkLogTimeStampFormat(t *testing.T, params runCmdParams, format string) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
rt, err := initRuntime(ctx, params, nil, false)
if err != nil {
@@ -417,7 +417,7 @@ func TestInitRuntimeAddrSetByUser(t *testing.T) {
params := newTestRunParams()
params.rt.Addrs = &[]string{"localhost:0"}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
rt, err := initRuntime(ctx, params, []string{}, cmd.Flags().Changed("addr"))
if err != nil {
+2 -2
View File
@@ -216,7 +216,7 @@ func failTrace(t *testing.T) []*topdown.Event {
rego.Trace(true),
rego.QueryTracer(tracer),
rego.Query("data.testing.test_p"),
).Eval(context.Background())
).Eval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
@@ -3655,7 +3655,7 @@ func TestWithDefaultRegoPlugin(t *testing.T) {
})
t.Run("repl", func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := repl.New(store, "", &buffer, "", 0, "")
+2 -3
View File
@@ -5,7 +5,6 @@
package compile
import (
"context"
"fmt"
"io/fs"
"maps"
@@ -77,7 +76,7 @@ func TestCompilerDefaultRegoVersion(t *testing.T) {
WithFS(fsys).
WithPaths(root)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if len(tc.expErrs) > 0 {
if err == nil {
@@ -336,7 +335,7 @@ p contains "B" if {
for _, bundleType := range bundleTypeCases {
for _, tc := range tests {
ctx := context.Background()
ctx := t.Context()
t.Run(fmt.Sprintf("%s, %s", bundleType.note, tc.note), func(t *testing.T) {
files := map[string]string{}
if bundleType.tar {
+1 -3
View File
@@ -1,8 +1,6 @@
module github.com/open-policy-agent/opa
go 1.23.12
toolchain go1.24.6
go 1.24.6
require (
github.com/bytecodealliance/wasmtime-go/v3 v3.0.2
+6 -7
View File
@@ -6,7 +6,6 @@ package presentation
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
@@ -126,8 +125,8 @@ func TestOutputJSONErrorStructuredASTErr(t *testing.T) {
func TestOutputJSONErrorStructuredStorageErr(t *testing.T) {
store := inmem.New()
txn := storage.NewTransactionOrDie(context.Background(), store)
err := store.Write(context.Background(), txn, storage.AddOp, storage.Path{}, map[string]any{"foo": 1})
txn := storage.NewTransactionOrDie(t.Context(), store)
err := store.Write(t.Context(), txn, storage.AddOp, storage.Path{}, map[string]any{"foo": 1})
expected := `{
"errors": [
{
@@ -156,7 +155,7 @@ func TestOutputJSONErrorStructuredTopdownErr(t *testing.T) {
_, err := rego.New(
rego.Module("test.rego", mod),
rego.Query("data.test.z"),
).Eval(context.Background())
).Eval(t.Context())
expected := `{
"errors": [
@@ -177,7 +176,7 @@ func TestOutputJSONErrorStructuredTopdownErr(t *testing.T) {
}
func TestOutputJSONErrorStructuredAstErr(t *testing.T) {
_, err := rego.New(rego.Query("count(0)")).Eval(context.Background())
_, err := rego.New(rego.Query("count(0)")).Eval(t.Context())
expected := `{
"errors": [
{
@@ -249,7 +248,7 @@ func TestOutputJSONErrorStructuredAstParseErr(t *testing.T) {
_, err := rego.New(
rego.Module("parse-err.rego", "!!!"),
rego.Query("!!!"),
).Eval(context.Background())
).Eval(t.Context())
expected := `{
"errors": [
@@ -359,7 +358,7 @@ q if {
_, err := rego.New(
rego.Module("error.rego", mod),
rego.Query("data"),
).PrepareForEval(context.Background())
).PrepareForEval(t.Context())
expected := `{
"errors": [
+1 -2
View File
@@ -1,7 +1,6 @@
package aws
import (
"context"
"encoding/json"
"io"
"net/http"
@@ -38,7 +37,7 @@ func TestECR(t *testing.T) {
}
creds := Credentials{}
token, err := ecr.GetAuthorizationToken(context.Background(), creds, "v4")
token, err := ecr.GetAuthorizationToken(t.Context(), creds, "v4")
if err != nil {
t.Errorf("ecrServer.getAuthorizationToken = %v", err)
}
+1 -2
View File
@@ -1,7 +1,6 @@
package aws
import (
"context"
"fmt"
"io"
"net/http"
@@ -44,7 +43,7 @@ func TestKMS_SignDigest(t *testing.T) {
kms := NewKMSWithURLClient(server.URL, server.Client(), logger)
creds := Credentials{}
signature, err := kms.SignDigest(context.Background(), []byte(tc.request.Message), tc.request.KeyID, tc.request.SigningAlgorithm, creds, "v4")
signature, err := kms.SignDigest(t.Context(), []byte(tc.request.Message), tc.request.KeyID, tc.request.SigningAlgorithm, creds, "v4")
if err != nil && tc.wantErr == false {
t.Fatalf("expected no error, got: %s", err)
}
+3 -4
View File
@@ -5,7 +5,6 @@
package report
import (
"context"
"encoding/json"
"fmt"
"net/http"
@@ -42,7 +41,7 @@ func TestSendReportBadRespStatus(t *testing.T) {
t.Fatalf("Unexpected error %v", err)
}
_, err = reporter.SendReport(context.Background())
_, err = reporter.SendReport(t.Context())
if err == nil {
t.Fatal("Expected error but got nil")
@@ -67,7 +66,7 @@ func TestSendReportDecodeError(t *testing.T) {
t.Fatalf("Unexpected error %v", err)
}
_, err = reporter.SendReport(context.Background())
_, err = reporter.SendReport(t.Context())
if err == nil {
t.Fatal("Expected error but got nil")
@@ -104,7 +103,7 @@ func TestSendReportWithOPAUpdate(t *testing.T) {
t.Fatalf("Unexpected error %v", err)
}
resp, err := reporter.SendReport(context.Background())
resp, err := reporter.SendReport(t.Context())
if err != nil {
t.Fatalf("Expected no error but got %v", err)
+1 -2
View File
@@ -6,7 +6,6 @@ package init
import (
"bytes"
"context"
"encoding/json"
"io"
"io/fs"
@@ -109,7 +108,7 @@ p = true { 1 = 2 }`
},
}
ctx := context.Background()
ctx := t.Context()
for _, useMemoryFS := range []bool{false, true} {
for _, tc := range tests {
+3 -3
View File
@@ -294,19 +294,19 @@ a = "c" if { input > 2 }`,
policy := compileRegoToWasm(eval.NewPolicy, test.Query, dump)
data := parseJSON(eval.NewData)
if err := instance.SetPolicyData(ctx, policy, data); err != nil {
t.Errorf(err.Error())
t.Errorf("%s", err.Error())
}
case eval.NewPolicy != "":
policy := compileRegoToWasm(eval.NewPolicy, test.Query, dump)
if err := instance.SetPolicy(ctx, policy); err != nil {
t.Errorf(err.Error())
t.Errorf("%s", err.Error())
}
case eval.NewData != "":
data := parseJSON(eval.NewData)
if err := instance.SetData(ctx, *data); err != nil {
t.Errorf(err.Error())
t.Errorf("%s", err.Error())
}
}
+1 -2
View File
@@ -5,7 +5,6 @@
package rego
import (
"context"
"reflect"
"strings"
"testing"
@@ -85,7 +84,7 @@ p contains x if {
}
test.WithTempFS(files, func(root string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
Load([]string{root}, nil),
+1 -2
View File
@@ -6,7 +6,6 @@ package repl
import (
"bytes"
"context"
"strings"
"testing"
@@ -94,7 +93,7 @@ func TestOneShot_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
+1 -2
View File
@@ -5,7 +5,6 @@
package sdk_test
import (
"context"
"fmt"
"reflect"
"strings"
@@ -17,7 +16,7 @@ import (
func TestDefaultRegoVersion(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.RawBundles(true),
+1 -2
View File
@@ -5,7 +5,6 @@
package tester
import (
"context"
"strings"
"testing"
"time"
@@ -134,7 +133,7 @@ func TestRun_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
modules := map[string]*ast.Module{
"test": &tc.module,
+2 -2
View File
@@ -310,7 +310,7 @@ func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) {
var err error
tpe, err = nestedObject(cpy, objPath, typeV)
if err != nil {
tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet
tc.err([]*Error{NewError(TypeErr, rule.Head.Location, "%s", err.Error())})
tpe = nil
}
} else if typeV != nil {
@@ -1318,7 +1318,7 @@ func processAnnotation(ss *SchemaSet, annot *SchemaAnnotation, rule *Rule, allow
tpe, err := loadSchema(schema, allowNet)
if err != nil {
return nil, NewError(TypeErr, rule.Location, err.Error()) //nolint:govet
return nil, NewError(TypeErr, rule.Location, "%s", err.Error())
}
return tpe, nil
+12 -12
View File
@@ -854,7 +854,7 @@ func (c *Compiler) PassesTypeCheckRules(rules []*Rule) Errors {
tpe, err := loadSchema(schema, allowNet)
if err != nil {
return Errors{NewError(TypeErr, nil, err.Error())} //nolint:govet
return Errors{NewError(TypeErr, nil, "%s", err.Error())}
}
c.inputType = tpe
}
@@ -1213,7 +1213,7 @@ func (c *Compiler) checkRuleConflicts() {
continue // don't self-conflict
}
msg := fmt.Sprintf("%v conflicts with rule %v defined at %v", childMod.Package, rule.Head.Ref(), rule.Loc())
c.err(NewError(TypeErr, mod.Package.Loc(), msg)) //nolint:govet
c.err(NewError(TypeErr, mod.Package.Loc(), "%s", msg))
}
}
}
@@ -1739,7 +1739,7 @@ func (c *Compiler) init() {
if schema := c.schemaSet.Get(SchemaRootRef); schema != nil {
tpe, err := loadSchema(schema, c.capabilities.AllowNet)
if err != nil {
c.err(NewError(TypeErr, nil, err.Error())) //nolint:govet
c.err(NewError(TypeErr, nil, "%s", err.Error()))
} else {
c.inputType = tpe
}
@@ -1907,7 +1907,7 @@ func (c *Compiler) resolveAllRefs() {
WalkRules(mod, func(rule *Rule) bool {
err := resolveRefsInRule(globals, rule)
if err != nil {
c.err(NewError(CompileErr, rule.Location, err.Error())) //nolint:govet
c.err(NewError(CompileErr, rule.Location, "%s", err.Error()))
}
return false
})
@@ -1932,7 +1932,7 @@ func (c *Compiler) resolveAllRefs() {
parsed, err := c.moduleLoader(c.Modules)
if err != nil {
c.err(NewError(CompileErr, nil, err.Error())) //nolint:govet
c.err(NewError(CompileErr, nil, "%s", err.Error()))
return
}
@@ -2861,7 +2861,7 @@ func (vis *ruleArgLocalRewriter) Visit(x any) Visitor {
Walk(vis, vcpy)
return k, vcpy, nil
}); err != nil {
vis.errs = append(vis.errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet
vis.errs = append(vis.errs, NewError(CompileErr, t.Location, "%s", err.Error()))
} else {
t.Value = cpy
}
@@ -5498,7 +5498,7 @@ func rewriteEveryStatement(g *localVarGenerator, stack *localDeclaredVars, expr
if v := every.Key.Value.(Var); !v.IsWildcard() {
gv, err := rewriteDeclaredVar(g, stack, v, declaredVar)
if err != nil {
return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) //nolint:govet
return nil, append(errs, NewError(CompileErr, every.Loc(), "%s", err.Error()))
}
every.Key.Value = gv
}
@@ -5510,7 +5510,7 @@ func rewriteEveryStatement(g *localVarGenerator, stack *localDeclaredVars, expr
if v := every.Value.Value.(Var); !v.IsWildcard() {
gv, err := rewriteDeclaredVar(g, stack, v, declaredVar)
if err != nil {
return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) //nolint:govet
return nil, append(errs, NewError(CompileErr, every.Loc(), "%s", err.Error()))
}
every.Value.Value = gv
}
@@ -5528,7 +5528,7 @@ func rewriteSomeDeclStatement(g *localVarGenerator, stack *localDeclaredVars, ex
switch v := decl.Symbols[i].Value.(type) {
case Var:
if _, err := rewriteDeclaredVar(g, stack, v, declaredVar); err != nil {
return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) //nolint:govet
return nil, append(errs, NewError(CompileErr, decl.Loc(), "%s", err.Error()))
}
case Call:
var key, val, container *Term
@@ -5558,7 +5558,7 @@ func rewriteSomeDeclStatement(g *localVarGenerator, stack *localDeclaredVars, ex
for _, v0 := range outputVarsForExprEq(e, container.Vars(), output).Sorted() {
if _, err := rewriteDeclaredVar(g, stack, v0, declaredVar); err != nil {
return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) //nolint:govet
return nil, append(errs, NewError(CompileErr, decl.Loc(), "%s", err.Error()))
}
}
return rewriteDeclaredVarsInExpr(g, stack, e, errs, strict)
@@ -5612,7 +5612,7 @@ func rewriteDeclaredAssignment(g *localVarGenerator, stack *localDeclaredVars, e
switch v := t.Value.(type) {
case Var:
if gv, err := rewriteDeclaredVar(g, stack, v, assignedVar); err != nil {
errs = append(errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet
errs = append(errs, NewError(CompileErr, t.Location, "%s", err.Error()))
} else {
t.Value = gv
}
@@ -5627,7 +5627,7 @@ func rewriteDeclaredAssignment(g *localVarGenerator, stack *localDeclaredVars, e
case Ref:
if RootDocumentRefs.Contains(t) {
if gv, err := rewriteDeclaredVar(g, stack, v[0].Value.(Var), assignedVar); err != nil {
errs = append(errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet
errs = append(errs, NewError(CompileErr, t.Location, "%s", err.Error()))
} else {
t.Value = gv
}
+1 -1
View File
@@ -2343,7 +2343,7 @@ func (p *Parser) genwildcard() string {
}
func (p *Parser) error(loc *location.Location, reason string) {
p.errorf(loc, reason) //nolint:govet
p.errorf(loc, "%s", reason)
}
func (p *Parser) errorf(loc *location.Location, f string, a ...any) {
+1 -1
View File
@@ -687,7 +687,7 @@ func parseModule(filename string, stmts []Statement, comments []*Comment, regoCo
case Body:
rule, err := ParseRuleFromBody(mod, stmt)
if err != nil {
errs = append(errs, NewError(ParseErr, stmt[0].Location, err.Error())) //nolint:govet
errs = append(errs, NewError(ParseErr, stmt[0].Location, "%s", err.Error()))
continue
}
rule.generatedBody = true
+1 -1
View File
@@ -115,7 +115,7 @@ func TestRegisterBundleActivatorWithStore(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
var store storage.Store
ctx = context.Background()
ctx = t.Context()
// Plumb in the bundle store if func provided.
if tc.storeFunc != nil {
+35 -35
View File
@@ -29,7 +29,7 @@ import (
func TestManifestStoreLifecycleSingleBundle(t *testing.T) {
store := inmemtst.New()
ctx := context.Background()
ctx := t.Context()
tb := Manifest{
Revision: "abc123",
Roots: &[]string{"/a/b", "/a/c"},
@@ -43,7 +43,7 @@ func TestManifestStoreLifecycleSingleBundle(t *testing.T) {
func TestManifestStoreLifecycleMultiBundle(t *testing.T) {
store := inmemtst.New()
ctx := context.Background()
ctx := t.Context()
bundles := map[string]Manifest{
"bundle1": {
@@ -66,7 +66,7 @@ func TestManifestStoreLifecycleMultiBundle(t *testing.T) {
func TestLegacyManifestStoreLifecycle(t *testing.T) {
store := inmemtst.New()
ctx := context.Background()
ctx := t.Context()
tb := Manifest{
Revision: "abc123",
Roots: &[]string{"/a/b", "/a/c"},
@@ -104,7 +104,7 @@ func TestLegacyManifestStoreLifecycle(t *testing.T) {
func TestMixedManifestStoreLifecycle(t *testing.T) {
store := inmemtst.New()
ctx := context.Background()
ctx := t.Context()
bundles := map[string]Manifest{
"bundle1": {
Revision: "abc123",
@@ -216,7 +216,7 @@ func verifyReadLegacyRevision(ctx context.Context, t *testing.T, store storage.S
}
func TestBundleLazyModeNoPolicyOrData(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -1827,7 +1827,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -1968,7 +1968,7 @@ func TestBundleLazyModeLifecycleRaw(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -2155,7 +2155,7 @@ func TestBundleLazyModeLifecycleRawInvalidData(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -2184,7 +2184,7 @@ func TestBundleLazyModeLifecycleRawInvalidData(t *testing.T) {
}
func TestBundleLazyModeLifecycle(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -2397,7 +2397,7 @@ func TestBundleLazyModeLifecycleRawNoBundleRoots(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -2564,7 +2564,7 @@ func TestBundleLazyModeLifecycleRawNoBundleRoots(t *testing.T) {
}
func TestBundleLazyModeLifecycleRawNoBundleRootsDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -2756,7 +2756,7 @@ func TestBundleLazyModeLifecycleRawNoBundleRootsDiskStorage(t *testing.T) {
}
func TestBundleLazyModeLifecycleNoBundleRoots(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
m := metrics.New()
@@ -2936,7 +2936,7 @@ func TestBundleLazyModeLifecycleNoBundleRoots(t *testing.T) {
}
func TestBundleLazyModeLifecycleNoBundleRootsDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -3148,7 +3148,7 @@ func TestBundleLazyModeLifecycleNoBundleRootsDiskStorage(t *testing.T) {
}
func TestBundleLazyModeLifecycleMixBundleTypeActivationDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -3301,7 +3301,7 @@ func TestBundleLazyModeLifecycleMixBundleTypeActivationDiskStorage(t *testing.T)
}
func TestBundleLazyModeLifecycleOldBundleEraseDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -3513,7 +3513,7 @@ func TestBundleLazyModeLifecycleOldBundleEraseDiskStorage(t *testing.T) {
}
func TestBundleLazyModeLifecycleRestoreBackupDB(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -3737,7 +3737,7 @@ func TestBundleLazyModeLifecycleRestoreBackupDB(t *testing.T) {
}
func TestDeltaBundleLazyModeLifecycleDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -4010,7 +4010,7 @@ func TestDeltaBundleLazyModeLifecycleDiskStorage(t *testing.T) {
}
func TestBundleLazyModeLifecycleOverlappingBundleRoots(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -4159,7 +4159,7 @@ func TestBundleLazyModeLifecycleOverlappingBundleRoots(t *testing.T) {
}
func TestBundleLazyModeLifecycleOverlappingBundleRootsDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -4316,7 +4316,7 @@ func TestBundleLazyModeLifecycleOverlappingBundleRootsDiskStorage(t *testing.T)
}
func TestBundleLazyModeLifecycleRawOverlappingBundleRoots(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -4449,7 +4449,7 @@ func TestBundleLazyModeLifecycleRawOverlappingBundleRoots(t *testing.T) {
}
func TestBundleLazyModeLifecycleRawOverlappingBundleRootsDiskStorage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(dir string) {
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
@@ -4586,7 +4586,7 @@ func TestBundleLazyModeLifecycleRawOverlappingBundleRootsDiskStorage(t *testing.
}
func TestDeltaBundleLazyModeLifecycle(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -4872,7 +4872,7 @@ func TestDeltaBundleLazyModeLifecycle(t *testing.T) {
}
func TestDeltaBundleLazyModeWithDefaultRules(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -5178,7 +5178,7 @@ func TestBundleLifecycle(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New(inmem.OptReturnASTValuesOnRead(tc.readAst))
compiler := ast.NewCompiler()
@@ -5372,7 +5372,7 @@ func TestDeltaBundleLifecycle(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New(inmem.OptReturnASTValuesOnRead(tc.readAst))
compiler := ast.NewCompiler()
@@ -5654,7 +5654,7 @@ func TestDeltaBundleActivate(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New(inmem.OptReturnASTValuesOnRead(tc.readAst))
compiler := ast.NewCompiler()
@@ -5773,7 +5773,7 @@ func assertEqual(t *testing.T, expectAst bool, expected string, actual any) {
func TestDeltaBundleBadManifest(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.New()
compiler := ast.NewCompiler()
@@ -5888,7 +5888,7 @@ func TestEraseData(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
cases := []struct {
note string
initialData map[string]any
@@ -5986,7 +5986,7 @@ func TestEraseData(t *testing.T) {
}
func TestErasePolicies(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
cases := []struct {
note string
initialPolicies map[string][]byte
@@ -6119,7 +6119,7 @@ func TestWriteData(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
cases := []struct {
note string
existingData map[string]any
@@ -6377,7 +6377,7 @@ func testWriteData(t *testing.T, tc testWriteModuleCase, legacy bool) {
t.Run(testName, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
mockStore := mock.NewWithData(tc.storeData)
txn := storage.NewTransactionOrDie(ctx, mockStore, storage.WriteParams)
@@ -6618,7 +6618,7 @@ func TestDoDFS(t *testing.T) {
}
func TestHasRootsOverlap(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
cases := []struct {
note string
@@ -6754,7 +6754,7 @@ func TestBundleStoreHelpers(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
bundles := map[string]*Bundle{
"bundle1": {
@@ -6995,7 +6995,7 @@ func TestActivate_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
compiler := ast.NewCompiler().WithDefaultRegoVersion(ast.RegoV0CompatV1)
@@ -7134,7 +7134,7 @@ func TestDeactivate_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
+2 -3
View File
@@ -1,7 +1,6 @@
package compile
import (
"context"
"fmt"
"io/fs"
"strconv"
@@ -29,7 +28,7 @@ func BenchmarkCompileDynamicPolicy(b *testing.B) {
for range b.N {
compiler := New().WithFS(fileSys).WithPaths(root)
if err := compiler.Build(context.Background()); err != nil {
if err := compiler.Build(b.Context()); err != nil {
b.Fatal("unexpected error", err)
}
}
@@ -84,7 +83,7 @@ func BenchmarkLargePartialRulePolicy(b *testing.B) {
for range b.N {
compiler := New().WithPaths(root)
if err := compiler.Build(context.Background()); err != nil {
if err := compiler.Build(b.Context()); err != nil {
b.Fatal("unexpected error", err)
}
}
+38 -39
View File
@@ -2,7 +2,6 @@ package compile
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
@@ -45,7 +44,7 @@ func TestCompilerV1Module(t *testing.T) {
WithFS(fsys).
WithPaths(root)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -78,7 +77,7 @@ func TestOrderedStringSet(t *testing.T) {
func TestCompilerInitErrors(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
tests := []struct {
note string
@@ -128,7 +127,7 @@ func TestCompilerLoadError(t *testing.T) {
err := New().
WithFS(fsys).
WithPaths(path.Join(root, "does-not-exist")).
Build(context.Background())
Build(t.Context())
if err == nil {
t.Fatal("expected failure")
}
@@ -138,7 +137,7 @@ func TestCompilerLoadError(t *testing.T) {
func TestCompilerLoadAsBundleSuccess(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
rv := strconv.Itoa(ast.DefaultRegoVersion.Int())
files := map[string]string{
@@ -431,7 +430,7 @@ p contains "B" if {
for _, bundleType := range bundleTypeCases {
for _, tc := range tests {
ctx := context.Background()
ctx := t.Context()
t.Run(fmt.Sprintf("%s, %s", bundleType.note, tc.note), func(t *testing.T) {
files := map[string]string{}
if bundleType.tar {
@@ -870,7 +869,7 @@ func compareRegoVersions(t *testing.T, exp, act *int) {
func TestCompilerLoadAsBundleMergeError(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
// Omit manifests (defaulting to '') to trigger a merge error
files := map[string]string{
@@ -921,7 +920,7 @@ func TestCompilerLoadFilesystem(t *testing.T) {
WithFS(fsys).
WithPaths(root)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -965,7 +964,7 @@ func TestCompilerLoadFilesystemWithEnablePrintStatementsFalse(t *testing.T) {
WithTarget("plan").WithEntrypoints("test/allow").
WithEnablePrintStatements(false)
if err := compiler.Build(context.Background()); err != nil {
if err := compiler.Build(t.Context()); err != nil {
t.Fatal(err)
}
@@ -1000,7 +999,7 @@ func TestCompilerLoadFilesystemWithEnablePrintStatementsTrue(t *testing.T) {
WithEntrypoints("test/allow").
WithEnablePrintStatements(true)
if err := compiler.Build(context.Background()); err != nil {
if err := compiler.Build(t.Context()); err != nil {
t.Fatal(err)
}
@@ -1033,7 +1032,7 @@ func TestCompilerLoadHonorsFilter(t *testing.T) {
return strings.HasSuffix(abspath, ".json")
})
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1060,7 +1059,7 @@ func TestCompilerInputBundle(t *testing.T) {
compiler := New().WithBundle(b)
if err := compiler.Build(context.Background()); err != nil {
if err := compiler.Build(t.Context()); err != nil {
t.Fatal(err)
}
@@ -1092,7 +1091,7 @@ func TestCompilerInputInvalidBundle(t *testing.T) {
compiler := New().WithBundle(b)
if err := compiler.Build(context.Background()); err == nil {
if err := compiler.Build(t.Context()); err == nil {
t.Fatal("duplicate module URL not detected")
} else if err.Error() != "duplicate module URL: /url" {
t.Fatal(err)
@@ -1115,7 +1114,7 @@ func TestCompilerError(t *testing.T) {
WithFS(fsys).
WithPaths(root)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err == nil {
t.Fatal("expected error")
}
@@ -1151,7 +1150,7 @@ func TestCompilerOptimizationL1(t *testing.T) {
WithOptimizationLevel(1).
WithEntrypoints("test/p")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1212,7 +1211,7 @@ func TestCompilerOptimizationL2(t *testing.T) {
WithOptimizationLevel(2).
WithEntrypoints("test/p")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1272,7 +1271,7 @@ func TestCompilerOptimizationWithConfiguredNamespace(t *testing.T) {
WithEntrypoints("test/p").
WithPartialNamespace("custom")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1673,7 +1672,7 @@ update {
WithEntrypoints(tc.entrypoint).
WithCapabilities(caps)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1940,7 +1939,7 @@ p if {
WithOptimizationLevel(1).
WithEntrypoints(tc.entrypoint)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2001,7 +2000,7 @@ func TestCompilerWasmTarget(t *testing.T) {
WithTarget("wasm").
WithEntrypoints("test/p", "test/q").
WithCapabilities(wasmABIVersions(ast.WasmABIVersion{Version: 1}))
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2037,7 +2036,7 @@ func TestCompilerWasmTargetWithCapabilitiesUnset(t *testing.T) {
WithPaths(root).
WithTarget("wasm").
WithEntrypoints("test/p", "test/q")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
@@ -2069,7 +2068,7 @@ func TestCompilerWasmTargetWithCapabilitiesMismatch(t *testing.T) {
WithTarget("wasm").
WithEntrypoints("test/p", "test/q").
WithCapabilities(caps)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err == nil {
t.Fatal("expected err, got nil")
}
@@ -2102,7 +2101,7 @@ func TestCompilerWasmTargetMultipleEntrypoints(t *testing.T) {
WithTarget("wasm").
WithEntrypoints("test/p", "policy/authz").
WithCapabilities(wasmABIVersions(ast.WasmABIVersion{Version: 1}))
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2168,7 +2167,7 @@ q = true`,
WithEntrypoints("test", "policy/q").
WithRegoAnnotationEntrypoints(true)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2243,7 +2242,7 @@ func TestCompilerWasmTargetEntrypointDependents(t *testing.T) {
WithTarget("wasm").
WithEntrypoints("test/r", "test/z").
WithCapabilities(wasmABIVersions(ast.WasmABIVersion{Version: 1}))
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2304,7 +2303,7 @@ func TestCompilerWasmTargetLazyCompile(t *testing.T) {
WithEntrypoints("test/p").
WithOptimizationLevel(1).
WithCapabilities(wasmABIVersions(ast.WasmABIVersion{Version: 1}))
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2353,7 +2352,7 @@ func TestCompilerPlanTarget(t *testing.T) {
WithPaths(root).
WithTarget("plan").
WithEntrypoints("test/p", "test/q")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2382,7 +2381,7 @@ func TestCompilerPlanTargetPruneUnused(t *testing.T) {
WithTarget("plan").
WithEntrypoints("test").
WithPruneUnused(true)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2424,7 +2423,7 @@ func TestCompilerPlanTargetUnmatchedEntrypoints(t *testing.T) {
WithPaths(root).
WithTarget("plan").
WithEntrypoints("test/p", "test/q", "test/no")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err == nil {
t.Error("expected error from unmatched entrypoint")
}
@@ -2443,7 +2442,7 @@ func TestCompilerPlanTargetUnmatchedEntrypoints(t *testing.T) {
WithPaths(root).
WithTarget("plan").
WithEntrypoints("foo", "foo.bar", "test/no")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err == nil {
t.Error("expected error from unmatched entrypoints")
}
@@ -2766,7 +2765,7 @@ q contains 3
WithEntrypoints(tc.entrypoints...).
WithRegoAnnotationEntrypoints(true).
WithPruneUnused(true)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2802,7 +2801,7 @@ func TestCompilerSetRevision(t *testing.T) {
WithFS(fsys).
WithPaths(root).
WithRevision("deadbeef")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2830,7 +2829,7 @@ func TestCompilerSetMetadata(t *testing.T) {
WithPaths(root).
WithMetadata(&metadata)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2859,7 +2858,7 @@ func TestCompilerSetRoots(t *testing.T) {
WithPaths(root).
WithRoots("test")
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2890,7 +2889,7 @@ func TestCompilerOutput(t *testing.T) {
WithFS(fsys).
WithPaths(root).
WithOutput(buf)
err := compiler.Build(context.Background())
err := compiler.Build(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2951,7 +2950,7 @@ func TestOptimizerNoops(t *testing.T) {
t.Run(tc.note, func(t *testing.T) {
o := getOptimizer(tc.modules, "", tc.entrypoints, nil, "", ast.ParserOptions{AllFutureKeywords: true})
cpy := o.bundle.Copy()
err := o.Do(context.Background())
err := o.Do(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3002,7 +3001,7 @@ func TestOptimizerErrors(t *testing.T) {
t.Run(tc.note, func(t *testing.T) {
o := getOptimizer(tc.modules, "", tc.entrypoints, nil, "", ast.ParserOptions{AllFutureKeywords: true})
cpy := o.bundle.Copy()
got := o.Do(context.Background())
got := o.Do(t.Context())
if got == nil || got.Error() != tc.wantErr.Error() {
t.Fatalf("expected error to be %v but got %v", tc.wantErr, got)
}
@@ -3500,7 +3499,7 @@ func TestOptimizerOutput(t *testing.T) {
popts := ast.ParserOptions{AllFutureKeywords: true}
o := getOptimizer(tc.modules, tc.data, tc.entrypoints, tc.roots, tc.namespace, popts)
original := o.bundle.Copy()
err := o.Do(context.Background())
err := o.Do(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3573,7 +3572,7 @@ func TestOptimizerError(t *testing.T) {
popts := ast.ParserOptions{AllFutureKeywords: true}
o := getOptimizer(tc.modules, "", tc.entrypoints, tc.roots, "", popts)
err := o.Do(context.Background())
err := o.Do(t.Context())
if err == nil {
t.Fatal("expected error but got nil")
}
+1 -2
View File
@@ -5,7 +5,6 @@
package cover
import (
"context"
"fmt"
"strings"
"testing"
@@ -28,7 +27,7 @@ func BenchmarkCoverBigLocalVar(b *testing.B) {
b.Fatal(err)
}
ctx := context.Background()
ctx := b.Context()
pq, err := rego.New(
rego.Module("test.rego", module),
+2 -3
View File
@@ -5,7 +5,6 @@
package cover
import (
"context"
"encoding/json"
"fmt"
"reflect"
@@ -60,7 +59,7 @@ p if {
rego.QueryTracer(cover),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -162,7 +161,7 @@ allow if { true }
rego.QueryTracer(cover),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
+13 -13
View File
@@ -145,7 +145,7 @@ f(x) := y if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
modName := "test1.rego"
@@ -289,7 +289,7 @@ p if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
modName := "test1.rego"
@@ -438,7 +438,7 @@ p if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
modName := "test1.rego"
@@ -505,7 +505,7 @@ p if {
}
func TestDebuggerEvalPrint(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(10*time.Second))
defer cancel()
files := map[string]string{
@@ -571,7 +571,7 @@ p if {
}
func TestFiles(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(10*time.Second))
defer cancel()
files := map[string]string{
@@ -757,7 +757,7 @@ func TestDebuggerAutomaticStop(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stk := newTestStack(testEvents...)
@@ -937,7 +937,7 @@ func TestDebuggerStopOnBreakpoint(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stk := newTestStack(tc.events...)
@@ -1083,7 +1083,7 @@ func TestDebuggerStepIn(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stk := newTestStack(tc.events...)
@@ -1260,7 +1260,7 @@ func TestDebuggerStepOver(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stk := newTestStack(tc.events...)
@@ -1421,7 +1421,7 @@ func TestDebuggerStepOut(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stk := newTestStack(tc.events...)
@@ -1575,7 +1575,7 @@ func TestDebuggerStackTrace(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(5*time.Second))
defer cancel()
stk := newTestStack(tc.events...)
@@ -1965,7 +1965,7 @@ func TestDebuggerScopeVariables(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
locals := ast.NewValueMap()
@@ -2240,7 +2240,7 @@ func (ts *testStack) Close() error {
}
func TestDebuggerCustomBuiltIn(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
decl := &rego.Function{
Name: "my.builtin",
+17 -17
View File
@@ -277,22 +277,22 @@ func AstWithOpts(x any, opts Opts) ([]byte, error) {
}
err := w.writeModule(x)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Package:
_, err := w.writePackage(x, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Import:
_, err := w.writeImports([]*ast.Import{x}, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Rule:
_, err := w.writeRule(x, false /* isElse */, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Head:
_, err := w.writeHead(x,
@@ -300,7 +300,7 @@ func AstWithOpts(x any, opts Opts) ([]byte, error) {
false, // isExpandedConst
nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case ast.Body:
_, err := w.writeBody(x, nil)
@@ -310,27 +310,27 @@ func AstWithOpts(x any, opts Opts) ([]byte, error) {
case *ast.Expr:
_, err := w.writeExpr(x, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.With:
_, err := w.writeWith(x, nil, false)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Term:
_, err := w.writeTerm(x, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case ast.Value:
_, err := w.writeTerm(&ast.Term{Value: x, Location: &ast.Location{}}, nil)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
case *ast.Comment:
err := w.writeComments([]*ast.Comment{x})
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
default:
return nil, fmt.Errorf("not an ast element: %v", x)
@@ -418,7 +418,7 @@ func (w *writer) writeModule(module *ast.Module) error {
sort.Slice(comments, func(i, j int) bool {
l, err := locLess(comments[i], comments[j])
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
return l
})
@@ -426,7 +426,7 @@ func (w *writer) writeModule(module *ast.Module) error {
sort.Slice(others, func(i, j int) bool {
l, err := locLess(others[i], others[j])
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
return l
})
@@ -524,12 +524,12 @@ func (w *writer) writeRules(rules []*ast.Rule, comments []*ast.Comment) ([]*ast.
var err error
comments, err = w.insertComments(comments, rule.Location)
if err != nil && !errors.As(err, &unexpectedCommentError{}) {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
comments, err = w.writeRule(rule, false, comments)
if err != nil && !errors.As(err, &unexpectedCommentError{}) {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
if i < len(rules)-1 && w.groupableOneLiner(rule) {
@@ -874,7 +874,7 @@ func (w *writer) writeBody(body ast.Body, comments []*ast.Comment) ([]*ast.Comme
comments, err = w.writeExpr(expr, comments)
if err != nil && !errors.As(err, &unexpectedCommentError{}) {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
w.endLine()
}
@@ -1563,7 +1563,7 @@ func (w *writer) writeComprehensionBody(openChar, closeChar byte, body ast.Body,
defer w.startLine()
defer func() {
if err := w.down(); err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
}()
@@ -1800,7 +1800,7 @@ func (w *writer) groupIterable(elements []any, last *ast.Location) ([][]any, err
slices.SortFunc(elements, func(i, j any) int {
l, err := locCmp(i, j)
if err != nil {
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, err.Error()))
w.errs = append(w.errs, ast.NewError(ast.FormatErr, &ast.Location{}, "%s", err.Error()))
}
return l
})
+1 -4
View File
@@ -1447,10 +1447,7 @@ func TestSchemas(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
test.WithTempFS(tc.files, func(rootDir string) {
err := os.Chdir(rootDir)
if err != nil {
t.Fatal(err)
}
t.Chdir(rootDir)
ss, err := Schemas(tc.path)
if tc.expErr != "" {
if err == nil {
+5 -6
View File
@@ -2,7 +2,6 @@ package logging
import (
"bytes"
"context"
"crypto/rand"
"net/url"
"strings"
@@ -56,10 +55,10 @@ func TestNoFormattingForSingleString(t *testing.T) {
// a format string but no args, the golang linters would yell. The indirection
// taken here is enough to not trigger linters.
x := url.PathEscape("/foo/bar/bar")
logger.Debug(x) //nolint:govet
logger.Info(x) //nolint:govet
logger.Warn(x) //nolint:govet
logger.Error(x) //nolint:govet
logger.Debug("%s", x)
logger.Info("%s", x)
logger.Warn("%s", x)
logger.Error("%s", x)
exp := `"%2Ffoo%2Fbar%2Fbar"`
expected := []string{
@@ -169,7 +168,7 @@ func TestDecsionIDFromContext(t *testing.T) {
if err != nil {
t.Fatal(err)
}
ctx := WithDecisionID(context.Background(), id)
ctx := WithDecisionID(t.Context(), id)
act, ok := DecisionIDFromContext(ctx)
if !ok {
+66 -66
View File
@@ -49,7 +49,7 @@ const (
func TestPluginOneShot(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -123,7 +123,7 @@ func TestPluginOneShot(t *testing.T) {
func TestPluginOneShotWithAstStore(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.NewWithOpts(inmem.OptRoundTripOnWrite(false), inmem.OptReturnASTValuesOnRead(true))
manager := getTestManagerWithOpts(nil, store)
defer manager.Stop(ctx)
@@ -225,7 +225,7 @@ corge contains 1 if {
}
popts := ast.ParserOptions{RegoVersion: regoVersion}
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -461,7 +461,7 @@ corge contains 1 if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
managerPopts := ast.ParserOptions{RegoVersion: tc.managerRegoVersion}
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(),
plugins.WithParserOptions(managerPopts))
@@ -559,7 +559,7 @@ corge contains 1 if {
func TestPluginOneShotWithAuthzSchemaVerification(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -705,7 +705,7 @@ func TestPluginOneShotWithAuthzSchemaVerification(t *testing.T) {
func TestPluginOneShotWithAuthzSchemaVerificationNonDefaultAuthzPath(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -827,7 +827,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
for _, rm := range readMode {
t.Run(rm.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
module := "package authz\n\ncorge=1"
@@ -999,7 +999,7 @@ func TestPluginOneShotDiskStorageMetrics(t *testing.T) {
t.Parallel()
test.WithTempFS(nil, func(dir string) {
ctx := context.Background()
ctx := t.Context()
met := metrics.New()
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
Dir: dir,
@@ -1109,7 +1109,7 @@ func TestPluginOneShotDiskStorageMetrics(t *testing.T) {
func TestPluginOneShotDeltaBundle(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -1213,7 +1213,7 @@ func TestPluginOneShotDeltaBundle(t *testing.T) {
func TestPluginOneShotDeltaBundleWithAstStore(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.NewWithOpts(inmem.OptRoundTripOnWrite(false), inmem.OptReturnASTValuesOnRead(true))
manager := getTestManagerWithOpts(nil, store)
defer manager.Stop(ctx)
@@ -1318,7 +1318,7 @@ func TestPluginOneShotDeltaBundleWithAstStore(t *testing.T) {
func TestPluginStart(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
bundles := map[string]*Source{}
@@ -1354,7 +1354,7 @@ func TestStop(t *testing.T) {
fmt.Fprintln(w) // Note: this is an invalid bundle and will fail the download
}))
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
defer ts.Close()
@@ -1406,7 +1406,7 @@ func TestStop(t *testing.T) {
func TestPluginOneShotBundlePersistence(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -1570,7 +1570,7 @@ corge contains 1 if {
}
popts := ast.ParserOptions{RegoVersion: regoVersion}
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(), plugins.WithParserOptions(popts))
if err != nil {
t.Fatal("unexpected error:", err)
@@ -1853,7 +1853,7 @@ corge contains 1 if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
managerPopts := ast.ParserOptions{RegoVersion: tc.managerRegoVersion}
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(),
plugins.WithParserOptions(managerPopts))
@@ -2012,7 +2012,7 @@ corge contains 1 if {
func TestPluginOneShotSignedBundlePersistence(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -2110,7 +2110,7 @@ func TestPluginOneShotSignedBundlePersistence(t *testing.T) {
func TestLoadAndActivateBundlesFromDisk(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -2198,7 +2198,7 @@ func TestLoadAndActivateBundlesFromDisk(t *testing.T) {
// Warning: This test modifies package variables, and as
// a result, cannot be run in parallel with other tests.
func TestLoadAndActivateBundlesFromDiskReservedChars(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -2416,7 +2416,7 @@ corge contains 2 if {
}
popts := ast.ParserOptions{RegoVersion: regoVersion}
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(),
plugins.WithParserOptions(popts))
if err != nil {
@@ -2631,7 +2631,7 @@ corge contains 1 if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
managerPopts := ast.ParserOptions{RegoVersion: tc.managerRegoVersion}
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(),
plugins.WithParserOptions(managerPopts))
@@ -2798,7 +2798,7 @@ func bundleRegoVersion(v ast.RegoVersion) int {
func TestLoadAndActivateDepBundlesFromDisk(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -2907,7 +2907,7 @@ is_one(x) if {
func TestLoadAndActivateDepBundlesFromDiskMaxAttempts(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -2977,7 +2977,7 @@ allow if {
func TestPluginOneShotCompileError(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -3071,7 +3071,7 @@ p contains x`),
func TestPluginOneShotHTTPError(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -3113,7 +3113,7 @@ func TestPluginOneShotHTTPError(t *testing.T) {
func TestPluginOneShotActivationRemovesOld(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -3192,7 +3192,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) {
func TestPluginOneShotActivationConflictingRoots(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -3262,7 +3262,7 @@ func TestPluginOneShotActivationConflictingRoots(t *testing.T) {
func TestPluginOneShotActivationPrefixMatchingRoots(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -3319,7 +3319,7 @@ func ensureBundleOverlapStatus(t *testing.T, p *Plugin, bundleNames []string, ex
func TestPluginListener(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := New(&Config{}, manager)
@@ -3434,7 +3434,7 @@ func validateStatus(t *testing.T, actual Status, expected string, expectStatusEr
func TestPluginListenerErrorClearedOn304(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -3489,7 +3489,7 @@ func TestPluginListenerErrorClearedOn304(t *testing.T) {
func TestPluginBulkListener(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -3693,7 +3693,7 @@ p contains x if { x = 1 }`
func TestPluginBulkListenerStatusCopyOnly(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -3771,7 +3771,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
for _, rm := range readMode {
t.Run(rm.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager := getTestManagerWithOpts(nil, inmem.NewWithOpts(inmem.OptReturnASTValuesOnRead(rm.readAst)))
plugin := Plugin{
manager: manager,
@@ -3917,7 +3917,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
func TestPluginSetCompilerOnContext(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -4005,7 +4005,7 @@ func TestPluginReconfigure(t *testing.T) {
fmt.Fprintln(w, "") // Note: this is an invalid bundle and will fail the download
}))
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
defer ts.Close()
@@ -4197,7 +4197,7 @@ func TestPluginReconfigure(t *testing.T) {
func TestPluginRequestVsDownloadTimestamp(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -4307,7 +4307,7 @@ func TestReconfigurePlugin_OneShot_BundleDeactivation(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(), plugins.WithParserOptions(ast.ParserOptions{RegoVersion: tc.runtimeRegoVersion}))
if err != nil {
t.Fatalf("unexpected error: %s", err)
@@ -4489,7 +4489,7 @@ func TestReconfigurePlugin_ManagerInit_BundleDeactivation(t *testing.T) {
bundleName: &b,
}
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New(nil, "test-instance-id", inmemtst.New(),
plugins.WithParserOptions(ast.ParserOptions{RegoVersion: tc.runtimeRegoVersion}),
plugins.InitBundles(bundles))
@@ -4570,7 +4570,7 @@ func TestReconfigurePlugin_ManagerInit_BundleDeactivation(t *testing.T) {
func TestUpgradeLegacyBundleToMuiltiBundleSameBundle(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
plugin := Plugin{
@@ -4668,7 +4668,7 @@ func TestUpgradeLegacyBundleToMuiltiBundleSameBundle(t *testing.T) {
func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
manager := getTestManager()
defer manager.Stop(ctx)
@@ -4827,7 +4827,7 @@ func TestLegacyBundleDataRead(t *testing.T) {
for _, rm := range readModes {
t.Run(rm.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager := getTestManagerWithOpts(nil, inmem.NewWithOpts(inmem.OptReturnASTValuesOnRead(rm.readAst)))
plugin := Plugin{
@@ -4919,7 +4919,7 @@ func TestSaveBundleToDiskNew(t *testing.T) {
t.Parallel()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
dir := t.TempDir()
@@ -4939,7 +4939,7 @@ func TestSaveBundleToDiskNewConfiguredPersistDir(t *testing.T) {
dir := t.TempDir()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
cfg := manager.GetConfig()
cfg.PersistenceDirectory = &dir
@@ -4952,11 +4952,11 @@ func TestSaveBundleToDiskNewConfiguredPersistDir(t *testing.T) {
bundles := map[string]*Source{}
plugin := New(&Config{Bundles: bundles}, manager)
err = plugin.Start(context.Background())
err = plugin.Start(t.Context())
if err != nil {
t.Fatalf("unexpected error %v", err)
}
defer plugin.Stop(context.Background())
defer plugin.Stop(t.Context())
err = plugin.saveBundleToDisk("foo", getTestRawBundle(t))
if err != nil {
@@ -4974,7 +4974,7 @@ func TestSaveBundleToDiskOverWrite(t *testing.T) {
t.Parallel()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
// test to check existing bundle is replaced
dir := t.TempDir()
@@ -5061,7 +5061,7 @@ func TestLoadBundleFromDisk(t *testing.T) {
t.Parallel()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
plugin := New(&Config{}, manager)
// no bundle on disk
@@ -5159,7 +5159,7 @@ func TestLoadSignedBundleFromDisk(t *testing.T) {
t.Parallel()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
plugin := New(&Config{}, manager)
// no bundle on disk
@@ -5203,7 +5203,7 @@ func TestGetDefaultBundlePersistPath(t *testing.T) {
t.Parallel()
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
plugin := New(&Config{}, manager)
path, err := plugin.getBundlePersistPath()
if err != nil {
@@ -5220,7 +5220,7 @@ func TestConfiguredBundlePersistPath(t *testing.T) {
persistPath := "/var/opa"
manager := getTestManager()
defer manager.Stop(context.Background())
defer manager.Stop(t.Context())
cfg := manager.GetConfig()
cfg.PersistenceDirectory = &persistPath
@@ -5287,7 +5287,7 @@ func TestPluginUsingFileLoader(t *testing.T) {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -5458,7 +5458,7 @@ p contains 7 if {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -5772,7 +5772,7 @@ p contains 7 if {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -5823,7 +5823,7 @@ func TestPluginUsingDirectoryLoader(t *testing.T) {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -5973,7 +5973,7 @@ p contains 7 if {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -6264,7 +6264,7 @@ p contains 7 if {
ch <- s
})
if err := p.Start(context.Background()); err != nil {
if err := p.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -6320,7 +6320,7 @@ func TestPluginReadBundleEtagFromDiskStore(t *testing.T) {
defer s.Close()
test.WithTempFS(nil, func(dir string) {
ctx := context.Background()
ctx := t.Context()
store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{
Dir: dir,
@@ -6549,7 +6549,7 @@ func TestPluginStateReconciliationOnReconfigure(t *testing.T) {
statusCh <- st
})
ctx := context.Background()
ctx := t.Context()
err := plugin.Start(ctx)
if err != nil {
t.Fatal(err)
@@ -6673,7 +6673,7 @@ func TestPluginStateReconciliationOnReconfigure(t *testing.T) {
func TestPluginManualTrigger(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
// setup fake http server with mock bundle
mockBundle := bundle.Bundle{
@@ -6765,7 +6765,7 @@ func TestPluginManualTrigger(t *testing.T) {
func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
module := "package authz\n\ncorge=1"
@@ -6923,7 +6923,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) {
func TestPluginManualTriggerMultiple(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
// setup fake http server with mock bundle
mockBundle1 := bundle.Bundle{
@@ -7032,7 +7032,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) {
func TestPluginManualTriggerWithTimeout(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second)
defer cancel()
s := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
@@ -7096,7 +7096,7 @@ func TestPluginManualTriggerWithTimeout(t *testing.T) {
func TestPluginManualTriggerWithServerError(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
s := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, _ *http.Request) {
@@ -7205,7 +7205,7 @@ func TestGetNormalizedBundleName(t *testing.T) {
}
func TestBundleActivationWithRootOverlap(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
plugin := getPluginWithExistingLoadedBundle(
t,
"policy-bundle",
@@ -7247,7 +7247,7 @@ result := true`,
}
func TestBundleActivationWithNoManifestRootsButWithPathConflict(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
plugin := getPluginWithExistingLoadedBundle(
t,
"policy-bundle",
@@ -7289,7 +7289,7 @@ result := true`,
}
func TestBundleActivationWithNoManifestRootsOverlap(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
plugin := getPluginWithExistingLoadedBundle(
t,
"policy-bundle",
@@ -7366,7 +7366,7 @@ func getTestBundleWithData(roots []string, data []byte, modules []testModule) bu
}
func getPluginWithExistingLoadedBundle(t *testing.T, bundleName string, roots []string, data []byte, modules []testModule) *Plugin {
ctx := context.Background()
ctx := t.Context()
store := inmem.NewWithOpts(inmem.OptRoundTripOnWrite(false), inmem.OptReturnASTValuesOnRead(true))
manager := getTestManagerWithOpts(nil, store)
plugin := New(&Config{}, manager)
+29 -29
View File
@@ -88,7 +88,7 @@ func TestEvaluateBundle(t *testing.T) {
info := ast.MustParseTerm(`{"name": "test/bundle1"}`)
config, err := evaluateBundle(context.Background(), "test-id", info, b, "data.foo.bar")
config, err := evaluateBundle(t.Context(), "test-id", info, b, "data.foo.bar")
if err != nil {
t.Fatal(err)
}
@@ -114,7 +114,7 @@ func TestEvaluateBundle(t *testing.T) {
}
func TestProcessBundle(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New([]byte(`{
"services": {
@@ -186,7 +186,7 @@ func TestProcessBundle(t *testing.T) {
}
func TestEnvVarSubstitution(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New([]byte(`{
"services": {
@@ -249,7 +249,7 @@ func TestEnvVarSubstitution(t *testing.T) {
}
func TestProcessBundleV1Compatible(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
popts := ast.ParserOptions{RegoVersion: ast.RegoV1}
manager, err := plugins.New([]byte(`{
@@ -371,7 +371,7 @@ decision_logs.partition_name := "bar" if { 3 == 3 }
}
func TestProcessBundleWithActiveConfig(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New([]byte(`{
"labels": {"x": "y"},
@@ -629,7 +629,7 @@ func TestStartWithBundlePersistence(t *testing.T) {
t.Fatal(err)
}
err = disco.Start(context.Background())
err = disco.Start(t.Context())
if err != nil {
t.Fatalf("unexpected error %v", err)
}
@@ -676,7 +676,7 @@ func TestOneShotWithBundlePersistence(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
@@ -766,7 +766,7 @@ func TestLoadAndActivateBundleFromDisk(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
@@ -857,7 +857,7 @@ func TestLoadAndActivateSignedBundleFromDisk(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
disco.config.Signing = bundleApi.NewVerificationConfig(map[string]*bundleApi.KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "foo", "", nil)
@@ -953,7 +953,7 @@ func TestLoadAndActivateBundleFromDiskMaxAttempts(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
@@ -1083,7 +1083,7 @@ bundles.authz.service := v if {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
@@ -1253,7 +1253,7 @@ bundles.authz.service := v if {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
disco.bundlePersistPath = filepath.Join(dir, ".opa")
@@ -1385,7 +1385,7 @@ func TestSaveBundleToDiskNewConfiguredPersistDir(t *testing.T) {
t.Fatal(err)
}
err = disco.Start(context.Background())
err = disco.Start(t.Context())
if err != nil {
t.Fatalf("unexpected error %v", err)
}
@@ -1444,7 +1444,7 @@ func TestReconfigure(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
initialBundle := makeDataBundle(1, `
{
@@ -1550,7 +1550,7 @@ func TestReconfigureV1Compatible(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
initialBundle := makeModuleBundle(1, `package config
labels := v if {
@@ -1692,7 +1692,7 @@ func TestReconfigureWithBundleRegoVersion(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
initialBundle := makeModuleBundleWithRegoVersion(1, `package config
labels := v if {
@@ -1767,7 +1767,7 @@ plugins.test_plugin := v if {
}
func TestReconfigureWithLocalOverride(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
bootConfigRaw := []byte(`{
"labels": {"x": "y"},
@@ -2326,7 +2326,7 @@ func TestMergeValuesAndListOverrides(t *testing.T) {
}
func TestReconfigureWithUpdates(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
bootConfigRaw := []byte(`{
"labels": {"x": "y"},
@@ -2700,7 +2700,7 @@ func TestReconfigureWithUpdates(t *testing.T) {
}
func TestProcessBundleWithSigning(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New([]byte(`{
"labels": {"x": "y"},
@@ -2739,7 +2739,7 @@ func TestProcessBundleWithSigning(t *testing.T) {
}
func TestProcessBundleWithNoSigningConfig(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, err := plugins.New([]byte(`{
"labels": {"x": "y"},
@@ -2826,7 +2826,7 @@ func TestStatusUpdates(t *testing.T) {
updates := make(chan status.UpdateRequestV1, 100)
ctx := context.Background()
ctx := t.Context()
// Enable status plugin which sends initial update.
disco.oneShot(ctx, download.Update{ETag: "etag-1", Bundle: makeDataBundle(1, `{
@@ -3008,7 +3008,7 @@ func TestStatusUpdatesFromPersistedBundlesDontDelayBoot(t *testing.T) {
}
// allow 2s of time to start before failing
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
// start Discovery instance, wait for it to complete Start()
@@ -3062,7 +3062,7 @@ func TestStatusUpdatesTimestamp(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
// simulate HTTP 200 response from downloader
disco.oneShot(ctx, download.Update{ETag: "etag-1", Bundle: makeDataBundle(1, `{
@@ -3111,7 +3111,7 @@ func TestStatusUpdatesTimestamp(t *testing.T) {
}
func TestStatusMetricsForLogDrops(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
testLogger := test.New()
@@ -3617,7 +3617,7 @@ func TestInterQueryBuiltinCacheConfigUpdate(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
initialBundle := makeDataBundle(1, `{
"config": {
@@ -3689,7 +3689,7 @@ func TestNDBuiltinCacheConfigUpdate(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
initialBundle := makeDataBundle(1, `{
"config": {
@@ -3719,7 +3719,7 @@ func TestNDBuiltinCacheConfigUpdate(t *testing.T) {
}
func TestPluginManualTriggerLifecycle(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
m := metrics.New()
fixture := newTestFixture(t)
@@ -3925,7 +3925,7 @@ func TestListeners(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
ensurePluginState(t, disco, plugins.StateNotReady)
@@ -4006,7 +4006,7 @@ func newTestFixture(t *testing.T) *testFixture {
stopCh: make(chan chan struct{}),
}
go tf.loop(context.Background())
go tf.loop(t.Context())
return &tf
}
+1 -2
View File
@@ -6,7 +6,6 @@ package logs
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
@@ -171,7 +170,7 @@ func TestEventBuffer_Upload(t *testing.T) {
e.Push(newTestEvent(t, strconv.Itoa(i), true))
}
err := e.Upload(context.Background())
err := e.Upload(t.Context())
if err != nil {
if tc.expectedError == "" || tc.expectedError != "" && err.Error() != tc.expectedError {
t.Fatal(err)
+3 -4
View File
@@ -1,7 +1,6 @@
package logs
import (
"context"
"fmt"
"testing"
@@ -137,7 +136,7 @@ const largeEvent = `{
func BenchmarkMaskingNop(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
store := inmem.New()
manager, err := plugins.New(nil, "test", store)
@@ -175,7 +174,7 @@ func BenchmarkMaskingNop(b *testing.B) {
func BenchmarkMaskingRuleCountsNop(b *testing.B) {
numRules := []int{1, 10, 100, 1000}
ctx := context.Background()
ctx := b.Context()
store := inmem.New()
manager, err := plugins.New(nil, "test", store)
@@ -215,7 +214,7 @@ func BenchmarkMaskingRuleCountsNop(b *testing.B) {
func BenchmarkMaskingErase(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
store := inmem.New()
err := storage.Txn(ctx, store, storage.WriteParams, func(txn storage.Transaction) error {
+8 -8
View File
@@ -176,12 +176,12 @@ func TestPluginStatusUpdateOnStartAndStop(t *testing.T) {
m.Register("p1", &testPlugin{m})
err = m.Start(context.Background())
err = m.Start(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
m.Stop(context.Background())
m.Stop(t.Context())
}
type testPlugin struct {
@@ -211,7 +211,7 @@ func TestPluginManagerLazyInitBeforePluginStart(t *testing.T) {
m.Register("someplugin", mock)
if err := m.Start(context.Background()); err != nil {
if err := m.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -226,7 +226,7 @@ func TestPluginManagerInitBeforePluginStart(t *testing.T) {
t.Fatal(err)
}
if err := m.Init(context.Background()); err != nil {
if err := m.Init(t.Context()); err != nil {
t.Fatal(err)
}
@@ -234,7 +234,7 @@ func TestPluginManagerInitBeforePluginStart(t *testing.T) {
m.Register("someplugin", mock)
if err := m.Start(context.Background()); err != nil {
if err := m.Start(t.Context()); err != nil {
t.Fatal(err)
}
@@ -251,7 +251,7 @@ func TestPluginManagerInitIdempotence(t *testing.T) {
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
if err := m.Init(ctx); err != nil {
t.Fatal(err)
@@ -337,7 +337,7 @@ func TestPluginManagerAuthPlugin(t *testing.T) {
t.Fatal(err)
}
if err := m.Init(context.Background()); err != nil {
if err := m.Init(t.Context()); err != nil {
t.Fatal(err)
}
@@ -416,7 +416,7 @@ func TestPluginManagerPrometheusRegister(t *testing.T) {
}
func TestPluginManagerTracerProvider(t *testing.T) {
_, tracerProvider, _, err := internal_tracing.Init(context.TODO(), []byte(`{ "distributed_tracing": { "type": "grpc" } }`), "test")
_, tracerProvider, _, err := internal_tracing.Init(t.Context(), []byte(`{ "distributed_tracing": { "type": "grpc" } }`), "test")
if err != nil {
t.Fatal(err)
}
+55 -55
View File
@@ -61,15 +61,15 @@ func TestEnvironmentCredentialService(t *testing.T) {
cs := &awsEnvironmentCredentialService{}
// wrong path: some required environment is missing
_, err := cs.credentials(context.Background())
_, err := cs.credentials(t.Context())
assertErr("no AWS_ACCESS_KEY_ID set in environment", err, t)
t.Setenv("AWS_ACCESS_KEY_ID", "MYAWSACCESSKEYGOESHERE")
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("no AWS_SECRET_ACCESS_KEY set in environment", err, t)
t.Setenv("AWS_SECRET_ACCESS_KEY", "MYAWSSECRETACCESSKEYGOESHERE")
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("no AWS_REGION set in environment", err, t)
t.Setenv("AWS_REGION", "us-east-1")
@@ -98,7 +98,7 @@ func TestEnvironmentCredentialService(t *testing.T) {
}
expectedCreds.SessionToken = testCase.tokenValue
envCreds, err := cs.credentials(context.Background())
envCreds, err := cs.credentials(t.Context())
if err != nil {
t.Error("unexpected error: " + err.Error())
}
@@ -142,7 +142,7 @@ aws_secret_access_key=%v
Profile: "foo",
RegionName: fooRegion,
}
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -165,7 +165,7 @@ aws_secret_access_key=%v
RegionName: defaultRegion,
}
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -208,7 +208,7 @@ aws_session_token=%s
t.Setenv(awsRegionEnvVar, defaultRegion)
cs := &awsProfileCredentialService{}
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -257,7 +257,7 @@ aws_session_token=%s
}
cs := &awsProfileCredentialService{RegionName: defaultRegion}
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -314,7 +314,7 @@ aws_access_key_id=accessKey
cs := &awsProfileCredentialService{
Path: cfgPath,
}
_, err := cs.credentials(context.Background())
_, err := cs.credentials(t.Context())
if err == nil {
t.Fatal("Expected error but got nil")
}
@@ -339,7 +339,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/token",
logger: logging.Get(),
}
_, err := cs.credentials(context.Background())
_, err := cs.credentials(t.Context())
assertErr("unsupported protocol scheme \"\"", err, t)
// wrong path: no role set but no ECS URI in environment
@@ -348,13 +348,13 @@ func TestMetadataCredentialService(t *testing.T) {
RegionName: "us-east-1",
logger: logging.Get(),
}
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("metadata endpoint cannot be determined from settings and environment", err, t)
// wrong path: missing token
t.Setenv(ecsFullPathEnvVar, "fullPath")
os.Unsetenv(ecsAuthorizationTokenEnvVar)
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("unable to get ECS metadata authorization token", err, t)
os.Unsetenv(ecsFullPathEnvVar)
@@ -362,7 +362,7 @@ func TestMetadataCredentialService(t *testing.T) {
// wrong path: bad file token
t.Setenv(ecsFullPathEnvVar, "fullPath")
t.Setenv(ecsAuthorizationTokenFileEnvVar, filepath.Join(path, "bad-file"))
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("failed to read ECS metadata authorization token from file", err, t)
os.Unsetenv(ecsFullPathEnvVar)
os.Unsetenv(ecsAuthorizationTokenFileEnvVar)
@@ -376,7 +376,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/token",
logger: logging.Get(),
}
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("metadata HTTP request returned unexpected status: 404 Not Found", err, t)
// wrong path: malformed JSON body
@@ -387,7 +387,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/token",
logger: logging.Get(),
}
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("failed to parse credential response from metadata service: invalid character 'T' looking for beginning of value", err, t)
// wrong path: token service error
@@ -398,7 +398,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/missing_token",
logger: logging.Get(),
} // will 404
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("metadata token HTTP request returned unexpected status: 404 Not Found", err, t)
// wrong path: token service returns bad token
@@ -409,7 +409,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/bad_token",
logger: logging.Get(),
} // not good
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("metadata HTTP request returned unexpected status: 401 Unauthorized", err, t)
// wrong path: bad result code from EC2 metadata service
@@ -426,7 +426,7 @@ func TestMetadataCredentialService(t *testing.T) {
tokenPath: ts.server.URL + "/latest/api/token",
logger: logging.Get(),
}
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("metadata service query did not succeed: Failure", err, t)
// happy path: base case
@@ -444,7 +444,7 @@ func TestMetadataCredentialService(t *testing.T) {
logger: logging.Get(),
}
var creds aws.Credentials
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -457,7 +457,7 @@ func TestMetadataCredentialService(t *testing.T) {
// happy path: verify credentials are cached based on expiry
ts.payload.AccessKeyID = "ICHANGEDTHISBUTWEWONTSEEIT"
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -484,7 +484,7 @@ func TestMetadataCredentialService(t *testing.T) {
Token: "MYAWSSECURITYTOKENGOESHERE",
Expiration: time.Now().UTC().Add(time.Minute * 2)} // short time
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -497,7 +497,7 @@ func TestMetadataCredentialService(t *testing.T) {
// second time through, with changes
ts.payload.AccessKeyID = "ICHANGEDTHISANDWEWILLSEEIT"
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -523,7 +523,7 @@ func TestMetadataCredentialService(t *testing.T) {
t.Setenv(ecsFullPathEnvVar, ts.server.URL+"/fullPath")
t.Setenv(ecsAuthorizationTokenEnvVar, "THIS_IS_A_GOOD_TOKEN")
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -555,7 +555,7 @@ func TestMetadataCredentialService(t *testing.T) {
Expiration: time.Now().UTC().Add(time.Minute * 2)} // short time
t.Setenv(ecsFullPathEnvVar, ts.server.URL+"/fullPath")
t.Setenv(ecsAuthorizationTokenFileEnvVar, filepath.Join(path, "good_token_file"))
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
if err != nil {
// Cannot proceed with test if unable to fetch credentials.
t.Fatal(err)
@@ -584,7 +584,7 @@ func TestMetadataServiceErrorHandled(t *testing.T) {
logger: logging.Get(),
}
_, err := cs.credentials(context.Background())
_, err := cs.credentials(t.Context())
assertErr("metadata HTTP request returned unexpected status: 404 Not Found", err, t)
}
@@ -642,7 +642,7 @@ func TestV4Signing(t *testing.T) {
for _, test := range tests {
t.Run(test.sigVersion, func(t *testing.T) {
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -711,7 +711,7 @@ func TestV4SigningUnsignedPayload(t *testing.T) {
},
}
for _, test := range tests {
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -761,7 +761,7 @@ func TestV4SigningForApiGateway(t *testing.T) {
strings.NewReader("{ \"payload\": 42 }"))
req.Header.Set("Content-Type", "application/json")
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -841,7 +841,7 @@ func TestV4SigningOmitsIgnoredHeaders(t *testing.T) {
for _, test := range tests {
t.Run(test.sigVersion, func(t *testing.T) {
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -880,7 +880,7 @@ func TestV4SigningCustomPort(t *testing.T) {
Expiration: time.Now().UTC().Add(time.Minute * 2)}
req, _ := http.NewRequest("GET", "https://custom.s3.server:9000/bundle.tar.gz", strings.NewReader(""))
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -935,7 +935,7 @@ func TestV4SigningDoesNotMutateBody(t *testing.T) {
req, _ := http.NewRequest("POST", "https://myrestapi.execute-api.us-east-1.amazonaws.com/prod/logs",
strings.NewReader("{ \"payload\": 42 }"))
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -1007,7 +1007,7 @@ func TestV4SigningWithMultiValueHeaders(t *testing.T) {
for _, test := range tests {
t.Run(test.sigVersion, func(t *testing.T) {
creds, err := cs.credentials(context.Background())
creds, err := cs.credentials(t.Context())
if err != nil {
t.Fatal("unexpected error getting credentials")
}
@@ -1133,43 +1133,43 @@ func TestWebIdentityCredentialService(t *testing.T) {
}
// wrong path: refresh with invalid web token file
err = cs.refreshFromService(context.Background())
err = cs.refreshFromService(t.Context())
assertErr("unable to read web token for sts HTTP request: open /nonsense: no such file or directory", err, t)
// wrong path: refresh with "bad token"
t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", badTokenFile)
_ = cs.populateFromEnv()
err = cs.refreshFromService(context.Background())
err = cs.refreshFromService(t.Context())
assertErr("STS HTTP request returned unexpected status: 401 Unauthorized", err, t)
// happy path: refresh with "good token"
t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", goodTokenFile)
_ = cs.populateFromEnv()
err = cs.refreshFromService(context.Background())
err = cs.refreshFromService(t.Context())
if err != nil {
t.Fatalf("Unexpected err: %s", err)
}
// happy path: refresh and get credentials
creds, _ := cs.credentials(context.Background())
creds, _ := cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh with session and get credentials
cs.expiration = time.Now()
cs.SessionName = "TEST_SESSION"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: don't refresh, but get credentials
ts.accessKey = "OTHERKEY"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy/wrong path: refresh with "bad token" but return previous credentials
t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", badTokenFile)
_ = cs.populateFromEnv()
cs.expiration = time.Now()
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
assertErr("STS HTTP request returned unexpected status: 401 Unauthorized", err, t)
@@ -1178,7 +1178,7 @@ func TestWebIdentityCredentialService(t *testing.T) {
t.Setenv("AWS_ROLE_ARN", "BrokenRole")
_ = cs.populateFromEnv()
cs.expiration = time.Now()
creds, err = cs.credentials(context.Background())
creds, err = cs.credentials(t.Context())
assertErr("failed to parse credential response from STS service: EOF", err, t)
})
}
@@ -1247,36 +1247,36 @@ func TestAssumeRoleCredentialServiceUsingEnvCredentialsProvider(t *testing.T) {
}
// wrong path: refresh and get credentials but signing credentials not set via env variables
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("no AWS_ACCESS_KEY_ID set in environment", err, t)
t.Setenv("AWS_ACCESS_KEY_ID", "MYAWSACCESSKEYGOESHERE")
_, err = cs.credentials(context.Background())
_, err = cs.credentials(t.Context())
assertErr("no AWS_SECRET_ACCESS_KEY set in environment", err, t)
t.Setenv("AWS_SECRET_ACCESS_KEY", "MYAWSSECRETACCESSKEYGOESHERE")
// happy path: refresh and get credentials
creds, _ := cs.credentials(context.Background())
creds, _ := cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh with session and get credentials
cs.expiration = time.Now()
cs.SessionName = "TEST_SESSION"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: don't refresh as credentials not expired so STS not called
// verify existing credentials haven't changed
ts.accessKey = "OTHERKEY"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh expired credentials
// verify new credentials are set
cs.expiration = time.Now()
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, ts.accessKey, t)
}
@@ -1337,25 +1337,25 @@ aws_session_token=%v
}
// happy path: refresh and get credentials
creds, _ := cs.credentials(context.Background())
creds, _ := cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh with session and get credentials
cs.expiration = time.Now()
cs.SessionName = "TEST_SESSION"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: don't refresh as credentials not expired so STS not called
// verify existing credentials haven't changed
ts.accessKey = "OTHERKEY"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh expired credentials
// verify new credentials are set
cs.expiration = time.Now()
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, ts.accessKey, t)
})
}
@@ -1410,25 +1410,25 @@ func TestAssumeRoleCredentialServiceUsingMetadataCredentialsProvider(t *testing.
}
// happy path: refresh and get credentials
creds, _ := cs.credentials(context.Background())
creds, _ := cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh with session and get credentials
cs.expiration = time.Now()
cs.SessionName = "TEST_SESSION"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: don't refresh as credentials not expired so STS not called
// verify existing credentials haven't changed
ts.accessKey = "OTHERKEY"
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, testAccessKey, t)
// happy path: refresh expired credentials
// verify new credentials are set
cs.expiration = time.Now()
creds, _ = cs.credentials(context.Background())
creds, _ = cs.credentials(t.Context())
assertEq(creds.AccessKey, ts.accessKey, t)
}
@@ -1985,7 +1985,7 @@ sso_region = us-east-1
}
// Get credentials
creds, err := service.credentials(context.Background())
creds, err := service.credentials(t.Context())
// Verify results
if tc.expectError {
+1 -2
View File
@@ -1,7 +1,6 @@
package rest
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
@@ -198,7 +197,7 @@ func TestAzureManagedIdentitiesAuthPlugin(t *testing.T) {
t.Fatalf("Unexpected error: %v", err)
}
ctx := context.Background()
ctx := t.Context()
_, _ = client.Do(ctx, "GET", "test")
ts.stop()
}
+1 -2
View File
@@ -1,7 +1,6 @@
package rest
import (
"context"
"errors"
"fmt"
"net/http"
@@ -36,7 +35,7 @@ func TestGCPMetadataAuthPlugin(t *testing.T) {
t.Fatalf("Unexpected error: %v", err)
}
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
+25 -26
View File
@@ -6,7 +6,6 @@ package rest
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
@@ -954,7 +953,7 @@ func TestDoWithResponseHeaderTimeout(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
tests := map[string]struct {
d time.Duration
@@ -1015,7 +1014,7 @@ func (*tracemock) NewHandler(http.Handler, string, tracing.Options) http.Handler
func TestDoWithDistributedTracingOpts(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
mock := tracemock{}
tracing.RegisterHTTPTracing(&mock)
@@ -1054,7 +1053,7 @@ func TestDoWithDistributedTracingOpts(t *testing.T) {
func TestDoWithResponseInClientLog(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
body := "Some Bad Request was received"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
@@ -1091,7 +1090,7 @@ func TestDoWithResponseInClientLog(t *testing.T) {
func TestDoWithTruncatedResponseInClientLog(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
@@ -1143,7 +1142,7 @@ func TestValidUrl(t *testing.T) {
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1172,7 +1171,7 @@ func testBearerToken(t *testing.T, scheme, token string) {
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1211,7 +1210,7 @@ func TestBearerTokenPath(t *testing.T) {
client := newTestBearerClient(t, &ts, tokenPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1278,7 +1277,7 @@ func TestBearerWithCustomCACert(t *testing.T) {
client := newTestBearerClient(t, &ts, tokenPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1310,7 +1309,7 @@ func TestBearerWithCustomCACertAndSystemCA(t *testing.T) {
client := newTestBearerClient(t, &ts, tokenPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1342,7 +1341,7 @@ func TestBearerTokenInvalidConfig(t *testing.T) {
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
@@ -1432,7 +1431,7 @@ func TestClientCert(t *testing.T) {
client := newTestClient(t, &ts, certPath, keyPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1493,7 +1492,7 @@ func TestClientCertPassword(t *testing.T) {
client := newTestClient(t, &ts, certPath, keyPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1524,7 +1523,7 @@ func TestClientTLSWithCustomCACert(t *testing.T) {
client := newTestClient(t, &ts, certPath, keyPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1556,7 +1555,7 @@ func TestClientTLSWithCustomCACertAndSystemCA(t *testing.T) {
client := newTestClient(t, &ts, certPath, keyPath)
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -1624,7 +1623,7 @@ func TestOauth2ClientCredentials(t *testing.T) {
}
client := newOauth2TestClient(t, tc.ts, tc.ots, tc.options)
ctx := context.Background()
ctx := t.Context()
_, err := client.Do(ctx, "GET", "test")
if err != nil && !tc.wantErr {
t.Fatalf("Unexpected error: %v", err)
@@ -1653,7 +1652,7 @@ func TestOauth2ClientCredentialsExpiringTokenIsRefreshed(t *testing.T) {
defer ots.stop()
client := newOauth2TestClient(t, &ts, &ots)
ctx := context.Background()
ctx := t.Context()
_, err := client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1668,7 +1667,7 @@ func TestOauth2ClientCredentialsExpiringTokenIsRefreshed(t *testing.T) {
defer ts.stop()
client = newOauth2TestClient(t, &ts, &ots)
ctx = context.Background()
ctx = t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1693,7 +1692,7 @@ func TestOauth2ClientCredentialsNonExpiringTokenIsReused(t *testing.T) {
defer ots.stop()
client := newOauth2TestClient(t, &ts, &ots)
ctx := context.Background()
ctx := t.Context()
_, err := client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1739,7 +1738,7 @@ func TestOauth2JwtBearerGrantType(t *testing.T) {
client := newOauth2JwtBearerTestClient(t, ks, &ts, &ots, func(c *Config) {
c.Credentials.OAuth2.SigningKeyID = keyID
})
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1786,7 +1785,7 @@ func TestOauth2JwtBearerGrantTypePKCS8EncodedPrivateKey(t *testing.T) {
client := newOauth2JwtBearerTestClient(t, ks, &ts, &ots, func(c *Config) {
c.Credentials.OAuth2.SigningKeyID = keyID
})
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1833,7 +1832,7 @@ func TestOauth2JwtBearerGrantTypeEllipticCurveAlgorithm(t *testing.T) {
c.Credentials.OAuth2.SigningKeyID = keyID
c.Credentials.OAuth2.IncludeJti = true
})
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -1880,7 +1879,7 @@ func TestOauth2ClientCredentialsJwtAuthentication(t *testing.T) {
client := newOauth2ClientCredentialsJwtAuthClient(t, ks, &ts, &ots, func(c *Config) {
c.Credentials.OAuth2.SigningKeyID = keyID
})
ctx := context.Background()
ctx := t.Context()
_, err = client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -2102,7 +2101,7 @@ func TestDebugLoggingRequestMaskAuthorizationHeader(t *testing.T) {
logger.SetLevel(logging.Debug)
client.logger = logger
ctx := context.Background()
ctx := t.Context()
if _, err := client.Do(ctx, "GET", "test"); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -2672,7 +2671,7 @@ func TestOauth2ClientCredentialsGrantTypeWithKms(t *testing.T) {
kms := aws.NewKMSWithURLClient(kmsServer.URL, kmsServer.Client(), logger)
client := newOauth2KmsClientCredentialsTestClient(t, &ts, &ots, kms)
ctx := context.Background()
ctx := t.Context()
_, err := client.Do(ctx, "GET", "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
@@ -2819,7 +2818,7 @@ func TestOauth2ClientCredentialsGrantTypeWithKeyVault(t *testing.T) {
}
client := newOauth2AzureKVClient(t, &ts, &ots, tokenerServer, fakePlugin)
_, err = client.Do(context.Background(), http.MethodGet, "test")
_, err = client.Do(t.Context(), http.MethodGet, "test")
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
+29 -28
View File
@@ -63,7 +63,7 @@ func TestStatusUpdateBuffer(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -165,7 +165,7 @@ func TestPluginPrometheus(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -335,7 +335,7 @@ func TestMetricsBundleWithoutRevision(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -367,7 +367,7 @@ func TestPluginStart(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -446,7 +446,7 @@ func TestPluginStartTriggerManualStart(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
tr := plugins.TriggerManual
fixture.plugin.config.Trigger = &tr
@@ -494,19 +494,20 @@ func TestPluginStartTriggerManual(t *testing.T) {
// trigger the status update
go func() {
_ = fixture.plugin.Trigger(context.Background())
_ = fixture.plugin.Trigger(t.Context())
}()
errCh := make(chan error, 1)
go func() {
update := <-fixture.plugin.trigger
err := fixture.plugin.oneShot(update.ctx)
if err != nil {
t.Error(err)
return
}
errCh <- err
}()
result := <-fixture.server.ch
if err := <-errCh; err != nil {
t.Fatal(err)
}
exp := UpdateRequestV1{
Labels: map[string]string{
@@ -528,7 +529,7 @@ func TestPluginStartTriggerManualMultiple(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
tr := plugins.TriggerManual
fixture.plugin.config.Trigger = &tr
@@ -569,7 +570,7 @@ func TestPluginStartTriggerManualMultiple(t *testing.T) {
}
func TestPluginStartTriggerManualWithTimeout(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second)
defer cancel()
s := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
@@ -630,7 +631,7 @@ func TestPluginStartTriggerManualWithTimeout(t *testing.T) {
}
func TestPluginStartTriggerManualWithError(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
managerConfig := []byte(`{
"labels": {
@@ -685,7 +686,7 @@ func TestPluginStartBulkUpdate(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -726,7 +727,7 @@ func TestPluginStartBulkUpdateMultiple(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -784,7 +785,7 @@ func TestPluginStartDiscovery(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -823,7 +824,7 @@ func TestPluginStartDecisionLogs(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -862,7 +863,7 @@ func TestPluginStartDecisionLogs(t *testing.T) {
func TestPluginBadAuth(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
fixture.server.expCode = 401
defer fixture.server.stop()
fixture.plugin.lastBundleStatuses = map[string]*bundle.Status{}
@@ -877,7 +878,7 @@ func TestPluginBadAuth(t *testing.T) {
func TestPluginBadPath(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
fixture.server.expCode = 404
defer fixture.server.stop()
fixture.plugin.lastBundleStatuses = map[string]*bundle.Status{}
@@ -892,7 +893,7 @@ func TestPluginBadPath(t *testing.T) {
func TestPluginBadStatus(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
fixture.server.expCode = 500
defer fixture.server.stop()
fixture.plugin.lastBundleStatuses = map[string]*bundle.Status{}
@@ -907,7 +908,7 @@ func TestPluginBadStatus(t *testing.T) {
func TestPluginNonstandardStatus(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
fixture.server.expCode = 599
defer fixture.server.stop()
fixture.plugin.lastBundleStatuses = map[string]*bundle.Status{}
@@ -922,7 +923,7 @@ func TestPluginNonstandardStatus(t *testing.T) {
func TestPlugin2xxStatus(t *testing.T) {
fixture := newTestFixture(t, nil)
ctx := context.Background()
ctx := t.Context()
fixture.server.expCode = 204
defer fixture.server.stop()
fixture.plugin.lastBundleStatuses = map[string]*bundle.Status{}
@@ -933,7 +934,7 @@ func TestPlugin2xxStatus(t *testing.T) {
}
func TestPluginReconfigure(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
fixture := newTestFixture(t, nil, func(c *Config) {
c.Prometheus = true
})
@@ -995,7 +996,7 @@ func TestMetrics(t *testing.T) {
fixture.server.ch = make(chan UpdateRequestV1)
defer fixture.server.stop()
ctx := context.Background()
ctx := t.Context()
err := fixture.plugin.Start(ctx)
if err != nil {
@@ -1263,7 +1264,7 @@ func (p *testPlugin) Log(_ context.Context, req *UpdateRequestV1) error {
}
func TestPluginCustomBackend(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
manager, _ := plugins.New(nil, "test-instance-id", inmem.New())
backend := &testPlugin{}
@@ -1312,7 +1313,7 @@ func (p prometheusRegisterMock) Unregister(collector prometheus.Collector) bool
func TestPluginTerminatesAfterGracefulShutdownPeriodWithoutStatus(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
fixture := newTestFixture(t, nil)
defer fixture.server.stop()
@@ -1333,7 +1334,7 @@ func TestPluginTerminatesAfterGracefulShutdownPeriodWithoutStatus(t *testing.T)
func TestPluginTerminatesAfterGracefulShutdownPeriodWithStatus(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
fixture := newTestFixture(t, nil)
fixture.server.ch = make(chan UpdateRequestV1, 1)
@@ -1393,7 +1394,7 @@ func TestSlowServer(t *testing.T) {
_, plugin := newPlugin(t, server.URL, nil)
// just start the loop, calling Start will also send a plugin status update that isn't needed for this test
go plugin.loop(context.Background())
go plugin.loop(t.Context())
status := bundle.Status{
Name: "test",
+1 -2
View File
@@ -5,7 +5,6 @@
package profiler
import (
"context"
"fmt"
"strings"
"testing"
@@ -29,7 +28,7 @@ func BenchmarkProfilerBigLocalVar(b *testing.B) {
b.Fatal(err)
}
ctx := context.Background()
ctx := b.Context()
pq, err := rego.New(
rego.Module("test.rego", module),
+7 -8
View File
@@ -6,7 +6,6 @@
package profiler
import (
"context"
_ "encoding/json"
"reflect"
"testing"
@@ -67,7 +66,7 @@ p if {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -144,7 +143,7 @@ func TestProfileCheckExprDuration(t *testing.T) {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -212,7 +211,7 @@ baz if {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -267,7 +266,7 @@ baz if {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -328,7 +327,7 @@ baz if {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -396,7 +395,7 @@ baz if {
rego.QueryTracer(profiler),
)
ctx := context.Background()
ctx := t.Context()
_, err = eval.Eval(ctx)
if err != nil {
@@ -454,7 +453,7 @@ allowed_operations = [
t.Fatal(err)
}
ctx := context.Background()
ctx := t.Context()
pq, err := rego.New(
rego.Module("test.rego", module),
+1 -1
View File
@@ -101,7 +101,7 @@ func TestTargetViaDefaultPlugin(t *testing.T) {
// Warning(philipc): This test modifies package variables, which means it cannot
// be run safely in parallel with other tests.
func TestPluginPrepareOptions(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
tp := testPlugin{}
RegisterPlugin("rego.target.foo", &tp)
t.Cleanup(resetPlugins)
+12 -13
View File
@@ -1,7 +1,6 @@
package rego
import (
"context"
"encoding/json"
"fmt"
"os"
@@ -18,7 +17,7 @@ import (
)
func BenchmarkPartialObjectRuleCrossModule(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000}
for _, n := range sizes {
@@ -76,7 +75,7 @@ func BenchmarkPartialObjectRuleCrossModule(b *testing.B) {
}
func BenchmarkCustomFunctionInHotPath(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
input := ast.MustParseTerm(mustReadFileAsString(b, "testdata/ast.json"))
module := ast.MustParseModule(`package test
@@ -121,7 +120,7 @@ func BenchmarkCustomFunctionInHotPath(b *testing.B) {
// BenchmarkAciTestBuildAndEval-10 37 30700209 ns/op 16437935 B/op 384211 allocs/op
// BenchmarkAciTestBuildAndEval-12 58 17566909 ns/op 15991409 B/op 304237 allocs/op
func BenchmarkAciTestBuildAndEval(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
for range b.N {
bundle, err := loader.NewFileLoader().
@@ -153,7 +152,7 @@ func BenchmarkAciTestBuildAndEval(b *testing.B) {
// BenchmarkAciTestOnlyEval-10 13521 86647 ns/op 47448 B/op 967 allocs/op // ref.CopyNonGround
// BenchmarkAciTestOnlyEval-12 21007 57551 ns/op 45323 B/op 920 allocs/op
func BenchmarkAciTestOnlyEval(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
bundle, err := loader.NewFileLoader().
WithRegoVersion(ast.RegoV0).
@@ -184,7 +183,7 @@ func BenchmarkAciTestOnlyEval(b *testing.B) {
// 15574 77121 ns/op 67249 B/op 1115 allocs/op // handleErr wrapping, not inlined
// 33862 35864 ns/op 5768 B/op 93 allocs/op // handleErr only on error, inlined
func BenchmarkArrayIteration(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
at := make([]*ast.Term, 512)
for i := range 511 {
@@ -226,7 +225,7 @@ func BenchmarkArrayIteration(b *testing.B) {
// 4800 272403 ns/op 80875 B/op 1193 allocs/op // handleErr wrapping, not inlined
// 4933 223234 ns/op 76772 B/op 681 allocs/op // handleErr only on error, not inlined
func BenchmarkSetIteration(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
at := make([]*ast.Term, 512)
for i := range 512 {
@@ -267,7 +266,7 @@ func BenchmarkSetIteration(b *testing.B) {
// 12067 99582 ns/op 72830 B/op 1126 allocs/op // handleErr wrapping, not inlined
// 15358 85080 ns/op 27752 B/op 615 allocs/op // handleErr only on error, not inlined
func BenchmarkObjectIteration(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
at := make([][2]*ast.Term, 512)
for i := range 512 {
@@ -310,7 +309,7 @@ func BenchmarkObjectIteration(b *testing.B) {
// BenchmarkStoreRefNotFound/inmem-go-10 5208 212288 ns/op 160609 B/op 2936 allocs/op
// BenchmarkStoreRefNotFound/inmem-ast-10 13929 90053 ns/op 39614 B/op 1012 allocs/op
func BenchmarkStoreRefNotFound(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
things := make(map[string]map[string]string, 100)
for i := range 100 {
@@ -360,7 +359,7 @@ r contains true if {
// 242.5 ns/op 168 B/op 7 allocs/op // original implementation
// 176.7 ns/op 96 B/op 4 allocs/op // sync.Pool in ptr.ValuePtr (saving 1 alloc/op per path part)
func BenchmarkStoreRead(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
store := inmem.NewFromObjectWithASTRead(map[string]any{
"foo": map[string]any{
"bar": map[string]any{
@@ -401,7 +400,7 @@ func BenchmarkStoreRead(b *testing.B) {
// 5222 ns/op 5639 B/op 89 allocs/op // ref.CopyNonGround
// 2786 ns/op 5090 B/op 77 allocs/op // Lazy init improvements
func BenchmarkTrivialPolicy(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
r := New(
ParsedQuery(ast.MustParseBody("data.p.r = x")),
ParsedModule(ast.MustParseModule(`package p
@@ -429,7 +428,7 @@ func BenchmarkTrivialQuery(b *testing.B) {
m := metrics.New()
r := New(ParsedQuery(ast.MustParseBody("1")), GenerateJSON(noOpGenerateJSON), Metrics(m))
ctx := context.Background()
ctx := b.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -462,7 +461,7 @@ func noOpGenerateJSON(*ast.Term, *EvalContext) (any, error) {
// 25671 ns/op 11488 B/op 300 allocs/op
// ...
func BenchmarkGlobalVsLocalLookup(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
module := ast.MustParseModule(`package p
global := 100
+83 -83
View File
@@ -99,7 +99,7 @@ p contains x if {
}
test.WithTempFS(files, func(root string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
Load([]string{root}, nil),
@@ -352,7 +352,7 @@ p contains x if {
}
test.WithTempFS(files, func(root string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
SetRegoVersion(tc.regoVersion),
@@ -396,7 +396,7 @@ p contains x if {
func assertEval(t *testing.T, r *Rego, expected string) {
t.Helper()
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -405,7 +405,7 @@ func assertEval(t *testing.T, r *Rego, expected string) {
func assertPreparedEvalQueryEval(t *testing.T, pq PreparedEvalQuery, options []EvalOption, expected string) {
t.Helper()
rs, err := pq.Eval(context.Background(), options...)
rs, err := pq.Eval(t.Context(), options...)
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -559,7 +559,7 @@ func TestRegoInputs(t *testing.T) {
func TestRegoRewrittenVarsCapture(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
r := New(
Query("a := 1; a != 0; a"),
@@ -578,7 +578,7 @@ func TestRegoRewrittenVarsCapture(t *testing.T) {
func TestRegoDoNotCaptureVoidCalls(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
r := New(Query("print(1)"))
@@ -608,7 +608,7 @@ func TestRegoCancellation(t *testing.T) {
return iter(ast.NullTerm())
})
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond*10)
r := New(Query(`test.sleep("1s")`))
rs, err := r.Eval(ctx)
cancel()
@@ -637,7 +637,7 @@ func TestRegoCustomBuiltinHalt(t *testing.T) {
},
)
r := New(Query(`halt_func("")`), funOpt)
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err == nil {
t.Fatalf("Expected halt error but got: %v", rs)
}
@@ -652,7 +652,7 @@ func TestRegoCustomBuiltinHalt(t *testing.T) {
func TestRegoMetrics(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m))
ctx := context.Background()
ctx := t.Context()
_, err := r.Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -670,7 +670,7 @@ func TestRegoMetrics(t *testing.T) {
func TestPreparedRegoMetrics(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m))
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
t.Fatal(err)
@@ -693,7 +693,7 @@ func TestPreparedRegoMetrics(t *testing.T) {
func TestPreparedRegoMetricsPrepareOnly(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m))
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
t.Fatal(err)
@@ -715,7 +715,7 @@ func TestPreparedRegoMetricsPrepareOnly(t *testing.T) {
func TestPreparedRegoMetricsEvalOnly(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x")) // No Metrics() passed in
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
t.Fatal(err)
@@ -750,7 +750,7 @@ func validateRegoMetrics(t *testing.T, m metrics.Metrics, expectedFields []strin
func TestRegoInstrumentExtraEvalCompilerStage(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m), Instrument(true))
ctx := context.Background()
ctx := t.Context()
_, err := r.Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -772,7 +772,7 @@ func TestRegoInstrumentExtraEvalCompilerStage(t *testing.T) {
func TestPreparedRegoInstrumentExtraEvalCompilerStage(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m), Instrument(true))
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
t.Fatal(err)
@@ -811,7 +811,7 @@ func TestPreparedRegoInstrumentExtraEvalCompilerStage(t *testing.T) {
func TestRegoInstrumentExtraPartialCompilerStage(t *testing.T) {
m := metrics.New()
r := New(Query("foo = 1"), Module("foo.rego", "package x"), Metrics(m), Instrument(true))
ctx := context.Background()
ctx := t.Context()
_, err := r.Partial(ctx)
if err != nil {
t.Fatal(err)
@@ -833,7 +833,7 @@ func TestRegoInstrumentExtraPartialCompilerStage(t *testing.T) {
func TestRegoInstrumentExtraPartialResultCompilerStage(t *testing.T) {
m := metrics.New()
r := New(Query("input.x"), Module("foo.rego", "package x"), Metrics(m), Instrument(true))
ctx := context.Background()
ctx := t.Context()
_, err := r.PartialResult(ctx)
if err != nil {
t.Fatal(err)
@@ -865,12 +865,12 @@ func TestPreparedRegoTracerNoPropagate(t *testing.T) {
Query("data"),
Module("foo.rego", mod),
Tracer(tracer),
Input(map[string]any{"x": 10})).PrepareForEval(context.Background())
Input(map[string]any{"x": 10})).PrepareForEval(t.Context())
if err != nil {
t.Fatalf("unexpected error %s", err)
}
_, err = pq.Eval(context.Background()) // no EvalTracer option
_, err = pq.Eval(t.Context()) // no EvalTracer option
if err != nil {
t.Fatalf("unexpected error %s", err)
}
@@ -893,12 +893,12 @@ func TestPreparedRegoQueryTracerNoPropagate(t *testing.T) {
Query("data"),
Module("foo.rego", mod),
QueryTracer(tracer),
Input(map[string]any{"x": 10})).PrepareForEval(context.Background())
Input(map[string]any{"x": 10})).PrepareForEval(t.Context())
if err != nil {
t.Fatalf("unexpected error %s", err)
}
_, err = pq.Eval(context.Background()) // no EvalQueryTracer option
_, err = pq.Eval(t.Context()) // no EvalQueryTracer option
if err != nil {
t.Fatalf("unexpected error %s", err)
}
@@ -925,13 +925,13 @@ func TestRegoDisableIndexing(t *testing.T) {
pq, err := New(
Query("data"),
Module("foo.rego", mod),
).PrepareForEval(context.Background())
).PrepareForEval(t.Context())
if err != nil {
t.Fatalf("unexpected error %s", err)
}
_, err = pq.Eval(
context.Background(),
t.Context(),
EvalQueryTracer(tracer),
EvalRuleIndexing(false),
EvalInput(map[string]any{"x": 10}),
@@ -977,13 +977,13 @@ func TestRegoDisableIndexingWithMatch(t *testing.T) {
pq, err := New(
Query("data"),
Module("foo.rego", mod),
).PrepareForEval(context.Background())
).PrepareForEval(t.Context())
if err != nil {
t.Fatalf("unexpected error %s", err)
}
rs, err := pq.Eval(
context.Background(),
t.Context(),
EvalQueryTracer(tracer),
EvalRuleIndexing(false),
EvalInput(map[string]any{"x": 1}),
@@ -1023,7 +1023,7 @@ func TestRegoCatchPathConflicts(t *testing.T) {
})),
)
ctx := context.Background()
ctx := t.Context()
_, err := r.Eval(ctx)
if err == nil {
@@ -1046,7 +1046,7 @@ func TestPartialRewriteEquals(t *testing.T) {
Module("test.rego", mod),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.Partial(ctx)
if err != nil {
@@ -1106,7 +1106,7 @@ func TestPrepareAndEvalRaceConditions(t *testing.T) {
Package("foo"),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1138,7 +1138,7 @@ func TestPrepareAndEvalNewInput(t *testing.T) {
Package("foo"),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1163,7 +1163,7 @@ func TestPrepareAndEvalNewMetrics(t *testing.T) {
Metrics(originalMetrics),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1197,7 +1197,7 @@ func TestPrepareAndEvalTransaction(t *testing.T) {
package test
x = data.foo.y
`
ctx := context.Background()
ctx := t.Context()
store := mock.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -1305,7 +1305,7 @@ func TestPrepareAndEvalIdempotent(t *testing.T) {
Package("foo"),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1332,7 +1332,7 @@ func TestPrepareAndEvalOriginal(t *testing.T) {
Input(map[string]int{"y": 2}),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1362,7 +1362,7 @@ func TestPrepareAndEvalOnlyOneErrorOccurredPrintOnce(t *testing.T) {
Input(map[string]int{"y": 2}),
)
_, err := r.PrepareForEval(context.Background())
_, err := r.PrepareForEval(t.Context())
if err == nil {
t.Fatal("Expected error but got nil")
}
@@ -1385,7 +1385,7 @@ func TestPrepareAndEvalNewPrintHook(t *testing.T) {
EnablePrintStatements(true),
)
pq, err := r.PrepareForEval(context.Background())
pq, err := r.PrepareForEval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
@@ -1427,7 +1427,7 @@ func TestPrepareAndPartialResult(t *testing.T) {
Input(map[string]int{"y": 2}),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -1465,7 +1465,7 @@ func TestPrepareWithPartialEval(t *testing.T) {
Package("foo"),
)
ctx := context.Background()
ctx := t.Context()
// Prepare the query and partially evaluate it
pq, err := r.PrepareForEval(ctx, WithPartialEval())
@@ -1493,7 +1493,7 @@ func TestPrepareAndPartial(t *testing.T) {
Module("test.rego", mod),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -1577,7 +1577,7 @@ foo contains __local1__1 if { __local1__1 = input.v }`,
SetRegoVersion(ast.RegoV1),
)
ctx := context.Background()
ctx := t.Context()
partialQuery, err := r.Partial(ctx)
if err != nil {
@@ -1612,7 +1612,7 @@ func TestPartialNamespace(t *testing.T) {
`),
)
pq, err := r.Partial(context.Background())
pq, err := r.Partial(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1648,7 +1648,7 @@ func TestPrepareAndCompile(t *testing.T) {
Package("foo"),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -1682,7 +1682,7 @@ func TestPartialResultWithInput(t *testing.T) {
Module("test.rego", mod),
)
ctx := context.Background()
ctx := t.Context()
pr, err := r.PartialResult(ctx)
if err != nil {
@@ -1713,7 +1713,7 @@ func TestPartialResultWithNamespace(t *testing.T) {
Compiler(c),
)
ctx := context.Background()
ctx := t.Context()
pr, err := r.PartialResult(ctx)
if err != nil {
@@ -1756,7 +1756,7 @@ func TestPreparedPartialResultWithTracer(t *testing.T) {
tracer := topdown.NewBufferTracer()
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForPartial(ctx)
if err != nil {
t.Fatalf("unexpected error from Rego.PrepareForPartial(): %s", err.Error())
@@ -1798,7 +1798,7 @@ func TestPreparedPartialResultWithQueryTracer(t *testing.T) {
tracer := topdown.NewBufferTracer()
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForPartial(ctx)
if err != nil {
t.Fatalf("unexpected error from Rego.PrepareForPartial(): %s", err.Error())
@@ -1845,7 +1845,7 @@ func TestPartialResultSetsValidConflictChecker(t *testing.T) {
Compiler(c),
)
ctx := context.Background()
ctx := t.Context()
pr, err := r.PartialResult(ctx)
if err != nil {
@@ -1862,7 +1862,7 @@ func TestMissingLocation(t *testing.T) {
// Create a query programmatically and evaluate it. The Location information
// is not set so the resulting expression value will not have it.
r := New(ParsedQuery(ast.NewBody(ast.NewExpr(ast.BooleanTerm(true)))))
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err != nil {
t.Fatal(err)
@@ -1896,7 +1896,7 @@ func TestBundlePassing(t *testing.T) {
Query("x = data.foo.allow"),
)
res, err := r.Eval(context.Background())
res, err := r.Eval(t.Context())
if err != nil {
t.Fatal(err)
@@ -1931,7 +1931,7 @@ func TestModulePassing(t *testing.T) {
p = 4`)),
)
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1957,7 +1957,7 @@ func TestModulePassing(t *testing.T) {
func TestUnsafeBuiltins(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
unsafeCountExpr := "unsafe built-in function calls in expression: count"
unsafeCountExprWith := `with keyword replacing built-in function: target must not be unsafe: "count"`
@@ -2083,7 +2083,7 @@ func TestUnsafeBuiltins(t *testing.T) {
p = count([])`),
)
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err != nil || len(rs) != 1 {
log.Fatalf("Unexpected error or result. Result: %v. Error: %v", rs, err)
}
@@ -2105,7 +2105,7 @@ func TestPreparedQueryGetModules(t *testing.T) {
regoArgs = append(regoArgs, Query("data"))
ctx := context.Background()
ctx := t.Context()
pq, err := New(regoArgs...).PrepareForEval(ctx)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
@@ -2136,7 +2136,7 @@ func TestRegoEvalWithFile(t *testing.T) {
}
test.WithTempFS(files, func(path string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
Load([]string{path}, nil),
@@ -2164,7 +2164,7 @@ func TestRegoEvalWithBundle(t *testing.T) {
}
test.WithTempFS(files, func(path string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
LoadBundle(path),
@@ -2200,7 +2200,7 @@ func TestRegoEvalWithBundleURL(t *testing.T) {
}
test.WithTempFS(files, func(path string) {
ctx := context.Background()
ctx := t.Context()
pq, err := New(
LoadBundle("file://"+path),
Query("data.x.p"),
@@ -2223,7 +2223,7 @@ func TestRegoEvalWithBundleURL(t *testing.T) {
func TestRegoEvalPoliciesInStore(t *testing.T) {
store := mock.New()
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
err := store.UpsertPolicy(ctx, txn, "a.rego", []byte("package a\np=1"))
@@ -2264,7 +2264,7 @@ func TestRegoEvalModulesOnCompiler(t *testing.T) {
t.Fatalf("Unexpected compile errors: %s", compiler.Errors)
}
ctx := context.Background()
ctx := t.Context()
pq, err := New(
Compiler(compiler),
@@ -2426,7 +2426,7 @@ func TestRegoEvalWithRegoV1(t *testing.T) {
for _, tc := range tests {
t.Run(fmt.Sprintf("%s: %s", s.name, tc.note), func(t *testing.T) {
test.WithTempFS(tc.policies, func(path string) {
ctx := context.Background()
ctx := t.Context()
options := append(s.options(path, tc.policies, t, ctx),
Query("data.test"),
@@ -2467,7 +2467,7 @@ func TestRegoEvalWithRegoV1(t *testing.T) {
}
func TestRegoLoadFilesWithProvidedStore(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
files := map[string]string{
@@ -2492,7 +2492,7 @@ func TestRegoLoadFilesWithProvidedStore(t *testing.T) {
}
func TestRegoLoadBundleWithProvidedStore(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := mock.New()
files := map[string]string{
@@ -2560,14 +2560,14 @@ func TestRegoCustomBuiltinPartialPropagate(t *testing.T) {
),
)
pr, err := originalRego.PartialResult(context.Background())
pr, err := originalRego.PartialResult(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
rs, err := pr.Rego(
Input(map[string]any{"foo": "/foo/bar/baz/"}),
).Eval(context.Background())
).Eval(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
@@ -2584,7 +2584,7 @@ func TestRegoPartialResultRecursiveRefs(t *testing.T) {
p if { input.x = 1 }`))
_, err := r.PartialResult(context.Background())
_, err := r.PartialResult(t.Context())
if err == nil {
t.Fatal("expected error")
}
@@ -2605,7 +2605,7 @@ func TestSkipPartialNamespaceOption(t *testing.T) {
p = true if { input }
`), SkipPartialNamespace(true))
pq, err := r.Partial(context.Background())
pq, err := r.Partial(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2637,7 +2637,7 @@ func TestShallowInliningOption(t *testing.T) {
`),
ShallowInlining(true))
pq, err := r.Partial(context.Background())
pq, err := r.Partial(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2679,7 +2679,7 @@ func TestRegoPartialResultSortedRules(t *testing.T) {
s = 100
`))
pq, err := r.Partial(context.Background())
pq, err := r.Partial(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2706,7 +2706,7 @@ func TestPrepareWithEmptyModule(t *testing.T) {
_, err := New(
Query("d"),
Module("example.rego", ""),
).PrepareForEval(context.Background())
).PrepareForEval(t.Context())
expected := "1 error occurred: example.rego:0: rego_parse_error: empty module"
if err == nil || err.Error() != expected {
@@ -2722,7 +2722,7 @@ func TestPrepareWithWasmTargetNotSupported(t *testing.T) {
}
test.WithTempFS(files, func(path string) {
ctx := context.Background()
ctx := t.Context()
_, err := New(
LoadBundle(path),
@@ -2757,7 +2757,7 @@ func TestEvalWithInterQueryCache(t *testing.T) {
config, _ := cache.ParseCachingConfig(nil)
interQueryCache := cache.NewInterQueryCache(config)
ctx := context.Background()
ctx := t.Context()
_, err := New(Query(query), InterQueryBuiltinCache(interQueryCache)).Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -2776,7 +2776,7 @@ func TestEvalWithInterQueryCache(t *testing.T) {
}
func TestEvalWithInterQueryValueCache(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
// add an inter-query value cache
config, _ := cache.ParseCachingConfig(nil)
@@ -2841,7 +2841,7 @@ func TestEvalWithNDCache(t *testing.T) {
ndBC.Put("arbitrary_experiment", arbitraryKey, arbitraryValue)
// Query execution of http.send should add an entry to the NDBuiltinCache.
ctx := context.Background()
ctx := t.Context()
_, err := New(Query(query), NDBuiltinCache(ndBC)).Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -2891,7 +2891,7 @@ func TestEvalWithPrebuiltNDCache(t *testing.T) {
// Timestamp ns value will be: 1451311705000000000
ndBC.Put("time.now_ns", ast.NewArray(), ast.Number(json.Number(strconv.FormatInt(timeValue.UnixNano(), 10))))
// time.now_ns should use the cached entry instead of the current time.
ctx := context.Background()
ctx := t.Context()
rs, err := New(Query(query), NDBuiltinCache(ndBC)).Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -2902,7 +2902,7 @@ func TestEvalWithPrebuiltNDCache(t *testing.T) {
}
func TestNDBCacheWithRuleBody(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer ts.Close()
@@ -2928,7 +2928,7 @@ p if {
// Catches issues around iteration with ND builtins.
func TestNDBCacheWithRuleBodyAndIteration(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
}))
defer ts.Close()
@@ -2999,7 +2999,7 @@ func TestNDBCacheMarshalUnmarshalJSON(t *testing.T) {
}
func TestStrictBuiltinErrors(t *testing.T) {
_, err := New(Query("1/0"), StrictBuiltinErrors(true)).Eval(context.Background())
_, err := New(Query("1/0"), StrictBuiltinErrors(true)).Eval(t.Context())
if err == nil {
t.Fatal("expected error")
}
@@ -3020,7 +3020,7 @@ func TestStrictBuiltinErrors(t *testing.T) {
func TestBuiltinErrorList(t *testing.T) {
var buf []topdown.Error
_, err := New(Query("1/0"), BuiltinErrorList(&buf)).Eval(context.Background())
_, err := New(Query("1/0"), BuiltinErrorList(&buf)).Eval(t.Context())
if err != nil {
t.Fatal("unexpected error")
}
@@ -3036,7 +3036,7 @@ func TestBuiltinErrorList(t *testing.T) {
func TestTimeSeedingOptions(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
clock := time.Now()
// Check expected time is returned.
@@ -3114,7 +3114,7 @@ func TestPrepareAndCompileWithSchema(t *testing.T) {
Schemas(schemaSet),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -3145,7 +3145,7 @@ x contains v if {
SetRegoVersion(ast.RegoV1),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
@@ -3183,7 +3183,7 @@ func TestRegoLazyObjDefault(t *testing.T) {
Store(store),
)
ctx := context.Background()
ctx := t.Context()
rs, err := r.Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -3213,7 +3213,7 @@ func TestRegoLazyObjNoRoundTripOnWrite(t *testing.T) {
Store(store),
)
ctx := context.Background()
ctx := t.Context()
rs, err := r.Eval(ctx)
if err != nil {
t.Fatal(err)
@@ -3243,7 +3243,7 @@ func TestRegoLazyObjCopyMaps(t *testing.T) {
Store(store),
)
ctx := context.Background()
ctx := t.Context()
pq, err := r.PrepareForEval(ctx)
if err != nil {
t.Fatal(err)
@@ -3395,7 +3395,7 @@ result := test.module("policy.rego")
`
t.Run("compiler not passed", func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
r := New(
Query("data.test.result"),
CompilerHook(func(c *ast.Compiler) { ctx = ast.WithCompiler(ctx, c) }),
@@ -3433,7 +3433,7 @@ result := test.module("policy.rego")
})
t.Run("compiler passed in", func(t *testing.T) { // when the compiler is passed, no hook is run
ctx := context.Background()
ctx := t.Context()
r := New(
Compiler(ast.NewCompiler()),
Query("data.test.result"),
+1 -2
View File
@@ -1,7 +1,6 @@
package rego_test
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/rego"
@@ -66,7 +65,7 @@ resp = { "allow": true } if { true }
rego.Query(tc.query),
rego.Module("", tc.module),
)
rs, err := r.Eval(context.Background())
rs, err := r.Eval(t.Context())
if err != nil {
t.Fatal(err)
}
+57 -58
View File
@@ -7,7 +7,6 @@ package repl
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@@ -27,7 +26,7 @@ import (
func TestFunction(t *testing.T) {
store := newTestStore()
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
mod1 := []byte(`package a.b.c
@@ -178,7 +177,7 @@ baz(_) = y if {
}
func TestComplete(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -267,7 +266,7 @@ r = 3 if { true }`)
}
func TestDump(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
input := `{"a": [1,2,3,4]}`
var data map[string]any
err := util.UnmarshalJSON([]byte(input), &data)
@@ -284,7 +283,7 @@ func TestDump(t *testing.T) {
}
func TestDumpPath(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
input := `{"a": [1,2,3,4]}`
var data map[string]any
err := util.UnmarshalJSON([]byte(input), &data)
@@ -320,7 +319,7 @@ func TestDumpPath(t *testing.T) {
}
func TestDumpPathCaseSensitive(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
input := `{"a": [1,2,3,4]}`
var data map[string]any
err := util.UnmarshalJSON([]byte(input), &data)
@@ -363,7 +362,7 @@ func TestHelp(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -379,7 +378,7 @@ func TestHelp(t *testing.T) {
}
func TestHelpWithOPAVersionReport(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -415,7 +414,7 @@ Release Notes : https://github.com/open-policy-agent/opa/releases/tag/
}
func TestShowDebug(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -471,7 +470,7 @@ func TestShowDebug(t *testing.T) {
// The rego.v1 import will be stripped from the output if the default rego-version is v1,
// so we need two flavours of this test: v0, and v1.
func TestShowV0(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).WithRegoVersion(ast.RegoV0)
@@ -557,7 +556,7 @@ p[2]` + "\n"
}
func TestShowV1(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).WithRegoVersion(ast.RegoV1)
@@ -643,7 +642,7 @@ p contains 2` + "\n"
}
func TestTypes(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -680,7 +679,7 @@ func TestTypes(t *testing.T) {
}
func TestUnknown(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -721,7 +720,7 @@ func TestUnknown(t *testing.T) {
}
}
func TestUnknownMetrics(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -771,7 +770,7 @@ func TestUnknownMetrics(t *testing.T) {
}
func TestUnknownJSON(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -805,7 +804,7 @@ func TestUnknownJSON(t *testing.T) {
}
func TestUnknownInvalid(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -827,7 +826,7 @@ func TestUnknownInvalid(t *testing.T) {
}
func TestUnset(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -951,7 +950,7 @@ func TestUnset(t *testing.T) {
func TestUnsetInputDocument(t *testing.T) {
// input is only allowed to be overridden in rego v0, so we only assert the following when that's the active version.
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).WithRegoVersion(ast.RegoV0)
@@ -975,7 +974,7 @@ func TestUnsetInputDocument(t *testing.T) {
}
func TestOneShotEmptyBufferOneExpr(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -991,7 +990,7 @@ func TestOneShotEmptyBufferOneExpr(t *testing.T) {
}
func TestOneShotEmptyBufferOneRule(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1008,7 +1007,7 @@ func TestOneShotEmptyBufferOneRule(t *testing.T) {
}
func TestOneShotRefHeadRulePrinted(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1021,7 +1020,7 @@ func TestOneShotRefHeadRulePrinted(t *testing.T) {
}
func TestOneShotBufferedExpr(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1040,7 +1039,7 @@ func TestOneShotBufferedExpr(t *testing.T) {
}
func TestOneShotBufferedRule(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1082,7 +1081,7 @@ func TestOneShotBufferedRule(t *testing.T) {
}
func TestOneShotJSON(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1238,7 +1237,7 @@ func TestOneShot_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1399,7 +1398,7 @@ func TestOneShot_RegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -1534,7 +1533,7 @@ p if { data := 1; data == 1 }`,
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -1574,7 +1573,7 @@ p if { data := 1; data == 1 }`,
}
func TestEvalData(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1639,7 +1638,7 @@ p = [1, 2, 3] if { true }`)
}
func TestEvalFalse(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1653,7 +1652,7 @@ func TestEvalFalse(t *testing.T) {
}
func TestEvalConstantRule(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1697,7 +1696,7 @@ func TestEvalConstantRule(t *testing.T) {
}
func TestEvalBooleanFlags(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -1745,7 +1744,7 @@ Rule 'flags2' defined in package repl. Type 'show' to see rules.
func TestEvalConstantRuleDefaultRootDoc(t *testing.T) {
// The 'input' document may only be shadowed in rego v0.
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -1766,7 +1765,7 @@ func TestEvalConstantRuleDefaultRootDoc(t *testing.T) {
}
func TestEvalConstantRuleAssignment(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
@@ -1825,7 +1824,7 @@ x := 2
func TestEvalConstantRuleAssignmentInputDocument(t *testing.T) {
// input is only allowed to be overridden in rego v0, so we only assert the following when that's the active version.
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -1855,7 +1854,7 @@ func TestEvalConstantRuleAssignmentInputDocument(t *testing.T) {
}
func TestEvalSingleTermMultiValue(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2053,7 +2052,7 @@ func TestEvalSingleTermMultiValue(t *testing.T) {
}
func TestEvalSingleTermMultiValueSetRef(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2242,7 +2241,7 @@ func TestEvalSingleTermMultiValueSetRef(t *testing.T) {
}
func TestEvalRuleCompileError(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2270,7 +2269,7 @@ func TestEvalRuleCompileError(t *testing.T) {
}
func TestEvalBodyCompileError(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2327,7 +2326,7 @@ func TestEvalBodyCompileError(t *testing.T) {
}
func TestEvalBodyContainingWildCards(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2353,7 +2352,7 @@ func TestEvalBodyContainingWildCards(t *testing.T) {
}
func TestEvalBodyInput(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -2389,7 +2388,7 @@ func TestEvalBodyInput(t *testing.T) {
}
func TestEvalBodyInputComplete(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -2490,7 +2489,7 @@ func TestEvalBodyInputComplete(t *testing.T) {
}
func TestEvalBodyWith(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2527,7 +2526,7 @@ func TestEvalBodyWith(t *testing.T) {
}
func TestEvalBodyRewrittenBuiltin(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2587,7 +2586,7 @@ func TestEvalBodyRewrittenBuiltin(t *testing.T) {
}
func TestEvalBodyRewrittenRef(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2711,7 +2710,7 @@ func TestEvalBodyRewrittenRef(t *testing.T) {
}
func TestEvalBodySomeDecl(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2747,7 +2746,7 @@ func TestEvalBodySomeDecl(t *testing.T) {
}
func TestEvalImport(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2783,7 +2782,7 @@ func TestEvalImport(t *testing.T) {
}
func TestEvalImportFutureKeywords(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).
@@ -2876,7 +2875,7 @@ p {
}
func TestEvalPackage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -2918,7 +2917,7 @@ func TestEvalPackage(t *testing.T) {
}
func TestMetrics(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
@@ -2971,7 +2970,7 @@ func TestMetrics(t *testing.T) {
func TestProfile(t *testing.T) {
store := newTestStore()
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
const numLines = 21
@@ -3053,7 +3052,7 @@ default allow = false
}
func TestStrictBuiltinErrors(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
@@ -3086,7 +3085,7 @@ func TestStrictBuiltinErrors(t *testing.T) {
}
func TestInstrument(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
@@ -3164,7 +3163,7 @@ func TestInstrument(t *testing.T) {
}
func TestEvalTrace(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -3210,7 +3209,7 @@ query:1 | Redo data.a[i].b.c[j] = x
}
func TestEvalNotes(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -3241,7 +3240,7 @@ true`)
}
func TestTruncatePrettyOutput(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -3265,7 +3264,7 @@ func TestTruncatePrettyOutput(t *testing.T) {
}
func TestUnsetPackage(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
@@ -3323,7 +3322,7 @@ func TestCapabilities(t *testing.T) {
}
}
capabilities.Builtins = allowedBuiltins
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer).WithCapabilities(capabilities)
@@ -3337,7 +3336,7 @@ func TestCapabilities(t *testing.T) {
}
func TestTraceArgument(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)
+2 -2
View File
@@ -102,7 +102,7 @@ func TestValidateMetricsUrl(t *testing.T) {
}
func TestRequestErrorLoggingWithHTTPRequestContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
logger := test.New()
@@ -164,7 +164,7 @@ func TestRequestErrorLoggingWithHTTPRequestContext(t *testing.T) {
}
func TestRequestLogging(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
logger := test.New()
+7 -7
View File
@@ -68,12 +68,12 @@ func TestRegisterPlugin(t *testing.T) {
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
rt, err := NewRuntime(context.Background(), params)
rt, err := NewRuntime(t.Context(), params)
if err != nil {
t.Fatal(err.Error())
}
if err := rt.Manager.Start(context.Background()); err != nil {
if err := rt.Manager.Start(t.Context()); err != nil {
t.Fatalf("Unable to initialize plugins: %v", err.Error())
}
@@ -100,12 +100,12 @@ func TestRegisterPluginNotStartedWithoutConfig(t *testing.T) {
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
rt, err := NewRuntime(context.Background(), params)
rt, err := NewRuntime(t.Context(), params)
if err != nil {
t.Fatal(err.Error())
}
if err := rt.Manager.Start(context.Background()); err != nil {
if err := rt.Manager.Start(t.Context()); err != nil {
t.Fatalf("Unable to initialize plugins: %v", err.Error())
}
@@ -132,7 +132,7 @@ func TestRegisterPluginBadBootConfig(t *testing.T) {
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
_, err := NewRuntime(context.Background(), params)
_, err := NewRuntime(t.Context(), params)
if err == nil || !strings.Contains(err.Error(), "config error: test") {
t.Fatal("expected config error but got:", err)
}
@@ -153,12 +153,12 @@ func TestWaitPluginsReady(t *testing.T) {
params := NewParams()
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
rt, err := NewRuntime(context.Background(), params)
rt, err := NewRuntime(t.Context(), params)
if err != nil {
t.Fatal(err.Error())
}
if err := rt.Manager.Start(context.Background()); err != nil {
if err := rt.Manager.Start(t.Context()); err != nil {
t.Fatalf("Unable to initialize plugins: %v", err.Error())
}
+26 -26
View File
@@ -85,7 +85,7 @@ func TestRuntimeProcessWatchEvents(t *testing.T) {
func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) {
t.Helper()
ctx := context.Background()
ctx := t.Context()
fs := map[string]string{
"test/some/data.json": `{
"hello": "world"
@@ -177,7 +177,7 @@ func TestRuntimeProcessWatchEventPolicyErrorWithBundle(t *testing.T) {
}
func testRuntimeProcessWatchEventPolicyError(t *testing.T, asBundle bool) {
ctx := context.Background()
ctx := t.Context()
fs := map[string]string{
"test/x.rego": `package test
@@ -284,7 +284,7 @@ func testRuntimeProcessWatchEventPolicyError(t *testing.T, asBundle bool) {
}
func TestRuntimeReplWithBundleBuiltWithV1Compatibility(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(nil, func(rootDir string) {
p := filepath.Join(rootDir, "bundle.tar.gz")
@@ -436,7 +436,7 @@ p contains 1 if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(fs, func(rootDir string) {
@@ -589,7 +589,7 @@ p contains 1 if {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(fs, func(rootDir string) {
@@ -735,7 +735,7 @@ func TestCheckOPAUpdateLoopLaterRequests(t *testing.T) {
t.Setenv("OPA_TELEMETRY_SERVICE_URL", baseURL)
ctx := context.Background()
ctx := t.Context()
logger := logging.New()
stdout := bytes.NewBuffer(nil)
@@ -784,7 +784,7 @@ func TestCheckOPAUpdateLoopWithNewUpdate(t *testing.T) {
}
func TestRuntimeWithAuthzSchemaVerification(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
fs := map[string]string{
"test/authz.rego": `package system.authz
@@ -841,7 +841,7 @@ func TestRuntimeWithAuthzSchemaVerification(t *testing.T) {
}
func TestRuntimeWithAuthzSchemaVerificationTransitive(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
fs := map[string]string{
"test/authz.rego": `package system.authz
@@ -886,7 +886,7 @@ func TestRuntimeWithAuthzSchemaVerificationTransitive(t *testing.T) {
}
func TestCheckAuthIneffective(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel() // NOTE(sr): The timeout will have been reached by the time `done` is closed.
params := NewParams()
@@ -919,7 +919,7 @@ func TestCheckAuthIneffective(t *testing.T) {
}
func TestServerInitialized(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel() // NOTE(sr): The timeout will have been reached by the time `done` is closed.
var output bytes.Buffer
@@ -1059,7 +1059,7 @@ func TestServerInitializedWithRegoV1(t *testing.T) {
for _, b := range bundle {
t.Run(fmt.Sprintf("%s; bundle=%v", tc.note, b), func(t *testing.T) {
test.WithTempFS(tc.files, func(root string) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel()
var output bytes.Buffer
@@ -1379,7 +1379,7 @@ func TestServerInitializedWithBundleRegoVersion(t *testing.T) {
}
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel()
var output bytes.Buffer
@@ -1431,7 +1431,7 @@ func TestGracefulTracerShutdown(t *testing.T) {
}
test.WithTempFS(fs, func(testDirRoot string) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel() // NOTE(sr): The timeout will have been reached by the time `done` is closed.
logger := testLog.New()
@@ -1468,7 +1468,7 @@ func TestGracefulTracerShutdown(t *testing.T) {
func TestUrlPathToConfigOverride(t *testing.T) {
params := NewParams()
params.Paths = []string{"https://www.example.com/bundles/bundle.tar.gz"}
ctx := context.Background()
ctx := t.Context()
rt, err := NewRuntime(ctx, params)
if err != nil {
t.Fatal(err)
@@ -1540,7 +1540,7 @@ func testCheckOPAUpdate(t *testing.T, url string, expected *report.DataResponse)
t.Helper()
t.Setenv("OPA_TELEMETRY_SERVICE_URL", url)
ctx := context.Background()
ctx := t.Context()
rt := getTestRuntime(ctx, t, logging.NewNoOpLogger())
result := rt.checkOPAUpdate(ctx)
@@ -1553,7 +1553,7 @@ func testCheckOPAUpdateLoop(t *testing.T, url, expected string) {
t.Helper()
t.Setenv("OPA_TELEMETRY_SERVICE_URL", url)
ctx := context.Background()
ctx := t.Context()
logger := logging.New()
stdout := bytes.NewBuffer(nil)
@@ -1604,7 +1604,7 @@ func TestAddrWarningMessage(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel()
params := NewParams()
@@ -1652,7 +1652,7 @@ func TestRuntimeWithExplicitMetricConfiguration(t *testing.T) {
params := NewParams()
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
_, err := NewRuntime(context.Background(), params)
_, err := NewRuntime(t.Context(), params)
if err != nil {
t.Fatal(err.Error())
}
@@ -1668,7 +1668,7 @@ func TestRuntimeWithExplicitBadMetricConfiguration(t *testing.T) {
params := NewParams()
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
_, err := NewRuntime(context.Background(), params)
_, err := NewRuntime(t.Context(), params)
if err == nil {
t.Fatalf("Expected error to be thrown on malformed metrics config")
}
@@ -1680,7 +1680,7 @@ func TestRuntimeWithExplicitBadMetricConfiguration(t *testing.T) {
}
func TestExtraDiscoveryOpts(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/discovery.tar.gz", map[string]string{
"main.rego": `
@@ -1780,7 +1780,7 @@ func (*factory) Reconfigure(context.Context, any) {
// in OPA run as server.
func TestCustomHandlerFlusher(t *testing.T) {
fact := &factory{}
ctx := context.Background()
ctx := t.Context()
spanExporter := tracetest.NewInMemoryExporter()
options := tracing.NewOptions(
otelhttp.WithTracerProvider(trace.NewTracerProvider(trace.WithSpanProcessor(trace.NewSimpleSpanProcessor(spanExporter)))),
@@ -1885,7 +1885,7 @@ func (ch *configHook) OnConfig(_ context.Context, c *config.Config) (*config.Con
}
func TestConfigHookAndNonReplacedEnvVars(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel() // NOTE(sr): The timeout will have been reached by the time `done` is closed.
testLogger := testLog.New()
@@ -1948,7 +1948,7 @@ func (j *iqvcHook) OnInterQueryValueCache(_ context.Context, c topdown_cache.Int
}
func TestCacheHooksOnServer(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Millisecond)
defer cancel() // NOTE(sr): The timeout will have been reached by the time `done` is closed.
testLogger := testLog.New()
@@ -2001,7 +2001,7 @@ func (f *fakeStore) Read(ctx context.Context, txn storage.Transaction, p storage
}
func TestCustomStoreBuilder(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
testLogger := testLog.New()
params := NewParams()
params.Logger = testLogger
@@ -2056,7 +2056,7 @@ func TestCustomStoreBuilder(t *testing.T) {
}
func TestExtraMiddleware(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
testLogger := testLog.New()
params := NewParams()
params.Logger = testLogger
@@ -2105,7 +2105,7 @@ func TestExtraMiddleware(t *testing.T) {
}
func TestExtraAuthorizerRoutes(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
testLogger := testLog.New()
params := NewParams()
params.Logger = testLogger
+1 -2
View File
@@ -1,7 +1,6 @@
package sdk
import (
"context"
"fmt"
"reflect"
"strings"
@@ -11,7 +10,7 @@ import (
)
func TestDefaultOptions(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
"main.rego": `
+43 -43
View File
@@ -50,7 +50,7 @@ import (
func TestDefaultRegoVersion(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.RawBundles(true),
@@ -156,7 +156,7 @@ func (factory) Validate(*plugins.Manager, []byte) (any, error) {
}
func TestPlugins(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
config := `{
"plugins": {
"test_plugin": {}
@@ -176,7 +176,7 @@ func TestPlugins(t *testing.T) {
}
func TestHookOnConfig(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
// We're setting up two hooks that smuggle in some new labels, and hold on
// to their config.
@@ -209,7 +209,7 @@ func TestHookOnConfig(t *testing.T) {
}
func TestHookOnConfigDiscovery(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
th0 := &testhook{k: "foo", v: "baz"}
th1 := &testhook{k: "fox", v: "quz"}
disco := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -269,7 +269,7 @@ func (h *testhook) OnConfigDiscovery(_ context.Context, c *config.Config) (*conf
}
func TestPluginPanic(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
opa, err := sdk.New(ctx, sdk.Options{})
if err != nil {
@@ -279,7 +279,7 @@ func TestPluginPanic(t *testing.T) {
}
func TestSDKConfigurableID(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -337,7 +337,7 @@ main = time.now_ns()
func TestDecision(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -400,7 +400,7 @@ loopback = input
func TestDecisionWithStrictBuiltinErrors(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -463,7 +463,7 @@ allow if {
func TestDecisionWithTrace(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -538,7 +538,7 @@ main if {
func TestDecisionWithMetrics(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -611,7 +611,7 @@ main = true
func TestDecisionWithIntrumentationAndProfile(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -703,7 +703,7 @@ main = true
func TestDecisionWithProvenance(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -769,7 +769,7 @@ main = true
func TestDecisionWithBundleData(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -819,7 +819,7 @@ main = data.foo
}
func TestDecisionWithConfigurableID(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -890,7 +890,7 @@ main = time.now_ns()
func TestPartial(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -970,7 +970,7 @@ allow if {
func TestPartialWithStrictBuiltinErrors(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1042,7 +1042,7 @@ allow if {
func TestPartialWithTrace(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1124,7 +1124,7 @@ main if {
func TestPartialWithMetrics(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1209,7 +1209,7 @@ allow if {
func TestPartialWithInstrumentationAndProfile(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1315,7 +1315,7 @@ allow if {
func TestPartialWithProvenance(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1391,7 +1391,7 @@ allow if {
func TestPartialWithConfigurableID(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1477,7 +1477,7 @@ allow if {
func TestUndefinedError(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1522,7 +1522,7 @@ func TestUndefinedError(t *testing.T) {
func TestDecisionLogging(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1588,7 +1588,7 @@ main = time.now_ns()
func TestDecisionLoggingWithMasking(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1696,7 +1696,7 @@ mask contains "/input/dossier/1/highly"
func TestDecisionLoggingWithNDBCache(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1770,7 +1770,7 @@ main = time.now_ns()
func TestQueryCaching(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -1836,7 +1836,7 @@ main = 7
func TestDiscovery(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/discovery.tar.gz", map[string]string{
@@ -2090,7 +2090,7 @@ main := v { v := 7 }`,
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
serverOpts := []func(*sdktest.Server) error{
sdktest.MockBundle("/bundles/discovery.tar.gz", tc.discoveryBundle),
@@ -2279,7 +2279,7 @@ bundles:
readyCh = make(chan struct{})
}
ctx := context.Background()
ctx := t.Context()
opa, err := sdk.New(ctx, sdk.Options{
Logger: logger,
Ready: readyCh,
@@ -2319,7 +2319,7 @@ bundles:
func TestAsync(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
callerReadyCh := make(chan struct{})
readyCh := make(chan struct{})
@@ -2396,7 +2396,7 @@ func TestCancelStartup(t *testing.T) {
}`, server.URL())
// Server will return 404 responses because bundle does not exist. OPA should timeout.
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)
ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond*100)
defer cancel()
_, err := sdk.New(ctx, sdk.Options{
@@ -2410,7 +2410,7 @@ func TestCancelStartup(t *testing.T) {
// TestStopWithDeadline asserts that a graceful shutdown of the SDK is possible.
func TestStopWithDeadline(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
opa, err := sdk.New(ctx, sdk.Options{
Config: strings.NewReader(`{
"plugins": {
@@ -2459,7 +2459,7 @@ bundles:
test:
resource: "/bundles/bundle.tar.gz"`, server.URL())
ctx := context.Background()
ctx := t.Context()
_, err := sdk.New(ctx, sdk.Options{
Config: strings.NewReader(config),
})
@@ -2503,7 +2503,7 @@ main = 8
}
}`, server.URL())
ctx := context.Background()
ctx := t.Context()
opa, err := sdk.New(ctx, sdk.Options{
Config: strings.NewReader(config1),
})
@@ -2564,7 +2564,7 @@ main = 8
}
func TestOpaVersion(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -2610,7 +2610,7 @@ opa_version := opa.runtime().version
}
func TestOpaRuntimeConfig(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -2674,7 +2674,7 @@ result := {
func TestOpaRuntimeEnvironmentVariableDefinedInOS(t *testing.T) {
t.Setenv("TOKEN_VERIFY_KEY", "B41BD5F462719C6D6118E673A2389")
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -2740,7 +2740,7 @@ authenticatedUser := a if {
}
func TestOpaRuntimeEnvironmentVariableDefinedInConfig(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -2810,7 +2810,7 @@ authenticatedUser := a if {
func TestPrintStatements(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
s := sdktest.MustNewServer(
sdktest.RawBundles(true), // non-raw bundles will be compiled server-side, which will change print location depending on parser rego-version (v1 drops rego.v1 import).
@@ -2868,7 +2868,7 @@ p if { print("XXX") }
}
func TestConfigurableManagerOpts(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
server := sdktest.MustNewServer(
sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{
@@ -2937,7 +2937,7 @@ func toMetricMap(metrics []*promdto.MetricFamily) map[string]bool {
}
func TestActivateV1Bundles(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)
ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond*100)
defer cancel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -2969,7 +2969,7 @@ func TestActivateV1Bundles(t *testing.T) {
defer opa.Stop(ctx)
d, err := opa.Decision(context.Background(), sdk.DecisionOptions{
d, err := opa.Decision(t.Context(), sdk.DecisionOptions{
Path: "v1bundle/authz",
Input: map[string]any{
"role": "admin",
@@ -2989,7 +2989,7 @@ func TestActivateV1Bundles(t *testing.T) {
func TestWithOwnStoreVSExtStore(t *testing.T) {
bundle.RegisterStoreFunc(inmem.New)
t.Cleanup(func() { bundle.RegisterStoreFunc(nil) })
ctx := context.Background()
ctx := t.Context()
opts := sdk.Options{
Store: inmem.New(),
}
+1 -1
View File
@@ -152,7 +152,7 @@ func (b *Basic) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if reason, ok := allowed["reason"]; ok {
message, ok := reason.(string)
if ok {
writer.Error(w, http.StatusUnauthorized, types.NewErrorV1(types.CodeUnauthorized, message)) //nolint:govet
writer.Error(w, http.StatusUnauthorized, types.NewErrorV1(types.CodeUnauthorized, "%s", message))
return
}
}
+1 -2
View File
@@ -6,7 +6,6 @@ package authorizer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
@@ -549,7 +548,7 @@ func TestInterQueryValueCache(t *testing.T) {
}
config, _ := cache.ParseCachingConfig(nil)
interQueryValueCache := cache.NewInterQueryValueCache(context.Background(), config)
interQueryValueCache := cache.NewInterQueryValueCache(t.Context(), config)
basic := NewBasic(&mockHandler{}, compiler, inmem.New(), InterQueryValueCache(interQueryValueCache), Decision(func() ast.Ref {
return ast.MustParseRef("data.system.authz.allow")
+1 -2
View File
@@ -1,7 +1,6 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"testing"
@@ -33,7 +32,7 @@ hello if input.message == "world"
}
func newBenchFixture(b *testing.B, opts ...any) *fixture {
ctx := context.Background()
ctx := b.Context()
server := New().
WithAddresses([]string{"localhost:8182"}).
WithStore(inmem.New()) // potentially overridden via opts
+37 -37
View File
@@ -144,7 +144,7 @@ func TestUnversionedGetHealthCheckBundleActivationSingleLegacy(t *testing.T) {
f := newFixture(t)
ctx := context.Background()
ctx := t.Context()
// The server doesn't know about any bundles, so return a healthy status
req := newReqUnversioned(http.MethodGet, "/health?bundle=true", "")
@@ -611,7 +611,7 @@ func TestUnversionedGetHealthWithPolicyMissing(t *testing.T) {
func TestUnversionedGetHealthWithPolicyUpdates(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
healthPolicy := `package system.health
@@ -653,7 +653,7 @@ func TestUnversionedGetHealthWithPolicyUpdates(t *testing.T) {
func TestUnversionedGetHealthWithPolicyUsingPlugins(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
healthPolicy := `package system.health
@@ -1183,7 +1183,7 @@ func TestCompileV1(t *testing.T) {
func TestCompileV1Observability(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(nil, func(root string) {
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
@@ -1687,7 +1687,7 @@ p = true if { false }`
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
test.WithTempFS(nil, func(root string) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
if err != nil {
@@ -1710,7 +1710,7 @@ p = true if { false }`
func TestDataV1Metrics(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(nil, func(root string) {
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
@@ -1803,7 +1803,7 @@ func TestConfigV1WithInvalidConfig(t *testing.T) {
}
// create a new server and manager
ctx := context.Background()
ctx := t.Context()
server := New().
WithAddresses([]string{"localhost:8182"}).
WithStore(inmem.New())
@@ -1993,7 +1993,7 @@ func TestDataGetV1CompressedRequestWithAuthorizer(t *testing.T) {
for _, test := range tests {
t.Run(test.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
authzPolicy := `package system.authz
@@ -2162,7 +2162,7 @@ func TestDataPostV1CompressedDecodingLimits(t *testing.T) {
for _, test := range tests {
t.Run(test.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
examplePolicy := `package example.authz
@@ -2610,7 +2610,7 @@ func TestCompileV1CompressedRequest(t *testing.T) {
func TestBundleScope(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(nil, func(root string) {
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
@@ -2736,7 +2736,7 @@ func TestBundleScope(t *testing.T) {
func TestBundleScopeMultiBundle(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
f := newFixture(t)
@@ -2802,7 +2802,7 @@ func TestBundleScopeMultiBundle(t *testing.T) {
func TestBundleNoRoots(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
f := newFixture(t)
@@ -3045,7 +3045,7 @@ p = [1, 2, 3, 4] if { true }`, 200, "")
// open write transaction on the store and execute a query.
// Then check the query is processed
ctx := context.Background()
ctx := t.Context()
_ = storage.NewTransactionOrDie(ctx, f.server.store, storage.WriteParams)
req := newReqV1(http.MethodPost, "/data/test/p", "")
@@ -3198,7 +3198,7 @@ func TestDataProvenanceSingleBundle(t *testing.T) {
t.Errorf("Unexpected provenance data: \n\n%+v\n\nExpected:\n%+v\n\n", result.Provenance, expectedProvenance)
}
ctx := context.Background()
ctx := t.Context()
// Update bundle revision and request again
err := storage.Txn(ctx, f.server.store, storage.WriteParams, func(txn storage.Transaction) error {
@@ -3241,7 +3241,7 @@ func TestDataProvenanceSingleFileBundle(t *testing.T) {
version.Hostname = "foo.bar.com"
// No bundle plugin initialized, just a legacy revision set
ctx := context.Background()
ctx := t.Context()
err := storage.Txn(ctx, f.server.store, storage.WriteParams, func(txn storage.Transaction) error {
return bundle.LegacyWriteManifestToStore(ctx, f.server.store, txn, bundle.Manifest{Revision: "r1"})
@@ -3321,7 +3321,7 @@ func TestDataProvenanceMultiBundle(t *testing.T) {
}
// Update bundle revision for a single bundle and make the request again
ctx := context.Background()
ctx := t.Context()
err := storage.Txn(ctx, f.server.store, storage.WriteParams, func(txn storage.Transaction) error {
return bundle.WriteManifestToStore(ctx, f.server.store, txn, "b1", bundle.Manifest{Revision: "r1"})
@@ -3395,7 +3395,7 @@ func TestDataMetricsEval(t *testing.T) {
// We're setting up the disk store because that injects a few extra metrics,
// which storage/inmem does not.
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(nil, func(root string) {
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
@@ -3980,7 +3980,7 @@ func TestStatusV1(t *testing.T) {
},
},
}, f.server.manager)
err := bs.Start(context.Background())
err := bs.Start(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -4058,7 +4058,7 @@ func TestStatusV1(t *testing.T) {
func TestStatusV1MetricsWithSystemAuthzPolicy(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
// Add the authz policy
store := inmem.New()
@@ -4114,7 +4114,7 @@ func TestStatusV1MetricsWithSystemAuthzPolicy(t *testing.T) {
},
},
}, f.server.manager).WithMetrics(prom)
err := bs.Start(context.Background())
err := bs.Start(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -4245,7 +4245,7 @@ func TestQueryPostBasic(t *testing.T) {
WithAddresses([]string{"localhost:8182"}).
WithStore(f.server.store).
WithManager(f.server.manager).
Init(context.Background())
Init(t.Context())
setup := []tr{
{http.MethodPost, "/query", `{"query": "a=data.k.x with data.k as {\"x\" : 7}"}`, 200, `{"result":[{"a":7}]}`},
@@ -4602,7 +4602,7 @@ func TestQueryV1(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
test.WithTempFS(nil, func(root string) {
disk, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir: root})
@@ -4877,7 +4877,7 @@ func TestQueryV1Explain(t *testing.T) {
func TestAuthorization(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
m, err := plugins.New([]byte{}, "test", store)
if err != nil {
@@ -4998,7 +4998,7 @@ func TestAuthorization(t *testing.T) {
func TestAuthorizationUsesInterQueryCache(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
m, err := plugins.New([]byte{}, "test", store)
if err != nil {
@@ -5139,7 +5139,7 @@ func TestServerReloadTrigger(t *testing.T) {
f := newFixture(t)
store := f.server.store
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
if err := store.UpsertPolicy(ctx, txn, "test", []byte("package test\np = 1")); err != nil {
panic(err)
@@ -5161,7 +5161,7 @@ func TestServerClearsCompilerConflictCheck(t *testing.T) {
f := newFixture(t)
store := f.server.store
ctx := context.Background()
ctx := t.Context()
// Make a new transaction
params := storage.WriteParams
@@ -5237,7 +5237,7 @@ func (queryBindingErrStore) Unregister(context.Context, storage.Transaction, str
func TestQueryBindingIterationError(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
mock := &queryBindingErrStore{}
m, err := plugins.New([]byte{}, "test", mock)
if err != nil {
@@ -5292,7 +5292,7 @@ type fixture struct {
}
func newFixture(t *testing.T, opts ...any) *fixture {
ctx := context.Background()
ctx := t.Context()
server := New().
WithAddresses([]string{"localhost:8182"}).
WithStore(inmem.New()) // potentially overridden via opts
@@ -5332,7 +5332,7 @@ func newFixture(t *testing.T, opts ...any) *fixture {
}
func newFixtureWithConfig(t *testing.T, config string, opts ...func(*Server)) *fixture {
ctx := context.Background()
ctx := t.Context()
server := New().
WithAddresses([]string{"localhost:8182"}).
WithStore(inmem.New()) // potentially overridden via opts
@@ -5362,7 +5362,7 @@ func newFixtureWithConfig(t *testing.T, config string, opts ...func(*Server)) *f
}
func newFixtureWithStore(t *testing.T, store storage.Store, opts ...any) *fixture {
ctx := context.Background()
ctx := t.Context()
var mOpts []func(*plugins.Manager)
for _, opt := range opts {
@@ -5607,7 +5607,7 @@ func TestShutdown(t *testing.T) {
}(loop)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), time.Duration(5)*time.Second)
defer cancel()
err = f.server.Shutdown(ctx)
if err != nil {
@@ -5632,7 +5632,7 @@ func TestShutdownError(t *testing.T) {
}
f.server.httpListeners = []httpListener{m}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), time.Duration(5)*time.Second)
defer cancel()
err := f.server.Shutdown(ctx)
if err == nil {
@@ -5663,7 +5663,7 @@ func TestShutdownMultipleErrors(t *testing.T) {
f.server.httpListeners = append(f.server.httpListeners, m)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), time.Duration(5)*time.Second)
defer cancel()
err := f.server.Shutdown(ctx)
if err == nil {
@@ -5961,7 +5961,7 @@ func TestDistributedTracingEnabled(t *testing.T) {
"type": "grpc"
}}`)
ctx := context.Background()
ctx := t.Context()
_, _, _, err := distributedtracing.Init(ctx, c, "foo")
if err != nil {
t.Fatalf("Unexpected error initializing gRPC trace exporter %v", err)
@@ -6003,7 +6003,7 @@ func TestDistributedTracingResourceAttributes(t *testing.T) {
attributes[semconv.ServiceInstanceIDKey],
attributes[semconv.DeploymentEnvironmentKey])
ctx := context.Background()
ctx := t.Context()
_, traceProvider, resource, err := distributedtracing.Init(ctx, c, "foo")
if err != nil {
t.Fatalf("Unexpected error initializing trace exporter %v", err)
@@ -6028,7 +6028,7 @@ func TestDistributedTracingResourceAttributes(t *testing.T) {
func TestCertPoolReloading(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
tempDir := t.TempDir()
@@ -6443,7 +6443,7 @@ func TestCertReloading(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
testCases := map[string]struct {
Server func(
+1 -1
View File
@@ -44,7 +44,7 @@ func ErrorAuto(w http.ResponseWriter, err error) {
// ErrorString writes a response with specified status, code, and message set to
// the err's string representation.
func ErrorString(w http.ResponseWriter, status int, code string, err error) {
Error(w, status, types.NewErrorV1(code, err.Error())) //nolint:govet
Error(w, status, types.NewErrorV1(code, "%s", err.Error()))
}
// Error writes a response with specified status and error response.
+1 -2
View File
@@ -5,7 +5,6 @@
package disk
import (
"context"
"errors"
"os"
"path/filepath"
@@ -105,7 +104,7 @@ storage:
func TestDataDirPrefix(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
tmpdir := t.TempDir()
d, err := New(ctx, logging.NewNoOpLogger(), nil, Options{
+11 -11
View File
@@ -108,7 +108,7 @@ func TestPolicies(t *testing.T) {
t.Parallel()
test.WithTempFS(map[string]string{}, func(dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: nil})
if err != nil {
t.Fatal(err)
@@ -185,7 +185,7 @@ func TestTruncateRelativeStoragePath(t *testing.T) {
}
func runTruncateTest(t *testing.T, dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: nil})
if err != nil {
t.Fatal(err)
@@ -312,7 +312,7 @@ func TestTruncateMultipleTxn(t *testing.T) {
t.Parallel()
test.WithTempFS(map[string]string{}, func(dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: nil, Badger: "memtablesize=4000;valuethreshold=600"})
if err != nil {
t.Fatal(err)
@@ -411,7 +411,7 @@ func TestDataPartitioningValidation(t *testing.T) {
test.WithTempFS(map[string]string{}, func(dir string) {
ctx := context.Background()
ctx := t.Context()
_, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: []storage.Path{
storage.MustParsePath("/foo/bar"),
@@ -593,7 +593,7 @@ func TestDataPartitioningValidation(t *testing.T) {
func TestDataPartitioningSystemPartitions(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
dir := "unused"
for _, part := range []string{
@@ -1152,7 +1152,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) {
partitions[i] = storage.MustParsePath(tc.partitions[i])
}
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: partitions})
if err != nil {
t.Fatal(err)
@@ -1308,7 +1308,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) {
partitions[i] = storage.MustParsePath(tc.partitions[i])
}
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: partitions})
if err != nil {
t.Fatal(err)
@@ -1464,7 +1464,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) {
partitions[i] = storage.MustParsePath(tc.partitions[i])
}
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: partitions})
if err != nil {
@@ -1506,7 +1506,7 @@ func TestDataPartitioningWriteInvalidPatchError(t *testing.T) {
t.Parallel()
test.WithTempFS(map[string]string{}, func(dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: []storage.Path{
storage.MustParsePath("/foo"),
}})
@@ -1562,7 +1562,7 @@ func TestDiskTriggers(t *testing.T) {
t.Parallel()
test.WithTempFS(map[string]string{}, func(dir string) {
ctx := context.Background()
ctx := t.Context()
store, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: []storage.Path{
storage.MustParsePath("/foo"),
}})
@@ -1702,7 +1702,7 @@ func TestLookup(t *testing.T) {
func TestDiskDiagnostics(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
t.Run("no partitions", func(t *testing.T) {
t.Parallel()
+2 -3
View File
@@ -5,7 +5,6 @@
package disk
import (
"context"
"errors"
"fmt"
"math/rand"
@@ -39,7 +38,7 @@ func TestSetTxnIsTooBigToFitIntoOneRequestWhenUseDiskStoreReturnsError(t *testin
t.Parallel()
test.WithTempFS(nil, func(dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: []storage.Path{
storage.MustParsePath("/foo"),
}})
@@ -81,7 +80,7 @@ func TestDeleteTxnIsTooBigToFitIntoOneRequestWhenUseDiskStore(t *testing.T) {
t.Parallel()
test.WithTempFS(nil, func(dir string) {
ctx := context.Background()
ctx := t.Context()
s, err := New(ctx, logging.NewNoOpLogger(), nil, Options{Dir: dir, Partitions: []storage.Path{
storage.MustParsePath("/foo"),
}})
+20 -20
View File
@@ -49,7 +49,7 @@ func TestInMemoryRead(t *testing.T) {
}
store := NewFromObject(data)
ctx := context.Background()
ctx := t.Context()
for idx, tc := range tests {
result, err := storage.ReadOne(ctx, store, storage.MustParsePath(tc.path))
@@ -99,7 +99,7 @@ func TestInMemoryReadAst(t *testing.T) {
}
store := NewFromObjectWithOpts(data, OptReturnASTValuesOnRead(true))
ctx := context.Background()
ctx := t.Context()
for idx, tc := range tests {
result, err := storage.ReadOne(ctx, store, storage.MustParsePath(tc.path))
@@ -188,7 +188,7 @@ func TestInMemoryWrite(t *testing.T) {
{"err: replace missing", "replace", "/dead/beef/1", "1", storageerrors.NewNotFoundError(storage.MustParsePath("/dead/beef/1")), "", nil},
}
ctx := context.Background()
ctx := t.Context()
for i, tc := range tests {
data := loadSmallTestData()
@@ -292,7 +292,7 @@ func TestInMemoryWriteOfStruct(t *testing.T) {
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
store := New()
ctx := context.Background()
ctx := t.Context()
err := storage.WriteOne(ctx, store, storage.AddOp, storage.MustParsePath("/x"), tc.value)
if err != nil {
@@ -337,7 +337,7 @@ func TestInMemoryWriteOfStructAst(t *testing.T) {
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
store := NewWithOpts(OptReturnASTValuesOnRead(true))
ctx := context.Background()
ctx := t.Context()
// Written non-AST values are expected to be converted to AST values
err := storage.WriteOne(ctx, store, storage.AddOp, storage.MustParsePath("/x"), tc.value)
@@ -361,7 +361,7 @@ func TestInMemoryWriteOfStructAst(t *testing.T) {
func TestInMemoryTxnMultipleWrites(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObject(loadSmallTestData())
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -443,7 +443,7 @@ func TestInMemoryTxnMultipleWrites(t *testing.T) {
func TestInMemoryTxnMultipleWritesAst(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(loadSmallTestData(), OptReturnASTValuesOnRead(true))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -534,7 +534,7 @@ func TestTruncateNoExistingPath(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -601,7 +601,7 @@ func TestTruncateNoExistingPath(t *testing.T) {
}
func TestTruncate(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObject(map[string]any{})
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -699,7 +699,7 @@ func TestTruncate(t *testing.T) {
}
func TestTruncateAst(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(true))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -807,7 +807,7 @@ func TestTruncateDataMergeError(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -853,7 +853,7 @@ func TestTruncateBadRootWrite(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -900,7 +900,7 @@ func TestInMemoryTxnWriteFailures(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(loadSmallTestData(), OptReturnASTValuesOnRead(tc.ast))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -945,7 +945,7 @@ func TestInMemoryTxnReadFailures(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(loadSmallTestData(), OptReturnASTValuesOnRead(tc.ast))
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -969,7 +969,7 @@ func TestInMemoryTxnReadFailures(t *testing.T) {
}
func TestInMemoryTxnBadWrite(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObject(loadSmallTestData())
txn := storage.NewTransactionOrDie(ctx, store)
if err := store.Write(ctx, txn, storage.RemoveOp, storage.MustParsePath("/a"), nil); !storage.IsInvalidTransaction(err) {
@@ -979,7 +979,7 @@ func TestInMemoryTxnBadWrite(t *testing.T) {
func TestInMemoryTxnPolicies(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := New()
txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
@@ -1082,7 +1082,7 @@ func TestInMemoryTriggers(t *testing.T) {
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObjectWithOpts(loadSmallTestData(), OptReturnASTValuesOnRead(tc.ast))
writeTxn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
readTxn := storage.NewTransactionOrDie(ctx, store)
@@ -1151,7 +1151,7 @@ func TestInMemoryTriggers(t *testing.T) {
}
func TestInMemoryTriggersUnregister(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := NewFromObject(loadSmallTestData())
writeTxn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams)
modifiedPath := storage.MustParsePath("/a")
@@ -1201,7 +1201,7 @@ func TestInMemoryTriggersUnregister(t *testing.T) {
func TestInMemoryContext(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
store := New()
params := storage.WriteParams
params.Context = storage.NewContext()
@@ -1334,7 +1334,7 @@ func TestOptRoundTripOnWrite(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db := NewWithOpts(tt.opts...)
ctx := context.Background()
ctx := t.Context()
txn, err := db.NewTransaction(ctx, storage.WriteParams)
if err != nil {
+2 -2
View File
@@ -49,7 +49,7 @@ func TestNonEmpty(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
for _, tc := range cases {
t.Run(tc.content, func(t *testing.T) {
@@ -83,7 +83,7 @@ func (*nonEmpty) NonEmpty(context.Context, storage.Transaction) func([]string) (
}
func TestNonEmptyer(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
ne := &nonEmpty{inmem.New()}
for _, path := range []string{"a", "a/b/c"} {
+1 -2
View File
@@ -5,7 +5,6 @@
package authz
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/ast"
@@ -51,7 +50,7 @@ func runAuthzBenchmark(b *testing.B, mode InputMode, numPaths int, extras ...boo
NumPaths: numPaths,
}
ctx := context.Background()
ctx := b.Context()
data := GenerateDataset(profile)
useDisk := len(extras) > 0 && extras[0]
+1 -2
View File
@@ -5,7 +5,6 @@
package authz
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/ast"
@@ -21,7 +20,7 @@ func TestAuthz(t *testing.T) {
NumPaths: 10,
}
ctx := context.Background()
ctx := t.Context()
data := GenerateDataset(profile)
store := inmem.NewFromObject(data)
txn := storage.NewTransactionOrDie(ctx, store)
@@ -5,7 +5,6 @@
package distributedtracing
import (
"context"
"encoding/json"
"flag"
"fmt"
@@ -816,7 +815,7 @@ func TestControlPlaneSpans(t *testing.T) {
}
defer mr.Body.Close()
_ = logs.Lookup(rt.Runtime.Manager).Trigger(context.Background())
_ = logs.Lookup(rt.Runtime.Manager).Trigger(t.Context())
spans = spanExp.GetSpans()
// Expect 2 spans:
+1 -1
View File
@@ -35,7 +35,7 @@ type benchmarkParams struct {
}
func runSchedulerBenchmark(b *testing.B, nodes int, pods int) {
ctx := context.Background()
ctx := b.Context()
params := setupBenchmark(nodes, pods)
b.ResetTimer()
for range b.N {
+1 -1
View File
@@ -20,7 +20,7 @@ import (
)
func TestScheduler(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
rego := setup(ctx, t, "data_10nodes_30pods.json")
rs, err := rego.Eval(ctx)
+8 -8
View File
@@ -168,7 +168,7 @@ func testRun(t *testing.T, conf testRunConfig) map[string]*ast.Module {
func doTestRunWithTmpDir(t *testing.T, dir string, conf testRunConfig) ([]*tester.Result, map[string]*ast.Module) {
t.Helper()
ctx := context.Background()
ctx := t.Context()
paths := []string{dir}
modules, store, err := tester.Load(paths, nil)
@@ -453,7 +453,7 @@ func testCancel(t *testing.T, bench bool) {
registerSleepBuiltin()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
module := `package foo
import rego.v1
@@ -510,7 +510,7 @@ func TestRunnerTimeoutBenchmark(t *testing.T) {
func testTimeout(t *testing.T, bench bool) {
registerSleepBuiltin()
ctx := context.Background()
ctx := t.Context()
files := map[string]string{
"/a_test.rego": `package foo
@@ -589,7 +589,7 @@ func TestRunnerPrintOutput(t *testing.T) {
p.q.r.test_k if { print("K") }`,
}
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(files, func(d string) {
paths := []string{d}
@@ -711,7 +711,7 @@ func TestRunnerWithCustomBuiltin(t *testing.T) {
test_c if { my_sum(4,1.0) == 5 }`,
}
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(files, func(d string) {
paths := []string{d}
@@ -782,7 +782,7 @@ func TestRunnerWithBuiltinErrors(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
@@ -940,7 +940,7 @@ func TestRun_DefaultRegoVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
modules := map[string]*ast.Module{
"test": &tc.module,
@@ -1062,7 +1062,7 @@ func TestReporterFormatsWithExplicitParallel(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
test.WithTempFS(files, func(d string) {
paths := []string{d}
+1 -2
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/ast"
@@ -32,7 +31,7 @@ func TestCustomBuiltinIterator(t *testing.T) {
},
})
ctx := context.Background()
ctx := t.Context()
rs, err := query.Run(ctx)
if err != nil {
+12 -12
View File
@@ -105,7 +105,7 @@ func TestInterValueCache_DefaultConfiguration(t *testing.T) {
InterQueryBuiltinValueCache: InterQueryBuiltinValueCacheConfig{},
}
c := NewInterQueryValueCache(context.Background(), &config)
c := NewInterQueryValueCache(t.Context(), &config)
if c.GetCache("foo") != nil {
t.Fatal("Expected cache to be disabled")
}
@@ -120,7 +120,7 @@ func TestInterValueCache_DefaultConfiguration(t *testing.T) {
MaxNumEntries: &[]int{5}[0],
})
c := NewInterQueryValueCache(context.Background(), &config)
c := NewInterQueryValueCache(t.Context(), &config)
if act := *c.GetCache("bar").(*interQueryValueCacheBucket).config.MaxNumEntries; act != 5 {
t.Fatalf("Expected 5 max entries, got %d", act)
}
@@ -137,7 +137,7 @@ func TestInterValueCache_DefaultConfiguration(t *testing.T) {
RegisterDefaultInterQueryBuiltinValueCacheConfig("baz", nil)
c := NewInterQueryValueCache(context.Background(), &cacheConfig)
c := NewInterQueryValueCache(t.Context(), &cacheConfig)
if c.GetCache("baz") != nil {
t.Fatal("Expected cache to be disabled")
}
@@ -158,7 +158,7 @@ func TestInterValueCache_DefaultConfiguration(t *testing.T) {
MaxNumEntries: &[]int{10}[0],
})
c := NewInterQueryValueCache(context.Background(), &cacheConfig)
c := NewInterQueryValueCache(t.Context(), &cacheConfig)
if act := *c.GetCache("box").(*interQueryValueCacheBucket).config.MaxNumEntries; act != 5 {
t.Fatalf("Expected 5 max entries, got %d", act)
}
@@ -179,7 +179,7 @@ func TestInterValueCache_NamedCaches(t *testing.T) {
},
}
c := NewInterQueryValueCache(context.Background(), &config)
c := NewInterQueryValueCache(t.Context(), &config)
nc := c.GetCache("foo").(*interQueryValueCacheBucket)
if act := *nc.config.MaxNumEntries; act != 2 {
@@ -230,7 +230,7 @@ func TestInterValueCache_NamedCaches(t *testing.T) {
},
}
c := NewInterQueryValueCache(context.Background(), &config)
c := NewInterQueryValueCache(t.Context(), &config)
c.Insert(ast.StringTerm("foo").Value, "bar")
@@ -371,7 +371,7 @@ func TestInterQueryValueCache(t *testing.T) {
t.Fatalf("Unexpected error %v", err)
}
cache := NewInterQueryValueCache(context.Background(), config)
cache := NewInterQueryValueCache(t.Context(), config)
cache.Insert(ast.StringTerm("foo").Value, "bar")
cache.Insert(ast.StringTerm("foo2").Value, "bar2")
@@ -590,7 +590,7 @@ func TestInsertWithExpiryAndEviction(t *testing.T) {
}
// This starts a background ticker at stale_entry_eviction_period_seconds to clean up items.
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cache := NewInterQueryCacheWithContext(ctx, config)
t.Cleanup(cancel)
@@ -639,7 +639,7 @@ func TestInsertHighTTLWithStaleEntryCleanup(t *testing.T) {
}
// This starts a background ticker at stale_entry_eviction_period_seconds to clean up items.
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cache := NewInterQueryCacheWithContext(ctx, config)
t.Cleanup(cancel)
@@ -685,7 +685,7 @@ func TestInsertHighTTLWithoutStaleEntryCleanup(t *testing.T) {
}
// This starts a background ticker at stale_entry_eviction_period_seconds to clean up items.
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cache := NewInterQueryCacheWithContext(ctx, config)
t.Cleanup(cancel)
@@ -728,7 +728,7 @@ func TestZeroExpiryTime(t *testing.T) {
}
// This starts a background ticker at stale_entry_eviction_period_seconds to clean up items.
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cache := NewInterQueryCacheWithContext(ctx, config)
t.Cleanup(cancel)
cacheValue := newInterQueryCacheValue(ast.StringTerm("bar").Value, 20)
@@ -758,7 +758,7 @@ func TestCancelNewInterQueryCacheWithContext(t *testing.T) {
t.Fatalf("Unexpected error %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cache := NewInterQueryCacheWithContext(ctx, config)
cacheValue := newInterQueryCacheValue(ast.StringTerm("bar").Value, 20)
cache.InsertWithExpiry(ast.StringTerm("foo").Value, cacheValue, time.Now().Add(100*time.Millisecond))
+1 -2
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"testing"
"time"
@@ -13,7 +12,7 @@ import (
func TestNetCIDRExpandCancellation(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{
`
+3 -3
View File
@@ -269,7 +269,7 @@ func TestContainsNestedRefOrCall(t *testing.T) {
func TestTopdownVirtualCache(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
tests := []struct {
@@ -724,7 +724,7 @@ func TestTopdownVirtualCache(t *testing.T) {
func TestPartialRule(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
tests := []struct {
@@ -1593,7 +1593,7 @@ func (*deadlineCtx) Done() <-chan struct{} {
func TestContextErrorHandling(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
tests := []struct {
+1 -2
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"os"
"sort"
@@ -81,7 +80,7 @@ func testRun(t *testing.T, tc cases.TestCase, regoVersion ast.RegoVersion, opts
t.Setenv(k, v)
}
ctx := context.Background()
ctx := t.Context()
modules := map[string]string{}
for i, module := range tc.Modules {
+2 -3
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
@@ -79,7 +78,7 @@ func TestGlobBuiltinInterQueryValueCache(t *testing.T) {
ip := []byte(`{"inter_query_builtin_value_cache": {"max_num_entries": "10"},}`)
config, _ := cache.ParseCachingConfig(ip)
interQueryValueCache := cache.NewInterQueryValueCache(context.Background(), config)
interQueryValueCache := cache.NewInterQueryValueCache(t.Context(), config)
ctx := BuiltinContext{InterQueryBuiltinValueCache: interQueryValueCache}
iter := func(*ast.Term) error { return nil }
@@ -136,7 +135,7 @@ func TestGlobBuiltinInterQueryValueCacheTypeMismatch(t *testing.T) {
ip := []byte(`{"inter_query_builtin_value_cache": {"max_num_entries": "10"},}`)
config, _ := cache.ParseCachingConfig(ip)
interQueryValueCache := cache.NewInterQueryValueCache(context.Background(), config)
interQueryValueCache := cache.NewInterQueryValueCache(t.Context(), config)
ctx := BuiltinContext{InterQueryBuiltinValueCache: interQueryValueCache}
iter := func(*ast.Term) error { return nil }
+7 -8
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"errors"
"fmt"
"os"
@@ -96,7 +95,7 @@ func TestGraphQLParseString(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -201,7 +200,7 @@ func TestGraphQLParseObject(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -316,7 +315,7 @@ func TestGraphQLSchemaIsValid(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -458,7 +457,7 @@ func TestGraphQLParseAndVerify(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -581,7 +580,7 @@ func TestGraphQLIsValid(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -681,7 +680,7 @@ func TestGraphQLParseQuery(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
@@ -781,7 +780,7 @@ func TestGraphQLParseSchema(t *testing.T) {
}
valueCache := cache.NewInterQueryValueCache(
context.Background(),
t.Context(),
&cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
NamedCacheConfigs: map[string]*cache.NamedValueCacheConfig{
+23 -23
View File
@@ -1268,7 +1268,7 @@ func TestHTTPSendIntraQueryCaching(t *testing.T) {
defer ts.Close()
config, _ := iCache.ParseCachingConfig([]byte(`{"inter_query_builtin_cache": {"max_size_bytes": 500, "stale_entry_eviction_period_seconds": 1, "forced_eviction_threshold_percentage": 80},}`))
interQueryCache := iCache.NewInterQueryCacheWithContext(context.Background(), config)
interQueryCache := iCache.NewInterQueryCacheWithContext(t.Context(), config)
opts := []func(*Query) *Query{
setTime(t0),
@@ -1429,7 +1429,7 @@ func TestHTTPSendInterQueryCaching(t *testing.T) {
q := newQuery(qStr, t0)
for i := range 3 {
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1588,7 +1588,7 @@ func TestHTTPSendInterQueryForceCaching(t *testing.T) {
q := newQuery(qStr, t0)
for i := range 3 {
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1684,7 +1684,7 @@ func TestHTTPSendInterQueryForceCachingRefresh(t *testing.T) {
request = strings.ReplaceAll(request, "%CACHE%", strconv.Itoa(cacheTime))
full := fmt.Sprintf("http.send(%s, x)", request)
config, _ := iCache.ParseCachingConfig([]byte(`{"inter_query_builtin_cache": {"max_size_bytes": 500, "stale_entry_eviction_period_seconds": 1, "forced_eviction_threshold_percentage": 80},}`))
interQueryCache := iCache.NewInterQueryCacheWithContext(context.Background(), config)
interQueryCache := iCache.NewInterQueryCacheWithContext(t.Context(), config)
q := NewQuery(ast.MustParseBody(full)).
WithInterQueryBuiltinCache(interQueryCache).
WithTime(t0)
@@ -1694,7 +1694,7 @@ func TestHTTPSendInterQueryForceCachingRefresh(t *testing.T) {
expired cache
*/
for i := range 2 {
resp, err := q.Run(context.Background())
resp, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1826,7 +1826,7 @@ func TestHTTPSendInterQueryCachingModifiedResp(t *testing.T) {
q := newQuery(qStr, t0)
for i := range 3 {
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1901,7 +1901,7 @@ func TestHTTPSendInterQueryCachingNewResp(t *testing.T) {
q := newQuery(qStr, t0)
for i := range 3 {
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -1987,7 +1987,7 @@ func TestInsertIntoHTTPSendInterQueryCacheError(t *testing.T) {
q := newQuery(qStr, t0)
for i := range 3 {
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -2298,7 +2298,7 @@ func TestInterQueryCheckCacheError(t *testing.T) {
input := ast.MustParseTerm(`{"force_cache": true}`)
inputObj := input.Value.(ast.Object)
_, err := newHTTPRequestExecutor(BuiltinContext{Context: context.Background()}, inputObj, inputObj)
_, err := newHTTPRequestExecutor(BuiltinContext{Context: t.Context()}, inputObj, inputObj)
if err == nil {
t.Fatal("expected error but got nil")
}
@@ -2943,7 +2943,7 @@ func TestCertSelectionLogic(t *testing.T) {
t.Setenv("CLIENT_CA_ENV", string(caCertPEM))
getClientTLSConfig := func(obj ast.Object) *tls.Config {
_, client, err := createHTTPRequest(BuiltinContext{Context: context.Background()}, obj)
_, client, err := createHTTPRequest(BuiltinContext{Context: t.Context()}, obj)
if err != nil {
t.Fatalf("Unexpected error creating HTTP request %v", err)
}
@@ -3080,7 +3080,7 @@ func TestHTTPSendCacheDefaultStatusCodesIntraQueryCache(t *testing.T) {
// out to the server again and getting a http.StatusOK response status code.
// The third request should now be served from the cache.
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3114,7 +3114,7 @@ func TestHTTPSendCacheDefaultStatusCodesInterQueryCache(t *testing.T) {
// add an inter-query cache
config, _ := iCache.ParseCachingConfig([]byte(`{"inter_query_builtin_cache": {"max_size_bytes": 500, "stale_entry_eviction_period_seconds": 1, "forced_eviction_threshold_percentage": 80},}`))
interQueryCache := iCache.NewInterQueryCacheWithContext(context.Background(), config)
interQueryCache := iCache.NewInterQueryCacheWithContext(t.Context(), config)
m := metrics.New()
@@ -3127,17 +3127,17 @@ func TestHTTPSendCacheDefaultStatusCodesInterQueryCache(t *testing.T) {
// out to the server again and getting a http.StatusOK response status code.
// The third request should now be served from the cache.
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
_, err = q.Run(context.Background())
_, err = q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
_, err = q.Run(context.Background())
_, err = q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3212,7 +3212,7 @@ func TestInterQueryCacheConcurrentModification(t *testing.T) {
}
qStr := "x = data.test.p; y = data.test.q"
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store)
q := NewQuery(ast.MustParseBody(qStr)).
@@ -3222,7 +3222,7 @@ func TestInterQueryCacheConcurrentModification(t *testing.T) {
WithInterQueryBuiltinCache(&interQueryCache).
WithTime(clock)
res, err := q.Run(context.Background())
res, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3394,7 +3394,7 @@ func TestHTTPSendMetrics(t *testing.T) {
// Execute query and verify http.send latency shows up in metrics registry.
m := metrics.New()
q := NewQuery(ast.MustParseBody(fmt.Sprintf(`http.send({"method": "get", "url": %q})`, ts.URL))).WithMetrics(m)
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3407,19 +3407,19 @@ func TestHTTPSendMetrics(t *testing.T) {
t.Run("cache hits", func(t *testing.T) {
// add an inter-query cache
config, _ := iCache.ParseCachingConfig([]byte(`{"inter_query_builtin_cache": {"max_size_bytes": 500, "stale_entry_eviction_period_seconds": 1, "forced_eviction_threshold_percentage": 80},}`))
interQueryCache := iCache.NewInterQueryCacheWithContext(context.Background(), config)
interQueryCache := iCache.NewInterQueryCacheWithContext(t.Context(), config)
// Execute query twice and verify http.send inter-query cache hit metric is incremented.
m := metrics.New()
q := NewQuery(ast.MustParseBody(fmt.Sprintf(`http.send({"method": "get", "url": %q, "cache": true})`, ts.URL))).
WithInterQueryBuiltinCache(interQueryCache).
WithMetrics(m)
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
// cache hit
_, err = q.Run(context.Background())
_, err = q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -3552,7 +3552,7 @@ func TestDistributedTracingEnableDisable(t *testing.T) {
tracing.RegisterHTTPTracing(&mock)
builtinContext := BuiltinContext{
Context: context.Background(),
Context: t.Context(),
DistributedTracingOpts: tracing.NewOptions(true), // any option means it's enabled
}
@@ -3574,7 +3574,7 @@ func TestDistributedTracingEnableDisable(t *testing.T) {
tracing.RegisterHTTPTracing(&mock)
builtinContext := BuiltinContext{
Context: context.Background(),
Context: t.Context(),
}
_, client, err := createHTTPRequest(builtinContext, ast.NewObject())
+7 -7
View File
@@ -18,7 +18,7 @@ import (
)
func BenchmarkJSONPatchAddShallowScalar(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -83,7 +83,7 @@ func BenchmarkJSONPatchAddShallowScalar(b *testing.B) {
}
func BenchmarkJSONPatchAddShallowComposite(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -148,7 +148,7 @@ func BenchmarkJSONPatchAddShallowComposite(b *testing.B) {
}
func BenchmarkJSONPatchAddRemove(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -308,7 +308,7 @@ func genRandom3LayerObjectJSONPatchListData(l1Keys, l2Keys, l3Keys, p int) ast.V
}
func BenchmarkJSONPatchReplace(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000}
@@ -372,7 +372,7 @@ func BenchmarkJSONPatchReplace(b *testing.B) {
}
func BenchmarkJSONPatchPathologicalNestedAddChainObject(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 500, 1000, 5000, 10000}
// Pre-generate the test datasets/patches.
@@ -403,7 +403,7 @@ func BenchmarkJSONPatchPathologicalNestedAddChainObject(b *testing.B) {
}
func BenchmarkJSONPatchPathologicalNestedAddChainArray(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 500, 1000, 5000, 10000}
// Pre-generate the test datasets/patches.
@@ -436,7 +436,7 @@ func BenchmarkJSONPatchPathologicalNestedAddChainArray(b *testing.B) {
// This one is tricky, because sets used content-based addressing.
// That means our sets for the path have to be recursively constructed!
func BenchmarkJSONPatchPathologicalNestedAddChainSet(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 500, 1000}
// Pre-generate the test datasets/patches.
+1 -2
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/topdown/cache"
@@ -303,7 +302,7 @@ func TestBuiltinJSONMatchSchemaCache(t *testing.T) {
}
`)
valueCache := cache.NewInterQueryValueCache(context.Background(), nil)
valueCache := cache.NewInterQueryValueCache(t.Context(), nil)
document := ast.String(`{ "id": 5 }`)
var result ast.Value
+1 -2
View File
@@ -6,7 +6,6 @@ package lineage
import (
"bytes"
"context"
"strings"
"testing"
@@ -181,7 +180,7 @@ Enter data.test.p = x
"test.rego": tc.module,
})
query := topdown.NewQuery(ast.MustParseBody("data.test.p = x")).WithCompiler(compiler).WithTracer(buf)
rs, err := query.Run(context.TODO())
rs, err := query.Run(t.Context())
if err != nil {
t.Fatal(err)
} else if len(rs) != 1 || !rs[0][ast.Var("x")].Equal(ast.BooleanTerm(true)) {
+6 -6
View File
@@ -59,7 +59,7 @@ func TestNetLookupIPAddr(t *testing.T) {
"v4-v6.org": ast.NewSet(ast.StringTerm("1.2.3.4"), ast.StringTerm("1:2:3::4")),
} {
t.Run(addr, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
bctx := BuiltinContext{
Context: ctx,
@@ -101,7 +101,7 @@ func TestNetLookupIPAddr(t *testing.T) {
for _, addr := range []string{"error.org", "nosuch.org"} {
t.Run(addr, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
bctx := BuiltinContext{
Context: ctx,
@@ -122,12 +122,12 @@ func TestNetLookupIPAddr(t *testing.T) {
}
cancelled := func() (context.Context, func()) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
cancel()
return ctx, cancel
}
timedOut := func() (context.Context, func()) {
return context.WithTimeout(context.Background(), time.Nanosecond)
return context.WithTimeout(t.Context(), time.Nanosecond)
}
for name, ctx := range map[string]func() (context.Context, func()){
@@ -167,7 +167,7 @@ func TestNetLookupIPAddr(t *testing.T) {
"allow_net match + additional host": {addr, "example.com"},
} {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
capabilities := ast.CapabilitiesForThisVersion()
capabilities.AllowNet = allowNet
@@ -195,7 +195,7 @@ func TestNetLookupIPAddr(t *testing.T) {
"allow_net no match": {"example.com"},
} {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
capabilities := ast.CapabilitiesForThisVersion()
capabilities.AllowNet = allowNet
+4 -5
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"math/rand"
"testing"
@@ -11,7 +10,7 @@ import (
func TestRandIntnZero(t *testing.T) {
t.Parallel()
qrs, err := NewQuery(ast.MustParseBody(`rand.intn("x", 0, out)`)).Run(context.Background())
qrs, err := NewQuery(ast.MustParseBody(`rand.intn("x", 0, out)`)).Run(t.Context())
if err != nil {
t.Fatal(err)
} else if len(qrs) != 1 {
@@ -30,7 +29,7 @@ func TestRandIntnZero(t *testing.T) {
func TestRandIntnNegative(t *testing.T) {
t.Parallel()
qrs, err := NewQuery(ast.MustParseBody(`rand.intn("x", -100, out)`)).Run(context.Background())
qrs, err := NewQuery(ast.MustParseBody(`rand.intn("x", -100, out)`)).Run(t.Context())
if err != nil {
t.Fatal(err)
} else if len(qrs) != 1 {
@@ -54,7 +53,7 @@ func TestRandIntnSeedingAndCaching(t *testing.T) {
q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(ast.NewCompiler())
ctx := context.Background()
ctx := t.Context()
qrs, err := q.Run(ctx)
if err != nil {
@@ -92,7 +91,7 @@ func TestRandIntnSavingDuringPartialEval(t *testing.T) {
q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(c)
queries, modules, err := q.PartialRun(context.Background())
queries, modules, err := q.PartialRun(t.Context())
if err != nil {
t.Fatal(err)
} else if len(modules) > 0 {
+2 -3
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
@@ -27,7 +26,7 @@ func genNxMObjectBenchmarkData(n, m int) ast.Value {
}
func BenchmarkObjectUnionN(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 250}
@@ -70,7 +69,7 @@ func BenchmarkObjectUnionNSlow(b *testing.B) {
// This benchmarks the suggested means to implement union
// without using the builtin, to give us an idea of whether or not
// the builtin is actually making things any faster.
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 250}
+5 -6
View File
@@ -2,7 +2,6 @@ package topdown
import (
"bytes"
"context"
"errors"
"strings"
"testing"
@@ -122,7 +121,7 @@ func TestTopDownPrint(t *testing.T) {
WithPrintHook(NewPrintHook(buf)).
WithCompiler(c)
qrs, err := q.Run(context.Background())
qrs, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -147,7 +146,7 @@ func TestTopDownPrintInternalError(t *testing.T) {
q := NewQuery(ast.MustParseBody("internal.print([1])")).WithPrintHook(NewPrintHook(buf))
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err == nil {
t.Fatal("expected error")
}
@@ -169,7 +168,7 @@ func TestTopDownPrintHookNotSupplied(t *testing.T) {
// in set comprehensions to avoid short-circuiting on undefined.
q := NewQuery(ast.MustParseBody(`x = 1; internal.print({1})`))
qrs, err := q.Run(context.Background())
qrs, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
}
@@ -193,7 +192,7 @@ func TestTopDownPrintWithStrictBuiltinErrors(t *testing.T) {
WithStrictBuiltinErrors(true).
WithCompiler(ast.NewCompiler())
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err == nil {
t.Fatal("expected error")
}
@@ -228,7 +227,7 @@ func TestTopDownPrintHookErrorPropagation(t *testing.T) {
WithStrictBuiltinErrors(true).
WithCompiler(ast.NewCompiler())
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err == nil {
t.Fatal("expected error")
} else if !strings.Contains(err.Error(), "print hook error") {
+7 -7
View File
@@ -85,7 +85,7 @@ func TestQueryTracerDontPlugLocalVars(t *testing.T) {
query = query.WithQueryTracer(tt)
}
_, err := query.Run(context.Background())
_, err := query.Run(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -122,7 +122,7 @@ func TestLegacyTracerUpgrade(t *testing.T) {
// If the deprecated Trace() API is called the test will fail.
query.WithTracer(tracer)
_, err := query.Run(context.Background())
_, err := query.Run(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -145,7 +145,7 @@ func TestLegacyTracerBackwardsCompatibility(t *testing.T) {
bt := NewBufferTracer()
query.WithQueryTracer(bt)
_, err := query.Run(context.Background())
_, err := query.Run(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -175,7 +175,7 @@ func TestDisabledTracer(t *testing.T) {
query.WithTracer(tracer)
query.WithQueryTracer(tracer)
_, err := query.Run(context.Background())
_, err := query.Run(t.Context())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -212,7 +212,7 @@ func TestRegoMetadataBuiltinCall(t *testing.T) {
c := ast.NewCompiler()
q := NewQuery(ast.MustParseBody(tc.query)).WithCompiler(c).
WithStrictBuiltinErrors(true)
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err == nil {
t.Fatalf("expected error")
@@ -229,7 +229,7 @@ func TestWithCompilerErrors(t *testing.T) {
t.Parallel()
store := inmem.New()
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)
@@ -246,7 +246,7 @@ p := data.q(42)`),
WithStore(store).
WithTransaction(txn)
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if err == nil {
t.Fatalf("expected error, got nil")
}
+2 -3
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
@@ -75,7 +74,7 @@ func TestRegexBuiltinInterQueryValueCache(t *testing.T) {
ip := []byte(`{"inter_query_builtin_value_cache": {"max_num_entries": "10"},}`)
config, _ := cache.ParseCachingConfig(ip)
interQueryValueCache := cache.NewInterQueryValueCache(context.Background(), config)
interQueryValueCache := cache.NewInterQueryValueCache(t.Context(), config)
ctx := BuiltinContext{InterQueryBuiltinValueCache: interQueryValueCache}
iter := func(*ast.Term) error { return nil }
@@ -128,7 +127,7 @@ func TestRegexBuiltinInterQueryValueCacheTypeMismatch(t *testing.T) {
ip := []byte(`{"inter_query_builtin_value_cache": {"max_num_entries": "10"},}`)
config, _ := cache.ParseCachingConfig(ip)
interQueryValueCache := cache.NewInterQueryValueCache(context.Background(), config)
interQueryValueCache := cache.NewInterQueryValueCache(t.Context(), config)
ctx := BuiltinContext{InterQueryBuiltinValueCache: interQueryValueCache}
iter := func(*ast.Term) error { return nil }
+2 -3
View File
@@ -4,7 +4,6 @@
package topdown
import (
"context"
"testing"
"github.com/open-policy-agent/opa/v1/ast"
@@ -13,7 +12,7 @@ import (
func TestOPARuntime(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
q := NewQuery(ast.MustParseBody("opa.runtime(x)")) // no runtime info
rs, err := q.Run(ctx)
if err != nil {
@@ -49,7 +48,7 @@ func TestOPARuntime(t *testing.T) {
func TestOPARuntimeConfigMasking(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
q := NewQuery(ast.MustParseBody("opa.runtime(x)")).WithRuntime(ast.MustParseTerm(`{"config": {
"labels": {"foo": "bar"},
"services": {
+4 -5
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
@@ -27,7 +26,7 @@ func genNxMSetBenchmarkData(n, m int) ast.Value {
}
func BenchmarkSetIntersection(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000}
@@ -68,7 +67,7 @@ func BenchmarkSetIntersection(b *testing.B) {
}
func BenchmarkSetIntersectionSlow(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 50, 100}
@@ -114,7 +113,7 @@ func BenchmarkSetIntersectionSlow(b *testing.B) {
}
func BenchmarkSetUnion(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 250}
@@ -161,7 +160,7 @@ func BenchmarkSetUnionSlow(b *testing.B) {
// This benchmarks the suggested means to implement union
// without using the builtin, to give us an idea of whether or not
// the builtin is actually making things any faster.
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 250}
+2 -3
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"fmt"
"strings"
"testing"
@@ -13,7 +12,7 @@ import (
func BenchmarkBulkStartsWithNaive(b *testing.B) {
data := generateBulkStartsWithInput()
ctx := context.Background()
ctx := b.Context()
store := inmem.NewFromObject(data)
compiler := ast.MustCompileModules(map[string]string{
@@ -52,7 +51,7 @@ result if {
func BenchmarkBulkStartsWithOptimized(b *testing.B) {
data := generateBulkStartsWithInput()
ctx := context.Background()
ctx := b.Context()
store := inmem.NewFromObject(data)
compiler := ast.MustCompileModules(map[string]string{
+1 -2
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
"time"
@@ -20,7 +19,7 @@ func TestTimeSeeding(t *testing.T) {
clock := time.Now()
q := NewQuery(ast.MustParseBody(query)).WithTime(clock).WithCompiler(ast.NewCompiler())
ctx := context.Background()
ctx := t.Context()
qrs, err := q.Run(ctx)
if err != nil {
+2 -3
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"fmt"
"testing"
"time"
@@ -35,7 +34,7 @@ const publicKey = `{
const keys = `{"keys": [` + publicKey + `]}`
func BenchmarkTokens(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
iter := func(*ast.Term) error { return nil }
bctx := BuiltinContext{
@@ -94,7 +93,7 @@ func BenchmarkTokens(b *testing.B) {
}
func BenchmarkTokens_Cache(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
iter := func(*ast.Term) error { return nil }
bctx := BuiltinContext{
+6 -7
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
@@ -267,7 +266,7 @@ func TestTopDownJWTEncodeSignES256(t *testing.T) {
path := []string{"generated", "p"}
var inputTerm *ast.Term
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)
@@ -407,7 +406,7 @@ func TestTopDownJWTEncodeSignES512(t *testing.T) {
path := []string{"generated", "p"}
var inputTerm *ast.Term
ctx := context.Background()
ctx := t.Context()
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)
@@ -539,7 +538,7 @@ func TestTopdownJWTEncodeSignECWithSeedReturnsSameSignature(t *testing.T) {
WithStrictBuiltinErrors(true).
WithCompiler(ast.NewCompiler())
qrs, err := q.Run(context.Background())
qrs, err := q.Run(t.Context())
if err != nil {
t.Fatal(err)
} else if len(qrs) != 1 {
@@ -769,7 +768,7 @@ func TestTopdownJWTDecodeVerifyIgnoresKeysOfUnknownAlgInJWKS(t *testing.T) {
}
func TestBuiltinJWTDecodeVerify_TokenCache(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
const privateKey = `{
"kty":"RSA",
@@ -1134,7 +1133,7 @@ func TestBuiltinJWTVerify_TokenCache(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
cacheConfig := cache.Config{
InterQueryBuiltinValueCache: cache.InterQueryBuiltinValueCacheConfig{
@@ -1284,7 +1283,7 @@ func TestBuiltinJWTDecodeVerify(t *testing.T) {
},
}
ctx := context.Background()
ctx := t.Context()
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
+15 -16
View File
@@ -6,7 +6,6 @@ package topdown
import (
"bytes"
"context"
"fmt"
"math/rand"
"strconv"
@@ -32,7 +31,7 @@ func BenchmarkArrayIteration(b *testing.B) {
}
func BenchmarkArrayPlugging(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -98,7 +97,7 @@ func BenchmarkObjectIteration(b *testing.B) {
}
func benchmarkIteration(b *testing.B, module string) {
ctx := context.Background()
ctx := b.Context()
query := ast.MustParseBody("data.test.main")
compiler := ast.MustCompileModules(map[string]string{
"test.rego": module,
@@ -118,7 +117,7 @@ func benchmarkIteration(b *testing.B, module string) {
func BenchmarkLargeJSON(b *testing.B) {
data := test.GenerateLargeJSONBenchmarkData()
ctx := context.Background()
ctx := b.Context()
store := inmem.NewFromObject(data)
compiler := ast.NewCompiler()
@@ -182,7 +181,7 @@ func BenchmarkConcurrency8Writers(b *testing.B) {
func benchmarkConcurrency(b *testing.B, params []storage.TransactionParams) {
mod, data := test.GenerateConcurrencyBenchmarkData()
ctx := context.Background()
ctx := b.Context()
store := inmem.NewFromObject(data)
mods := map[string]*ast.Module{"module": ast.MustParseModule(mod)}
compiler := ast.NewCompiler()
@@ -278,7 +277,7 @@ func BenchmarkVirtualDocs1000x1000(b *testing.B) {
func runVirtualDocsBenchmark(b *testing.B, numTotalRules, numHitRules int) {
mod, inp := test.GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules)
ctx := context.Background()
ctx := b.Context()
compiler := ast.NewCompiler()
mods := map[string]*ast.Module{"module": ast.MustParseModule(mod)}
input := ast.NewTerm(ast.MustInterfaceToValue(inp))
@@ -326,7 +325,7 @@ func BenchmarkPartialEvalCompile(b *testing.B) {
}
func runPartialEvalBenchmark(b *testing.B, numRoles int) {
ctx := context.Background()
ctx := b.Context()
compiler := ast.NewCompiler()
if compiler.Compile(map[string]*ast.Module{"authz": ast.MustParseModule(partialEvalBenchmarkPolicy)}); compiler.Failed() {
@@ -401,7 +400,7 @@ func runPartialEvalBenchmark(b *testing.B, numRoles int) {
func runPartialEvalCompileBenchmark(b *testing.B, numRoles int) {
ctx := context.Background()
ctx := b.Context()
data := generatePartialEvalBenchmarkData(numRoles)
store := inmem.NewFromObject(data)
@@ -541,7 +540,7 @@ func generatePartialEvalBenchmarkInput(numRoles int) *ast.Term {
func BenchmarkWalk(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{100, 1000, 2000, 3000}
for _, n := range sizes {
@@ -587,7 +586,7 @@ func genWalkBenchmarkData(n int) map[string]any {
}
func BenchmarkComprehensionIndexing(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
cases := []struct {
note string
module string
@@ -670,7 +669,7 @@ func BenchmarkComprehensionIndexing(b *testing.B) {
}
func BenchmarkFunctionArgumentIndex(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000}
@@ -723,7 +722,7 @@ func genComprehensionIndexingData(n int) map[string]any {
}
func BenchmarkObjectSubset(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -780,7 +779,7 @@ func BenchmarkObjectSubsetSlow(b *testing.B) {
// This benchmarks the suggested means to implement object.subset
// without using the builtin, to give us an idea of whether or not
// the builtin is actually making things any faster.
ctx := context.Background()
ctx := b.Context()
sizes := []int{10, 100, 1000, 10000}
@@ -854,7 +853,7 @@ func randomString(symbols []rune, length int) string {
}
func BenchmarkGlob(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
// Benchmark Strategy:
//
@@ -939,7 +938,7 @@ func BenchmarkMemberWithKeyFromBaseDoc(b *testing.B) {
main if { "key99", "value99" in data.values }
`
ctx := context.Background()
ctx := b.Context()
query := ast.MustParseBody("data.test.main")
compiler := ast.MustCompileModules(map[string]string{
"test.rego": mod,
@@ -964,7 +963,7 @@ func BenchmarkObjectGetFromBaseDoc(b *testing.B) {
main if { object.get(data.values, "key99", false) == "value99" }
`
ctx := context.Background()
ctx := b.Context()
query := ast.MustParseBody("data.test.main")
compiler := ast.MustCompileModules(map[string]string{
"test.rego": mod,
+1 -2
View File
@@ -1,7 +1,6 @@
package topdown
import (
"context"
"strconv"
"testing"
@@ -12,7 +11,7 @@ import (
func BenchmarkInliningFullScan(b *testing.B) {
ctx := context.Background()
ctx := b.Context()
body := ast.MustParseBody("data.test.p = true")
unknowns := []*ast.Term{ast.MustParseTerm("input")}
compiler := ast.MustCompileModules(map[string]string{
+1 -1
View File
@@ -4964,7 +4964,7 @@ q if { input.x = 7 }`},
},
}
ctx := context.Background()
ctx := t.Context()
for _, tc := range tests {
params := fixtureParams{
+13 -13
View File
@@ -36,7 +36,7 @@ import (
func TestTopDownQueryIDsUnique(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
inputTerm := &ast.Term{}
txn := storage.NewTransactionOrDie(ctx, store)
@@ -76,7 +76,7 @@ func TestTopDownQueryIDsUnique(t *testing.T) {
func TestTopDownIndexExpr(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)
@@ -172,7 +172,7 @@ func TestTopDownUnsupportedBuiltin(t *testing.T) {
})
body := ast.MustParseBody(`unsupported_builtin()`)
ctx := context.Background()
ctx := t.Context()
compiler := ast.NewCompiler()
store := inmem.New()
txn := storage.NewTransactionOrDie(ctx, store)
@@ -190,7 +190,7 @@ func TestTopDownUnsupportedBuiltin(t *testing.T) {
func TestTopDownQueryCancellation(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{
`
@@ -239,7 +239,7 @@ func TestTopDownQueryCancellation(t *testing.T) {
func TestTopDownQueryCancellationEvery(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
module := func(ev ast.Every, _ ...any) *ast.Module {
t.Helper()
@@ -1511,7 +1511,7 @@ arr := [1, 2, 3, 4, 5]
t.Parallel()
countExit := 1 + tc.extraExit
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{tc.module})
size := 1000
arr := make([]any, size)
@@ -1682,7 +1682,7 @@ func TestTopDownEvery(t *testing.T) {
t.Run(tc.note, func(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
c := ast.NewCompiler().WithEnablePrintStatements(true)
mod := ast.MustParseModuleWithOpts(tc.module, ast.ParserOptions{AllFutureKeywords: true})
if c.Compile(map[string]*ast.Module{"test": mod}); c.Failed() {
@@ -1764,7 +1764,7 @@ func (m *contextPropagationStore) Read(ctx context.Context, _ storage.Transactio
func TestTopDownContextPropagation(t *testing.T) {
t.Parallel()
ctx := context.WithValue(context.Background(), contextPropagationMock{}, "bar")
ctx := context.WithValue(t.Context(), contextPropagationMock{}, "bar")
compiler := ast.NewCompiler()
compiler.Compile(map[string]*ast.Module{
@@ -1831,7 +1831,7 @@ func TestTopdownStoreAST(t *testing.T) {
t.Parallel()
body := ast.MustParseBody(`data.stored = x`)
ctx := context.Background()
ctx := t.Context()
compiler := ast.NewCompiler()
store := &astStore{path: "/stored", value: ast.String("value")}
@@ -1857,7 +1857,7 @@ func TestTopdownLazyObj(t *testing.T) {
t.Parallel()
body := ast.MustParseBody(`data.stored = x`)
ctx := context.Background()
ctx := t.Context()
compiler := ast.NewCompiler()
foo := map[string]any{
"foo": "bar",
@@ -1889,7 +1889,7 @@ func TestTopdownLazyObjOptOut(t *testing.T) {
t.Parallel()
body := ast.MustParseBody(`data.stored = x`)
ctx := context.Background()
ctx := t.Context()
compiler := ast.NewCompiler()
foo := map[string]any{
"foo": "bar",
@@ -2075,13 +2075,13 @@ func setRoundTripper(t CustomizeRoundTripper) func(*Query) *Query {
func runTopDownTestCase(t *testing.T, data map[string]any, note string, rules []string, expected any, options ...func(*Query) *Query) {
t.Helper()
runTopDownTestCaseWithContext(context.Background(), t, data, note, rules, nil, "", expected, options...)
runTopDownTestCaseWithContext(t.Context(), t, data, note, rules, nil, "", expected, options...)
}
func runTopDownTestCaseWithModules(t *testing.T, data map[string]any, note string, rules []string, modules []string, input string, expected any) {
t.Helper()
runTopDownTestCaseWithContext(context.Background(), t, data, note, rules, modules, input, expected)
runTopDownTestCaseWithContext(t.Context(), t, data, note, rules, modules, input, expected)
}
func runTopDownTestCaseWithContext(ctx context.Context, t *testing.T, data map[string]any, note string, rules []string, modules []string, input string, expected any,
+16 -17
View File
@@ -6,7 +6,6 @@ package topdown
import (
"bytes"
"context"
"fmt"
"maps"
"reflect"
@@ -63,7 +62,7 @@ func TestPrettyTrace(t *testing.T) {
p if { q[x]; plus(x, 1, n) }
q contains x if { x = data.a[_] }`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -125,7 +124,7 @@ func TestPrettyTraceWithLocation(t *testing.T) {
p if { q[x]; plus(x, 1, n) }
q contains x if { x = data.a[_] }`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -182,7 +181,7 @@ query:3 | | Redo data.test.q[x]
func TestPrettyTraceWithLocationTruncatedPaths(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
compiler := ast.MustCompileModulesWithOpts(map[string]string{
"authz_bundle/com/foo/bar/baz/qux/acme/corp/internal/authz/policies/abac/v1/beta/policy.rego": `package test
@@ -255,7 +254,7 @@ authz_bundle/...ternal/authz/policies/abac/v1/beta/policy.rego:5 | | Redo da
func TestPrettyTracePartialWithLocationTruncatedPaths(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
compiler := ast.MustCompileModulesWithOpts(map[string]string{
"authz_bundle/com/foo/bar/baz/qux/acme/corp/internal/authz/policies/rbac/v1/beta/policy.rego": `
@@ -435,7 +434,7 @@ func TestTraceDuplicate(t *testing.T) {
p contains 1
`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -474,7 +473,7 @@ func TestTraceNote(t *testing.T) {
p if { q[x]; plus(x, 1, n); trace(sprintf("n=%v", [n])) }
q contains x if { x = data.a[_] }`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -541,7 +540,7 @@ func TestTraceNoteWithLocation(t *testing.T) {
p if { q[x]; plus(x, 1, n); trace(sprintf("n=%v", [n])) }
q contains x if { x = data.a[_] }`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -603,7 +602,7 @@ query:3 | | Redo data.test.q[x]
func TestMultipleTracers(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
buf1 := NewBufferTracer()
buf2 := NewBufferTracer()
@@ -635,7 +634,7 @@ func TestTraceRewrittenQueryVars(t *testing.T) {
y = [1, 2, 3]`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
queryCompiler := compiler.QueryCompiler()
data := loadSmallTestData()
@@ -771,7 +770,7 @@ func TestTraceRewrittenVars(t *testing.T) {
func TestTraceEveryEvaluation(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
events := func(es ...string) []string {
return es
@@ -1058,7 +1057,7 @@ func TestBufferTracerTraceConfig(t *testing.T) {
func TestTraceInput(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
module := `
package test
@@ -1102,7 +1101,7 @@ func TestTraceInput(t *testing.T) {
func TestTracePlug(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctx := t.Context()
module := `
package test
@@ -1210,7 +1209,7 @@ chain_with_output_var if {
foo == []
}`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -1292,7 +1291,7 @@ func TestPrettyTraceWithUnifyOps(t *testing.T) {
x = 1
}`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
store := inmem.NewFromObject(nil)
txn := storage.NewTransactionOrDie(ctx, store)
@@ -1360,7 +1359,7 @@ do_math(a, b) := c if {
}
`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
@@ -1446,7 +1445,7 @@ do_math(a, b) := c if {
}
`
ctx := context.Background()
ctx := t.Context()
compiler := compileModules([]string{module})
data := loadSmallTestData()
store := inmem.NewFromObject(data)
+3 -4
View File
@@ -5,7 +5,6 @@
package topdown
import (
"context"
"errors"
"math/rand"
"testing"
@@ -20,7 +19,7 @@ func TestUUIDRFC4122SeedingAndCaching(t *testing.T) {
q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(ast.NewCompiler())
ctx := context.Background()
ctx := t.Context()
qrs, err := q.Run(ctx)
if err != nil {
@@ -59,7 +58,7 @@ func TestUUIDRFC4122SeedError(t *testing.T) {
q := NewQuery(ast.MustParseBody(query)).WithSeed(fakeSeedErrorReader{}).WithCompiler(ast.NewCompiler()).WithStrictBuiltinErrors(true)
_, err := q.Run(context.Background())
_, err := q.Run(t.Context())
if topdownErr, ok := err.(*Error); !ok || topdownErr.Code != BuiltinErr {
t.Fatal("unexpected error (or lack of error):", err)
@@ -77,7 +76,7 @@ func TestUUIDRFC4122SavingDuringPartialEval(t *testing.T) {
q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(c)
queries, modules, err := q.PartialRun(context.Background())
queries, modules, err := q.PartialRun(t.Context())
if err != nil {
t.Fatal(err)
} else if len(modules) > 0 {