DEV Community

Shunsuke Suzuki
Shunsuke Suzuki

Posted on

OPA Policy Testing by Table Driven Test

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"},
        },
    ]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]))
Enter fullscreen mode Exit fullscreen mode
$ 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()"
Enter fullscreen mode Exit fullscreen mode

That's it.

Discussion (0)