Skip to content

API Reference

Creating Assertions

assertion := kcltest.NewKCLAssertion(t, "path/to/main.k").
    WithTestInput(
        kcltest.WithInputFile("input.yaml"),
        kcltest.WithStringOverride([]string{"path", "to", "value"}, "new-value"),
    )
assertion := kcltest.NewKCLAssertion(t, "path/to/main.k").
    WithInput(map[string]any{
        "oxr": oxrData,
        "ctx": ctxData,
    })

Test Input Options

Function Description Example
WithInputFile(path) Load input from YAML file WithInputFile("input.yaml")
WithStringOverride(path, value) Override string value WithStringOverride([]string{"oxr", "spec", "region"}, "us-west-1")
WithBoolOverride(path, value) Override boolean value WithBoolOverride([]string{"oxr", "spec", "enabled"}, true)
WithIntOverride(path, value) Override integer value WithIntOverride([]string{"oxr", "spec", "replicas"}, 3)
WithSliceOverride(path, value) Override slice/array value WithSliceOverride([]string{"oxr", "spec", "admins"}, []string{"a@ex.com"})
WithMapOverride(path, value) Override map value WithMapOverride([]string{"oxr", "spec", "labels"}, map[string]string{"env": "prod"})
WithOverride(path, value) Override any value (generic) WithOverride([]string{"oxr", "spec", "config"}, complexValue)

Assertion Methods

Resource Existence

Method Description
AssertItemExists(kind, msg...) Assert resource of kind exists
AssertItemDoesNotExist(kind, msg...) Assert resource of kind does not exist

Counting

Method Description
AssertItemCount(count, msg...) Assert total number of resources
AssertItemCountByKind(kind, count, msg...) Assert count of specific resource kind

Metadata

Method Description
AssertAllItemsHaveAnnotation(key) Assert all items have annotation
AssertAllItemsHaveLabel(key) Assert all items have label

Policies

Method Description
AssertAllDeletionPoliciesEqual(policy) Assert all items have deletion policy
AssertProviderConfigForKinds(provider, kinds) Assert provider config for specific kinds

Path Assertions

Dot-notation

Use dot-notation strings like "spec.forProvider.region" for clean, readable path expressions.

Basic Path Assertions

Method Description
AssertPath(kind, path, expected) Assert value at path equals expected
AssertPathExists(kind, path) Assert path exists
AssertPathNotExists(kind, path) Assert path does not exist
AssertPathByIndex(kind, index, path, expected) Assert value at path for item at index

Multi-Item Path Assertions

Method Description
AssertAllOfKindHavePath(kind, path, expected) Assert all items of kind have value at path
AssertAnyOfKindHasPath(kind, path, expected) Assert at least one item has value at path
AssertPathMatches(kind, path, matcherFn) Assert path value matches custom function

Escaping Dots

For keys containing dots (like Kubernetes annotations), escape with backslash:

assertion.AssertPath(
    "Subaccount",
    `metadata.annotations.krm\.kcl\.dev/composition-resource-name`,
    "my-resource",
)

Type-Safe Assertions

String Assertions

Method Description
AssertPathString(kind, path, expected) Assert string value equals expected
AssertPathContains(kind, path, substring) Assert string contains substring
AssertPathHasPrefix(kind, path, prefix) Assert string has prefix
AssertPathHasSuffix(kind, path, suffix) Assert string has suffix
AssertPathNotEmpty(kind, path) Assert string is not empty

Numeric Assertions

Method Description
AssertPathInt(kind, path, expected) Assert integer value equals expected
AssertPathFloat64(kind, path, expected) Assert float64 value equals expected
AssertPathGreaterThan(kind, path, value) Assert numeric value is greater than
AssertPathLessThan(kind, path, value) Assert numeric value is less than

Boolean & Slice Assertions

Method Description
AssertPathBool(kind, path, expected) Assert boolean value equals expected
AssertPathStringSlice(kind, path, expected) Assert string slice equals expected

Scoped Assertions with ForKind()

Focus assertions on a specific resource kind for cleaner tests.

assertion.ForKind("Subaccount").
    AssertCount(1).
    AssertExists().
    AssertPath("spec.forProvider.region", "eu10").
    AssertPathString("spec.deletionPolicy", "Delete").
    Done()  // Return to parent assertion
assertion.ForKind("Subaccount").
    AssertCount(1).
    AssertPath("spec.forProvider.region", "eu10").
    Done().
ForKind("RoleCollectionAssignment").
    AssertCount(2).
    AssertAnyHasPath("spec.forProvider.roleCollectionName", "Admin").
    Done().
ForKind("Usage").
    AssertNotExists().
    Done()
assertion.ForKind("RoleCollectionAssignment").Each(func(i int, item map[string]any) {
    name, _ := kcltest.GetByPath[string](item, "metadata.name")
    assert.Contains(t, name, "role-assignment-")
}).Done()

ForKind Methods

Method Description
AssertCount(n) Assert count of items
AssertExists() Assert at least one item exists
AssertNotExists() Assert no items exist
AssertPath(path, expected) Assert path value (first item)
AssertPathString(path, expected) Assert string at path (first item)
AssertPathExists(path) Assert path exists (first item)
AssertAllHavePath(path, expected) Assert all items have value at path
AssertAnyHasPath(path, expected) Assert any item has value at path
Each(fn) Iterate over all items
GetItems() Get all items
GetFirst() Get first item
GetByIndex(i) Get item at index
Done() Return to parent assertion

Finding Resources

Method Description
FindItemByKind(kind) Find first item by kind
FindItemByAnnotation(key, value) Find item by annotation
GetItems() Get all items
GetYAML() Get raw YAML output
GetResult() Get parsed result

Helper Functions

Function Description
GetAllDeletionPolicies(result) Get all deletion policies
CountItemsByKind(result) Count items by kind
FindItemsByKind(result, kind) Find all items of a kind
ValidateProviderConfigs(result, provider, kinds...) Validate provider configs

Nested Map Utilities

Function Description
SetByPath(data, path, value) Set value at path (creates intermediate maps)
GetByPath[T](item, path) Get typed value at path
GetByPathAny(item, path) Get untyped value at path
ParseDotPath(path) Parse dot-notation path to array
GetMapKeys(item) Get map keys

Snapshot Testing

// Match against snapshot (use UPDATE_SNAPS=true to update)
kcltest.MatchSnapshot(t, assertion.GetYAML())

Updating Snapshots

Set UPDATE_SNAPS=true environment variable to update snapshots instead of comparing.


Debugging

// Log a summary of all generated resources
assertion.LogResourceSummary("Resources created:")

Mock Runner

Test assertion logic without actual KCL execution.

runner := kcltest.NewMockKCLRunner(`
items:
  - kind: Subaccount
    metadata:
      name: test-subaccount
    spec:
      forProvider:
        region: eu10
`)

assertion := kcltest.NewKCLAssertionWithRunner(t, "any-path.k", runner).
    WithInput(map[string]any{})

assertion.
    AssertItemExists("Subaccount").
    AssertPath("Subaccount", "spec.forProvider.region", "eu10")
// Verify what was passed to the runner
assert.Len(t, runner.Calls, 1)
assert.Equal(t, "any-path.k", runner.Calls[0].Path)
// Create a mock that returns an error
errorRunner := kcltest.NewMockKCLRunnerWithError(
    errors.New("KCL compilation failed"),
)