mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-12 19:32:48 -06:00
Add gocritic linter, fix a bunch of stuff (#7377)
Brace yourselves! For there are many touched files here. No changes in semantics however. Spent a long time trying out the various optional rules gocritic provides, and settled for a few of them. There are more I really like, but that would take many hours to address across the codebase. Perhaps others find gocritic too pedantic? If so, we can merge the fixes without enabling the rule. Signed-off-by: Anders Eknert <anders@styra.com>
This commit is contained in:
+1
-1
@@ -1 +1 @@
|
||||
1.23.6
|
||||
1.24.0
|
||||
|
||||
@@ -3,6 +3,10 @@ run:
|
||||
|
||||
issues:
|
||||
max-same-issues: 0 # don't hide issues in CI runs because they are the same type
|
||||
exclude-dirs:
|
||||
- internal/gojsonschema
|
||||
- internal/gqlparser
|
||||
- internal/jwx
|
||||
exclude-rules:
|
||||
- path: ast/
|
||||
linters:
|
||||
@@ -140,6 +144,37 @@ issues:
|
||||
linters-settings:
|
||||
lll:
|
||||
line-length: 200
|
||||
gocritic:
|
||||
disabled-checks:
|
||||
- appendAssign
|
||||
# NOTE(ae): this one should be enabled, but there were too
|
||||
# many violations to fix in one go... revisit later
|
||||
- singleCaseSwitch
|
||||
# Reasonable rule, but not sure what to replace with in
|
||||
# many locations, so disabling for now
|
||||
- exitAfterDefer
|
||||
# The following 3 rules are disabled from the perfomance tag
|
||||
# enabled further down. The first two are reasonable, but not
|
||||
# super important. appendCombine is really nice though! And
|
||||
# should be enabled. Just many places to fix..
|
||||
- hugeParam
|
||||
- preferFprint
|
||||
- appendCombine
|
||||
enabled-checks:
|
||||
# NOTE that these are rules enabled in addition to the default set
|
||||
- filepathJoin
|
||||
- dupImport
|
||||
- redundantSprint
|
||||
- stringConcatSimplify
|
||||
enabled-tags:
|
||||
- performance
|
||||
settings:
|
||||
ifElseChain:
|
||||
# ridiculous value set for now, but this should be
|
||||
# lowered to something more reasonable, as the rule
|
||||
# is reasonable (replace long if-else chains with
|
||||
# switch)... just too many violations right now
|
||||
minThreshold: 10
|
||||
govet:
|
||||
enable:
|
||||
- deepequalerrors
|
||||
@@ -175,4 +210,5 @@ linters:
|
||||
- unconvert
|
||||
- copyloopvar
|
||||
- perfsprint
|
||||
- gocritic
|
||||
# - gosec # too many false positives
|
||||
|
||||
+1
-3
@@ -66,11 +66,9 @@ func TestCompile_DefaultRegoVersion(t *testing.T) {
|
||||
|
||||
if len(tc.expErrs) > 0 {
|
||||
assertErrors(t, compiler.Errors, tc.expErrs)
|
||||
} else {
|
||||
if len(compiler.Errors) > 0 {
|
||||
} else if len(compiler.Errors) > 0 {
|
||||
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,11 +108,9 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) {
|
||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -216,11 +214,9 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) {
|
||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ func TestParser_DefaultRegoVersion(t *testing.T) {
|
||||
p[x] {
|
||||
c = ["a", "b", "c"][i]
|
||||
}`,
|
||||
expStmtCount: 2, //package, p
|
||||
expStmtCount: 2, // package, p
|
||||
},
|
||||
{
|
||||
note: "v1",
|
||||
@@ -30,7 +30,7 @@ p contains x if {
|
||||
c = ["a", "b", "c"][i]
|
||||
}`,
|
||||
// v1 Keywords are not recognized, and interpreted as individual statements
|
||||
expStmtCount: 5, //package, p, contains, x, if
|
||||
expStmtCount: 5, // package, p, contains, x, if
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ func main() {
|
||||
|
||||
err = doc.GenMarkdownTree(command, dir)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
log.Fatal(err) //nolint: gocritic
|
||||
}
|
||||
|
||||
files, err := os.ReadDir(dir)
|
||||
|
||||
@@ -86,18 +86,6 @@ func TestHasRootsOverlap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
//err := hasRootsOverlap(ctx, mockStore, txn, bundles)
|
||||
//if !tc.overlaps && err != nil {
|
||||
// t.Fatalf("unepected error: %s", err)
|
||||
//} else if tc.overlaps && (err == nil || !strings.Contains(err.Error(), "detected overlapping roots in bundle manifest")) {
|
||||
// t.Fatalf("expected overlapping roots error, got: %s", err)
|
||||
//}
|
||||
|
||||
//err = mockStore.Commit(ctx, txn)
|
||||
//if err != nil {
|
||||
// t.Fatalf("unexpected error: %s", err)
|
||||
//}
|
||||
|
||||
mockStore.AssertValid(t)
|
||||
})
|
||||
}
|
||||
|
||||
+3
-3
@@ -175,7 +175,7 @@ func TestRunBenchmarkE2EWithOPAConfigFile(t *testing.T) {
|
||||
|
||||
params := testBenchParams()
|
||||
params.e2e = true
|
||||
params.configFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.configFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
args := []string{"1 + 1"}
|
||||
var buf bytes.Buffer
|
||||
@@ -580,7 +580,7 @@ func TestBenchMainInvalidInputFile(t *testing.T) {
|
||||
}
|
||||
args := []string{"1+1"}
|
||||
test.WithTempFS(files, func(path string) {
|
||||
params.inputPath = filepath.Join(path, "definitely/not/input.yaml")
|
||||
params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml")
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
@@ -662,7 +662,7 @@ func TestBenchMainInvalidInputFileE2E(t *testing.T) {
|
||||
}
|
||||
args := []string{"1+1"}
|
||||
test.WithTempFS(files, func(path string) {
|
||||
params.inputPath = filepath.Join(path, "definitely/not/input.yaml")
|
||||
params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml")
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
|
||||
+1
-1
@@ -190,7 +190,7 @@ import rego.v1`,
|
||||
for i := range tests {
|
||||
tc := tests[i]
|
||||
tc.bundleMode = true
|
||||
tc.note = tc.note + " (as bundle)"
|
||||
tc.note += " (as bundle)"
|
||||
tests = append(tests, tc)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ import rego.v1`,
|
||||
for i := range tests {
|
||||
tc := tests[i]
|
||||
tc.bundleMode = true
|
||||
tc.note = tc.note + " (as bundle)"
|
||||
tc.note += " (as bundle)"
|
||||
tests = append(tests, tc)
|
||||
}
|
||||
|
||||
|
||||
+3
-9
@@ -70,11 +70,9 @@ a contains x if {
|
||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -249,11 +247,9 @@ p contains 3 if {
|
||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -566,11 +562,9 @@ p contains 4 if {
|
||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
+1
-3
@@ -680,11 +680,9 @@ p contains v if {
|
||||
t.Fatalf("Expected error:\n\n%v\n\nbut got:\n\n%v", expErr, err.Error())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -33,7 +33,7 @@ func (cf cmdFlagsImpl) CheckEnvironmentVariables(command *cobra.Command) error {
|
||||
}
|
||||
command.Flags().VisitAll(func(f *pflag.Flag) {
|
||||
configName := f.Name
|
||||
configName = strings.Replace(configName, "-", "_", -1)
|
||||
configName = strings.ReplaceAll(configName, "-", "_")
|
||||
if !f.Changed && v.IsSet(configName) {
|
||||
val := v.Get(configName)
|
||||
err := command.Flags().Set(f.Name, fmt.Sprintf("%v", val))
|
||||
|
||||
@@ -237,7 +237,7 @@ func TestExec(t *testing.T) {
|
||||
})
|
||||
|
||||
err := Exec(ctx, opa, params)
|
||||
output := strings.Replace(buf.String(), dir, "%ROOT%", -1)
|
||||
output := strings.ReplaceAll(buf.String(), dir, "%ROOT%")
|
||||
tt.assertion(t, output, err)
|
||||
})
|
||||
})
|
||||
|
||||
+8
-12
@@ -144,7 +144,7 @@ p = 1
|
||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||
}
|
||||
|
||||
expectedOutput := strings.Replace(`{
|
||||
expectedOutput := strings.ReplaceAll(`{
|
||||
"package": {
|
||||
"location": {
|
||||
"file": "TEMPDIR/x.rego",
|
||||
@@ -238,7 +238,7 @@ p = 1
|
||||
}
|
||||
]
|
||||
}
|
||||
`, "TEMPDIR", tempDirPath, -1)
|
||||
`, "TEMPDIR", tempDirPath)
|
||||
|
||||
gotLines := strings.Split(string(stdout), "\n")
|
||||
wantLines := strings.Split(expectedOutput, "\n")
|
||||
@@ -350,7 +350,7 @@ a.b.c := true
|
||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||
}
|
||||
|
||||
expectedOutput := strings.Replace(`{
|
||||
expectedOutput := strings.ReplaceAll(`{
|
||||
"package": {
|
||||
"location": {
|
||||
"file": "TEMPDIR/x.rego",
|
||||
@@ -464,7 +464,7 @@ a.b.c := true
|
||||
}
|
||||
]
|
||||
}
|
||||
`, "TEMPDIR", tempDirPath, -1)
|
||||
`, "TEMPDIR", tempDirPath)
|
||||
|
||||
gotLines := strings.Split(string(stdout), "\n")
|
||||
wantLines := strings.Split(expectedOutput, "\n")
|
||||
@@ -508,7 +508,7 @@ allow = true if {
|
||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||
}
|
||||
|
||||
expectedOutput := strings.Replace(`{
|
||||
expectedOutput := strings.ReplaceAll(`{
|
||||
"package": {
|
||||
"location": {
|
||||
"file": "TEMPDIR/x.rego",
|
||||
@@ -925,7 +925,7 @@ allow = true if {
|
||||
}
|
||||
]
|
||||
}
|
||||
`, "TEMPDIR", tempDirPath, -1)
|
||||
`, "TEMPDIR", tempDirPath)
|
||||
|
||||
gotLines := strings.Split(string(stdout), "\n")
|
||||
wantLines := strings.Split(expectedOutput, "\n")
|
||||
@@ -1015,11 +1015,9 @@ a contains x if {
|
||||
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if len(stderr) > 0 {
|
||||
} else if len(stderr) > 0 {
|
||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1172,11 +1170,9 @@ p contains v if {
|
||||
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if len(stderr) > 0 {
|
||||
} else if len(stderr) > 0 {
|
||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -176,11 +176,9 @@ func TestValidateSignParams(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,11 +386,9 @@ p contains "B" if {
|
||||
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ func TestGenerateBundleInfoWithFileDir(t *testing.T) {
|
||||
expectedNamespaces := map[string][]string{
|
||||
"data": {filepath.Join(rootDir, "data.json")},
|
||||
"data.bar": {filepath.Join(rootDir, "base.rego")},
|
||||
"data.foo": {filepath.Join(rootDir, "baz/authz.rego"), filepath.Join(rootDir, "foo/policy.rego")},
|
||||
"data.fuz": {filepath.Join(rootDir, "fuz/fuz.rego"), filepath.Join(rootDir, "fuz/data.json")},
|
||||
"data.foo": {filepath.Join(rootDir, "baz", "authz.rego"), filepath.Join(rootDir, "foo", "policy.rego")},
|
||||
"data.fuz": {filepath.Join(rootDir, "fuz", "fuz.rego"), filepath.Join(rootDir, "fuz", "data.json")},
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(info.Namespaces, expectedNamespaces) {
|
||||
@@ -253,7 +253,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) {
|
||||
expectedWasmModules := []map[string]interface{}{}
|
||||
expectedWasmModule1 := map[string]interface{}{
|
||||
"path": "/example/policy.wasm",
|
||||
"url": filepath.Join(bundleFile, "/example/policy.wasm"),
|
||||
"url": filepath.Join(bundleFile, "example", "policy.wasm"),
|
||||
"entrypoints": []string{"data.http.example.foo.allow"},
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ func LoadBundleFromDiskForRegoVersion(regoVersion ast.RegoVersion, path, name st
|
||||
|
||||
_, err := os.Stat(bundlePath)
|
||||
if err == nil {
|
||||
f, err := os.Open(filepath.Join(bundlePath))
|
||||
f, err := os.Open(bundlePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ func GetAddressRange(ipNet net.IPNet) (net.IP, net.IP) {
|
||||
copy(lastIPMask, ipNet.Mask)
|
||||
for i := range lastIPMask {
|
||||
lastIPMask[len(lastIPMask)-i-1] = ^lastIPMask[len(lastIPMask)-i-1]
|
||||
lastIP[net.IPv6len-i-1] = lastIP[net.IPv6len-i-1] | lastIPMask[len(lastIPMask)-i-1]
|
||||
lastIP[net.IPv6len-i-1] |= lastIPMask[len(lastIPMask)-i-1]
|
||||
}
|
||||
|
||||
return firstIP, lastIP
|
||||
|
||||
@@ -127,11 +127,9 @@ func TestVerifyAuthorizationPolicySchema(t *testing.T) {
|
||||
t.Errorf("Expected error %v not found", e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,7 +340,7 @@ func (c *Compiler) initModule() error {
|
||||
// two times. But let's deal with that when it happens.
|
||||
if _, ok := c.funcs[name]; ok { // already seen
|
||||
c.debug.Printf("function name duplicate: %s (%d)", name, fn.Index)
|
||||
name = name + ".1"
|
||||
name += ".1"
|
||||
}
|
||||
c.funcs[name] = fn.Index
|
||||
}
|
||||
@@ -348,7 +348,7 @@ func (c *Compiler) initModule() error {
|
||||
for _, fn := range c.policy.Funcs.Funcs {
|
||||
|
||||
params := make([]types.ValueType, len(fn.Params))
|
||||
for i := 0; i < len(params); i++ {
|
||||
for i := range params {
|
||||
params[i] = types.I32
|
||||
}
|
||||
|
||||
@@ -996,12 +996,16 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
|
||||
for _, stmt := range block.Stmts {
|
||||
switch stmt := stmt.(type) {
|
||||
case *ir.ResultSetAddStmt:
|
||||
instrs = append(instrs, instruction.GetLocal{Index: c.lrs})
|
||||
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Value)})
|
||||
instrs = append(instrs, instruction.Call{Index: c.function(opaSetAdd)})
|
||||
instrs = append(instrs,
|
||||
instruction.GetLocal{Index: c.lrs},
|
||||
instruction.GetLocal{Index: c.local(stmt.Value)},
|
||||
instruction.Call{Index: c.function(opaSetAdd)},
|
||||
)
|
||||
case *ir.ReturnLocalStmt:
|
||||
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Source)})
|
||||
instrs = append(instrs, instruction.Return{})
|
||||
instrs = append(instrs,
|
||||
instruction.GetLocal{Index: c.local(stmt.Source)},
|
||||
instruction.Return{},
|
||||
)
|
||||
case *ir.BlockStmt:
|
||||
for i := range stmt.Blocks {
|
||||
block, err := c.compileBlock(stmt.Blocks[i])
|
||||
@@ -1029,8 +1033,10 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
|
||||
return instrs, err
|
||||
}
|
||||
case *ir.AssignVarStmt:
|
||||
instrs = append(instrs, c.instrRead(stmt.Source))
|
||||
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)})
|
||||
instrs = append(instrs,
|
||||
c.instrRead(stmt.Source),
|
||||
instruction.SetLocal{Index: c.local(stmt.Target)},
|
||||
)
|
||||
case *ir.AssignVarOnceStmt:
|
||||
instrs = append(instrs, instruction.Block{
|
||||
Instrs: []instruction.Instruction{
|
||||
@@ -1535,8 +1541,7 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul
|
||||
}
|
||||
|
||||
instrs := *result
|
||||
instrs = append(instrs, instruction.I32Const{Value: ef.ID})
|
||||
instrs = append(instrs, instruction.I32Const{Value: 0}) // unused context parameter
|
||||
instrs = append(instrs, instruction.I32Const{Value: ef.ID}, instruction.I32Const{Value: 0}) // unused context parameter
|
||||
|
||||
for _, arg := range stmt.Args {
|
||||
instrs = append(instrs, c.instrRead(arg))
|
||||
@@ -1545,9 +1550,11 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul
|
||||
instrs = append(instrs, instruction.Call{Index: c.function(builtinDispatchers[len(stmt.Args)])})
|
||||
|
||||
if ef.Decl.Result() != nil {
|
||||
instrs = append(instrs, instruction.TeeLocal{Index: c.local(stmt.Result)})
|
||||
instrs = append(instrs, instruction.I32Eqz{})
|
||||
instrs = append(instrs, instruction.BrIf{Index: 0})
|
||||
instrs = append(instrs,
|
||||
instruction.TeeLocal{Index: c.local(stmt.Result)},
|
||||
instruction.I32Eqz{},
|
||||
instruction.BrIf{Index: 0},
|
||||
)
|
||||
} else {
|
||||
instrs = append(instrs, instruction.Drop{})
|
||||
}
|
||||
|
||||
@@ -306,7 +306,7 @@ discovery:
|
||||
`}
|
||||
|
||||
test.WithTempFS(fs, func(rootDir string) {
|
||||
configFile := filepath.Join(rootDir, "/some/config.yaml")
|
||||
configFile := filepath.Join(rootDir, "some", "config.yaml")
|
||||
configOverrides := []string{"services.acmecorp.credentials.bearer.token=bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"}
|
||||
|
||||
configBytes, err := Load(configFile, configOverrides, nil)
|
||||
@@ -361,8 +361,8 @@ discovery:
|
||||
}
|
||||
|
||||
test.WithTempFS(fs, func(rootDir string) {
|
||||
configFile := filepath.Join(rootDir, "/some/config.yaml")
|
||||
secretFile := filepath.Join(rootDir, "/some/secret.txt")
|
||||
configFile := filepath.Join(rootDir, "some", "config.yaml")
|
||||
secretFile := filepath.Join(rootDir, "some", "secret.txt")
|
||||
overrideFiles := []string{"services.acmecorp.credentials.bearer.token=" + secretFile}
|
||||
|
||||
configBytes, err := Load(configFile, nil, overrideFiles)
|
||||
|
||||
@@ -85,7 +85,7 @@ func Init(ctx context.Context, raw []byte, id string) (*otlptrace.Exporter, *tra
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
if strings.ToLower(distributedTracingConfig.Type) != "grpc" {
|
||||
if !strings.EqualFold(distributedTracingConfig.Type, "grpc") {
|
||||
return nil, nil, nil, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ func (vector *BitVector) Length() int {
|
||||
// position of the last byte in the slice.
|
||||
// This returns the bit that was shifted off of the last byte.
|
||||
func shiftLower(bit byte, b []byte) byte {
|
||||
bit = bit << 7
|
||||
bit <<= 7
|
||||
for i := len(b) - 1; i >= 0; i-- {
|
||||
newByte := b[i] >> 1
|
||||
newByte |= bit
|
||||
|
||||
@@ -1180,5 +1180,5 @@ func (e *EditTree) Filter(paths []ast.Ref) *ast.Term {
|
||||
type termSlice []*ast.Term
|
||||
|
||||
func (s termSlice) Less(i, j int) bool { return ast.Compare(s[i].Value, s[j].Value) < 0 }
|
||||
func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
||||
func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s termSlice) Len() int { return len(s) }
|
||||
|
||||
@@ -86,7 +86,7 @@ func Test(t *testing.T, filename string, f func(t *testing.T, input string) Spec
|
||||
for i, tok := range result.Tokens {
|
||||
expected := spec.Tokens[i]
|
||||
|
||||
if !strings.EqualFold(strings.Replace(expected.Kind, "_", "", -1), tok.Kind) {
|
||||
if !strings.EqualFold(strings.ReplaceAll(expected.Kind, "_", ""), tok.Kind) {
|
||||
t.Errorf("token[%d].kind should be %s, was %s", i, expected.Kind, tok.Kind)
|
||||
}
|
||||
if expected.Value != "undefined" && expected.Value != tok.Value {
|
||||
|
||||
@@ -159,8 +159,6 @@ func unexpectedTypeMessageOnly(v *ast.Value) ErrorOption {
|
||||
return Message(`Float cannot represent non numeric value: %s`, v.String())
|
||||
case "ID", "ID!":
|
||||
return Message(`ID cannot represent a non-string and non-integer value: %s`, v.String())
|
||||
//case "Enum":
|
||||
// return Message(`Enum "%s" cannot represent non-enum value: %s`, v.ExpectedType.String(), v.String())
|
||||
default:
|
||||
if v.Definition.Kind == ast.Enum {
|
||||
return Message(`Enum "%s" cannot represent non-enum value: %s.`, v.ExpectedType.String(), v.String())
|
||||
|
||||
@@ -223,7 +223,7 @@ func (v *varValidator) validateVarType(typ *ast.Type, val reflect.Value) (reflec
|
||||
if fieldDef.Type.NonNull && field.IsNil() {
|
||||
return val, gqlerror.ErrorPathf(v.path, "cannot be null")
|
||||
}
|
||||
//allow null object field and skip it
|
||||
// allow null object field and skip it
|
||||
if !fieldDef.Type.NonNull && field.IsNil() {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -37,8 +37,8 @@ func ParsePatchPathEscaped(str string) (path storage.Path, ok bool) {
|
||||
// the substitutions in this order, an implementation avoids the error of
|
||||
// turning '~01' first into '~1' and then into '/', which would be
|
||||
// incorrect (the string '~01' correctly becomes '~1' after transformation)."
|
||||
path[i] = strings.Replace(path[i], "~1", "/", -1)
|
||||
path[i] = strings.Replace(path[i], "~0", "~", -1)
|
||||
path[i] = strings.ReplaceAll(path[i], "~1", "/")
|
||||
path[i] = strings.ReplaceAll(path[i], "~0", "~")
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
@@ -114,7 +114,7 @@ func parse(jwkSrc string) (*Set, error) {
|
||||
|
||||
// ParseBytes parses JWK from the incoming byte buffer.
|
||||
func ParseBytes(buf []byte) (*Set, error) {
|
||||
return parse(string(buf[:]))
|
||||
return parse(string(buf))
|
||||
}
|
||||
|
||||
// ParseString parses JWK from the incoming string.
|
||||
|
||||
@@ -111,7 +111,7 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte
|
||||
return nil, errors.New(`attempt to verify empty buffer`)
|
||||
}
|
||||
|
||||
parts, err := SplitCompact(string(buf[:]))
|
||||
parts, err := SplitCompact(string(buf))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed extract from compact serialization format: %w", err)
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func VerifyWithJWKSet(buf []byte, keyset *jwk.Set) (payload []byte, err error) {
|
||||
|
||||
// ParseByte parses a JWS value serialized via compact serialization and provided as []byte.
|
||||
func ParseByte(jwsCompact []byte) (m *Message, err error) {
|
||||
return parseCompact(string(jwsCompact[:]))
|
||||
return parseCompact(string(jwsCompact))
|
||||
}
|
||||
|
||||
// ParseString parses a JWS value serialized via compact serialization and provided as string.
|
||||
|
||||
@@ -336,7 +336,7 @@ func TestEncode(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify with standard ecdsa library
|
||||
parts, err := jws.SplitCompact(string(jwsCompact[:]))
|
||||
parts, err := jws.SplitCompact(string(jwsCompact))
|
||||
if err != nil {
|
||||
t.Fatal("Failed to split compact JWT")
|
||||
}
|
||||
|
||||
@@ -497,7 +497,6 @@ func (p *Planner) planDotOr(obj ir.Local, key ir.Operand, or stmtFactory, iter p
|
||||
|
||||
func (p *Planner) planNestedObjects(obj ir.Local, ref ast.Ref, iter planLocalIter) error {
|
||||
if len(ref) == 0 {
|
||||
//return fmt.Errorf("nested object construction didn't create object")
|
||||
return iter(obj)
|
||||
}
|
||||
|
||||
@@ -991,8 +990,7 @@ func (p *Planner) planExprCall(e *ast.Expr, iter planiter) error {
|
||||
op := e.Operator()
|
||||
|
||||
if replacement := p.mocks.Lookup(operator); replacement != nil {
|
||||
switch r := replacement.Value.(type) {
|
||||
case ast.Ref:
|
||||
if r, ok := replacement.Value.(ast.Ref); ok {
|
||||
if !r.HasPrefix(ast.DefaultRootRef) && !r.HasPrefix(ast.InputRootRef) {
|
||||
// replacement is builtin
|
||||
operator = r.String()
|
||||
|
||||
@@ -492,7 +492,7 @@ func prettyASTNode(x interface{}, regoVersion ast.RegoVersion) (string, int, err
|
||||
return "", 0, fmt.Errorf("format error: %w", err)
|
||||
}
|
||||
var maxLineWidth int
|
||||
s := strings.Trim(strings.Replace(string(bs), "\t", " ", -1), "\n")
|
||||
s := strings.Trim(strings.ReplaceAll(string(bs), "\t", " "), "\n")
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
width := tablewriter.DisplayWidth(line)
|
||||
if width > maxLineWidth {
|
||||
|
||||
@@ -216,7 +216,7 @@ func (s *httpSigner) Build() (signedRequest, error) {
|
||||
|
||||
signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength)
|
||||
|
||||
rawQuery := strings.Replace(query.Encode(), "+", "%20", -1)
|
||||
rawQuery := strings.ReplaceAll(query.Encode(), "+", "%20")
|
||||
|
||||
canonicalURI := v4Internal.GetURIPath(req.URL)
|
||||
|
||||
|
||||
@@ -434,8 +434,7 @@ func TestWalkPaths(t *testing.T) {
|
||||
test.WithTempFS(files, func(rootDir string) {
|
||||
|
||||
paths := []string{}
|
||||
paths = append(paths, filepath.Join(rootDir, "bundle1"))
|
||||
paths = append(paths, filepath.Join(rootDir, "bundle2"))
|
||||
paths = append(paths, filepath.Join(rootDir, "bundle1"), filepath.Join(rootDir, "bundle2"))
|
||||
|
||||
// bundle mode
|
||||
loaded, err := WalkPaths(paths, nil, true)
|
||||
|
||||
@@ -57,7 +57,7 @@ func TruncateFilePaths(maxIdealWidth, maxWidth int, path ...string) (map[string]
|
||||
}
|
||||
|
||||
// Drop the overall length down to match our substitution
|
||||
longestLocation = longestLocation - (len(lcs) - 3)
|
||||
longestLocation -= (len(lcs) - 3)
|
||||
}
|
||||
|
||||
return result, longestLocation
|
||||
|
||||
@@ -148,8 +148,6 @@ func (t *parser) key(data map[string]interface{}) error {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("key %q has no value", string(k))
|
||||
//set(data, string(k), "")
|
||||
//return err
|
||||
case last == '[':
|
||||
// We are in a list index context, so we need to set an index.
|
||||
i, err := t.keyIndex()
|
||||
@@ -168,7 +166,7 @@ func (t *parser) key(data map[string]interface{}) error {
|
||||
set(data, kk, list)
|
||||
return err
|
||||
case last == '=':
|
||||
//End of key. Consume =, Get value.
|
||||
// End of key. Consume =, Get value.
|
||||
// FIXME: Get value list first
|
||||
vl, e := t.valList()
|
||||
switch e {
|
||||
|
||||
@@ -16,6 +16,7 @@ limitations under the License.
|
||||
package strvals
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
@@ -382,7 +383,7 @@ func TestParseSet(t *testing.T) {
|
||||
t.Fatalf("Error serializing parsed value: %s", err)
|
||||
}
|
||||
|
||||
if string(y1) != string(y2) {
|
||||
if !bytes.Equal(y1, y2) {
|
||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
||||
}
|
||||
}
|
||||
@@ -407,7 +408,7 @@ func TestParseSet(t *testing.T) {
|
||||
t.Fatalf("Error serializing parsed value: %s", err)
|
||||
}
|
||||
|
||||
if string(y1) != string(y2) {
|
||||
if !bytes.Equal(y1, y2) {
|
||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
||||
}
|
||||
}
|
||||
@@ -443,7 +444,7 @@ func TestParseInto(t *testing.T) {
|
||||
t.Fatalf("Error serializing parsed value: %s", err)
|
||||
}
|
||||
|
||||
if string(y1) != string(y2) {
|
||||
if !bytes.Equal(y1, y2) {
|
||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||
}
|
||||
}
|
||||
@@ -476,7 +477,7 @@ func TestParseIntoString(t *testing.T) {
|
||||
t.Fatalf("Error serializing parsed value: %s", err)
|
||||
}
|
||||
|
||||
if string(y1) != string(y2) {
|
||||
if !bytes.Equal(y1, y2) {
|
||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||
}
|
||||
}
|
||||
@@ -509,7 +510,7 @@ func TestParseIntoFile(t *testing.T) {
|
||||
t.Fatalf("Error serializing parsed value: %s", err)
|
||||
}
|
||||
|
||||
if string(y1) != string(y2) {
|
||||
if !bytes.Equal(y1, y2) {
|
||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,8 +330,7 @@ func scopeCompare(s1, s2 string) int {
|
||||
}
|
||||
|
||||
func scopeOrder(s string) int {
|
||||
switch s {
|
||||
case annotationScopeRule:
|
||||
if s == annotationScopeRule {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
|
||||
+1
-1
@@ -3401,7 +3401,7 @@ func (b *Builtin) IsTargetPos(i int) bool {
|
||||
|
||||
func init() {
|
||||
BuiltinMap = map[string]*Builtin{}
|
||||
for _, b := range DefaultBuiltins {
|
||||
for _, b := range &DefaultBuiltins {
|
||||
RegisterBuiltin(b)
|
||||
}
|
||||
}
|
||||
|
||||
+4
-6
@@ -306,11 +306,9 @@ func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) {
|
||||
tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet
|
||||
tpe = nil
|
||||
}
|
||||
} else {
|
||||
if typeV != nil {
|
||||
} else if typeV != nil {
|
||||
tpe = typeV
|
||||
}
|
||||
}
|
||||
case MultiValue:
|
||||
typeK := cpy.GetByValue(rule.Head.Key.Value)
|
||||
if typeK != nil {
|
||||
@@ -732,8 +730,8 @@ func (rc *refChecker) Visit(x interface{}) bool {
|
||||
}
|
||||
|
||||
func (rc *refChecker) checkApply(curr *TypeEnv, ref Ref) *Error {
|
||||
switch tpe := curr.GetByRef(ref).(type) {
|
||||
case *types.Function: // NOTE(sr): We don't support first-class functions, except for `with`.
|
||||
if tpe, ok := curr.GetByRef(ref).(*types.Function); ok {
|
||||
// NOTE(sr): We don't support first-class functions, except for `with`.
|
||||
return newRefErrUnsupported(ref[0].Location, rc.varRewriter(ref), len(ref)-1, tpe)
|
||||
}
|
||||
|
||||
@@ -1003,7 +1001,7 @@ type ArgErrDetail struct {
|
||||
func (d *ArgErrDetail) Lines() []string {
|
||||
lines := make([]string, 2)
|
||||
lines[0] = "have: " + formatArgs(d.Have)
|
||||
lines[1] = "want: " + fmt.Sprint(d.Want)
|
||||
lines[1] = "want: " + d.Want.String()
|
||||
return lines
|
||||
}
|
||||
|
||||
|
||||
@@ -1529,9 +1529,7 @@ func TestCheckErrorOrdering(t *testing.T) {
|
||||
inputReversed[i] = mod.Rules[i]
|
||||
}
|
||||
|
||||
tmp := inputReversed[1]
|
||||
inputReversed[1] = inputReversed[2]
|
||||
inputReversed[2] = tmp
|
||||
inputReversed[1], inputReversed[2] = inputReversed[2], inputReversed[1]
|
||||
|
||||
_, errs1 := newTypeChecker().CheckTypes(nil, input, nil)
|
||||
_, errs2 := newTypeChecker().CheckTypes(nil, inputReversed, nil)
|
||||
|
||||
+1
-1
@@ -236,7 +236,7 @@ func Compare(a, b interface{}) int {
|
||||
type termSlice []*Term
|
||||
|
||||
func (s termSlice) Less(i, j int) bool { return Compare(s[i].Value, s[j].Value) < 0 }
|
||||
func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
||||
func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s termSlice) Len() int { return len(s) }
|
||||
|
||||
func sortOrder(x interface{}) int {
|
||||
|
||||
+1
-3
@@ -3545,11 +3545,9 @@ func (n *TreeNode) add(path Ref, rule *Rule) {
|
||||
}
|
||||
node.Children[sub.Key] = sub
|
||||
node.Sorted = append(node.Sorted, sub.Key)
|
||||
} else {
|
||||
if rule != nil {
|
||||
} else if rule != nil {
|
||||
node.Values = append(node.Values, rule)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Size returns the number of rules in the tree.
|
||||
|
||||
@@ -10164,13 +10164,11 @@ func runStrictnessQueryTestCase(t *testing.T, cases []strictnessQueryTestCase) {
|
||||
if !strings.Contains(err.Error(), tc.expectedErrors.Error()) {
|
||||
t.Fatalf("Expected error %v but got: %v", tc.expectedErrors, err)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error from %v: %v", tc.query, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.note+"_strict", makeTestRunner(tc, true))
|
||||
@@ -11493,11 +11491,9 @@ func TestCompile_DefaultRegoVersion(t *testing.T) {
|
||||
|
||||
if len(tc.expErrs) > 0 {
|
||||
assertErrors(t, compiler.Errors, tc.expErrs, false)
|
||||
} else {
|
||||
if len(compiler.Errors) > 0 {
|
||||
} else if len(compiler.Errors) > 0 {
|
||||
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,11 +113,9 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) {
|
||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -226,11 +224,9 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) {
|
||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,8 +101,8 @@ func (s *Scanner) Keyword(lit string) tokens.Token {
|
||||
func (s *Scanner) AddKeyword(kw string, tok tokens.Token) {
|
||||
s.keywords[kw] = tok
|
||||
|
||||
switch tok {
|
||||
case tokens.Every: // importing 'every' means also importing 'in'
|
||||
if tok == tokens.Every {
|
||||
// importing 'every' means also importing 'in'
|
||||
s.keywords["in"] = tokens.In
|
||||
}
|
||||
}
|
||||
@@ -398,7 +398,7 @@ func (s *Scanner) scanComment() string {
|
||||
end := s.offset - 1
|
||||
// Trim carriage returns that precede the newline
|
||||
if s.offset > 1 && s.bs[s.offset-2] == '\r' {
|
||||
end = end - 1
|
||||
end -= 1
|
||||
}
|
||||
|
||||
return util.ByteSliceToString(s.bs[start:end])
|
||||
|
||||
+3
-3
@@ -134,7 +134,7 @@ func (c parsedTermCache) String() string {
|
||||
s.WriteRune('{')
|
||||
var e *parsedTermCacheItem
|
||||
for e = c.m; e != nil; e = e.next {
|
||||
s.WriteString(fmt.Sprintf("%v", e))
|
||||
s.WriteString(e.String())
|
||||
}
|
||||
s.WriteRune('}')
|
||||
return s.String()
|
||||
@@ -2063,7 +2063,7 @@ func (p *Parser) parseTermPairList(end tokens.Token, r [][2]*Term) [][2]*Term {
|
||||
func (p *Parser) parseTermOp(values ...tokens.Token) *Term {
|
||||
for i := range values {
|
||||
if p.s.tok == values[i] {
|
||||
r := RefTerm(VarTerm(fmt.Sprint(p.s.tok)).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
|
||||
r := RefTerm(VarTerm(p.s.tok.String()).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
|
||||
p.scan()
|
||||
return r
|
||||
}
|
||||
@@ -2612,7 +2612,7 @@ func parseAuthorString(s string) (*AuthorAnnotation, error) {
|
||||
strings.HasSuffix(trailing, emailSuffix) {
|
||||
email = trailing[len(emailPrefix):]
|
||||
email = email[0 : len(email)-len(emailSuffix)]
|
||||
namePartCount = namePartCount - 1
|
||||
namePartCount -= 1
|
||||
}
|
||||
|
||||
name := strings.Join(parts[0:namePartCount], " ")
|
||||
|
||||
+16
-16
@@ -140,7 +140,7 @@ func TestSetTypesWithPodSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAllOfSchemas(t *testing.T) {
|
||||
//Test 1: object schema
|
||||
// Test 1: object schema
|
||||
objectSchemaStaticProps := []*types.StaticProperty{}
|
||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine1", Value: types.S})
|
||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine2", Value: types.S})
|
||||
@@ -151,10 +151,10 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
||||
objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil)
|
||||
|
||||
//Test 2: array schema
|
||||
// Test 2: array schema
|
||||
arrayExpectedType := types.NewArray(nil, types.N)
|
||||
|
||||
//Test 3: parent variation
|
||||
// Test 3: parent variation
|
||||
parentVariationStaticProps := []*types.StaticProperty{}
|
||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
||||
@@ -162,13 +162,13 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
||||
parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil)
|
||||
|
||||
//Test 4: empty schema with allOf
|
||||
// Test 4: empty schema with allOf
|
||||
emptyExpectedType := types.A
|
||||
|
||||
//Tests 5 & 6: schema with array of arrays, object and array as siblings
|
||||
// Tests 5 & 6: schema with array of arrays, object and array as siblings
|
||||
expectedError := errors.New("unable to merge these schemas")
|
||||
|
||||
//Test 7: array of objects
|
||||
// Test 7: array of objects
|
||||
arrayOfObjectsStaticProps := []*types.StaticProperty{}
|
||||
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
||||
@@ -179,7 +179,7 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
innerType := types.NewObject(arrayOfObjectsStaticProps, nil)
|
||||
arrayOfObjectsExpectedType := types.NewArray(nil, innerType)
|
||||
|
||||
//Tests 8 & 9: allOf schema with type not specified
|
||||
// Tests 8 & 9: allOf schema with type not specified
|
||||
objectMissingStaticProps := []*types.StaticProperty{}
|
||||
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
||||
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||
@@ -189,10 +189,10 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil)
|
||||
arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil)
|
||||
|
||||
//Tests 10 & 11: allOf schema with array that contains different types (with and without error)
|
||||
// Tests 10 & 11: allOf schema with array that contains different types (with and without error)
|
||||
arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil)
|
||||
|
||||
//Test 12: array inside of object
|
||||
// Test 12: array inside of object
|
||||
arrayInObjectstaticProps := []*types.StaticProperty{}
|
||||
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "age", Value: types.N})
|
||||
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "name", Value: types.S})
|
||||
@@ -203,7 +203,7 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{
|
||||
types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil)
|
||||
|
||||
//Test 13: allOf inside core schema
|
||||
// Test 13: allOf inside core schema
|
||||
coreStaticProps := []*types.StaticProperty{}
|
||||
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessMe", Value: types.S})
|
||||
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessYou", Value: types.S})
|
||||
@@ -213,12 +213,12 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
outerType = append(outerType, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
||||
coreSchemaExpectedType := types.NewObject(outerType, nil)
|
||||
|
||||
//Tests 14-17: other types besides array and object
|
||||
// Tests 14-17: other types besides array and object
|
||||
expectedStringType := types.NewString()
|
||||
expectedIntegerType := types.NewNumber()
|
||||
expectedBooleanType := types.NewBoolean()
|
||||
|
||||
//Test 18: array with uneven numbers of items children to merge
|
||||
// Test 18: array with uneven numbers of items children to merge
|
||||
expectedUnevenArrayType := types.NewArray([]types.Type{types.N, types.N, types.S}, nil)
|
||||
|
||||
tests := []struct {
|
||||
@@ -357,7 +357,7 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseSchemaUntypedField(t *testing.T) {
|
||||
//Expected type is: object<foo: any>
|
||||
// Expected type is: object<foo: any>
|
||||
staticProps := []*types.StaticProperty{}
|
||||
staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.A})
|
||||
expectedType := types.NewObject(staticProps, nil)
|
||||
@@ -365,13 +365,13 @@ func TestParseSchemaUntypedField(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseSchemaNoChildren(t *testing.T) {
|
||||
//Expected type is: object[any: any]
|
||||
// Expected type is: object[any: any]
|
||||
expectedType := types.NewObject(nil, &types.DynamicProperty{Key: types.A, Value: types.A})
|
||||
testParseSchema(t, noChildrenObjectSchema, expectedType, nil)
|
||||
}
|
||||
|
||||
func TestParseSchemaArrayNoItems(t *testing.T) {
|
||||
//Expected type is: object<b: array[any]>
|
||||
// Expected type is: object<b: array[any]>
|
||||
staticProps := []*types.StaticProperty{}
|
||||
staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.A)})
|
||||
expectedType := types.NewObject(staticProps, nil)
|
||||
@@ -379,7 +379,7 @@ func TestParseSchemaArrayNoItems(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseSchemaBooleanField(t *testing.T) {
|
||||
//Expected type is: object<a: boolean>
|
||||
// Expected type is: object<a: boolean>
|
||||
staticProps := []*types.StaticProperty{}
|
||||
staticProps = append(staticProps, &types.StaticProperty{Key: "a", Value: types.B})
|
||||
expectedType := types.NewObject(staticProps, nil)
|
||||
|
||||
+7
-7
@@ -1391,14 +1391,14 @@ func (arr *Array) String() string {
|
||||
|
||||
defer sbPool.Put(sb)
|
||||
|
||||
sb.WriteRune('[')
|
||||
sb.WriteByte('[')
|
||||
for i, e := range arr.elems {
|
||||
if i > 0 {
|
||||
sb.WriteString(", ")
|
||||
}
|
||||
sb.WriteString(e.String())
|
||||
}
|
||||
sb.WriteRune(']')
|
||||
sb.WriteByte(']')
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
@@ -1589,14 +1589,14 @@ func (s *set) String() string {
|
||||
|
||||
defer sbPool.Put(sb)
|
||||
|
||||
sb.WriteRune('{')
|
||||
sb.WriteByte('{')
|
||||
for i := range s.sortedKeys() {
|
||||
if i > 0 {
|
||||
sb.WriteString(", ")
|
||||
}
|
||||
sb.WriteString(s.keys[i].Value.String())
|
||||
}
|
||||
sb.WriteRune('}')
|
||||
sb.WriteByte('}')
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
@@ -2217,7 +2217,7 @@ type objectElem struct {
|
||||
type objectElemSlice []*objectElem
|
||||
|
||||
func (s objectElemSlice) Less(i, j int) bool { return Compare(s[i].key.Value, s[j].key.Value) < 0 }
|
||||
func (s objectElemSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
||||
func (s objectElemSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s objectElemSlice) Len() int { return len(s) }
|
||||
|
||||
// Item is a helper for constructing an tuple containing two Terms
|
||||
@@ -2502,7 +2502,7 @@ func (obj *object) String() string {
|
||||
|
||||
defer sbPool.Put(sb)
|
||||
|
||||
sb.WriteRune('{')
|
||||
sb.WriteByte('{')
|
||||
|
||||
for i, elem := range obj.sortedKeys() {
|
||||
if i > 0 {
|
||||
@@ -2512,7 +2512,7 @@ func (obj *object) String() string {
|
||||
sb.WriteString(": ")
|
||||
sb.WriteString(elem.value.String())
|
||||
}
|
||||
sb.WriteRune('}')
|
||||
sb.WriteByte('}')
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
@@ -324,8 +324,8 @@ func BenchmarkObjectConstruction(b *testing.B) {
|
||||
for i := range n {
|
||||
es = append(es, struct{ k, v int }{i, i})
|
||||
}
|
||||
rand.New(rand.NewSource(seed)) // Seed the PRNG.
|
||||
rand.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] })
|
||||
r := rand.New(rand.NewSource(seed)) // Seed the PRNG.
|
||||
r.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] })
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
obj := NewObject()
|
||||
|
||||
+2
-3
@@ -867,7 +867,6 @@ func TestSetConcurrentReads(t *testing.T) {
|
||||
numbers[i] = IntNumberTerm(i)
|
||||
}
|
||||
// Shuffle numbers array for random insertion order.
|
||||
rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
||||
rand.Shuffle(len(numbers), func(i, j int) {
|
||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||
})
|
||||
@@ -909,8 +908,8 @@ func TestObjectConcurrentReads(t *testing.T) {
|
||||
numbers[i] = IntNumberTerm(i)
|
||||
}
|
||||
// Shuffle numbers array for random insertion order.
|
||||
rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
||||
rand.Shuffle(len(numbers), func(i, j int) {
|
||||
r := rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
||||
r.Shuffle(len(numbers), func(i, j int) {
|
||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||
})
|
||||
// Build an object with numbers in unsorted order.
|
||||
|
||||
@@ -599,11 +599,9 @@ func TestReadWithSignatures(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,11 +52,9 @@ func TestValidateAndInjectDefaultsVerificationConfig(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(tc.vc.PublicKeys, tc.publicKeys) {
|
||||
t.Fatalf("Expected public keys %v but got %v", tc.publicKeys, tc.vc.PublicKeys)
|
||||
@@ -99,11 +97,9 @@ func TestGetPublicKey(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(kc, tc.kc) {
|
||||
t.Fatalf("Expected key config %v but got %v", tc.kc, kc)
|
||||
@@ -328,7 +324,7 @@ func TestGetClaimsErrors(t *testing.T) {
|
||||
}
|
||||
|
||||
test.WithTempFS(files, func(rootDir string) {
|
||||
//json unmarshal error
|
||||
// json unmarshal error
|
||||
sc := NewSigningConfig("secret", "HS256", filepath.Join(rootDir, "claims.json"))
|
||||
_, err := sc.GetClaims()
|
||||
if err == nil {
|
||||
|
||||
+1
-3
@@ -101,12 +101,10 @@ func generatePayload(files []FileInfo, sc *SigningConfig, keyID string) ([]byte,
|
||||
for claim, value := range claims {
|
||||
payload[claim] = value
|
||||
}
|
||||
} else {
|
||||
if keyID != "" {
|
||||
} else if keyID != "" {
|
||||
// keyid claim is deprecated but include it for backwards compatibility.
|
||||
payload["keyid"] = keyID
|
||||
}
|
||||
}
|
||||
return json.Marshal(payload)
|
||||
}
|
||||
|
||||
|
||||
@@ -6621,11 +6621,9 @@ func TestDoDFS(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,11 +63,9 @@ func TestVerifyBundleSignature(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -210,11 +208,9 @@ yQjtQ8mbDOsiLLvh7wIDAQAB==
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -277,11 +273,9 @@ func TestVerifyBundleFile(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func BenchmarkCompileDynamicPolicy(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func generateDynamicPolicyBenchmarkData(N int) map[string]string {
|
||||
func generateDynamicPolicyBenchmarkData(n int) map[string]string {
|
||||
files := map[string]string{
|
||||
"main.rego": `
|
||||
package main
|
||||
@@ -56,19 +56,19 @@ func generateDynamicPolicyBenchmarkData(N int) map[string]string {
|
||||
}`,
|
||||
}
|
||||
|
||||
for i := range N {
|
||||
for i := range n {
|
||||
files[fmt.Sprintf("policy%d.rego", i)] = generateDynamicMockPolicy(i)
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
func generateDynamicMockPolicy(N int) string {
|
||||
func generateDynamicMockPolicy(n int) string {
|
||||
return fmt.Sprintf(`package policies["%d"]["%d"].policy%d
|
||||
denies contains x if {
|
||||
input.attribute == "%d"
|
||||
x := "policy%d"
|
||||
}`, N, N, N, N, N)
|
||||
}`, n, n, n, n, n)
|
||||
}
|
||||
|
||||
func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
||||
@@ -95,13 +95,13 @@ func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func generateLargePartialRuleBenchmarkData(N int) map[string]string {
|
||||
func generateLargePartialRuleBenchmarkData(n int) map[string]string {
|
||||
var policy strings.Builder
|
||||
policy.Grow((140 * N) + 100) // Each rule takes around 130 characters.
|
||||
policy.Grow((140 * n) + 100) // Each rule takes around 130 characters.
|
||||
|
||||
policy.WriteString(`package example.large.partial.rules.policy["dynamic_part"].main`)
|
||||
policy.WriteString("\n\n")
|
||||
for i := range N {
|
||||
for i := range n {
|
||||
policy.WriteString(generateLargePartialRuleMockRule(i))
|
||||
policy.WriteString("\n\n")
|
||||
}
|
||||
@@ -115,11 +115,11 @@ func generateLargePartialRuleBenchmarkData(N int) map[string]string {
|
||||
return files
|
||||
}
|
||||
|
||||
func generateLargePartialRuleMockRule(N int) string {
|
||||
func generateLargePartialRuleMockRule(n int) string {
|
||||
return fmt.Sprintf(`deny contains [resource, errormsg] if {
|
||||
resource := "example.%d"
|
||||
i := %d
|
||||
i %% 2 != 0
|
||||
errormsg := "denied because %d is an odd number."
|
||||
}`, N, N, N)
|
||||
}`, n, n, n)
|
||||
}
|
||||
|
||||
@@ -481,11 +481,9 @@ p contains "B" if {
|
||||
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1246,11 +1244,9 @@ func TestCompilerOptimizationL2(t *testing.T) {
|
||||
if !compiler.bundle.Modules[1].Parsed.Equal(prunedExp) {
|
||||
t.Fatalf("expected pruned module to be:\n\n%v\n\ngot:\n\n%v", prunedExp, compiler.bundle.Modules[1])
|
||||
}
|
||||
} else {
|
||||
if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) {
|
||||
} else if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) {
|
||||
t.Fatalf("expected optimized module to be:\n\n%v\n\ngot:\n\n%v", optimizedExp, compiler.bundle.Modules[1])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ func (c Config) PluginNames() (result []string) {
|
||||
|
||||
// PluginsEnabled returns true if one or more plugin features are enabled.
|
||||
//
|
||||
// Deprecated. Use PluginNames instead.
|
||||
// Deprecated: Use PluginNames instead.
|
||||
func (c Config) PluginsEnabled() bool {
|
||||
return c.Bundle != nil || c.Bundles != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0
|
||||
}
|
||||
|
||||
+2
-7
@@ -299,12 +299,7 @@ func hasFileLocation(loc *ast.Location) bool {
|
||||
|
||||
// Check the expression and return true if it should be included in the coverage report
|
||||
func includeExprInCoverage(x *ast.Expr) bool {
|
||||
includeExprType := true
|
||||
_, excludeExprType := x.Terms.(*ast.SomeDecl)
|
||||
|
||||
switch x.Terms.(type) {
|
||||
case *ast.SomeDecl:
|
||||
includeExprType = false
|
||||
}
|
||||
|
||||
return includeExprType && hasFileLocation(x.Location)
|
||||
return !excludeExprType && hasFileLocation(x.Location)
|
||||
}
|
||||
|
||||
@@ -850,7 +850,7 @@ func (s *session) AddBreakpoint(loc location.Location) (Breakpoint, error) {
|
||||
return s.breakpoints.add(loc), nil
|
||||
}
|
||||
|
||||
func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
||||
func (s *session) RemoveBreakpoint(id BreakpointID) (Breakpoint, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
@@ -858,9 +858,9 @@ func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
||||
s.mtx.Lock()
|
||||
defer s.mtx.Unlock()
|
||||
|
||||
bp := s.breakpoints.remove(ID)
|
||||
bp := s.breakpoints.remove(id)
|
||||
if bp == nil {
|
||||
return nil, fmt.Errorf("breakpoint %d not found", ID)
|
||||
return nil, fmt.Errorf("breakpoint %d not found", id)
|
||||
}
|
||||
|
||||
return bp, nil
|
||||
|
||||
@@ -2096,12 +2096,10 @@ func assertVariables(t *testing.T, s Session, variables []Variable, exp map[stri
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
assertVariables(t, s, vars, expVar.children)
|
||||
} else {
|
||||
if v.VariablesReference() != 0 {
|
||||
} else if v.VariablesReference() != 0 {
|
||||
t.Errorf("Expected zero variables reference")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupDebuggerSession(ctx context.Context, stk stack, launchProperties LaunchProperties, eh EventHandler,
|
||||
|
||||
@@ -232,8 +232,7 @@ func (d *Downloader) loop(ctx context.Context) {
|
||||
|
||||
if err != nil {
|
||||
delay = util.DefaultBackoff(float64(minRetryDelay), float64(*d.config.Polling.MaxDelaySeconds), retry)
|
||||
} else {
|
||||
if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil {
|
||||
} else if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil {
|
||||
// revert the response header timeout value on the http client's transport
|
||||
if *d.client.Config().ResponseHeaderTimeoutSeconds == 0 {
|
||||
d.client = d.client.SetResponseHeaderTimeout(&d.respHdrTimeoutSec)
|
||||
@@ -242,7 +241,6 @@ func (d *Downloader) loop(ctx context.Context) {
|
||||
max := float64(*d.config.Polling.MaxDelaySeconds)
|
||||
delay = time.Duration(((max - min) * rand.Float64()) + min)
|
||||
}
|
||||
}
|
||||
|
||||
d.logger.Debug("Waiting %v before next download/retry.", delay)
|
||||
|
||||
|
||||
+1
-3
@@ -63,13 +63,11 @@ func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) {
|
||||
var parserOpts ast.ParserOptions
|
||||
if opts.ParserOptions != nil {
|
||||
parserOpts = *opts.ParserOptions
|
||||
} else {
|
||||
if regoVersion == ast.RegoV1 {
|
||||
} else if regoVersion == ast.RegoV1 {
|
||||
// If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported.
|
||||
// Otherwise, we'll default to the default rego-version.
|
||||
parserOpts.RegoVersion = ast.RegoV1
|
||||
}
|
||||
}
|
||||
|
||||
if parserOpts.RegoVersion == ast.RegoUndefined {
|
||||
parserOpts.RegoVersion = ast.DefaultRegoVersion
|
||||
|
||||
@@ -72,11 +72,9 @@ func TestParseKeysConfig(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(kc, tc.result) {
|
||||
t.Fatalf("Expected key config %v but got %v", tc.result, kc)
|
||||
|
||||
@@ -504,8 +504,8 @@ func TestLoadDirRecursive(t *testing.T) {
|
||||
}
|
||||
mod1 := ast.MustParseModule(files["/a/e.rego"])
|
||||
mod2 := ast.MustParseModule(files["/b/d/e.rego"])
|
||||
expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/a/e.rego"))].Parsed
|
||||
expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/b/d/e.rego"))].Parsed
|
||||
expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "a", "e.rego"))].Parsed
|
||||
expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "b", "d", "e.rego"))].Parsed
|
||||
if !mod1.Equal(expectedMod1) {
|
||||
t.Fatalf("Expected:\n%v\n\nGot:\n%v", expectedMod1, mod1)
|
||||
}
|
||||
@@ -807,7 +807,7 @@ func TestAsBundleWithDir(t *testing.T) {
|
||||
}
|
||||
|
||||
expectedModulePaths := map[string]struct{}{
|
||||
filepath.Join(rootDir, "foo/policy.rego"): {},
|
||||
filepath.Join(rootDir, "foo", "policy.rego"): {},
|
||||
filepath.Join(rootDir, "base.rego"): {},
|
||||
}
|
||||
for _, mf := range b.Modules {
|
||||
@@ -849,7 +849,7 @@ func TestAsBundleWithFileURLDir(t *testing.T) {
|
||||
t.Fatalf("expected 1 modules, got %d", len(b.Modules))
|
||||
}
|
||||
expectedModulePaths := map[string]struct{}{
|
||||
filepath.Join(rootDir, "/foo/policy.rego"): {},
|
||||
filepath.Join(rootDir, "foo", "policy.rego"): {},
|
||||
}
|
||||
for _, mf := range b.Modules {
|
||||
if _, found := expectedModulePaths[mf.Path]; !found {
|
||||
@@ -977,11 +977,9 @@ func TestCheckForUNCPath(t *testing.T) {
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,11 +175,9 @@ func (c *Config) validateAndInjectDefaults(services []string, keys map[string]*k
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid configuration for bundle %q: %s", name, err.Error())
|
||||
}
|
||||
} else {
|
||||
if len(keys) > 0 {
|
||||
} else if len(keys) > 0 {
|
||||
source.Signing = bundle.NewVerificationConfig(keys, "", "", nil)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(source.Resource, "file://") {
|
||||
if _, err := url.Parse(source.Resource); err != nil {
|
||||
|
||||
@@ -434,9 +434,7 @@ func (p *Plugin) loadAndActivateBundlesFromDisk(ctx context.Context) {
|
||||
|
||||
func (p *Plugin) newDownloader(name string, source *Source, bundles map[string]*Source) Loader {
|
||||
|
||||
if u, err := url.Parse(source.Resource); err == nil {
|
||||
switch u.Scheme {
|
||||
case "file":
|
||||
if u, err := url.Parse(source.Resource); err == nil && u.Scheme == "file" {
|
||||
return &fileLoader{
|
||||
name: name,
|
||||
path: u.Path,
|
||||
@@ -446,7 +444,6 @@ func (p *Plugin) newDownloader(name string, source *Source, bundles map[string]*
|
||||
bundleParserOpts: p.manager.ParserOptions(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
conf := source.Config
|
||||
client := p.manager.Client(source.Service)
|
||||
|
||||
@@ -921,11 +921,9 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
|
||||
if ast.Compare(result, expected) != 0 {
|
||||
t.Fatalf("expected data to be %v but got %v", expected, result)
|
||||
}
|
||||
} else {
|
||||
if !reflect.DeepEqual(result, mockBundle1.Data["p"]) {
|
||||
} else if !reflect.DeepEqual(result, mockBundle1.Data["p"]) {
|
||||
t.Fatalf("expected data to be %v but got %v", mockBundle1.Data, result)
|
||||
}
|
||||
}
|
||||
|
||||
result, err = storage.ReadOne(ctx, manager.Store, storage.Path{"q"})
|
||||
if err != nil {
|
||||
@@ -937,11 +935,9 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
|
||||
if ast.Compare(result, expected) != 0 {
|
||||
t.Fatalf("expected data to be %v but got %v", expected, result)
|
||||
}
|
||||
} else {
|
||||
if !reflect.DeepEqual(result, mockBundle2.Data["q"]) {
|
||||
} else if !reflect.DeepEqual(result, mockBundle2.Data["q"]) {
|
||||
t.Fatalf("expected data to be %v but got %v", mockBundle2.Data, result)
|
||||
}
|
||||
}
|
||||
|
||||
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
||||
defer manager.Store.Abort(ctx, txn)
|
||||
@@ -1348,7 +1344,7 @@ func TestStop(t *testing.T) {
|
||||
|
||||
serviceName := "test-svc"
|
||||
err := manager.Reconfigure(&config.Config{
|
||||
Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)),
|
||||
Services: []byte(fmt.Sprintf("{%q:{ \"url\": %q}}", serviceName, ts.URL+tsURLBase)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Error configuring plugin manager: %s", err)
|
||||
@@ -3008,7 +3004,7 @@ p contains x`),
|
||||
|
||||
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
||||
|
||||
_, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego"))
|
||||
_, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego"))
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
@@ -3037,7 +3033,7 @@ p contains x`),
|
||||
|
||||
txn = storage.NewTransactionOrDie(ctx, manager.Store)
|
||||
|
||||
_, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego"))
|
||||
_, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego"))
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
@@ -3149,7 +3145,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) {
|
||||
ids, err := manager.Store.ListPolicies(ctx, txn)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !slices.Equal([]string{filepath.Join(bundleName, "/example2.rego")}, ids) {
|
||||
} else if !slices.Equal([]string{filepath.Join(bundleName, "example2.rego")}, ids) {
|
||||
return errors.New("expected updated policy ids")
|
||||
}
|
||||
data, err := manager.Store.Read(ctx, txn, storage.Path{})
|
||||
@@ -3813,7 +3809,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
||||
} else {
|
||||
expData = util.MustUnmarshalJSON([]byte(exp))
|
||||
}
|
||||
expIDs := []string{filepath.Join(bundleName, "bundle/id1"), "some/id2", "some/id3"}
|
||||
expIDs := []string{filepath.Join(bundleName, "bundle", "id1"), "some/id2", "some/id3"}
|
||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil)
|
||||
|
||||
// Activate a bundle that is scoped to a/a3 ad a/a6. Include a function
|
||||
@@ -3853,7 +3849,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
||||
} else {
|
||||
expData = util.MustUnmarshalJSON([]byte(exp))
|
||||
}
|
||||
expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "some/id3"}
|
||||
expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "some/id3"}
|
||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
||||
map[string]interface{}{
|
||||
"a": map[string]interface{}{"a1": "deadbeef"},
|
||||
@@ -3877,7 +3873,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
||||
|
||||
// Ensure bundle activation failed by checking that previous revision is
|
||||
// still active.
|
||||
expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "not_scoped", "some/id3"}
|
||||
expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "not_scoped", "some/id3"}
|
||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
||||
map[string]interface{}{
|
||||
"a": map[string]interface{}{"a1": "deadbeef"},
|
||||
@@ -3943,7 +3939,7 @@ func TestPluginSetCompilerOnContext(t *testing.T) {
|
||||
t.Fatalf("Expected 2 events but got: %+v", events)
|
||||
} else if compiler := plugins.GetCompilerOnContext(events[1].Context); compiler == nil {
|
||||
t.Fatalf("Expected compiler on 2nd event but got: %+v", events)
|
||||
} else if !compiler.Modules[filepath.Join(bundleName, "/test.rego")].Equal(exp) {
|
||||
} else if !compiler.Modules[filepath.Join(bundleName, "test.rego")].Equal(exp) {
|
||||
t.Fatalf("Expected module on compiler but got: %v", compiler.Modules)
|
||||
}
|
||||
}
|
||||
@@ -5420,11 +5416,9 @@ p contains 7 if {
|
||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if s.LastSuccessfulActivation.IsZero() {
|
||||
} else if s.LastSuccessfulActivation.IsZero() {
|
||||
t.Fatal("expected successful activation")
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -5737,11 +5731,9 @@ p contains 7 if {
|
||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if s.LastSuccessfulActivation.IsZero() {
|
||||
} else if s.LastSuccessfulActivation.IsZero() {
|
||||
t.Fatal("expected successful activation")
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -5942,11 +5934,9 @@ p contains 7 if {
|
||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if s.LastSuccessfulActivation.IsZero() {
|
||||
} else if s.LastSuccessfulActivation.IsZero() {
|
||||
t.Fatal("expected successful activation")
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -6236,11 +6226,9 @@ p contains 7 if {
|
||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if s.LastSuccessfulActivation.IsZero() {
|
||||
} else if s.LastSuccessfulActivation.IsZero() {
|
||||
t.Fatal("expected successful activation")
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -101,11 +101,9 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid configuration for discovery service: %s", err.Error())
|
||||
}
|
||||
} else {
|
||||
if len(confKeys) > 0 {
|
||||
} else if len(confKeys) > 0 {
|
||||
c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil)
|
||||
}
|
||||
}
|
||||
|
||||
if c.Resource != nil {
|
||||
c.path = *c.Resource
|
||||
@@ -126,9 +124,9 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
|
||||
c.service = service
|
||||
|
||||
if c.Decision != nil {
|
||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Decision, "/"), "/", ".", -1))
|
||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Decision, "/"), "/", "."))
|
||||
} else if c.Name != nil {
|
||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Name, "/"), "/", ".", -1))
|
||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Name, "/"), "/", "."))
|
||||
} else {
|
||||
c.query = ast.DefaultRootDocument.String()
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ import (
|
||||
"github.com/open-policy-agent/opa/v1/logging/test"
|
||||
"github.com/open-policy-agent/opa/v1/metrics"
|
||||
"github.com/open-policy-agent/opa/v1/plugins"
|
||||
"github.com/open-policy-agent/opa/v1/plugins/bundle"
|
||||
bundlePlugin "github.com/open-policy-agent/opa/v1/plugins/bundle"
|
||||
"github.com/open-policy-agent/opa/v1/plugins/logs"
|
||||
"github.com/open-policy-agent/opa/v1/plugins/status"
|
||||
@@ -3339,11 +3338,9 @@ bundles:
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3406,11 +3403,9 @@ decision_logs:
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3479,11 +3474,9 @@ status:
|
||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3832,8 +3825,8 @@ func TestListeners(t *testing.T) {
|
||||
|
||||
ensurePluginState(t, disco, plugins.StateNotReady)
|
||||
|
||||
var status *bundle.Status
|
||||
disco.RegisterListener("testlistener", func(s bundle.Status) {
|
||||
var status *bundlePlugin.Status
|
||||
disco.RegisterListener("testlistener", func(s bundlePlugin.Status) {
|
||||
status = &s
|
||||
})
|
||||
|
||||
@@ -3954,7 +3947,7 @@ func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metr
|
||||
rego.Metrics(m),
|
||||
)
|
||||
|
||||
//Run evaluation.
|
||||
// Run evaluation.
|
||||
rs, err := r.Eval(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -183,8 +183,8 @@ func (enc *chunkEncoder) reset() ([][]byte, error) {
|
||||
enc.initialize()
|
||||
|
||||
var result [][]byte
|
||||
for _, event := range events {
|
||||
chunk, err := enc.Write(event)
|
||||
for i := range events {
|
||||
chunk, err := enc.Write(events[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -893,8 +893,8 @@ func (p *Plugin) oneShot(ctx context.Context) (ok bool, err error) {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, event := range events {
|
||||
p.encodeAndBufferEvent(event)
|
||||
for i := range events {
|
||||
p.encodeAndBufferEvent(events[i])
|
||||
}
|
||||
} else {
|
||||
// requeue the chunk
|
||||
|
||||
@@ -803,7 +803,7 @@ func (m *Manager) Reconfigure(config *config.Config) error {
|
||||
|
||||
m.Config = config
|
||||
m.interQueryBuiltinCacheConfig = interQueryBuiltinCacheConfig
|
||||
for name, client := range services {
|
||||
for name, client := range services { //nolint:gocritic
|
||||
m.services[name] = client
|
||||
}
|
||||
|
||||
|
||||
@@ -206,7 +206,7 @@ func convertSignatureToBase64(alg string, der []byte) (string, error) {
|
||||
return signatureData, nil
|
||||
}
|
||||
|
||||
func pointsFromDER(der []byte) (R, S *big.Int, err error) {
|
||||
func pointsFromDER(der []byte) (R, S *big.Int, err error) { //nolint:gocritic
|
||||
R, S = &big.Int{}, &big.Int{}
|
||||
data := asn1.RawValue{}
|
||||
if _, err := asn1.Unmarshal(der, &data); err != nil {
|
||||
@@ -394,12 +394,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) SignWithKMS(ctx context.Context, pa
|
||||
|
||||
encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf)
|
||||
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
||||
input := strings.Join(
|
||||
[]string{
|
||||
encodedHdr,
|
||||
encodedPayload,
|
||||
}, ".",
|
||||
)
|
||||
input := encodedHdr + "." + encodedPayload
|
||||
digest, err := messageDigest([]byte(input), ap.AWSKmsKey.Algorithm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -628,7 +623,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) requestToken(ctx context.Context) (
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if strings.ToLower(tokenResponse.TokenType) != "bearer" {
|
||||
if !strings.EqualFold(tokenResponse.TokenType, "bearer") {
|
||||
return nil, errors.New("unknown token type returned from token endpoint")
|
||||
}
|
||||
|
||||
|
||||
@@ -341,7 +341,7 @@ func (c Client) Do(ctx context.Context, method, path string) (*http.Response, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(string(dump)) < defaultResponseSizeLimitBytes {
|
||||
if len(dump) < defaultResponseSizeLimitBytes {
|
||||
c.loggerFields["response"] = string(dump)
|
||||
} else {
|
||||
c.loggerFields["response"] = fmt.Sprintf("%v...", string(dump[:defaultResponseSizeLimitBytes]))
|
||||
|
||||
@@ -939,11 +939,9 @@ func TestDoWithResponseHeaderTimeout(t *testing.T) {
|
||||
if !strings.Contains(err.Error(), tc.errMsg) {
|
||||
t.Fatalf("Expected error %v but got %v", tc.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2013,11 +2011,9 @@ func TestAWSCredentialServiceChain(t *testing.T) {
|
||||
if !strings.Contains(err.Error(), tc.errMsg) {
|
||||
t.Fatalf("Expected error message %v but got %v", tc.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
} else if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2149,7 +2149,7 @@ func TestRegoEvalWithBundle(t *testing.T) {
|
||||
t.Fatalf("expected %d modules, found %d", exp, act)
|
||||
}
|
||||
for act := range mods {
|
||||
if exp := filepath.Join(path, "x/x.rego"); exp != act {
|
||||
if exp := filepath.Join(path, "x", "x.rego"); exp != act {
|
||||
t.Errorf("expected module name %q, got %q", exp, act)
|
||||
}
|
||||
}
|
||||
@@ -2176,7 +2176,7 @@ func TestRegoEvalWithBundleURL(t *testing.T) {
|
||||
t.Fatalf("expected %d modules, found %d", exp, act)
|
||||
}
|
||||
for act := range mods {
|
||||
if exp := filepath.Join(path, "x/x.rego"); exp != act {
|
||||
if exp := filepath.Join(path, "x", "x.rego"); exp != act {
|
||||
t.Errorf("expected module name %q, got %q", exp, act)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -513,7 +513,7 @@ func (r *REPL) cmdShow(args []string) error {
|
||||
}
|
||||
fmt.Fprint(r.output, string(bs))
|
||||
return nil
|
||||
} else if strings.Compare(args[0], "debug") == 0 {
|
||||
} else if args[0] == "debug" {
|
||||
debug := replDebugState{
|
||||
Explain: r.explain,
|
||||
Metrics: r.metricsEnabled(),
|
||||
@@ -707,7 +707,7 @@ func (r *REPL) unsetRule(ctx context.Context, name ast.Var) (bool, error) {
|
||||
}
|
||||
|
||||
func (r *REPL) unsetPackage(_ context.Context, pkg *ast.Package) (bool, error) {
|
||||
path := fmt.Sprintf("%v", pkg.Path)
|
||||
path := pkg.Path.String()
|
||||
_, ok := r.modules[path]
|
||||
if ok {
|
||||
delete(r.modules, path)
|
||||
@@ -1418,10 +1418,10 @@ func newCommand(line string) *command {
|
||||
return nil
|
||||
}
|
||||
inputCommand := strings.ToLower(p[0])
|
||||
for _, c := range builtin {
|
||||
if c.name == inputCommand {
|
||||
for i := range builtin {
|
||||
if builtin[i].name == inputCommand {
|
||||
return &command{
|
||||
op: c.name,
|
||||
op: builtin[i].name,
|
||||
args: p[1:],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestRegisterPlugin(t *testing.T) {
|
||||
|
||||
RegisterPlugin("test", Factory{})
|
||||
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
rt, err := NewRuntime(context.Background(), params)
|
||||
if err != nil {
|
||||
@@ -98,7 +98,7 @@ func TestRegisterPluginNotStartedWithoutConfig(t *testing.T) {
|
||||
|
||||
RegisterPlugin("test", Factory{})
|
||||
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
rt, err := NewRuntime(context.Background(), params)
|
||||
if err != nil {
|
||||
@@ -130,7 +130,7 @@ func TestRegisterPluginBadBootConfig(t *testing.T) {
|
||||
|
||||
RegisterPlugin("test", Factory{})
|
||||
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
_, err := NewRuntime(context.Background(), params)
|
||||
if err == nil || !strings.Contains(err.Error(), "config error: test") {
|
||||
@@ -151,7 +151,7 @@ func TestWaitPluginsReady(t *testing.T) {
|
||||
RegisterPlugin("test", Factory{})
|
||||
|
||||
params := NewParams()
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
rt, err := NewRuntime(context.Background(), params)
|
||||
if err != nil {
|
||||
|
||||
@@ -697,7 +697,7 @@ func (rt *Runtime) Serve(ctx context.Context) error {
|
||||
return rt.gracefulServerShutdown(rt.server)
|
||||
case err := <-errc:
|
||||
rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Listener failed.")
|
||||
os.Exit(1)
|
||||
os.Exit(1) //nolint:gocritic
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -744,7 +744,7 @@ func (rt *Runtime) StartREPL(ctx context.Context) {
|
||||
if rt.Params.Watch {
|
||||
if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadPrinter(rt.Params.Output)); err != nil {
|
||||
fmt.Fprintln(rt.Params.Output, "error opening watch:", err)
|
||||
os.Exit(1)
|
||||
os.Exit(1) //nolint:gocritic
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -140,11 +140,9 @@ func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) {
|
||||
if ast.Compare(val, exp) == 0 {
|
||||
return // success
|
||||
}
|
||||
} else {
|
||||
if reflect.DeepEqual(val, expected) {
|
||||
} else if reflect.DeepEqual(val, expected) {
|
||||
return // success
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1402,7 +1400,7 @@ func TestGracefulTracerShutdown(t *testing.T) {
|
||||
logger := testLog.New()
|
||||
|
||||
params := NewParams()
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
params.Addrs = &[]string{"localhost:0"}
|
||||
params.GracefulShutdownPeriod = 1
|
||||
params.Logger = logger
|
||||
@@ -1603,7 +1601,7 @@ func TestRuntimeWithExplicitMetricConfiguration(t *testing.T) {
|
||||
|
||||
test.WithTempFS(fs, func(testDirRoot string) {
|
||||
params := NewParams()
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
_, err := NewRuntime(context.Background(), params)
|
||||
if err != nil {
|
||||
@@ -1619,7 +1617,7 @@ func TestRuntimeWithExplicitBadMetricConfiguration(t *testing.T) {
|
||||
|
||||
test.WithTempFS(fs, func(testDirRoot string) {
|
||||
params := NewParams()
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
||||
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||
|
||||
_, err := NewRuntime(context.Background(), params)
|
||||
if err == nil {
|
||||
|
||||
+1
-1
@@ -276,7 +276,7 @@ func (s *Server) handleOCIBundles(w http.ResponseWriter, r *http.Request) {
|
||||
tag := "" // image tag used in request path verification
|
||||
repo := "" // image repo used in request path verification
|
||||
var buf bytes.Buffer
|
||||
//get first key that matches request url pattern
|
||||
// get first key that matches request url pattern
|
||||
for key := range s.bundles {
|
||||
// extract tag
|
||||
parsedRef := strings.Split(key, ":")
|
||||
|
||||
@@ -268,13 +268,9 @@ func TestBasicEscapeError(t *testing.T) {
|
||||
|
||||
req.URL.Path = `/invalid/path/foo%LALALA`
|
||||
|
||||
compiler := func() *ast.Compiler {
|
||||
return ast.NewCompiler()
|
||||
}
|
||||
|
||||
store := inmem.New()
|
||||
|
||||
NewBasic(&mockHandler{}, compiler, store).ServeHTTP(recorder, req)
|
||||
NewBasic(&mockHandler{}, ast.NewCompiler, store).ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("Expected bad request but got: %v", recorder)
|
||||
|
||||
@@ -131,7 +131,7 @@ func (w *compressResponseWriter) doCompressedResponse() error {
|
||||
w.Header().Del(contentLengthHeader)
|
||||
w.writeHeader()
|
||||
// there's nothing to write
|
||||
if len(w.buffer) <= 0 {
|
||||
if len(w.buffer) == 0 {
|
||||
return nil
|
||||
}
|
||||
gzipWriter := gzipPool.Get().(*gzip.Writer)
|
||||
|
||||
+3
-3
@@ -581,9 +581,9 @@ func (b *baseHTTPListener) Type() httpListenerType {
|
||||
return b.t
|
||||
}
|
||||
|
||||
func isMinTLSVersionSupported(TLSVersion uint16) bool {
|
||||
func isMinTLSVersionSupported(tlsVersion uint16) bool {
|
||||
for _, version := range supportedTLSVersions {
|
||||
if TLSVersion == version {
|
||||
if tlsVersion == version {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -2722,7 +2722,7 @@ func getBoolParam(url *url.URL, name string, ifEmpty bool) bool {
|
||||
}
|
||||
|
||||
for _, x := range p {
|
||||
if strings.ToLower(x) == "true" {
|
||||
if strings.EqualFold(x, "true") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ func (t TraceV1) MarshalJSON() ([]byte, error) {
|
||||
|
||||
// UnmarshalJSON unmarshals the TraceV1 from a JSON representation.
|
||||
func (t *TraceV1) UnmarshalJSON(b []byte) error {
|
||||
*t = TraceV1(b[:])
|
||||
*t = TraceV1(b)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -56,8 +56,7 @@ func (err *Error) Error() string {
|
||||
|
||||
// IsNotFound returns true if this error is a NotFoundErr.
|
||||
func IsNotFound(err error) bool {
|
||||
switch err := err.(type) {
|
||||
case *Error:
|
||||
if err, ok := err.(*Error); ok {
|
||||
return err.Code == NotFoundErr
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -1109,11 +1109,9 @@ func TestInMemoryTriggers(t *testing.T) {
|
||||
if err != nil || ast.Compare(expAstValue, result) != 0 {
|
||||
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
||||
}
|
||||
} else {
|
||||
if err != nil || !reflect.DeepEqual(result, expectedValue) {
|
||||
} else if err != nil || !reflect.DeepEqual(result, expectedValue) {
|
||||
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
||||
}
|
||||
}
|
||||
event = evt
|
||||
},
|
||||
})
|
||||
|
||||
@@ -89,7 +89,7 @@ func copyEntry(sourceRoot string, sourceRegoVersion ast.RegoVersion, e os.DirEnt
|
||||
}
|
||||
|
||||
// Format test modules
|
||||
for _, testCase := range testCases.Cases {
|
||||
for _, testCase := range testCases.Cases { //nolint:gocritic
|
||||
for i, module := range testCase.Modules {
|
||||
bs, err := format.SourceWithOpts(fmt.Sprintf("mod%d.rego", i), []byte(module),
|
||||
format.Opts{
|
||||
|
||||
@@ -82,7 +82,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
queryPath := strings.Replace(testAuthz.AllowQuery, ".", "/", -1)
|
||||
queryPath := strings.ReplaceAll(testAuthz.AllowQuery, ".", "/")
|
||||
url := testRuntime.URL() + "/v1/" + queryPath
|
||||
|
||||
input, expected := testAuthz.GenerateInput(profile, mode)
|
||||
|
||||
@@ -55,7 +55,6 @@ func TestH2CHTTPListeners(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("failed to GET %s: %s", u, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if expected, actual := http.StatusOK, resp.StatusCode; expected != actual {
|
||||
t.Errorf("resp status: expected %d, got %d", expected, actual)
|
||||
@@ -63,5 +62,7 @@ func TestH2CHTTPListeners(t *testing.T) {
|
||||
if expected, actual := 2, resp.ProtoMajor; expected != actual {
|
||||
t.Errorf("resp.ProtoMajor: expected %d, got %d", expected, actual)
|
||||
}
|
||||
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -353,19 +352,19 @@ func (t *TestRuntime) UploadData(data io.Reader) error {
|
||||
func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error {
|
||||
client := &http.Client{}
|
||||
|
||||
urlPath := strings.TrimSuffix(filepath.Join("/v1/data"+path), "/")
|
||||
urlPath := strings.TrimSuffix("/v1/data"+path, "/")
|
||||
|
||||
req, err := http.NewRequest("PUT", t.URL()+urlPath, data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unexpected error creating request: %s", err)
|
||||
return fmt.Errorf("unexpected error creating request: %s", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to PUT data: %s", err)
|
||||
return fmt.Errorf("failed to PUT data: %s", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
return fmt.Errorf("Unexpected response: %d %s", resp.StatusCode, resp.Status)
|
||||
return fmt.Errorf("unexpected response: %d %s", resp.StatusCode, resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ type compiledTestCase struct {
|
||||
|
||||
func compileTestCases(ctx context.Context, tests cases.Set) (*compiledTestCaseSet, error) {
|
||||
result := make([]compiledTestCase, 0, len(tests.Cases))
|
||||
for _, tc := range tests.Cases {
|
||||
for _, tc := range tests.Cases { //nolint:gocritic
|
||||
|
||||
var numExpects int
|
||||
|
||||
@@ -171,7 +171,7 @@ func run(params params) error {
|
||||
return err
|
||||
}
|
||||
|
||||
dst := strings.Replace(files[i].Name(), ".yaml", ".json", -1)
|
||||
dst := strings.ReplaceAll(files[i].Name(), ".yaml", ".json")
|
||||
return writeFile(tw, dst, bs)
|
||||
}()
|
||||
if err != nil {
|
||||
|
||||
@@ -219,7 +219,7 @@ func (r PrettyReporter) fmtBenchmark(tr *Result) string {
|
||||
// This converts the test case name like data.foo.bar.test_auth to be more
|
||||
// like BenchmarkDataFooBarTestAuth.
|
||||
camelCaseName := ""
|
||||
for _, part := range strings.Split(strings.Replace(name, "_", ".", -1), ".") {
|
||||
for _, part := range strings.Split(strings.ReplaceAll(name, "_", "."), ".") {
|
||||
camelCaseName += strings.Title(part) //nolint:staticcheck // SA1019, no unicode here
|
||||
}
|
||||
name = "Benchmark" + camelCaseName
|
||||
|
||||
@@ -314,12 +314,12 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) {
|
||||
if b.a == nil {
|
||||
b.a = new([maxLinearScan]bindingArrayKeyValue)
|
||||
} else if i := b.find(key); i >= 0 {
|
||||
(*b.a)[i].value = value
|
||||
b.a[i].value = value
|
||||
return
|
||||
}
|
||||
|
||||
if b.n < maxLinearScan {
|
||||
(*b.a)[b.n] = bindingArrayKeyValue{key, value}
|
||||
b.a[b.n] = bindingArrayKeyValue{key, value}
|
||||
b.n++
|
||||
return
|
||||
}
|
||||
@@ -342,7 +342,7 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) {
|
||||
func (b *bindingsArrayHashmap) Get(key *ast.Term) (value, bool) {
|
||||
if b.m == nil {
|
||||
if i := b.find(key); i >= 0 {
|
||||
return (*b.a)[i].value, true
|
||||
return b.a[i].value, true
|
||||
}
|
||||
|
||||
return value{}, false
|
||||
@@ -361,7 +361,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) {
|
||||
if i := b.find(key); i >= 0 {
|
||||
n := b.n - 1
|
||||
if i < n {
|
||||
(*b.a)[i] = (*b.a)[n]
|
||||
b.a[i] = b.a[n]
|
||||
}
|
||||
|
||||
b.n = n
|
||||
@@ -375,7 +375,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) {
|
||||
func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) {
|
||||
if b.m == nil {
|
||||
for i := range b.n {
|
||||
if f((*b.a)[i].key, (*b.a)[i].value) {
|
||||
if f(b.a[i].key, b.a[i].value) {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -392,7 +392,7 @@ func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) {
|
||||
func (b *bindingsArrayHashmap) find(key *ast.Term) int {
|
||||
v := key.Value.(ast.Var)
|
||||
for i := range b.n {
|
||||
if (*b.a)[i].key.Value.(ast.Var) == v {
|
||||
if b.a[i].key.Value.(ast.Var) == v {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -46,7 +46,7 @@ func builtinToNumber(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term
|
||||
return builtins.NewOperandTypeErr(1, operands[0].Value, "null", "boolean", "number", "string")
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case *ast.Array:
|
||||
@@ -64,7 +64,7 @@ func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term)
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case *ast.Array:
|
||||
@@ -80,7 +80,7 @@ func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case ast.String:
|
||||
@@ -90,7 +90,7 @@ func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case ast.Boolean:
|
||||
@@ -100,7 +100,7 @@ func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case ast.Null:
|
||||
@@ -110,7 +110,7 @@ func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term)
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated in v0.13.0.
|
||||
// Deprecated: deprecated in v0.13.0.
|
||||
func builtinToObject(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||
switch val := operands[0].Value.(type) {
|
||||
case ast.Object:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user