golden

package module
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2025 License: MIT Imports: 16 Imported by: 0

README

golden

pkg.go.dev

golden provides utilities for golden file tests.

package a_test

import (
	"flag"
	"os"
	"path/filepath"
	"testing"

	"github.com/tenntenn/golden"
)

var (
	flagUpdate bool
)

func init() {
	flag.BoolVar(&flagUpdate, "update", false, "update golden files")
}

func testTarget(dir string) error {
	if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("hello"), 0700); err != nil {
		return err
	}

	if err := os.WriteFile(filepath.Join(dir, "b.txt"), []byte("world"), 0700); err != nil {
		return err
	}

	return nil
}

func Test(t *testing.T) {
	dir := t.TempDir()
	if err := testTarget(dir); err != nil {
		t.Fatal("unexpected error:", err)
	}

	got := golden.Txtar(t, dir)
	if diff := golden.Check(t, flagUpdate, "testdata", "mytest", got); diff != "" {
		t.Error(diff)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check added in v0.3.0

func Check(t *testing.T, update bool, testdata, name string, data any, opts ...cmp.Option) string

Check updates a golden file when update is true otherwise compares data with the exsiting golden file by DiffWithOpts. If update is true Check does not compare and just return "".

var flagUpdate bool

func init() {
	flag.BoolVar(&flagUpdate, "update", false, "update golden files")
}

func Test(t *testing.T) {
	got := doSomething()
	if diff := golden.Check(t, flagUpdate, "testdata", t.Name(), got); diff != "" {
		t.Error(diff)
	}
}

func Diff

func Diff(t *testing.T, testdata, name string, data any) string

Diff compares between the given data and a golden file which is stored in testdata as name+".golden". Diff returns difference of them. Diff uses go-cmp to compare.

func DiffWithOpts added in v0.3.0

func DiffWithOpts(t *testing.T, testdata, name string, data any, opts ...cmp.Option) string

DiffWithOpts compares between the given data and a golden file which is stored in testdata as name+".golden". DiffWithOpts returns difference of them. DiffWithOpts uses go-cmp to compare.

func DirInit added in v0.2.0

func DirInit(t *