Skip to content

Instantly share code, notes, and snippets.

@lawrencegripper
Created January 13, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawrencegripper/3d1a2822dd57d000237d0b5153977c7f to your computer and use it in GitHub Desktop.
Save lawrencegripper/3d1a2822dd57d000237d0b5153977c7f to your computer and use it in GitHub Desktop.
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?
res.response.patch
# 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
isPatchResponse(body)
# 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