/function-unit-test

Experimental Unit test function

Primary LanguageGoApache License 2.0Apache-2.0

function-unit-test

CI

function-unit-test is a Crossplane function that can run CEL expressions against your desired state. This allows you to test the results of a Composition pipeline.

Installing

Functions require Crossplane 1.14 or newer. Apply the following manifest to your cluster:

apiVersion: pkg.crossplane.io/v1beta1
kind: Function
metadata:
  name: crossplane-contrib-function-unit-test
spec:
  package: xpkg.upbound.io/crossplane-contrib/function-unit-test:v0.1.0

Configuring Unit Tests

See tests in examples.

After all your desired resources have been rendered with other functions, call the unittest function and define CEL TestCases.

If errorOnFailedTest is set to true, failing tests will return an error. This is useful when running this function in CI pipelines via crossplane beta render.

 - step:
    functionRef:
      name: crossplane-contrib-function-unit-test
    input:
      apiVersion: unittest.fn.crossplane.io/v1beta1
      kind: TestCases
      errorOnFailedTest: false
      testCases:
      - description: "test pass"
        assert: observed.composite.resource.spec.env == "dev"
      - description: "test fail"
        assert: observed.composite.resource.spec.env == "prod"
      # - description: "test error"
      #   assert: a == b
      - assert: |-
          "kind" in desired.resources['test-resource'].resource &&
          desired.resources['test-resource'].resource.kind == 'NopResource'
        description: all resources "test" is of "NopResource" kind
      - assert: |- 
          desired.resources.all(r, "labels" in desired.resources[r].resource.metadata && 
          "security-setting" in desired.resources[r].resource.metadata.labels &&
          desired.resources[r].resource.metadata.labels["security-setting"] == "true")
        description: All resources have the "security-setting" label

Building the Function

# Run code generation - see input/generate.go
$ go generate ./...

# Run tests - see fn_test.go
$ go test ./...

# Build the function's runtime image - see Dockerfile
$ docker build . --tag=function-unit-test-runtime

# Build a function package - see package/crossplane.yaml
$ crossplane xpkg build -f package --embed-runtime-image=function-unit-test-runtime

Reference Links