Testing
It is important to ensure the policies you write are correct. Sentinel includes a built-in test framework that can be run locally and in CI environments to test that policies behave as expected.
A common pitfall with many simple ACL systems is that they provide no easy way to verify their correctness. You basically have to set the ACL and try the behaviors against a real system to verify it is working as expected. This requires a lot of setup and is unique to each system.
Sentinel's built-in test framework has zero dependencies. Contained within the Sentinel CLI, it can mock the data that real systems are exposing to the policy. It is designed to be CI-friendly and enables continuous testing of your policies. This is necessary for policy as code.
Detailed documentation on testing policies is available in the Sentinel Testing reference.
Writing Tests
For this example, save the following policy as officehours.sentinel
:
is_weekday = rule { day not in ["saturday", "sunday"] }
is_open_hours = rule { hour > 8 and hour < 17 }
main = rule { is_open_hours and is_weekday }
Next, let's write a passing test case. This will test that the policy actually passes
when we expect it to pass. Sentinel is opiniated about the test folder structure. Save the following in test/officehours/good.hcl
:
global "day" {
value = "monday"
}
global "hour" {
value = 14
}
And run sentinel test
:
$ sentinel test
PASS - officehours.sentinel
PASS - test/officehours/good.hcl
The sentinel test
command will automatically find all Sentinel policies
and their associated test cases and run them all. The test framework will
run all HCL files as individual test cases, allowing you to test a variety
of scenarios for your policies.
Try adding another test case to force the policy to fail. This test case can
be saved at test/officehours/fail.hcl
. For test cases with intentional
failures, you'll need to use the test assertions described in the testing
reference.
Now that you have a good grasp of what Sentinel is and how to use it, please feel free to look through the next steps you can take to further your Sentinel knowledge.