xtest

Infrastructure and DevOps Testing

Kubernetes Testing Strategies

This course teaches practical strategies for testing applications and infrastructure that run on Kubernetes. It covers a layered testing approach that spans unit tests for application code, static validation of Kubernetes manifests, integration tests against a real or simulated cluster, end-to-end tests of deployed workloads, and chaos experiments that probe resilience under failure. Learners will work with real, publicly available tools including kubectl, kind, k3d, Helm, conftest, kubeval, pytest, Testcontainers and Litmus Chaos. The course is aimed at QA engineers, SREs and developers who need confidence that manifests, Helm charts, operators and microservices behave correctly before and after they reach production, and who want a repeatable way to catch configuration drift, broken rollouts and fragile failure handling early in a pipeline.

Intermediate · By the Xtest team · About 39 minutes to read

Introduction

Testing an application that runs on Kubernetes is not the same job as testing the application alone. Kubernetes adds a declarative configuration layer (manifests and Helm charts), a scheduler that decides where and when workloads run, a networking model with services and ingress rules, and a reconciliation loop that constantly tries to make the live cluster match the desired state. A bug can live in any of these layers: the application code itself, a YAML manifest with a wrong field, a Helm template that renders incorrectly for one set of values, a network policy that blocks traffic it should allow, or a liveness probe that kills a pod too eagerly during a slow startup. A testing strategy that only runs unit tests against application code misses all of this.

This course builds a layered approach, often described as a testing pyramid for cloud-native systems: fast unit tests at the base, static manifest and policy validation above that, integration tests against a real or lightweight cluster in the middle, and a smaller number of end-to-end and chaos tests at the top that exercise the whole system under realistic and failure conditions. Each layer catches a different class of problem, and each layer costs more time to run than the one below it, which is why the pyramid shape matters: you want many cheap, fast checks and only a few expensive, slow ones. By the end of the course you will know which tool fits which layer, how to wire these checks into a CI/CD pipeline, and how to design experiments that prove a system recovers gracefully when a pod, a node or a dependency fails.

Foundations: Building a Testing Pyramid for Kubernetes Workloads

Why Kubernetes Needs Its Own Testing Strategy

A Kubernetes deployment is the sum of several independently changeable parts: application code, container images, Kubernetes manifests (Deployments, Services, ConfigMaps, Ingress rules, NetworkPolicies), and often a Helm chart or Kustomize overlay that generates those manifests from templates and values. A defect can appear in any one of these without appearing in the others. A testing strategy for Kubernetes has to check each layer on its own, because a passing unit test suite says nothing about whether a Service selector actually matches a Deployment's pod labels.

The Four Layers

  • Unit tests: ordinary tests of application code, with no cluster involved. These stay exactly as they would for any other application and should remain the largest, fastest layer.
  • Static validation: checking manifests and chart output against schemas and organizational policy before anything is applied to a cluster. Tools like kubeval or kubeconform check a manifest against the Kubernetes API schema; conftest, built on Open Policy Agent's Rego language, checks manifests against your own rules, such as "every container must set a resource limit" or "no container may run as root".
  • Integration tests: applying manifests to a real cluster, usually a disposable local one, and asserting on the result through the Kubernetes API: did the Deployment reach the desired number of ready replicas, does the Service route to the right pods, does a ConfigMap change get picked up.
  • End-to-end and chaos tests: exercising the deployed system as a whole, including failure injection such as killing a pod or partitioning a node, to confirm the system behaves correctly and recovers.

Disposable Clusters Are the Key Enabler

The layer that most teams skip is integration testing, usually because spinning up a cluster feels too slow or too risky to do in CI. Tools such as kind (Kubernetes in Docker) and k3d (k3s in Docker) solve this by creating a real, API-compliant cluster inside a container in under a minute, entirely disposable, and safe to destroy after every test run. This turns "does my manifest actually work" from a manual, production-adjacent check into an automated step that runs on every pull request.

Putting It Together

A healthy pipeline runs unit tests on every commit, static validation on every manifest change, integration tests against a kind cluster on every pull request, and a smaller end-to-end or chaos suite on a schedule or before a release. The rest of this section walks through setting up that first integration layer in detail, since it is the foundation the higher layers build on.

The Kubernetes Testing Pyramid in Practice

Think of the pyramid as a budget for your team's patience, not just a diagram. Unit tests should number in the hundreds or thousands and run in seconds, because they run on every keystroke in a developer's editor and every commit in CI. Static manifest validation should run in a few seconds too, since it is just parsing YAML and checking it against a schema or a policy set, with no cluster involved at all. Integration tests against a disposable cluster are slower, typically tens of seconds to a few minutes, because they involve starting a cluster, applying manifests, and waiting for pods to become ready; these should number in the tens, covering the critical paths of how your workloads are wired together: does this Service find this Deployment, does this Ingress route to this Service, does this ConfigMap change propagate.

End-to-end and chaos tests sit at the top and should be the fewest, often single digits to low tens, because they take the longest and are the hardest to make reliable: they depend on real timing, real networking, and sometimes real external systems. A common mistake is inverting this pyramid, writing dozens of slow end-to-end tests because they feel more realistic, and ending up with a CI pipeline that takes an hour and fails intermittently for reasons unrelated to the code being tested. Keep the heavy layer thin and specific: a handful of end-to-end tests that prove the system works as a whole, backed by a much larger base of fast, deterministic checks that catch most problems long before a full cluster is involved.

Setting Up Disposable Clusters with kind and k3d

kind and k3d both let you create a full Kubernetes cluster inside Docker containers on a laptop or a CI runner, with no cloud account and no persistent infrastructure to maintain. kind runs each cluster node as a Docker container running the real kubelet and control plane components, which makes it behave very closely to a production cluster for the purposes of testing manifests and controllers. k3d does the same using k3s, a smaller Kubernetes distribution, which starts faster and uses less memory, a useful trade-off when a CI runner has tight resource limits.

The typical workflow is: create a cluster with a config file that pins the Kubernetes version and any port mappings you need, apply your manifests or install your Helm chart, run assertions against the live API using kubectl or a client library, and then delete the cluster. Because creation and deletion are both fast, a fresh cluster per test run (or even per test file) is affordable, which avoids a common source of flaky tests: state left behind by a previous run. Naming clusters uniquely per CI job, and always tearing them down in a cleanup step that runs even when a test fails, keeps a shared CI environment from accumulating orphaned clusters that quietly eat resources over time. For teams testing multiple Kubernetes versions, both tools let you specify the node image version, making it straightforward to run the same integration suite against the oldest and newest versions you support.

# Create a disposable, pinned-version cluster with kind
cat <<EOF > kind-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  image: kindest/node:v1.29.0
EOF

kind create cluster --name ci-test --config kind-config.yaml

# Apply the manifests under test
kubectl apply -f manifests/

# Wait for the Deployment to be ready before testing further
kubectl rollout status deployment/payments-api --timeout=60s

# Always clean up, even on failure
kind delete cluster --name ci-test

Creates a pinned-version disposable cluster with kind, applies the manifests being tested, waits for the rollout to finish, and tears the cluster down. This is the standard shape of a Kubernetes integration test setup step in CI.

# Statically validate manifests before they ever touch a cluster
# 1. Schema validation against the Kubernetes API
kubeconform -summary -strict manifests/*.yaml

# 2. Organizational policy checks with conftest and a Rego policy
cat <<'EOF' > policy/resources.rego
package main

deny[msg] {
  input.kind == "Deployment"
  container := input.spec.template.spec.containers[_]
  not container.resources.limits.memory
  msg := sprintf("container %s has no memory limit", [container.name])
}
EOF

conftest test manifests/*.yaml --policy policy/

Runs two layers of static validation: kubeconform checks that manifests match the Kubernetes API schema, and conftest enforces a custom rule (here, that every container sets a memory limit) using Open Policy Agent's Rego language.

from kubernetes import client, config, watch
import pytest

@pytest.fixture(scope="module")
def k8s_apps_v1():
    # Assumes KUBECONFIG points at the disposable kind cluster
    config.load_kube_config()
    return client.AppsV1Api()

def test_deployment_reaches_desired_replicas(k8s_apps_v1):
    namespace = "default"
    name = "payments-api"
    deployment = k8s_apps_v1.read_namespaced_deployment(name, namespace)
    desired = deployment.spec.replicas

    w = watch.Watch()
    for event in w.stream(
        k8s_apps_v1.list_namespaced_deployment,
        namespace=namespace,
        timeout_seconds=60,
    ):
        dep = event["object"]
        if dep.metadata.name == name and dep.status.ready_replicas == desired:
            w.stop()
            return

    pytest.fail(f"deployment {name} did not reach {desired} ready replicas in time")

A pytest integration test using the official Kubernetes Python client to assert that a Deployment applied to the disposable cluster actually reaches its desired number of ready replicas, rather than just checking that kubectl apply did not error.

Tips

  • Pin the Kubernetes node image version in kind or k3d so your integration tests run against the same version your production cluster uses, and rerun the suite against the next version before you upgrade.
  • Create one disposable cluster per CI job rather than sharing a long-lived test cluster across runs; this removes an entire class of flaky failures caused by leftover state from a previous test.
  • Run static validation (schema and policy checks) as a separate, earlier CI step than cluster-based integration tests, since it is far cheaper and catches a large share of mistakes before a cluster is even started.
  • Always put cluster teardown in a step that runs unconditionally, such as a CI job's 'always' or 'finally' block, so a failed test does not leave an orphaned cluster running on a shared runner.

Common pitfalls

  • Testing manifests only by eyeballing them or applying them to a real staging cluster by hand. A schema validator like kubeconform plus a policy tool like conftest catches most mistakes in seconds, before anything is ever applied anywhere.
  • Asserting only that 'kubectl apply' exits with code 0. Applying a manifest can succeed even when the resulting pods crash-loop or the rollout never completes, so integration tests must also check the live status of the resource, such as ready replica counts, not just the apply step.
  • Writing integration tests against a shared, persistent cluster used by multiple developers or pipelines at once. Resource name collisions and leftover state from other runs make failures hard to reproduce; a disposable per-run cluster with kind or k3d avoids this entirely.
  • Letting integration and end-to-end tests dominate the suite because they feel more realistic. This inverts the testing pyramid and produces a slow, sometimes flaky pipeline; keep the fast unit and static-validation layers as the largest part of the suite.

Validating Manifests, Helm Charts and Policy

Before a manifest ever reaches a live cluster, a well-designed pipeline should catch structural errors, templating mistakes, and policy violations entirely offline. This layer of testing is cheap to run, fast to fail, and catches the overwhelming majority of configuration mistakes that would otherwise surface as a failed rollout or, worse, a runtime incident.

Static validation starts with schema checking. Tools like kubeval and its more actively maintained successor kubeconform parse every YAML document against the Kubernetes OpenAPI schema for a target cluster version, flagging unknown fields, wrong types, and deprecated or removed API versions (a common source of breakage after a cluster upgrade). This check belongs in every pull request pipeline because it requires no cluster access and runs in seconds across an entire manifest directory.

Beyond schema correctness, teams need to verify that the logic of their templates produces the intended output. Helm charts are rendered with helm template to produce plain manifests, which can then be piped into schema validators or inspected directly for correctness. helm unittest goes further, letting you assert on specific fields of the rendered output, such as replica counts, environment variables, or label selectors, across multiple values files representing different environments. Kustomize overlays deserve the same treatment: run kustomize build against each overlay and diff or validate the result, since overlay patches frequently introduce subtle mismatches between a Deployment's selector and its Pod template labels, a mistake that passes schema validation but breaks rollouts.

The final layer is policy as code. Open Policy Agent, through conftest, and Kyverno let organizations encode rules such as mandatory resource requests and limits, disallowed :latest tags, or required labels, and enforce them identically in CI and at admission time in the cluster.

Schema and Template Validation in CI

The most effective static validation pipelines run in a strict order: render first, then validate. For raw manifests, that means pointing kubeconform at the directory with the correct Kubernetes version and any custom resource schemas it needs (CRDs are not part of the core OpenAPI spec, so kubeconform supports pulling schemas from a configured schema location or skipping unknown kinds explicitly, which is safer than silently ignoring them).

For Helm charts, never validate the chart's source templates directly; validate the rendered output, because that is what actually gets applied. Run helm template <chart> -f values-staging.yaml -f values-prod.yaml for every values file your environments use, since a chart that renders cleanly with default values can still produce invalid YAML, duplicate keys, or missing required fields under a less common configuration. Pipe each rendered output into kubeconform in the same CI step so a broken template and an invalid manifest are caught by the same gate.

helm unittest complements this by testing assertions that schema validation cannot express: that a Deployment's replica count matches an expected value for a given values file, that a Secret is not accidentally rendered when a feature flag is off, or that an Ingress host matches the expected domain per environment. Write these tests alongside the chart itself and run them before template rendering tests, since a failing unit test usually points to the root cause faster than a downstream schema error does.

Policy as Code with OPA and Kyverno

Schema validation confirms a manifest is well-formed; policy validation confirms it is well-governed. Open Policy Agent, accessed through the conftest CLI, lets you write Rego rules that inspect rendered manifests for organizational standards: every container must declare CPU and memory limits, no container may run as root, every Deployment must carry a team label for cost attribution, and so on. Because conftest consumes the same rendered YAML that schema validators use, it slots into the same CI step with no extra rendering work.

Kyverno offers a YAML-based alternative to Rego that many teams find easier to read and maintain, and critically, the same Kyverno policies can run in two places: as a CI check via the kyverno apply CLI against rendered manifests, and as an admission controller inside the cluster itself. Running identical policy at both stages closes the gap between what CI approved and what actually reaches the API server, since CI can only validate what is committed, not what is applied through kubectl edit, a Helm rollback, or a manual patch.

A practical rollout strategy is to start every new policy in audit or warn mode, collecting violations without blocking merges or admissions, then promote it to enforcing once the existing manifest base is clean. Pushing a policy straight to enforcing mode on day one is the single most common way these initiatives get rolled back after breaking a legitimate deploy.

# Render the Helm chart with production values, then validate the output
helm template my-app ./charts/my-app -f values-production.yaml > rendered.yaml
kubeconform -summary -kubernetes-version 1.29.0 -ignore-missing-schemas rendered.yaml

# Run policy checks against the same rendered manifests with conftest
conftest test rendered.yaml --policy ./policy/

# Example Rego policy: deny containers without resource limits
# policy/limits.rego
# package main
#
# deny[msg] {
#   input.kind == "Deployment"
#   container := input.spec.template.spec.containers[_]
#   not container.resources.limits
#   msg := sprintf("container %s has no resource limits", [container.name])
# }

A CI pipeline step that renders a Helm chart for a specific environment, validates the resulting manifests against the Kubernetes schema, and then runs an OPA/conftest policy check that rejects any container missing resource limits.

# helm unittest test file: tests/deployment_test.yaml
suite: test deployment replicas and labels
templates:
  - deployment.yaml
tests:
  - it: should set replicas from values
    set:
      replicaCount: 3
    asserts:
      - equal:
          path: spec.replicas
          value: 3
  - it: selector labels must match template labels
    asserts:
      - equal:
          path: spec.selector.matchLabels
          value:
            app: my-app
      - equal:
          path: spec.template.metadata.labels.app
          value: my-app

A helm unittest suite that asserts the replica count renders correctly from values.yaml and explicitly checks that the Deployment's selector labels match its Pod template labels, catching the selector mismatch that breaks rollouts but passes schema validation.

Tips

  • Always validate the rendered output of Helm charts and Kustomize overlays, never the raw templates; the templates can look fine while the rendered manifest is broken.
  • Pin the Kubernetes version argument in kubeconform or kubeval to match your actual target cluster, since API versions that are valid on one version may be deprecated or removed on another.
  • Introduce new OPA or Kyverno policies in audit/warn mode first and only switch to enforcing once existing manifests pass, to avoid blocking unrelated merges the day a policy lands.
  • Keep policy-as-code rules themselves under version control and tested with example manifests that should pass and fail, so a typo in a Rego rule doesn't silently disable the check.

Common pitfalls

  • Validating only the default `values.yaml` for a Helm chart: many real misconfigurations only appear under environment-specific overrides, so run `helm template` and schema validation against every values file your environments actually use.
  • Treating a selector label mismatch as a schema problem: kubeconform and kubeval will happily pass a Deployment whose selector no longer matches its Pod template labels, so this must be caught with an explicit template test like helm unittest rather than assumed to be covered by schema checks.

Integration Testing Microservices on a Cluster

Once services are deployed to Kubernetes, unit tests alone cannot catch the failures that only appear when containers actually talk to each other across a cluster's network, DNS, and policy layers. Integration testing at this level validates that service discovery resolves correctly, that NetworkPolicy rules allow or block traffic as designed, that ConfigMaps and Secrets reach the pods that depend on them, and that an application behaves correctly against real dependencies such as a database or message broker running as pods rather than mocks.

This section covers the practical techniques for writing these tests: verifying DNS resolution and service-to-service calls inside the cluster, asserting that NetworkPolicy objects actually isolate namespaces or pods as intended, confirming that a changed ConfigMap or Secret propagates to a running pod (and that your app picks up the change, whether via restart or live reload), and spinning up disposable test environments with Testcontainers or a throwaway kind/k3d cluster so tests run against real Postgres, Redis, or Kafka instances instead of fakes.

A recurring theme is isolation and repeatability: tests that create a namespace, run assertions, and tear everything down cleanly so that a failed run never leaves orphaned resources that break the next run. We also cover idempotent fixtures, meaning setup code that can be run twice without erroring or duplicating state, which matters enormously in CI where retries and flaky infrastructure are common.

By the end of this section you should be able to write a test suite that deploys a small set of interdependent services into an ephemeral namespace, confirms they can discover and reach each other under the NetworkPolicy rules you expect to enforce in production, and exercises real data paths against containerized dependencies before tearing the whole thing down automatically.

Service Discovery, DNS, and NetworkPolicy Verification

Kubernetes gives every Service a DNS name resolvable from inside the cluster, typically of the form service-name.namespace.svc.cluster.local. Integration tests should confirm this resolution works from the caller's actual pod, not just from a developer's laptop, because CoreDNS configuration, namespace scoping, and search-domain quirks can behave differently in-cluster. A simple pattern is to run a throwaway debug pod (for example kubectl run with a busybox or curlimages/curl image) inside the namespace under test and issue a DNS lookup or HTTP call against the target service, asserting on the response.

NetworkPolicy testing is subtler because the absence of a policy means all traffic is allowed, while a misconfigured policy can silently block traffic that should flow or allow traffic that should be denied. A solid test strategy deploys the policy alongside the services it protects, then runs both a positive test (traffic from an allowed source succeeds) and a negative test (traffic from a disallowed source times out or is refused). Because NetworkPolicy enforcement depends on the CNI plugin installed in the cluster, these tests should run against a cluster configured with the same CNI as production, not a minimal test cluster that silently ignores NetworkPolicy objects altogether, which is a common and misleading false pass.

ConfigMap and Secret propagation tests typically assert two things: that the value mounted into the pod (as a file or environment variable) matches what was applied, and that an update to the ConfigMap or Secret is reflected within the kubelet's sync interval if the app is expected to pick up changes without a restart. If your app only reads config at startup, your test should instead assert that a rolling restart is required and triggered correctly.

Real Dependencies with Testcontainers and Disposable Clusters

Mocking a database or message broker hides real integration bugs such as connection pool exhaustion, serialization mismatches, or transaction isolation issues. Testcontainers lets you start a real Postgres, MySQL, Kafka, or Redis container for the lifetime of a test run, wire your application to it, and tear it down automatically when the test process exits, giving you production-like behavior without a shared, stateful test environment that other test runs could corrupt.

For cluster-level integration tests, the same idea extends to the whole namespace: tools like kind or k3d let you spin up a full, disposable Kubernetes cluster inside CI in under a minute, deploy your manifests, run your test suite against it, and destroy the cluster afterward. This avoids the classic problem of a shared staging cluster accumulating leftover resources and state from previous runs that make failures hard to reproduce.

Idempotent fixtures are essential here. A setup routine that creates a namespace should first check whether it exists (or use kubectl apply rather than kubectl create, since apply is idempotent) and a teardown routine should be written so that running it twice, or running it after a partial failure, never errors out. Namespace deletion in Kubernetes is asynchronous, so a teardown that immediately recreates the same namespace name can race with the deletion still finishing in the background. A reliable pattern is to generate a unique namespace name per test run (for example suffixed with a short random string or the CI build ID) so parallel runs and retries never collide, and to always run teardown in a finally block or its CI equivalent so a failed assertion still cleans up the cluster.

import pytest
from testcontainers.postgres import PostgresContainer
from testcontainers.kafka import KafkaContainer

@pytest.fixture(scope="module")
def postgres():
    with PostgresContainer("postgres:15") as pg:
        yield pg

@pytest.fixture(scope="module")
def kafka():
    with KafkaContainer() as kc:
        yield kc

def test_order_service_writes_and_publishes(postgres, kafka):
    conn_str = postgres.get_connection_url()
    bootstrap_servers = kafka.get_bootstrap_server()

    # Point the service under test at the real containers
    response = create_order(conn_str, bootstrap_servers, order_id="ord-1")
    assert response.status_code == 201

    # Assert the row landed in the real database
    row = fetch_order(conn_str, "ord-1")
    assert row is not None

    # Assert a real message was published to the real broker
    message = consume_one(bootstrap_servers, topic="orders")
    assert message["order_id"] == "ord-1"

A Python/pytest integration test that starts real Postgres and Kafka containers with Testcontainers, exercises the service under test against them, and asserts on both the database row and the published message, with automatic container teardown when the fixtures go out of scope.

#!/usr/bin/env bash
set -euo pipefail

NAMESPACE="it-$(date +%s)-$RANDOM"

cleanup() {
  kubectl delete namespace "$NAMESPACE" --wait=false || true
}
trap cleanup EXIT

kubectl create namespace "$NAMESPACE"
kubectl apply -n "$NAMESPACE" -f manifests/

kubectl wait -n "$NAMESPACE" --for=condition=available deployment/order-service --timeout=60s

# Verify DNS resolution and a real HTTP call from inside the cluster
kubectl run dns-check -n "$NAMESPACE" --rm -i --restart=Never \
  --image=curlimages/curl -- curl -sf http://order-service.$NAMESPACE.svc.cluster.local/healthz

echo "Integration test passed"

A bash script that creates a uniquely named, disposable namespace, deploys the manifests under test, waits for readiness, verifies in-cluster DNS resolution and connectivity with a throwaway debug pod, and always deletes the namespace on exit via a trap, keeping the fixture idempotent and safe to rerun.

Tips

  • Run NetworkPolicy tests against a cluster using the same CNI plugin as production, since some CNIs ignore NetworkPolicy objects entirely and will give you a false sense of security.
  • Generate a unique namespace name per test run instead of reusing a fixed name, so parallel CI jobs and retries never collide or interfere with each other's state.
  • Prefer `kubectl apply` over `kubectl create` in setup fixtures, since apply is idempotent and safe to rerun after a partial failure.

Common pitfalls

  • Testing service-to-service calls from outside the cluster (a developer laptop or CI runner) and assuming the result reflects in-cluster DNS and network behavior, when CoreDNS resolution and NetworkPolicy enforcement only apply to traffic that actually originates from inside the cluster.
  • Writing teardown logic that assumes namespace deletion is synchronous; Kubernetes deletes namespaces asynchronously, so immediately recreating a namespace with the same name can race with the old one still terminating and cause flaky failures.

Chaos Engineering and Resilience Testing

Chaos engineering on Kubernetes means deliberately injecting failure into a running system to learn whether it recovers the way its design assumes it will. A Deployment, a StatefulSet, a Service and a set of resource limits are all claims about behavior under stress, and the only way to know whether those claims hold is to break something on purpose and watch what happens. Tools such as Litmus Chaos and Chaos Mesh turn this from an ad-hoc exercise into a repeatable, declarative practice: experiments are defined as Kubernetes custom resources, scheduled, versioned alongside application manifests, and run in CI or on a recurring cadence against a staging or even production environment.

The common experiment types map directly onto the failure modes a cluster will eventually hit on its own: killing a pod to confirm a Deployment's controller reschedules it and a Service keeps routing traffic to the survivors; draining or cordoning a node to confirm the scheduler places evicted pods elsewhere within an acceptable window; injecting network latency or packet loss between two services to see whether timeouts, retries and circuit breakers behave as configured rather than cascading into a full outage; and exhausting a container's CPU or memory to confirm resource limits, requests and eviction policies actually protect the node rather than only existing on paper.

None of this is useful without discipline around the experiment itself. Every run should start from a written hypothesis ('the Service will keep p99 latency under 500ms when one of three pods is killed'), a defined steady-state metric to watch, a blast radius limited to a non-critical namespace or a small percentage of replicas, and an automatic rollback if the system breaches a safety threshold. Recovery time, error rate during the fault, and whether alerts fired are the three numbers worth recording from each experiment, because they turn a one-off exercise into a trend line the team can track release over release.

Designing the Experiment: Hypothesis, Steady State, and Blast Radius

A chaos experiment without a hypothesis is just an outage you caused yourself. Before touching a cluster, write down the expected behavior in a single testable sentence: what should stay true while the fault is active, and by when should the system return to its steady state once the fault ends. Steady state is usually a small set of observable metrics already available from the cluster or the application: request success rate, p95/p99 latency, replica count matching the Deployment's desired count, or queue depth staying below a threshold.

Blast radius is the second design decision. Start experiments against a single pod or a single node in a non-production namespace, with a label selector scoped tightly enough that an experiment gone wrong cannot touch unrelated workloads. Chaos Mesh and Litmus both support scoping by namespace, label selector and even a percentage of matching pods, so an experiment can start at 10% of replicas and only widen once the team trusts the result. Every experiment should also define its own abort condition: a monitoring alert, an error budget burn rate, or a simple timeout after which the chaos is withdrawn automatically rather than left running while someone investigates.

Finally, treat the experiment definition itself as a versioned artifact. Storing Chaos Mesh Workflow or Litmus ChaosEngine manifests in the same repository as the application manifests means a resilience regression can be bisected the same way a functional regression can: by checking which commit changed the expected recovery time.

Measuring Recovery and Catching Regressions in CI

An experiment that runs once and is never looked at again teaches nothing. The value of chaos engineering comes from running the same experiment repeatedly, usually on a schedule or as a gate in a deployment pipeline, and comparing recovery time and error rate against a baseline recorded from a previous passing run. A CronJob that fires a pod-kill experiment nightly against staging, paired with a script that queries Prometheus for the time between the kill and the Deployment's ready replica count returning to its desired value, turns resilience into a number that can regress and be caught before release.

In CI, the most practical pattern is to run a small, fast subset of experiments, typically pod deletion and short network-latency injection, against a freshly deployed namespace for each pull request, failing the build if recovery time exceeds a fixed threshold or if any pod remains unready past a timeout. Longer or more destructive experiments, such as node drains or sustained resource exhaustion, are better suited to a nightly or weekly job rather than a PR gate, both because they take longer to recover from and because running them too frequently against shared infrastructure increases the chance of masking a real incident behind a scheduled one. Whichever cadence is chosen, the experiment's result, pass or fail, recovery time and error count, should be exported as a build artifact or a dashboard so a trend is visible rather than only a single pass/fail per run.

apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
  name: kill-order-service-pod
  namespace: staging
spec:
  action: pod-kill
  mode: fixed-percent
  value: "33"
  selector:
    namespaces:
      - staging
    labelSelectors:
      app: order-service
  scheduler:
    cron: "@every 10m"

A Chaos Mesh PodChaos experiment that kills 33% of pods labeled app=order-service in the staging namespace every ten minutes, used to confirm the Deployment's controller reschedules replacements and the Service keeps routing traffic without a sustained drop in success rate.

#!/usr/bin/env bash
set -euo pipefail

# Kill one pod of the target deployment, then poll until the
# desired replica count is ready again, printing recovery time.
DEPLOYMENT=order-service
NAMESPACE=staging
START=$(date +%s)

POD=$(kubectl get pods -n "$NAMESPACE" -l app="$DEPLOYMENT" -o jsonpath='{.items[0].metadata.name}')
kubectl delete pod "$POD" -n "$NAMESPACE"

until [ "$(kubectl get deployment "$DEPLOYMENT" -n "$NAMESPACE" -o jsonpath='{.status.readyReplicas}')" = "$(kubectl get deployment "$DEPLOYMENT" -n "$NAMESPACE" -o jsonpath='{.spec.replicas}')" ]; do
  sleep 2
done

END=$(date +%s)
echo "Recovery time: $((END - START)) seconds"

A minimal recovery-time check usable in a CI job: deletes one pod of a Deployment and polls until the ready replica count matches the desired count again, printing the elapsed seconds so it can be compared against a threshold and failed if exceeded.

Tips

  • Always record a steady-state baseline before the first experiment runs, so later runs have a known-good recovery time to compare against rather than an arbitrary threshold.
  • Scope every experiment with a label selector and a namespace boundary first, and only widen the blast radius once a smaller version has passed cleanly several times.
  • Export recovery time and error count from every scheduled experiment to the same dashboard used for other test results, so a resilience regression is as visible as a failing functional test.

Common pitfalls

  • Running an experiment with no hypothesis and no abort condition, so a fault that cascades beyond its intended scope has no automatic way to stop; always define a rollback trigger before the experiment starts.
  • Only ever testing pod kills and skipping node drains, network faults and resource exhaustion, which leaves the scheduler's rescheduling logic and the application's retry and circuit-breaker behavior completely unverified.

Wiring It Into CI/CD

A testing strategy only pays off once it runs automatically on every change, without someone remembering to trigger it by hand. The goal in this section is to assemble the layers built in earlier sections (manifest linting, policy checks, integration tests, chaos experiments) into a pipeline that runs the right tests at the right moment: fast checks on every pull request, heavier integration tests on merge, and the slowest, most disruptive tests on a schedule against a staging environment rather than on every commit.

The pipeline is organized as a funnel. Static validation (schema checks, kubeval or kubeconform, policy checks with conftest or kyverno test) runs in seconds and catches malformed YAML, missing resource limits, or forbidden image registries before anything touches a cluster. Integration tests spin up an ephemeral kind cluster, apply the manifests, and verify that pods actually start, services resolve, and probes pass; these take minutes and run on merge to the main branch rather than on every push to a feature branch, to keep pull request feedback fast. Chaos and end-to-end suites, which might kill nodes, inject network latency, or simulate a dependency outage, are the slowest and most disruptive, so they run on a schedule against a dedicated staging cluster rather than inline with every deployment.

This staged approach means a contributor gets a yes or no answer on a pull request in under a minute for the common case of a typo or misconfigured limit, while the organization still gets full confidence before a release through the scheduled suite. The same pipeline is also the natural place to gate a deployment: a release job simply refuses to proceed unless the prior stage's job succeeded, and GitHub Actions, GitLab CI and Jenkins all support this through job dependencies and required status checks.

Structuring the Pipeline by Stage

Each CI system expresses staging differently, but the underlying pattern is the same: fast, cheap jobs gate slower, more expensive ones. In GitHub Actions this is a needs: dependency between jobs; in GitLab CI it is stages: with jobs assigned to a stage; in Jenkins it is sequential stages in a declarative pipeline. Static validation should be the very first stage and should fail the build in seconds, before any cluster is provisioned, because provisioning a kind cluster even briefly costs real minutes of runner time.

The integration stage then provisions a kind cluster fresh for each run, applies the manifests, waits for readiness, runs the test suite, and tears the cluster down regardless of outcome, so no state leaks between runs. This is where most teams get burned: a cluster that is not deterministically destroyed (for example, left running after a job is cancelled) leaves orphaned resources on the runner that quietly break the next run.

The scheduled chaos and end-to-end stage is best kept entirely separate from the pull request pipeline, triggered by a cron schedule or a manual dispatch rather than a push event, and pointed at a long-lived staging cluster rather than an ephemeral one, since chaos experiments need an environment that resembles production closely enough for the results to mean anything. Keep its results visible in a dashboard or a scheduled report rather than only in a build log, since no one checks a nightly job's log unless something prompts them to.

Gating Releases and Reporting Back

A deployment job should depend on the test jobs that matter for that release, not just succeed by default when the pipeline reaches it. In GitHub Actions this means the deploy job declares needs: [static-validation, integration-tests]; in GitLab CI the deploy job is in a later stage and GitLab will not run it if an earlier stage failed; in Jenkins a scripted or declarative pipeline can check the result of a prior stage before entering the deploy stage. For releases gated on the scheduled chaos suite, the deploy job can check the latest scheduled run's conclusion via the CI system's API before proceeding, since the chaos suite itself does not run inline with the release.

Reporting failures back to the pull request closes the loop for the contributor. Both GitHub Actions and GitLab CI can post a check run or a merge request comment summarizing which manifest failed validation and why, and attaching the relevant log excerpt rather than a link to a wall of text saves reviewers time. A common pitfall here is reporting only pass or fail without saying which resource or which policy rule failed, which forces the author back into the full log to find the actual cause; a one-line summary per failing rule, generated from conftest's or kyverno test's structured output, is worth the small extra scripting effort.

name: k8s-pipeline
on: [pull_request, push]
jobs:
  static-validation:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Validate manifests
        run: kubeconform -strict -summary manifests/**/*.yaml
      - name: Policy check
        run: conftest test manifests/ --policy policies/

  integration-tests:
    needs: static-validation
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: helm/kind-action@v1
        with:
          cluster_name: ci-cluster
      - name: Apply manifests
        run: kubectl apply -f manifests/
      - name: Wait for rollout
        run: kubectl rollout status deployment/app --timeout=120s
      - name: Run integration suite
        run: ./scripts/run-integration-tests.sh

  deploy:
    needs: [static-validation, integration-tests]
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - run: ./scripts/deploy-staging.sh

A GitHub Actions workflow that gates deployment on static validation and integration tests passing first, keeping fast checks on pull requests and the full cluster test only on pushes to main.

#!/usr/bin/env bash
set -euo pipefail

# Fail the build unless every pod in the ephemeral kind cluster is Ready
NOT_READY=$(kubectl get pods --no-headers | awk '$2 !~ /^[0-9]+\/\1$/' || true)

if [ -n "$NOT_READY" ]; then
  echo "The following pods are not fully ready:"
  echo "$NOT_READY"
  exit 1
fi

echo "All pods ready; running integration test suite"
./bin/integration-tests --cluster=kind-ci-cluster

A readiness gate script that checks every pod reached a Ready state before the integration test suite runs, failing fast with a clear message if the cluster never stabilized.

Tips

  • Keep static validation as its own job so a YAML typo fails in seconds instead of waiting on a cluster to provision
  • Always tear down the kind cluster in a cleanup step that runs even if the test job fails, so orphaned clusters do not pile up on shared runners
  • Run the chaos and end-to-end suite on a schedule against staging rather than inline with every pull request, since it is the slowest and most disruptive layer

Common pitfalls

  • Running integration tests on every push to a feature branch instead of only on merge, which slows down pull request feedback for no real safety benefit; reserve the full kind cluster run for merges to main and keep pull requests on the fast static checks
  • Reporting pipeline failures back to the pull request as a bare pass or fail, forcing reviewers to dig through the full log to find the actual broken rule; generate a short summary from the policy tool's structured output and post that as the check's message

Exercises

Exercise 1: Build a Disposable Cluster Integration Test

In this exercise you will set up a local disposable Kubernetes cluster, deploy a sample application to it, and write an automated check that confirms the deployment actually becomes healthy rather than just assuming it does because kubectl did not report an error. This mirrors the first and most commonly skipped layer of the Kubernetes testing pyramid: integration tests against a real, if temporary, cluster. You will need Docker installed along with kind and kubectl. Start by writing a simple Deployment and Service manifest for any small container image (a basic web server image is fine). Create a kind cluster with a pinned Kubernetes version using a config file, then apply your manifests to it. Rather than trusting the apply step, use kubectl rollout status or a small script with the Kubernetes client library to poll the Deployment until its ready replica count matches the desired count, failing the check if that does not happen within a reasonable timeout. Then verify that the Service correctly routes to the pods by port-forwarding to the Service and making a request to confirm you get a response from the application, not just a connection refused or a timeout. Finally, write a cleanup step that deletes the kind cluster, and confirm that running your whole script twice in a row from a clean state produces the same result both times, proving the test is repeatable and not dependent on leftover state.

  1. Install Docker, kind and kubectl on your machine if not already installed.
  2. Write a Deployment manifest (with at least 2 replicas) and a matching Service manifest for a simple web server container image.
  3. Create a kind cluster with a config file that pins a specific Kubernetes node image version.
  4. Apply your manifests to the cluster and use 'kubectl rollout status' to wait for the Deployment to become ready, failing with a clear error if it times out.
  5. Port-forward to the Service and make an HTTP request to confirm traffic actually reaches a pod.
  6. Delete the kind cluster as a final cleanup step.
  7. Run the entire script twice from a clean starting state and confirm both runs produce the same successful result.

Expected outcome: A repeatable script or test file that creates a disposable cluster, deploys an application, proves both that the Deployment reached its desired ready state and that the Service actually routes traffic to it, and tears the cluster down afterward, with identical results on repeated runs.

Exercise 2: Catch a Bad Manifest Before It Reaches a Cluster

This exercise focuses on the static validation layer. You will deliberately introduce three common mistakes into a Kubernetes manifest and write policy checks that catch each one automatically, before the manifest is ever applied to a cluster. The three mistakes to introduce, one at a time, are: a container with no memory or CPU limit set, a Service whose selector labels do not match any pod's labels, and a manifest using a deprecated or incorrect apiVersion field. For the first mistake, write a Rego policy for conftest that flags any container missing resource limits. For the second, this will not be caught by schema validation alone since it is semantically valid YAML; note in your exercise write-up why this class of mistake needs an integration test rather than static validation to catch reliably. For the third, run kubeconform against the manifest and observe how it reports the invalid apiVersion. Document which of the three mistakes each tool catches and which it misses, to build an understanding of why multiple testing layers are needed rather than just one.

  1. Write a baseline Deployment and Service manifest that passes all checks cleanly.
  2. Introduce a container with no resource limits, write a conftest Rego policy that flags it, and confirm it fails the check.
  3. Fix that issue, then introduce a Service selector that does not match the Deployment's pod labels, and confirm that neither kubeconform nor conftest catches it.
  4. Fix that issue, then change the apiVersion field to an invalid or deprecated value, and confirm kubeconform flags it.
  5. Write a short summary table of which tool caught which mistake, and which mistake needed an integration test instead.

Expected outcome: A working conftest policy that blocks containers without resource limits, a documented demonstration that schema validation alone cannot catch a Service and Deployment label mismatch, and a clear written understanding of why static validation and integration testing are complementary rather than redundant.

Quiz

1. Why is testing a Kubernetes-based system different from testing the application code alone?

  1. Because Kubernetes manifests, Helm charts, networking rules and the scheduler can each introduce defects that application-level unit tests never exercise
  2. Because Kubernetes requires every test to run inside a container
  3. Because Kubernetes does not support automated testing of any kind
  4. Because application code behaves differently when compiled for Kubernetes
Show answer

A. Because Kubernetes manifests, Helm charts, networking rules and the scheduler can each introduce defects that application-level unit tests never exercise

Kubernetes adds several independently changeable layers on top of application code, such as manifests, Helm templates, Service routing and network policy, and a defect can live in any one of them without showing up in a unit test of the application code itself.

2. In a testing pyramid for Kubernetes workloads, which layer should contain the fewest tests and take the longest to run?

  1. Unit tests of application code
  2. Static manifest and policy validation
  3. End-to-end and chaos tests against a running cluster
  4. Linting of YAML syntax
Show answer

C. End-to-end and chaos tests against a running cluster

End-to-end and chaos tests exercise the whole deployed system, often including failure injection, which makes them slower and more complex to keep reliable, so they should be the smallest and most targeted layer.

3. What problem do tools like kind and k3d solve for Kubernetes integration testing?

  1. They let you create and destroy a real, disposable Kubernetes cluster quickly, often in under a minute, without needing a cloud account
  2. They automatically fix broken manifests
  3. They replace the need for any unit testing of application code
  4. They generate Kubernetes manifests from application source code
Show answer

A. They let you create and destroy a real, disposable Kubernetes cluster quickly, often in under a minute, without needing a cloud account

kind runs a real cluster inside Docker containers and k3d does the same with k3s, both letting a team spin up and tear down a disposable, API-compliant cluster fast enough to use in everyday CI runs.

4. A Service's selector labels do not match any pod's labels, so traffic never reaches the pods, but the manifest is syntactically valid YAML that passes schema validation. What is the best way to catch this before it reaches production?

  1. Rely on schema validation tools like kubeconform, since they check all possible mistakes
  2. An integration test that applies the manifests to a real or disposable cluster and checks that the Service actually routes traffic to a pod
  3. Add more unit tests to the application code
  4. This type of mistake cannot be caught by automated testing
Show answer

B. An integration test that applies the manifests to a real or disposable cluster and checks that the Service actually routes traffic to a pod

A label selector mismatch is semantically valid YAML, so schema validators cannot detect it. Only an integration test that applies the manifests to a cluster and checks live routing behavior, such as port-forwarding to the Service and making a request, reliably catches it.

5. What is the purpose of a chaos engineering experiment, such as killing a pod with a tool like Litmus Chaos?

  1. To permanently remove unnecessary pods from a cluster to save resources
  2. To test a hypothesis about how the system behaves and recovers under a specific failure condition, such as whether a Deployment reschedules a killed pod within an expected time
  3. To replace the need for integration tests
  4. To measure the exact dollar cost of running a cluster
Show answer

B. To test a hypothesis about how the system behaves and recovers under a specific failure condition, such as whether a Deployment reschedules a killed pod within an expected time

A chaos experiment is built around a hypothesis, such as 'the Deployment will reschedule a killed pod within 30 seconds', and the experiment injects the failure, such as killing a pod, to measure whether that hypothesis holds, revealing gaps in resilience before they occur in production.

Related docs

All courses