In this post, I introduce how to write OPA's Policy Tests with table driven test.
By applying Test Driven Test to OPA's Policy Testing, you can test various test cases simply.
I have created an example.
You can define table entries as the following.
seeds := [
{
"msg": "pass",
"resource": {
"type": "aws_cloudwatch_log_group",
"address": "aws_cloudwatch_log_group.main",
"values": {"retention_in_days": 7},
},
"exp": set(),
},
{
"msg": "retention_in_days should be greater than 0",
"resource": {
"type": "aws_cloudwatch_log_group",
"address": "aws_cloudwatch_log_group.main",
"values": {"retention_in_days": 0},
},
"exp": {"aws_cloudwatch_log_group.main: retention_in_days should be set and greater than 0"},
},
{
"msg": "retention_in_days should be set",
"resource": {
"type": "aws_cloudwatch_log_group",
"address": "aws_cloudwatch_log_group.main",
"values": {},
},
"exp": {"aws_cloudwatch_log_group.main: retention_in_days should be set and greater than 0"},
},
]
And you can test as the following.
some i
seed := seeds[i]
result := deny_aws_cloudwatch_log_grop_retention_in_days with input as wrap_single_resource(seed.resource)
result != seed.exp
The trace log is useful for debug.
trace(sprintf("FAIL %s (%d): %s, wanted %v, got %v", ["test_deny_aws_cloudwatch_log_grop_retention_in_days", i, seed.msg, seed.exp, result]))
$ conftest verify --trace | grep Note
TRAC | | | | Note "FAIL test_deny_aws_cloudwatch_log_grop_retention_in_days (1): retention_in_days should be greater than 0, wanted {\"aws_cloudwatch_log_group.main: retention_in_days should be set and greater than 0\"}, got set()"
That's it.
Top comments (0)