open-policy-agent / gatekeeper

🐊 Gatekeeper - Policy Controller for Kubernetes
https://open-policy-agent.github.io/gatekeeper/
Apache License 2.0
3.69k stars 757 forks source link

How to mock external_data #2826

Open NitroCao opened 1 year ago

NitroCao commented 1 year ago

I write some rules which use external_data keyword and want to write unit tests for them, but have no idea cause the original opa command doesn't support external_data. Is there any solution or workaround for this? Gatekeeper version: 3.11.0

fseldow commented 1 year ago

my own workaround is that, in unit test file, I directly wrote the multiple external data source functions that output different results for different object.keys inputs

My example: (my input is a list of container images)

test_input_not_allow {
    input := xxx
    results := violation with input as input
    count(results) == 1
}

external_data(object) = out {
    array_contains(object.keys, "system_error_image")
    out = {
        "status_code": 504,
        "system_error": "provider not responsing",
    }
}

external_data(object) = out {
    not array_contains(object.keys, "system_error_image")
    out = {
        "errors": {x| x:=object.keys[i];x=="error_image"},
        "responses": {x | x:=verifier_report(object.keys[i]); object.keys[i] != "error_image"},
        "status_code": 200,
        "system_error": ""
    }
}
sozercan commented 1 year ago

We should add this to https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata

NitroCao commented 1 year ago

@fseldow Thanks for your solution, it's a good idea!🤩 @sozercan Is it better to close this issue with a PR to avoid missing this task?😃

fardin01 commented 1 year ago

Similar solution: https://github.com/open-policy-agent/opa/issues/5956

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

ritazh commented 1 year ago

not stale