github.com/rajeev159/opa@v0.45.0/topdown/uuid_test.go (about) 1 // Copyright 2020 The OPA Authors. All rights reserved. 2 // Use of this source code is governed by an Apache2 3 // license that can be found in the LICENSE file. 4 5 package topdown 6 7 import ( 8 "context" 9 "errors" 10 "math/rand" 11 "testing" 12 13 "github.com/open-policy-agent/opa/ast" 14 ) 15 16 func TestUUIDRFC4122SeedingAndCaching(t *testing.T) { 17 18 query := `uuid.rfc4122("x",x); uuid.rfc4122("y", y); uuid.rfc4122("x",x2)` 19 20 q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(ast.NewCompiler()) 21 22 ctx := context.Background() 23 24 qrs, err := q.Run(ctx) 25 if err != nil { 26 t.Fatal(err) 27 } else if len(qrs) != 1 { 28 t.Fatal("expected exactly one result but got:", qrs) 29 } 30 31 exp := ast.MustParseTerm(` 32 { 33 { 34 x: "0194fdc2-fa2f-4cc0-81d3-ff12045b73c8", 35 x2: "0194fdc2-fa2f-4cc0-81d3-ff12045b73c8", 36 y: "6e4ff95f-f662-45ee-a82a-bdf44a2d0b75", 37 } 38 } 39 `) 40 41 result := queryResultSetToTerm(qrs) 42 43 if !result.Equal(exp) { 44 t.Fatalf("expected %v but got %v", exp, result) 45 } 46 47 } 48 49 type fakeSeedErrorReader struct{} 50 51 func (fakeSeedErrorReader) Read([]byte) (int, error) { 52 return 0, errors.New("xxx") 53 } 54 55 func TestUUIDRFC4122SeedError(t *testing.T) { 56 57 query := `uuid.rfc4122("x",x)` 58 59 q := NewQuery(ast.MustParseBody(query)).WithSeed(fakeSeedErrorReader{}).WithCompiler(ast.NewCompiler()).WithStrictBuiltinErrors(true) 60 61 _, err := q.Run(context.Background()) 62 63 if topdownErr, ok := err.(*Error); !ok || topdownErr.Code != BuiltinErr { 64 t.Fatal("unexpected error (or lack of error):", err) 65 } 66 67 } 68 69 func TestUUIDRFC4122SavingDuringPartialEval(t *testing.T) { 70 71 query := `foo = "x"; uuid.rfc4122(foo,x)` 72 c := ast.NewCompiler(). 73 WithCapabilities(&ast.Capabilities{Builtins: []*ast.Builtin{ast.UUIDRFC4122}}) 74 // Must compile to initialize type environment after WithCapabilities 75 c.Compile(nil) 76 77 q := NewQuery(ast.MustParseBody(query)).WithSeed(rand.New(rand.NewSource(0))).WithCompiler(c) 78 79 queries, modules, err := q.PartialRun(context.Background()) 80 if err != nil { 81 t.Fatal(err) 82 } else if len(modules) > 0 { 83 t.Fatal("expected no support") 84 } 85 86 exp := ast.MustParseBody(`uuid.rfc4122("x", x); foo = "x"`) 87 88 if len(queries) != 1 || !queries[0].Equal(exp) { 89 t.Fatalf("expected %v but got: %v", exp, queries) 90 } 91 } 92 93 func queryResultSetToTerm(qrs QueryResultSet) *ast.Term { 94 s := ast.NewSet() 95 for i := range qrs { 96 bindings := ast.NewObject() 97 for k := range qrs[i] { 98 bindings.Insert(ast.NewTerm(k), qrs[i][k]) 99 } 100 s.Add(ast.NewTerm(bindings)) 101 } 102 return ast.NewTerm(s) 103 }