Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
opa blog part3
# patch we expect to be generated
expectedPatch = {
"op": "add",
"path": "spec/nodeSelector",
"value": {
"agentpool": "pool1"
# Helper to check patch is set
hasPatch(patches, expectedPatch) {
# One of the patches returned should match the `expectedPatch`
patches[_] == expectedPatch
# Checks the response is a patch response
isPatchResponse(res) {
# Is the response patch type correct?
res.response.patchType = "JSONPatch"
# Is the patch body set?
# Is the patch body an array with more than one item?
count(res.response.patch) > 0
# Test that the controller correctly sets a patch on a pod
# to assign it the correct `nodeSelector` of `agentpool=pool1`
test_response_patch {
# Invoke the policy main with a pod which doesn't have a node selector
# and is in the default namespace
body := main with input as testdata.example_pod_doesnt_have_node_selector
# Check policy returned an allowed response
body.response.allowed = true
# Check the response is a patch response
# The admission controller response is an array of base64 encoded
# jsonpatches so deserialize so we can review them.
patches := json.unmarshal(base64.decode(body.response.patch))
# Output some tracing... `opa test *.rego -v --explain full` to see them
trace(sprintf("TEST:appliedPatch = '%s'", [patches]))
trace(sprintf("TEST:expectedPatch = '%s'", [expectedPatch]))
# Check the policy created the expected patch
hasPatch(patches, expectedPatch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment