Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Unit Testing CUE Models

Unit testing CUE models is a crucial part of the development process, allowing you to validate the logic and behavior of your models in isolation, before publishing them for use. This can help catch errors early, ensure your models behave as expected, and provide confidence in their correctness.

Cuestomize, being built as a Go library, allows you to write unit tests for your CUE models using Go’s testing framework.

The following code blocks show an example of how to write unit tests for a CUE model using the Cuestomize library.

// TestValidationModel tests the validation model with various configurations and resources.
func TestValidationModel(t *testing.T) {
	okConfig := loadConfigFromFile(t, "./kustomize/validator.yaml")
	invalidConfig := loadConfig(t, wrongConfigString)
	okDeploy := loadResource(t, "./kustomize/deployment.yaml")
	invalidDeploy := loadResource(t, "./kustomize/invalid_deployment.yaml")

	tt := []struct {
		name      string
		config    *api.KRMInput
		resources []*kyaml.RNode
		expErr    bool
	}{
		{
			name:      "ok config with valid resources",
			config:    okConfig,
			resources: []*kyaml.RNode{okDeploy},
		},
		{
			name:   "ok config, empty resources",
			config: okConfig,
		},
		{
			name:   "invalid config",
			config: invalidConfig,
			expErr: true,
		},
		{
			name:      "ok config with invalid resources",
			config:    okConfig,
			resources: []*kyaml.RNode{invalidDeploy},
			expErr:    true,
		},
		{
			name:      "ok config with both valid and invalid resources",
			config:    okConfig,
			resources: []*kyaml.RNode{okDeploy, invalidDeploy},
			expErr:    true,
		},
	}

	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			provider := model.NewLocalPathProvider("./cue")

			items, err := cuestomize.Cuestomize(
				t.Context(), tc.resources, tc.config, cuestomize.WithModelProvider(provider),
			)
			if tc.expErr {
				assert.Error(t, err)
			} else {
				assert.NoError(t, err)
				// we expect the same number of resources back since this is a validation-only function
				assert.Len(t, items, len(tc.resources))
			}
		})
	}
}

The test files can live in the same repository as your CUE model, and you can use a local path provider to point the Cuestomize function to the local directory where your CUE model is located. This allows you to test your CUE model without needing to publish it to an OCI registry, enabling a fast development and testing cycle.