Provisioning an Environment with Mocked Services
This example replaces a service that the application under test calls with a mock, so the temporary environment does not need to run that service or hold its data and credentials. Prism reads the OpenAPI file of the service and answers each request with the example that the file defines for it.
The example builds on Provisioning an Environment with Helm and follows the pattern
described in Provisioning Test Environments. It installs
podinfo and sets the backend value of its chart to the address of the
mock. podinfo sends the requests of its /api/echo endpoint to that address and returns the answers.
To use the example with your own application:
- Replace the OpenAPI file with the OpenAPI file of the service that your application calls.
- Replace the
backendvalue with the setting that tells your application the address of that service. - In the test Workflow, replace the request and the expected
messagewith a request that your application passes on to the service and a value that only the mock returns. - Replace the chart, its values and the published URL, as in the Helm example.
This Workflows functionality is not available when running the Testkube Runner in Standalone Mode - Read More
Prerequisites
This example reuses the following resources, so create them first:
- The
env-provisionerServiceAccount from the Helm example. It already allows the ConfigMap, Deployment and Service that the mock consists of. - The teardown Workflow
env-helm-teardownand the cleanup Workflowenv-helm-cleanupof the Helm example. - The test Workflow
env-smoke-test.
The Provisioning Workflow
apiVersion: testworkflows.testkube.io/v1
kind: TestWorkflow
metadata:
name: env-mock-provision
spec:
config:
namespace:
type: string
content:
files:
- path: /mock/openapi.yaml
content: |
openapi: 3.0.3
info:
title: Backend
version: 1.0.0
paths:
/api/echo:
post:
requestBody:
content:
application/json:
schema: {}
responses:
"202":
description: Accepted
content:
application/json:
example:
source: backend-mock
message: Hello from the mock backend
- path: /mock/backend-mock.yaml
content: |
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend-mock
spec:
replicas: 1
selector:
matchLabels:
app: backend-mock
template:
metadata:
labels:
app: backend-mock
spec:
containers:
- name: prism
image: stoplight/prism:5.14.3
args: ["mock", "-h", "0.0.0.0", "-p", "4010", "/spec/openapi.yaml"]
ports:
- containerPort: 4010
readinessProbe:
tcpSocket:
port: 4010
periodSeconds: 2
volumeMounts:
- name: spec
mountPath: /spec
volumes:
- name: spec
configMap:
name: backend-spec
---
apiVersion: v1
kind: Service
metadata:
name: backend-mock
spec:
selector:
app: backend-mock
ports:
- port: 4010
targetPort: 4010
pod:
serviceAccountName: env-provisioner
container:
image: alpine/k8s:1.32.3
steps:
- name: Create namespace
shell: |
date +%s > /data/started
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Namespace
metadata:
name: {{ config.namespace }}
labels:
testkube.io/ephemeral-environment: "true"
EOF
- name: Start the mock backend
shell: |
kubectl create configmap backend-spec --from-file=openapi.yaml=/mock/openapi.yaml \
--namespace "{{ config.namespace }}"
kubectl apply -f /mock/backend-mock.yaml --namespace "{{ config.namespace }}"
kubectl rollout status deployment/backend-mock \
--namespace "{{ config.namespace }}" --timeout 3m
date +%s > /data/mocked
- name: Install chart
shell: |
helm upgrade --install podinfo oci://ghcr.io/stefanprodan/charts/podinfo --version 6.17.0 \
--namespace "{{ config.namespace }}" \
--set backend=http://backend-mock:4010/api/echo \
--wait --timeout 3m
date +%s > /data/installed
kubectl rollout status deployment/podinfo \
--namespace "{{ config.namespace }}" --timeout 3m
date +%s > /data/ready
- name: Publish environment URL
shell: |
echo -n "http://podinfo.{{ config.namespace }}.svc.cluster.local:9898" > /testkube/outputs/url
- name: Export provisioning metrics
shell: |
started=$(cat /data/started); mocked=$(cat /data/mocked)
installed=$(cat /data/installed); ready=$(cat /data/ready)
pods=$(kubectl get pods --namespace "{{ config.namespace }}" -o json | jq '.items | length')
mkdir -p /data/artifacts
cat > /data/artifacts/provisioning.lp <<EOF
environment_provisioning,provisioner=helm-prism,app=podinfo mock_seconds=$((mocked - started)),install_seconds=$((installed - mocked)),ready_wait_seconds=$((ready - installed)),total_seconds=$((ready - started)),pods=${pods}i
EOF
artifacts:
paths:
- /data/artifacts/*.lp
The Workflow is the provisioning Workflow of the Helm example with a mock added:
- The
spec.content.filesproperty mounts two files into every step:/mock/openapi.yaml, the OpenAPI file of the service that the mock replaces, and/mock/backend-mock.yaml, a Deployment that runs Prism and a Service in front of it. Keep the-h 0.0.0.0argument of the Prism container: without it, Prism listens only on127.0.0.1, and the Service cannot reach it. The files are inline to keep the example self-contained. In your own Workflow, keep them in your repository and mount them withcontent.git. - The
Start the mock backendstep stores the OpenAPI file in the ConfigMapbackend-specunder the keyopenapi.yaml. The Prism container mounts the ConfigMap at/spec, where the key becomes the file/spec/openapi.yamlthat Prism serves. The step then creates the Deployment and the Service in the temporary namespace and waits until Prism is ready. - The
Install chartstep sets thebackendvalue of the chart to the URL of the mock. The short Service namebackend-mockresolves because the mock and the application run in the same namespace. - The
Export provisioning metricsstep adds the fieldmock_seconds, the time until the mock was ready, and tags the record withprovisioner=helm-prism, so these environments get their own series in Environment Metrics.
Prism checks every request against the OpenAPI file and rejects a request that does not match it. podinfo still answers
with status 200 when the mock rejects a request, so a mismatch is easy to miss. Make sure that each operation in your
OpenAPI file accepts the requests that your application sends. In this example, podinfo sends the request body without
a Content-Type header, so the operation declares a requestBody with an empty schema.
The readiness probe of the mock checks every 2 seconds instead of the default 10 seconds, so the mock is ready sooner.
The Test Workflow
The test Workflow of the pattern checks that the application is up. This one checks that a request reaches the mock through the application:
apiVersion: testworkflows.testkube.io/v1
kind: TestWorkflow
metadata:
name: env-mock-test
spec:
config:
url:
type: string
steps:
- name: Call the application and its mocked backend
run:
image: curlimages/curl:8.11.1
shell: |
set -e
response=$(curl -sS --fail-with-body -X POST -H 'Content-Type: application/json' \
-d '{"hello":"world"}' "{{ config.url }}/api/echo")
echo "$response"
case "$response" in
*"Hello from the mock backend"*) echo "The answer came from the mock backend" ;;
*) echo "The answer did not come from the mock backend"; exit 1 ;;
esac
The Workflow passes only when the answer contains the message of the example in the OpenAPI file. podinfo answers
with status 200 even when the call to the mock fails, so the Workflow checks the content of the answer instead of its
status. The answer then contains backend ... call failed when podinfo cannot reach the mock, or
backend ... response status code when the mock rejects the request. When you adapt the test, check for a value that
only the mock returns.
The Composite Workflow
The composite Workflow provisions the environment, runs both test Workflows against it in parallel and removes it with
the teardown Workflow of the Helm example. Deleting the namespace removes the mock together with the application. The
teardown gets provisioner: helm-prism, so its health record carries the same tag as the provisioning record of this
example.
apiVersion: testworkflows.testkube.io/v1
kind: TestWorkflow
metadata:
name: env-mock-suite
spec:
steps:
- name: Provision environment
execute:
workflows:
- name: env-mock-provision
as: env
config:
namespace: "env-{{ execution.id }}"
- name: Run tests
execute:
workflows:
- name: env-smoke-test
config:
url: '{{ execution("env").outputs.url }}'
- name: env-mock-test
config:
url: '{{ execution("env").outputs.url }}'
- name: Tear down environment
condition: always
execute:
workflows:
- name: env-helm-teardown
config:
namespace: "env-{{ execution.id }}"
provisioner: helm-prism
Run it like any other Workflow:
testkube run testworkflow env-mock-suite --watch
The log of the execution shows the provisioning, the two test executions running in parallel and the teardown:
env-mock-provision-2 • scheduled (6b0b39b50e24955d2a04811f)
env-mock-provision-2 • passed
env-mock-test-1 • scheduled (6b0b39cf8efdcaade644118a)
env-smoke-test-3 • scheduled (6b0b39cf8efdcaade644118c)
env-mock-test-1 • passed
env-smoke-test-3 • passed
env-helm-teardown-4 • scheduled (6b0b39d48efdcaade64411bb)
env-helm-teardown-4 • passed
Cleaning Up
The cleanup Workflow of the Helm example also deletes expired environments of this example, because the provisioning Workflow labels the namespace in the same way.