Tests of Rego
A Rego test is a rule whose name starts with test_. opa test runs the tests of a directory.
In rego4k, rego4k-testing-core runs them with the outcomes and the text of opa test of OPA 1.23.0.
rego4k-testing-junit makes each Rego test a JUnit test.
Run the tests
PolicyFiles.read reads the files of opa test <path>...:
- each
.regofile is a module; - each
.jsonor.yamlfile is data at the path of its directory.
TestRunner runs the tests, and gives a TestResult for each test rule: its outcome (PASS, FAIL, SKIPPED
or ERROR), its duration, its error, its print output and its test cases.
PrettyReport gives the text of opa test, or of opa test -v.
val runner = TestRunner(Rego.standard(Re2Engine))
// as `opa test policies`
val results = runner.run(PolicyFiles.read(policies))
// the text of `opa test -v`
val report = PrettyReport.text(results, verbose = true)
val passed = results.all { it.outcome == Outcome.PASS }RegoTestRuns.kt, lines 28 to 33, on GitHubThe engine gives the builtins of the tests. A test rule with test cases (test_sums[tc.note] if { ... }) needs
internal.test_case, and Builtins.Pure.stdlib(regex) has it.
The README of rego4k-testing-core tells each rule of
opa test that the runner copies, and the differences. For example, rego4k does not have the flags --coverage
and --bench.
In JUnit
RegoTests.junit gives the tests as JUnit 5 dynamic tests for a @TestFactory. Each package is a container.
- The source of each test is the file and the line of its rule, so an IDE goes to the rule from the test.
- A failure shows the text of
opa test -vfor the test.
See Test your Rego with JUnit.
http.send in a test
A policy that calls http.send needs the network in production. In a test, give the engine Builtins.httpSend
with an http4k handler in memory. The handler gets each request of the policy, and the
test needs no network or server:
val staffDirectory = routes(
"/staff/{id}" bind GET to {
Response(OK)
.header("Content-Type", "application/json")
.body("""{"manager": "bob"}""")
},
)
val rego = Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.httpSend(staffDirectory))
val policy = rego.compile(
RegoFileName("staff.rego") to RegoFile(
"package staff\n\nmanager := http.send(" +
"{\"method\": \"GET\", \"url\": \"https://directory/staff/alice\"}" +
").body.manager\n",
),
)
// "bob"
val manager = policy.eval("data.staff.manager")?.toKotlin()RegoTestRuns.kt, lines 42 to 58, on GitHubThe builtin gives the results of OPA: the same request object, the same response object, and the same errors. See
rego4k-builtins-http4k-send.