|
| 1 | +# Testing Module SDK hooks |
| 2 | + |
| 3 | +This document describes how we test hooks built on top of the Module SDK. |
| 4 | + |
| 5 | +The goal is simple: **let module developers test hook logic with the same speed and confidence as plain Go code**, without standing up a real Kubernetes cluster, addon-operator, or shell-operator. |
| 6 | + |
| 7 | +## TL;DR |
| 8 | + |
| 9 | +There are three layers, picked by the size of the test you want to write: |
| 10 | + |
| 11 | +| Layer | Use it for | Speed | Lives at | |
| 12 | +| --- | --- | --- | --- | |
| 13 | +| **Mocks** | Tests that need precise control over a single dependency | µs | [`testing/mock`](./testing/mock) | |
| 14 | +| **Helpers** | Unit tests of a single hook handler | µs | [`testing/helpers`](./testing/helpers) | |
| 15 | +| **Framework** | Functional tests driving the whole hook pipeline against a fake K8s cluster | ms | [`testing/framework`](./testing/framework) | |
| 16 | + |
| 17 | +Pick the smallest layer that lets you write the assertion you actually care about. |
| 18 | + |
| 19 | +## Test pyramid |
| 20 | + |
| 21 | +```text |
| 22 | + ┌──────────────────────┐ |
| 23 | + │ framework (slow) │ end-to-end behaviour |
| 24 | + ├──────────────────────┤ |
| 25 | + │ helpers (fast) │ handler-level units |
| 26 | + ├──────────────────────┤ |
| 27 | + │ mock (fastest) │ single-collaborator |
| 28 | + └──────────────────────┘ |
| 29 | +``` |
| 30 | + |
| 31 | +Most modules end up with a wide base of `helpers`-based unit tests and a thin layer of `framework` functional tests for the trickiest paths. |
| 32 | + |
| 33 | +## Layer 1 — `testing/mock` |
| 34 | + |
| 35 | +`testing/mock` is generated with [`minimock`](https://github.com/gojuno/minimock) from the interfaces in [`pkg`](./pkg). It is the lowest-level layer: you compose mocks yourself and assemble a `*pkg.HookInput` by hand. |
| 36 | + |
| 37 | +Use it when you need **precise control** over a single dependency: |
| 38 | + |
| 39 | +```go |
| 40 | +values := mock.NewOutputPatchableValuesCollectorMock(t) |
| 41 | +values.GetMock.When("global.discovery.clusterDomain"). |
| 42 | + Then(gjson.Result{Type: gjson.String, Str: "cluster.local"}) |
| 43 | + |
| 44 | +input := &pkg.HookInput{ |
| 45 | + Values: values, |
| 46 | + Logger: log.NewNop(), |
| 47 | +} |
| 48 | +require.NoError(t, MyHook(ctx, input)) |
| 49 | +``` |
| 50 | + |
| 51 | +This layer is the right call when: |
| 52 | + |
| 53 | +- you want to assert on the **exact sequence** of calls a hook makes against a collaborator; |
| 54 | +- you need to inject an **error from a specific call** (e.g. `ArrayCount → error`); |
| 55 | +- the hook is small enough that a real values store is overkill. |
| 56 | + |
| 57 | +## Layer 2 — `testing/helpers` |
| 58 | + |
| 59 | +`testing/helpers` is the **default** unit-test layer. It bundles a set of small, hand-written building blocks on top of the real implementations from `pkg/*`: |
| 60 | + |
| 61 | +- `InputBuilder` — fluent assembly of `*pkg.HookInput`. |
| 62 | +- `StaticSnapshots` — in-memory `pkg.Snapshots` backed by JSON / YAML / Go values. |
| 63 | +- `RecordingPatchCollector` — a `pkg.PatchCollector` that records every call. |
| 64 | +- `NewValuesFromJSON/YAML/Map` — a real `pkg.PatchableValuesCollector` seeded from your input. |
| 65 | +- `JQRunOnString/Object` — apply a JQ filter and decode the result in one call. |
| 66 | + |
| 67 | +Typical test: |
| 68 | + |
| 69 | +```go |
| 70 | +in := helpers.NewInputBuilder(t). |
| 71 | + WithSnapshot("nodes", helpers.SnapshotJSON(`{"name":"n1"}`)). |
| 72 | + WithValuesJSON(`{"my":{"existing":"value"}}`). |
| 73 | + WithRecordingPatchCollector(). |
| 74 | + Build() |
| 75 | + |
| 76 | +require.NoError(t, MyHook(context.Background(), in)) |
| 77 | + |
| 78 | +// Real values store: actual patches were recorded. |
| 79 | +require.Len(t, in.Values.GetPatches(), 1) |
| 80 | +``` |
| 81 | + |
| 82 | +Use this layer when: |
| 83 | + |
| 84 | +- you know exactly what the hook should see and do; |
| 85 | +- you want to test the **happy path and a few error paths** of a single handler; |
| 86 | +- you're writing **a JQ filter test** with `helpers.JQRunOn*`. |
| 87 | + |
| 88 | +A complete reference is at [`testing/helpers/README.md`](./testing/helpers/README.md). |
| 89 | + |
| 90 | +## Layer 3 — `testing/framework` |
| 91 | + |
| 92 | +`testing/framework` is the **functional-test** layer, mirroring [`deckhouse/testing/hooks`](https://github.com/deckhouse/deckhouse/tree/main/testing/hooks). The framework: |
| 93 | + |
| 94 | +1. owns a **fake dynamic Kubernetes client** seeded from YAML; |
| 95 | +2. **generates snapshots** from the hook's `KubernetesConfig` bindings (selectors + JQ); |
| 96 | +3. runs the handler with a real `*pkg.HookInput`; |
| 97 | +4. **applies values patches** back to the values store; |
| 98 | +5. **replays cluster patches** (`Create` / `Delete` / `Patch`) against the fake cluster. |
| 99 | + |
| 100 | +After `RunHook`, you assert on: |
| 101 | +- snapshots passed in, |
| 102 | +- final values & config values, |
| 103 | +- recorded patch operations, |
| 104 | +- post-hook cluster state via `KubernetesResource(...)`, |
| 105 | +- collected metrics, |
| 106 | +- captured logs. |
| 107 | + |
| 108 | +Typical test: |
| 109 | + |
| 110 | +```go |
| 111 | +f := framework.HookExecutionConfigInit(t, cfg, handler, `{}`, `{}`) |
| 112 | +f.KubeStateSet(` |
| 113 | +--- |
| 114 | +apiVersion: v1 |
| 115 | +kind: Pod |
| 116 | +metadata: {name: app, namespace: default} |
| 117 | +status: {phase: Running} |
| 118 | +`) |
| 119 | +f.RunHook() |
| 120 | + |
| 121 | +require.NoError(t, f.HookError()) |
| 122 | +require.NotNil(t, f.KubernetesResource("ConfigMap", "default", "app-status")) |
| 123 | +``` |
| 124 | + |
| 125 | +Use this layer when: |
| 126 | + |
| 127 | +- the hook reads multiple bindings or relies on label / namespace selectors; |
| 128 | +- the hook ends up issuing several patch operations and you want to verify the **resulting cluster state**; |
| 129 | +- the hook talks to the API server through `input.DC.GetK8sClient()`; |
| 130 | +- you want one test to walk through several state transitions. |
| 131 | + |
| 132 | +A complete reference is at [`testing/framework/README.md`](./testing/framework/README.md). |
| 133 | + |
| 134 | +## Picking a layer in practice |
| 135 | + |
| 136 | +A small flowchart: |
| 137 | + |
| 138 | +```text |
| 139 | +Are you only testing a JQ filter? |
| 140 | + └─► helpers.JQRunOn{String,Object} |
| 141 | +
|
| 142 | +Are you testing a single handler in isolation, |
| 143 | +with snapshots and values you can describe inline? |
| 144 | + └─► helpers.NewInputBuilder + RecordingPatchCollector |
| 145 | +
|
| 146 | +Do you need to assert on the resulting Kubernetes objects |
| 147 | +(Create + Delete chains, Patch results, JQ mutations)? |
| 148 | + └─► testing/framework |
| 149 | +
|
| 150 | +Do you need to inject a very specific failure from one |
| 151 | +collaborator (e.g. ArrayCount returning an error)? |
| 152 | + └─► testing/mock + a hand-built *pkg.HookInput |
| 153 | +``` |
| 154 | + |
| 155 | +It's normal — and expected — to mix layers in the same package. See e.g. [`examples/example-module/hooks/subfolder`](./examples/example-module/hooks/subfolder), where: |
| 156 | + |
| 157 | +- `*_test.go` files use `helpers.NewInputBuilder` for the bulk of unit tests; |
| 158 | +- `*_framework_test.go` files use `testing/framework` for end-to-end coverage; |
| 159 | +- a handful of error-path tests fall back to `testing/mock` for a specific failure. |
| 160 | + |
| 161 | +## Project-wide testing conventions |
| 162 | + |
| 163 | +- **No global state.** Tests should not rely on `registry.Registry()` having a particular content; build a `*pkg.HookConfig` locally in the test or share it via a small helper in the package. |
| 164 | +- **Ginkgo is being phased out.** New tests should use plain `*testing.T` + `testify`. Existing Ginkgo suites are migrated when their package is touched. |
| 165 | +- **Real values stores beat value mocks.** If you can use `helpers.NewValuesFromJSON`, do — the assertions become "did the hook produce the right `add`/`remove` operations?", which is more honest than "did the hook call `Set` with these arguments?". |
| 166 | +- **JQ filters are tested in isolation** via `helpers.JQRunOn{String,Object}`. This keeps the filter expression visible in the test source and decouples it from the hook handler. |
| 167 | +- **Functional tests are sparse but high-value.** Aim for a handful of `framework` tests per hook, not one per code path. |
| 168 | +- **Lint and vet are required.** `go vet ./...` and `golangci-lint run ./...` must stay green; this is enforced by `make test` and `make lint`. |
| 169 | + |
| 170 | +## Running the tests |
| 171 | + |
| 172 | +```sh |
| 173 | +# Module SDK and common-hooks |
| 174 | +make test |
| 175 | +make lint |
| 176 | + |
| 177 | +# Each example module is a standalone Go module under examples/. |
| 178 | +make examples |
| 179 | +``` |
| 180 | + |
| 181 | +Each example module has its own `go.mod` and its own test suite — they are deliberately self-contained so they double as documentation. |
| 182 | + |
| 183 | +## See also |
| 184 | + |
| 185 | +- [`testing/README.md`](./testing/README.md) — overview of the testing tree. |
| 186 | +- [`testing/framework/README.md`](./testing/framework/README.md) — functional-test harness reference. |
| 187 | +- [`testing/helpers/README.md`](./testing/helpers/README.md) — unit-test helper reference. |
| 188 | +- [`pkg/jq`](./pkg/jq) — JQ engine, useful when you want to debug a snapshot filter expression. |
0 commit comments