stacktest

package
v0.2.0-beta.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

Stacktest - Generation Contract Checks

Go Reference

Checks an ApplicationConfig against the generation contract from the config author's own tests.

The contract (stack.ApplicationConfig; the Stack page § Generation contract) says that what Generate returns belongs to the caller: kure writes to the returned objects, and so may the caller. A config that hands out the same object, map, slice or pointer twice therefore lets one result's edits reach another, and nothing fails at the point of the mistake. Neither does a wrapper that hides the config's optional interfaces. This package finds both.

Checking a config in a test

func TestMyConfig_Conformance(t *testing.T) {
    stacktest.AssertGeneration(t, stack.NewApplication("web", "default", &MyConfig{}))
}

AssertGeneration calls Application.Generate twice, so Validate runs before each call as in a walk, and fails the test for an error or for every value it reports, naming both paths. CheckGeneration returns the same findings as a Report instead:

app := stack.NewApplication("web", "default", &cachingConfig{})
report, err := stacktest.CheckGeneration(app)
if err != nil {
    fmt.Println(err)
    return
}
for _, s := range report.Shared {
    fmt.Printf("%s shared: %s\n", s.Kind, s.First)
}

cachingConfig keeps the labels map it built on the first call and puts it on every ConfigMap, so this prints map shared: [0].(*v1.ConfigMap).ObjectMeta.Labels.

What is reported

Field Holds
Report.Shared values the two results share
Report.Internal values one result reaches at two paths, such as one map used as both labels and selector
Report.Interfaces the optional interfaces the config implements

Each Sharing names the Kind of the value (object, map, slice for a slice's backing array, pointer for any other pointer) and its two paths. A path starts at the result slice: [1].(*v1.Deployment).Spec.Selector.MatchLabels is the selector map of the Deployment the second entry holds, and the empty path is the result slice itself.

Storage counts as shared when it overlaps, not only when two pointers are equal: a re-sliced cached slice, a pointer into another result's slice and a pointer into a struct another result holds are all reported. A value inside one already reported at both of its paths is not listed again, so a shared *Deployment is one entry, not one per map inside it.

Wrappers and optional interfaces

kure finds stack.Validator, layout.LayoutAugmenter and layout.LayoutIntentAugmenter by type assertion on the config itself. A wrapper that embeds the ApplicationConfig interface hides them; compare it with the config it wraps:

inner := &validatedConfig{}
missing := stacktest.InterfacesOf(wrapped{inner}).Missing(stacktest.InterfacesOf(inner))
fmt.Println(missing)

wrapped embeds stack.ApplicationConfig and validatedConfig implements Validate, so this prints [stack.Validator].

Limits

  • Two calls are compared, not every call: a config that shares only from its third call on passes.
  • A time.Time (so a metav1.Time) is not walked: time.Now gives every value the same package-level location, and a deep copy shares it too. Strings are immutable and are not checked.
  • A value that contains itself is walked once and is not reported.
  • A slice's elements are walked up to its length. A value held only between its length and capacity (items[:0] over an array holding a cached map) is not checked, though reslicing reaches it.
  • A func, channel or unsafe pointer in a result is returned as an error. So is a map with a key that is not a string, bool, integer or float (directly or held in an interface), and a map with two keys that print alike (two NaN keys, or 1 and "1" in a map[any]any), whose entries would share a path. Kubernetes objects hold none of these.
  • Concurrency safety and what an augmenter adds to the layout are not checked.

Documentation

Overview

Package stacktest checks an ApplicationConfig against the generation contract (stack.ApplicationConfig, pkg/stack README § Generation contract) from the config author's own tests.

It catches the two mistakes the contract names that fail silently:

  • Sharing. CheckGeneration calls Application.Generate twice and reports every object, map, slice backing array or pointer the two results share, and every one a single result reaches by two paths (a labels map that is also a selector). kure and its caller write into what Generate returns, so a shared value carries one result's edits into the other.
  • Lost optional interfaces. InterfacesOf reports which of stack.Validator, layout.LayoutAugmenter and layout.LayoutIntentAugmenter a config implements, so a wrapper can be compared with the config it wraps.

It checks two calls, not every call, and does not check concurrency safety or what an augmenter adds.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Interfaces

type Interfaces struct {
	Validator             bool // stack.Validator
	LayoutAugmenter       bool // layout.LayoutAugmenter
	LayoutIntentAugmenter bool // layout.LayoutIntentAugmenter
}

Interfaces records which optional interfaces kure finds on a config by type assertion.

func InterfacesOf

func InterfacesOf(cfg stack.ApplicationConfig) Interfaces

InterfacesOf reports the optional interfaces cfg implements. A nil cfg implements none.

Example

InterfacesOf compares a wrapper with the config it wraps.

package main

import (
	"fmt"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/stack"
	"github.com/go-kure/kure/pkg/stack/stacktest"
)

// cachingConfig keeps the labels map it builds and hands the same map to
// every ConfigMap it generates.
type cachingConfig struct {
	labels map[string]string
}

func (c *cachingConfig) Generate(*stack.Application) ([]*client.Object, error) {
	if c.labels == nil {
		c.labels = map[string]string{"app": "web"}
	}
	var cm client.Object = &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{Name: "web", Labels: c.labels},
	}
	return []*client.Object{&cm}, nil
}

// wrapped is a wrapper that embeds the ApplicationConfig interface, so the
// wrapped config's Validate is no longer found.
type wrapped struct{ stack.ApplicationConfig }

type validatedConfig struct{ cachingConfig }

func (*validatedConfig) Validate() error { return nil }

func main() {
	inner := &validatedConfig{}
	missing := stacktest.InterfacesOf(wrapped{inner}).Missing(stacktest.InterfacesOf(inner))
	fmt.Println(missing)
}
Output:
[stack.Validator]

func (Interfaces) Missing

func (got Interfaces) Missing(want Interfaces) []string

Missing returns the names of the interfaces want has and got lacks, in the order of the Interfaces fields: what a wrapper (got) hides of the config it wraps (want).

type Report

type Report struct {
	// Shared lists the values the two results share, sorted by First.
	Shared []Sharing
	// Internal lists the values one result reaches at two paths, sorted by
	// First. An entry found in both results is listed once.
	Internal []Sharing
	// Interfaces are the optional interfaces app.Config implements.
	Interfaces Interfaces
}

Report is the outcome of CheckGeneration.

func AssertGeneration

func AssertGeneration(t testing.TB, app *stack.Application) *Report

AssertGeneration runs CheckGeneration and fails t, with Errorf, for an error or for each value in the report's Shared and Internal lists, naming both paths. It returns the report, or nil after an error.

func CheckGeneration

func CheckGeneration(app *stack.Application) (*Report, error)

CheckGeneration calls app.Generate twice, so Validate runs before each call as in a walk, and reports every value the two results share, every value one result reaches at two paths, and the config's optional interfaces.

Storage counts as shared when it overlaps, not only when two pointers are equal: a pointer into another result's slice, or into a struct another result holds, is reported. A match inside a value already reported at both of its paths is not listed again. A time.Time (so a metav1.Time) is not walked: time.Now gives every value the same package-level location. Strings are immutable and are not checked. A value that contains itself is walked once and is not reported. A slice's elements are walked up to its length: a value held only between its length and capacity, which reslicing reaches, is not checked.

An error from either call is returned wrapped with the call number, with no report. So is a func, channel or unsafe pointer value in a result, a map with a key that is not a string, bool, integer or float (directly or in an interface), or a map with two keys that print alike (two NaN keys), which a Kubernetes object never holds.

Example

CheckGeneration finds the labels map the two results share: a label kure or the caller adds to one ConfigMap would appear on the other.

package main

import (
	"fmt"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/stack"
	"github.com/go-kure/kure/pkg/stack/stacktest"
)

// cachingConfig keeps the labels map it builds and hands the same map to
// every ConfigMap it generates.
type cachingConfig struct {
	labels map[string]string
}

func (c *cachingConfig) Generate(*stack.Application) ([]*client.Object, error) {
	if c.labels == nil {
		c.labels = map[string]string{"app": "web"}
	}
	var cm client.Object = &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{Name: "web", Labels: c.labels},
	}
	return []*client.Object{&cm}, nil
}

func main() {
	app := stack.NewApplication("web", "default", &cachingConfig{})
	report, err := stacktest.CheckGeneration(app)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, s := range report.Shared {
		fmt.Printf("%s shared: %s\n", s.Kind, s.First)
	}
}
Output:
map shared: [0].(*v1.ConfigMap).ObjectMeta.Labels

type Sharing

type Sharing struct {
	// Kind is what the value at First is: "object" (a pointer to a
	// client.Object, or a *client.Object entry), "map", "slice" (a slice's
	// backing array) or "pointer" (any other pointer).
	Kind string
	// First is the path in the first result, or for sharing within one
	// result the path the walk reached first.
	First string
	// Second is the path in the second result, or the later path within
	// one result.
	Second string
}

Sharing is one value reached at two paths.

A path starts at the result slice: "[1].(*v1.Deployment).Spec.Selector.MatchLabels" is the selector map of the Deployment the second entry holds. Indexing a slice, array or map adds "[i]" or "[key]", a struct field ".Field", an interface ".(T)" with the dynamic type; following a pointer adds nothing. The empty path is the result slice itself.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL