Test your deployment code against a fake Kubernetes API¶
This page shows how to run your own tests of code that drives Piceli (a
composition, a release spec, a script around PlanExecutor) against the
in-process fake Kubernetes API server that Piceli’s own acceptance suite uses,
with no cluster.
Maturity: preview
piceli.testing is public and covered by semantic versioning from 0.4.0: the
names listed below change only in a minor release with a changelog entry. The
server is a test double, not a conformance-tested API server (see
What it does not do).
Prerequisites¶
Piceli installed (
pip install piceli);piceli.testingships in the wheel.pytestfor the fixture (the context manager needs nothing else).
Steps¶
Start a fake cluster in a test.
fake_cluster()serves a freshFakeAPIon a loopback port and gives you a ready provider:from piceli.testing import fake_cluster, manifest from piceli.k8s.ops import ResourceIdentity def test_settings_are_readable(): with fake_cluster() as cluster: cluster.api.put(manifest("ConfigMap", "settings", value="on")) found = cluster.provider.get( ResourceIdentity("v1", "ConfigMap", cluster.namespace, "settings") ) assert found.manifest["data"] == {"mode": "on"}
Or enable the ready-made fixture in your
conftest.py:pytest_plugins = ["piceli.testing.pytest_plugin"] def test_with_fixture(piceli_fake_cluster): piceli_fake_cluster.api.put(manifest("ConfigMap", "settings"))
Run commands against it through an explicit kubeconfig. Write a kubeconfig for the server and use the
loopback-httptransport, which Piceli accepts only for a literal loopbackhttp://address:kubeconfig = cluster.kubeconfig(tmp_path / "kubeconfig") # context "fake"
# release.toml [target] kubeconfig = "kubeconfig" context = "fake" namespace = "piceli-test" # piceli.testing.TARGET.namespace transport = "loopback-http"
piceli import livetakes--transport loopback-httpfor the same purpose.Check what the server received and holds.
cluster.api.objectsmaps(kind, name)to the stored manifest;cluster.api.requestsrecords every request (method, path, query, body, content type).Inject faults.
cluster.api.inject("PATCH", "/deployments/web", status=503)fails the next matching request once. Other keys:delay,after_commit_delay,disconnect_before,disconnect_after,raw(a response body) anddry_run(match only dry-run or only real requests). To stop a client at an exact step, setcluster.api.interceptto a function(request, phase) -> bool; it is called withphase"received"(before the server acts) and"committed"(after it acted, before the response), and returningTruedrops the connection there. Piceli’s own kill tests use it to SIGKILLpiceli release applyat every write.Model field ownership when you test adoption. Set
cluster.api.field_ownership = Trueand seed objects with the field managers that created them:cluster.api.field_ownership = True cluster.api.put(deployment, managers=[("kubectl-create", "Update", deployment)])
The server then tracks
managedFields, reports server-side apply conflicts and prunes fields a manager stops applying.cluster.api.scale("Deployment", "web", 3)writesspec.replicasthe way a HorizontalPodAutoscaler does (ascalesubresource entry ofkube-controller-manager).
Expected result¶
Tests run in milliseconds, use the real kubernetes client transport and
never read ~/.kube/config.
If it fails¶
403for a namespaced object. Every namespaced object lives in one namespace,TARGET.namespace(piceli-test) unless you passFakeAPI(namespace="my-app")(0.8.0); requests for another namespace are refused.404for a kind. The server serves the kinds inTYPES. PassFakeAPI(types={...})(plural →(apiVersion, kind, namespaced)) andfake_cluster(api)to serve others.422on a patch. Withoutfield_ownership, server-side apply requests must setforce=false, and adoption (a field-manager transfer) needsfield_ownership = True.loopback-http is only for a literal loopback http:// test API. The kubeconfig must point at the fake’shttp://127.0.0.1:<port>URL.
API¶
Importing piceli.testing has no side effects: it starts no server, opens no
socket and reads no kubeconfig. The names are loaded on first use.
Name |
What it is |
|---|---|
|
Context manager: runs a server and yields a |
|
Context manager: yields |
|
A |
|
A credential-free kubeconfig for the server |
|
The server state ( |
|
The |
|
The default served kinds: ConfigMap, Secret, Service, Pod, PersistentVolumeClaim, PersistentVolume, Namespace, Deployment, ReplicaSet (0.8.0), NetworkPolicy, ServiceAccount, Role, RoleBinding, ClusterRole, ClusterRoleBinding, a test |
|
A minimal valid object for seeding |
|
Helpers for |
|
The |
|
0.15.0: a provider for |
|
0.15.0: a loopback HTTP server answering Hetzner’s |
What it does not do¶
No admission, no defaulting beyond status (Deployments report ready replicas, PVCs bind, Services get a cluster IP), no watch, only equality and existence label selectors on lists (
k,!k,k=v,k!=v), no Pods created from Deployments (except the failing pods offail_pods).One namespace (
FakeAPI(namespace=...)) and one cluster identity (kube-systemUIDcluster-uid, namespace UIDnamespace-uid).It exists to test Piceli’s clients, not Kubernetes semantics: keep one integration test against a disposable
kindcluster for anything that depends on the real API server.