Skip to content

Commit

Permalink
Fix input document definition in REPL
Browse files Browse the repository at this point in the history
Fixes #231
  • Loading branch information
tsandall committed Jan 26, 2017
1 parent a2db2b1 commit 545332f
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 5 deletions.
21 changes: 16 additions & 5 deletions repl/repl.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,21 +582,32 @@ func (r *REPL) evalStatement(ctx context.Context, stmt interface{}) error {
if err != nil {
return err
}

body, err := r.compileBody(s, input)

if err != nil {
return err
}
if rule, err := ast.ParseRuleFromBody(body); err == nil {
if err := r.compileRule(rule); err != nil {
rule, err2 := ast.ParseRuleFromBody(s)
if err2 != nil {
// The statement cannot be understood as a rule, so the original
// error returned from compiling the query should be given the
// caller.
return err
}
return nil
return r.compileRule(rule)
}

rule, err3 := ast.ParseRuleFromBody(body)
if err3 == nil {
return r.compileRule(rule)
}

compiler, err := r.loadCompiler()
if err != nil {
return err
}

return r.evalBody(ctx, compiler, input, body)

case *ast.Rule:
if err := r.compileRule(s); err != nil {
fmt.Fprintln(r.output, "error:", err)
Expand Down
56 changes: 56 additions & 0 deletions repl/repl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,62 @@ func TestEvalBodyInput(t *testing.T) {
}
}

func TestEvalBodyInputComplete(t *testing.T) {
ctx := context.Background()
store := newTestStore()
var buffer bytes.Buffer
repl := newRepl(store, &buffer)

// Test that input can be defined completely:
// https://github.com/open-policy-agent/opa/issues/231
repl.OneShot(ctx, `package repl`)
repl.OneShot(ctx, `input = 1`)
repl.OneShot(ctx, `input`)

result := buffer.String()
if result != "1\n" {
t.Fatalf("Expected 1 but got: %v", result)
}

buffer.Reset()

// Test that input is as expected
repl.OneShot(ctx, `package ex1`)
repl.OneShot(ctx, `x = input`)
repl.OneShot(ctx, `x`)

result = buffer.String()
if result != "1\n" {
t.Fatalf("Expected 1 but got: %v", result)
}

buffer.Reset()

// Test that local input replaces other inputs
repl.OneShot(ctx, `package ex2`)
repl.OneShot(ctx, `input = 2`)
repl.OneShot(ctx, `input`)

result = buffer.String()

if result != "2\n" {
t.Fatalf("Expected 2 but got: %v", result)
}

buffer.Reset()

// Test that original input is intact
repl.OneShot(ctx, `package ex3`)
repl.OneShot(ctx, `input`)

result = buffer.String()

if result != "1\n" {
t.Fatalf("Expected 1 bu got: %v", result)
}

}

func TestEvalImport(t *testing.T) {
ctx := context.Background()
store := newTestStore()
Expand Down

0 comments on commit 545332f

Please sign in to comment.