golden

package
v0.0.0-...-d60ed11 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package golden provides instrumentation for discovering, reading, rendering and writing golden files.

Index

Examples

Constants

View Source
const (
	// DefaultDirPerm is a default permissions for [DirWriter].
	DefaultDirPerm os.FileMode = os.ModeDir | 0o755
	// DefaultFilePerm is a default permissions for [FileWriter].
	DefaultFilePerm os.FileMode = 0o644
)
View Source
const DefaultFilename = "golden.tmpl"

DefaultFilename is a default golden file basename.

View Source
const DirKeepMarkerFilename = ".gitkeep"

DirKeepMarkerFilename is a filename for unofficial convention used to force Git to track an empty directory.

Variables

This section is empty.

Functions

This section is empty.

Types

type Data

type Data interface {
	// TmplVars converts data into format compartible with text/template.
	TmplVars() (any, error)
	// Format render data as text to save into golden file.
	Format(Formatter) ([]byte, error)
	// Valid checks whether or not data should be saved as golden file.
	Valid(DataFilter) bool
}

Data is a target representation of arbitrary datum.

type DataAdapter

type DataAdapter interface {
	// AdaptRaw adapts raw bytes as concrete Data implementation.
	// Error free adapt function should be used, since validity will
	// be checked by any of Data methods.
	AdaptRaw([]byte) Data
}

DataAdapter is to adapt arbitrary data by concrete Formatter.

type DataAny

type DataAny struct {
	// contains filtered or unexported fields
}

DataAny is a generic datum representation.

func (DataAny) Format

func (d DataAny) Format(f Formatter) ([]byte, error)

Format render data as text to save into golden file.

func (DataAny) TmplVars

func (d DataAny) TmplVars() (any, error)

TmplVars converts data into format compartible with text/template.

func (DataAny) Valid

func (d DataAny) Valid(f DataFilter) bool

Valid checks whether or not data should be saved as golden file.

type DataFilter

type DataFilter func(any) bool

DataFilter is for check whether or not data should be filtered.

func NewDataFilterEmpty

func NewDataFilterEmpty() DataFilter

NewDataFilterEmpty instantiate DataFilter to check whether or not data is empty, or equal to zero value, or zero length.

Example (Empty)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	f := golden.NewDataFilterEmpty()
	fmt.Println(f(make(map[string]struct{})))
}
Output:
true
Example (Nil)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	f := golden.NewDataFilterEmpty()
	fmt.Println(f(nil))
}
Output:
true
Example (Ok)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	f := golden.NewDataFilterEmpty()
	s := struct {
		F *struct{}
	}{
		F: new(struct{}),
	}
	fmt.Println(f(s))
}
Output:
false
Example (Zero)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	f := golden.NewDataFilterEmpty()
	var s struct {
		F *struct{}
	}
	fmt.Println(f(s))
}
Output:
true

type DataJSON

type DataJSON json.RawMessage

DataJSON is a JSON datum representation.

func (DataJSON) Format

func (d DataJSON) Format(f Formatter) ([]byte, error)

Format render data as text to save into golden file.

func (DataJSON) TmplVars

func (d DataJSON) TmplVars() (any, error)

TmplVars converts data into format compartible with text/template.

func (DataJSON) Valid

func (d DataJSON) Valid(f DataFilter) bool

Valid checks whether or not data should be saved as golden file.

type DirWriter

type DirWriter func(string, os.FileMode) error

DirWriter is a creator of directories.

type FS

type FS struct {
	// contains filtered or unexported fields
}

FS is golden files read and write store wrapper. Any implementation of io/fs.FS could be used as source (e.g. os.DirFS or embed.FS). Writes are performed over host filesystem if Writer option is not used.

func NewFS

func NewFS(opts ...FSOption) *FS

NewFS instantiate FS.

func (*FS) RenderDir

func (f *FS) RenderDir(t TestingT, actual fs.FS) (fs.FS, error)

RenderDir handle same as FS.RenderFile every fs.FS entry. Note that filename from Locator is always ignored. Symlinks are handled as regular directories/files, and like so they are will be saved as golden.

Example
package main

import (
	"bytes"
	"fmt"
	"io/fs"
	"path/filepath"
	"testing"
	"testing/fstest"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	got := fstest.MapFS{
		"file.txt": &fstest.MapFile{
			Data: []byte(`plaintext`),
		},
		"subdir/file.json": &fstest.MapFile{
			Data: []byte(`{"key":"value"}`),
		},
	}

	fsys := golden.NewFS(
		golden.WithFSFormatter(golden.NewStrFormatter()),
		golden.WithFSLocator(func(golden.LocationVars) fmt.Stringer {
			return bytes.NewBufferString(filepath.Join("testdata", "golden", "dir-example", "example.tmpl"))
		}),
		golden.WithFSDirEntryOverrides(
			filepath.Join("subdir", "file.json"), golden.WithFSFormatter(golden.NewJSONFormatter()),
		),
	)
	want, err := fsys.RenderDir(new(testing.T), got)
	_ = fs.WalkDir(want, ".", func(path string, d fs.DirEntry, _ error) error {
		if !d.IsDir() {
			f, er := fs.ReadFile(want, path)
			fmt.Printf("%s: %s, %v\n", path, f, er)
		}

		return nil
	})
	fmt.Println(err)
}
Output:
file.txt: plaintext, <nil>
subdir/file.json: {
    "key": "value"
}
, <nil>
<nil>

func (*FS) RenderFile

func (f *FS) RenderFile(t TestingT, actual any) ([]byte, error)

RenderFile locate and read golden file, render it as text/template with actual data, and write result back if `-update` flag defined. File will be auto created if doesn't exists. Value of `actual` is the result of operation which being tested, and could be of type golden.Data, json.RawMessage or any other type convertible to text.

Example (Embedfs)
package main

import (
	"bytes"
	"embed"
	"fmt"
	"path/filepath"
	"testing"

	"github.com/Serjick/gon-gild-on/golden"
)

//go:embed *
var goldens embed.FS

func main() {
	/* -- testdata/golden/example.tmpl --
	{
	    "key": "{{ .Actual.key }}"
	}
	*/
	path := filepath.Join("testdata", "golden", "example.tmpl")
	f := golden.NewFS(golden.WithFSSource(golden.NewSourceFS(goldens)),
		golden.WithFSLocator(func(golden.LocationVars) fmt.Stringer {
			return bytes.NewBufferString(path)
		}),
	)
	b, err := f.RenderFile(new(testing.T), map[string]string{"key": "value"})
	fmt.Printf("%s", b)
	fmt.Print(err)
}
Output:
{
    "key": "value"
}
<nil>

func (*FS) WithDataFilter

func (f *FS) WithDataFilter(df DataFilter) *FS

WithDataFilter is a immutable setter for filter of actual data to prevent writes.

func (*FS) WithDirEntryOverrides

func (f *FS) WithDirEntryOverrides(path string, opts ...FSOption) *FS

WithDirEntryOverrides is a immutable setter for dir entry options override. Passing empty FSOption list equivalent to override deletion.

func (*FS) WithForceUpdate

func (f *FS) WithForceUpdate() *FS

WithForceUpdate is a immutable setter to always overwrite golden file with actual data.

func (*FS) WithFormatter

func (f *FS) WithFormatter(fmt Formatter) *FS

WithFormatter is a golden file content formatter immutable setter.

func (*FS) WithLocator

func (f *FS) WithLocator(l Locator) *FS

WithLocator is a golden file location resolver immutable setter.

func (*FS) WithOptions

func (f *FS) WithOptions(opts ...FSOption) *FS

WithOptions is a multiple options immutable setter.

func (*FS) WithPreSaveHook

func (f *FS) WithPreSaveHook(h PreSaveHook) *FS

WithPreSaveHook is a immutable setter for pre golden file save hook.

func (*FS) WithRoot

func (f *FS) WithRoot(dir string) *FS

WithRoot is a root directory immutable setter.

func (*FS) WithSource

func (f *FS) WithSource(src Source) *FS

WithSource is a golden files Source immutable setter.

func (*FS) WithTmplFuncFactory

func (f *FS) WithTmplFuncFactory(tf TmplFuncFactory) *FS

WithTmplFuncFactory is a immutable merger of text/template functions collection factories.

func (*FS) WithWriter

func (f *FS) WithWriter(dir DirWriter, file FileWriter) *FS

WithWriter is a dir and file writers implementations immutable setter.

type FSOption

type FSOption func(*FS) *FS

FSOption is a single setting setter for FS in a immutable way.

func WithFSDataFilter

func WithFSDataFilter(f DataFilter) FSOption

WithFSDataFilter is a immutable setter for filter of actual data to prevent FS writes.

func WithFSDirEntryOverrides

func WithFSDirEntryOverrides(path string, opts ...FSOption) FSOption

WithFSDirEntryOverrides is a immutable setter for FS dir entry options override.

func WithFSForceUpdate

func WithFSForceUpdate() FSOption

WithFSForceUpdate is to force golden file overwrite with actual data by FS.

func WithFSFormatter

func WithFSFormatter(f Formatter) FSOption

WithFSFormatter is a golden file content formatter immutable setter for FS.

func WithFSLocator

func WithFSLocator(l Locator) FSOption

WithFSLocator is a golden file location resolver immutable setter for FS.

func WithFSPreSaveHook

func WithFSPreSaveHook(h PreSaveHook) FSOption

WithFSPreSaveHook is a immutable setter for pre golden file FS save hook.

func WithFSRoot

func WithFSRoot(dir string) FSOption

WithFSRoot is a root directory immutable setter for FS writes.

func WithFSSource

func WithFSSource(src Source) FSOption

WithFSSource is a golden files Source immutable setter for FS.

func WithFSTmplFuncFactory

func WithFSTmplFuncFactory(tf TmplFuncFactory) FSOption

WithFSTmplFuncFactory is a golden files text/template functions factories immutable merger for FS.

func WithFSWriter

func WithFSWriter(d DirWriter, f FileWriter) FSOption

WithFSWriter is a dir and file writers implementations immutable setter for FS.

type FileWriter

type FileWriter func(string, []byte, os.FileMode) error

FileWriter is a creator and writer of files.

type FnFormatter

type FnFormatter func(...any) string

FnFormatter is implementation of Formatter compartible with stdlib fmt package.

func NewFmtFormatter

func NewFmtFormatter() FnFormatter

NewFmtFormatter instantiates fmt.Sprintln as FnFormatter.

func NewPatternFormatter

func NewPatternFormatter(pattern string) FnFormatter

NewPatternFormatter instantiates fmt.Sprintf with specified pattern as FnFormatter.

func NewStrFormatter

func NewStrFormatter() FnFormatter

NewStrFormatter instantiates fmt.Sprintf with simple string pattern as FnFormatter.

func (FnFormatter) Bytes

func (f FnFormatter) Bytes(data any) ([]byte, error)

Bytes dump any data as is.

Example
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	b, err := golden.NewFmtFormatter().Bytes(`title = "TOML"` + "\n\n" + "[example]" + "\n" + `name = "fmt"`)
	fmt.Printf("%s", b)
	fmt.Print(err)
}
Output:
title = "TOML"

[example]
name = "fmt"
<nil>

type Formatter

type Formatter interface {
	// Bytes converts arbitrary data into text to use as golden file content.
	Bytes(any) ([]byte, error)
}

Formatter is golden file content converter.

type Hooks

type Hooks struct {
	// contains filtered or unexported fields
}

Hooks is a compose of arbitrary hooks for golden file handle phases.

func NewHooksDefault

func NewHooksDefault() Hooks

NewHooksDefault instatiates default Hooks.

type JSONFormatter

type JSONFormatter struct {
	// contains filtered or unexported fields
}

JSONFormatter is implementation of Formatter based on encoding/json.

func NewJSONFormatter

func NewJSONFormatter() *JSONFormatter

NewJSONFormatter instantiates JSONFormatter.

func (*JSONFormatter) AdaptRaw

func (*JSONFormatter) AdaptRaw(b []byte) Data

AdaptRaw adapts raw bytes as JSON Data.

func (*JSONFormatter) Bytes

func (f *JSONFormatter) Bytes(data any) ([]byte, error)

Bytes dump any data as json.

Example (Nil)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	b, err := golden.NewJSONFormatter().Bytes(nil)
	fmt.Printf("%s", b)
	fmt.Print(err)
}
Output:
null
<nil>
Example (Raw)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	b, err := golden.NewJSONFormatter().Bytes(json.RawMessage(`{"F": {}}`))
	fmt.Printf("%s", b)
	fmt.Print(err)
}
Output:
{
    "F": {}
}
<nil>
Example (Struct)
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	var s struct {
		F struct{}
	}
	b, err := golden.NewJSONFormatter().Bytes(&s)
	fmt.Printf("%s", b)
	fmt.Print(err)
}
Output:
{
    "F": {}
}
<nil>

type Location

type Location struct {
	// Dir is a [Location] directory.
	Dir string
	// File is a [Location] path relative to [Location.Dir].
	// It may or may not contain directory.
	File string
}

Location is a directory and filename tuple.

func (Location) Rel

func (l Location) Rel() string

Rel returns directory relative to Location.Dir.

func (Location) String

func (l Location) String() string

String returns path.

func (Location) WithFile

func (l Location) WithFile(f ...string) Location

WithFile is a Location.File immutable setter.

type LocationVars

type LocationVars struct {
	TestName string
}

LocationVars is a variables for Locator to resolve path to golden file.

type Locator

type Locator func(LocationVars) fmt.Stringer

Locator is a golden file path resolver.

func NewLocatorDefault

func NewLocatorDefault() Locator

NewLocatorDefault instantiates default Locator.

Example
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	l := golden.NewLocatorDefault()
	fmt.Println(l(golden.LocationVars{
		TestName: "TestFoo/Bar",
	}))
}
Output:
testdata/golden/TestFoo/Bar/golden.tmpl

func NewLocatorFilename

func NewLocatorFilename(name string) Locator

NewLocatorFilename instantiates Locator with custom golden file basename.

Example
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	l := golden.NewLocatorFilename("example.json")
	fmt.Println(l(golden.LocationVars{
		TestName: "TestFoo",
	}))
}
Output:
testdata/golden/TestFoo/example.json

func NewLocatorSubDir

func NewLocatorSubDir(dir string) Locator

NewLocatorSubDir instantiates Locator with custom directories.

Example
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	l := golden.NewLocatorSubDir("api")
	fmt.Println(l(golden.LocationVars{
		TestName: "TestFoo",
	}))
}
Output:
testdata/golden/api/TestFoo/golden.tmpl

func NewLocatorSubDirFilename

func NewLocatorSubDirFilename(dir, filename string) Locator

NewLocatorSubDirFilename instantiates Locator with custom directories and golden file basename.

Example
package main

import (
	"fmt"

	"github.com/Serjick/gon-gild-on/golden"
)

func main() {
	l := golden.NewLocatorSubDirFilename("api", "example.json")
	fmt.Println(l(golden.LocationVars{
		TestName: "TestFoo",
	}))
}
Output:
testdata/golden/api/TestFoo/example.json

type PreSaveHook

type PreSaveHook func(TestingT, []byte, PreSaveHookVars) []byte

PreSaveHook is a hook calling before golden file write.

func NewPreSaveHookDefault

func NewPreSaveHookDefault() PreSaveHook

NewPreSaveHookDefault instatiates default PreSaveHook.

type PreSaveHookVars

type PreSaveHookVars struct {
	// Current is a present content of golden file.
	Current []byte
	// TmplFuncs is a composition of functions from all TmplFuncFactory.
	TmplFuncs template.FuncMap
}

PreSaveHookVars is a variables available from presave hooks implementations.

type Source

type Source func(SourceVars) fs.FS

Source is a factory of filesystem where golden files are located.

func MustNewSourceRel

func MustNewSourceRel() Source

MustNewSourceRel creates Source which uses directory relative to caller as a fs.FS root.

func NewSourceCaller

func NewSourceCaller() Source

NewSourceCaller creates Source which uses SourceVars.RenderCallerDir as a fs.FS root.

func NewSourceCwd

func NewSourceCwd() Source

NewSourceCwd instantiate Source which uses directory from which `go test` has been run as a fs.FS root.

func NewSourceDir

func NewSourceDir(dir string) Source

NewSourceDir instantiate Source which uses specified dir as a fs.FS root.

func NewSourceFS

func NewSourceFS(f fs.FS) Source

NewSourceFS instantiate Source which utilizes specified fs.FS.

type SourceVars

type SourceVars struct {
	// RenderCallerDir is a directory of [FS.RenderFile] caller.
	RenderCallerDir string
}

SourceVars is a for Source to instantiate fs.FS.

type TestingT

type TestingT interface {

	// TempDir returns a temporary directory for the test to use.
	// The directory is automatically removed when the test and
	// all its subtests complete.
	// Each subsequent call to t.TempDir returns a unique directory;
	// if the directory creation fails, TempDir terminates the test by calling Fatal.
	TempDir() string
	// contains filtered or unexported methods
}

TestingT is a interface compartible with standart testing.T.

type TmplFuncFactory

type TmplFuncFactory func(TestingT, TmplFuncFactoryVars) template.FuncMap

TmplFuncFactory is a text/template functions collection factory.

type TmplFuncFactoryVars

type TmplFuncFactoryVars struct{}

TmplFuncFactoryVars is a variables for TmplFuncFactory used to create functions collection.

type UpdateAllower

type UpdateAllower func() bool

UpdateAllower is for allow/deny golden file overwrite with actual data.

func NewUpdateAllowerByFlag

func NewUpdateAllowerByFlag() UpdateAllower

NewUpdateAllowerByFlag returns UpdateAllower allowing update only when `-gon-gild-on.update` or `-update` flag is specified and it is not `false`.

type Writer

type Writer struct {
	Dir  DirWriter
	File FileWriter
}

Writer is composion of all writers.

Directories

Path Synopsis
Package gildedk8sapimachinery provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/kubernetes/apimachinery.
Package gildedk8sapimachinery provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/kubernetes/apimachinery.
Package gildedsergigodiff provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/sergi/go-diff.
Package gildedsergigodiff provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/sergi/go-diff.
internal
Package internal of gildedsergigodiff.
Package internal of gildedsergigodiff.
Package gildedspew provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/davecgh/go-spew.
Package gildedspew provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/davecgh/go-spew.
Package gildedtestify provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/stretchr/testify.
Package gildedtestify provides implementations for github.com/Serjick/gon-gild-on/golden based on github.com/stretchr/testify.

Jump to

Keyboard shortcuts

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