goldie

repository·master·Indexed 42 days ago

https://github.com/sebdah/goldie

A golden file testing utility for Go designed to simplify testing of large data bodies, such as HTTP responses, by comparing actual output against stored golden files. It supports raw byte assertions, JSON and XML validation with automatic indentation, and Go templates for dynamic values. Features include configurable diff engines (Classic, Colored, Simple), customizable fixture directories, and the ability to update fixtures using the -update and -clean flags.

Tokens
6.6K
Snippets
30
Records
47
Agent score
51%

What's inside goldie

  1. How golden file testing works in goldie

    master

    Goldie is a utility for testing large data bodies (like API responses) by comparing actual output against a stored "golden file".

    1. Storage: Valid response data is saved in a fixture file (defaulting to the testdata directory).
    2. Assertion: During a test, goldie performs a byte comparison between the actual output and the golden file.
    3. Failure: If the bytes differ, the test fails.
    4. Updating: To update the golden files when the expected output changes, run your tests with the -update flag:
    go test -update ./...
  2. Install goldie v2

    master

    To install the latest version (v2) of goldie, use the following command:

    go get -u github.com/sebdah/goldie/v2

    For the legacy v1 release, use:

    go get -u github.com/sebdah/goldie
    go get -u github.com/sebdah/goldie/v2
  3. Configure Goldie with Options

    master

    The New function accepts functional options to customize the Goldie instance. While the specific option functions are defined in other parts of the package, they allow you to control:

    • fixtureDir: The base directory for fixtures (defaults to testdata).
    • fileNameSuffix: Suffix for golden files (defaults to .golden).
    • filePerms / dirPerms: File and directory permissions.
    • diffEngine: The engine used for diffing (e.g., ClassicDiff, ColoredDiff).
    • ignoreTemplateErrors: Whether to ignore errors in templates.
    • useTestNameForDir: Whether to use the test name to organize the directory structure.
    • useSubTestNameForDir: Whether to use the sub-test name to organize the directory structure.
  4. Configure goldie using functional options

    master

    You can customize goldie's behavior by passing functional options to goldie.New().

    Commonly used options include:

    • WithFixtureDir(string): Set the directory where fixtures are stored (default: testdata).
    • WithNameSuffix(string): Set the suffix for fixture files (default: .golden).
    • WithDiffEngine(engine): Choose the diff output mode (goldie.ClassicDiff, goldie.ColoredDiff, or goldie.Simple).
    • WithTestNameForDir(bool): Create a folder named after the test for the fixtures.
    • WithSubTestNameForDir(bool): Create a folder named after the sub-test for the fixtures.
    • WithDirPerms(os.FileMode): Set directory permissions for fixtures (default: 0755).
    • WithFilePerms(os.FileMode): Set file permissions for fixtures (default: 0644).
    • WithIgnoreTemplateErrors(bool): Whether to ignore errors from templates (default: false).
    • WithDiffFn(fn): Provide custom diff logic.
    func TestNewExample(t *testing.T) {
        g := goldie.New(
            t,
            goldie.WithFixtureDir("test-fixtures"),
            goldie.WithNameSuffix(".golden.json"),
            goldie.WithDiffEngine(goldie.ColoredDiff),
            goldie.WithTestNameForDir(true),
        )
    
        g.Assert(t, "example", []byte("my example data"))
    }
  5. Update golden files using the -update flag

    master

    Instead of calling Update() manually in your code, the recommended way to refresh your golden files is to run your tests with the -update flag:

    go test -update ./...

    When this flag is provided, Goldie will overwrite existing golden files with the actual data received during the test run.

  6. Perform assertions using templates with AssertWithTemplate

    master

    If your golden files contain dynamic values, you can use Go templates within the .golden file. Use g.AssertWithTemplate(t, name, data, actualBytes) to pass a data object to the template during comparison.

    Example golden file (example.golden):

    This is a {{ .Type }} file.

    Example Test:

    func TestTemplateExample(t *testing.T) {
        // ... setup ...
        data := struct {
            Type string
        }{
            Type: "Golden",
        }
    
        g := goldie.New(t)
        g.AssertWithTemplate(t, "example", data, recorder.Body.Bytes())
    }
    func TestTemplateExample(t *testing.T) {
        recorder := httptest.NewRecorder()
        req, err := http.NewRequest("POST", "/example/Golden", nil)
        assert.Nil(t, err)
    
        handler := http.HandlerFunc(ExampleHandler)
        handler.ServeHTTP()
    
        data := struct {
            Type string
        }{
            Type: "Golden",
        }
    
        g := goldie.New(t)
        g.AssertWithTemplate(t, "example", data, recorder.Body.Bytes())
    }
  7. Perform basic assertions with Assert

    master

    Use goldie.New(t) to initialize a goldie instance and g.Assert(t, name, data) to compare a byte slice against a golden file named {name}.golden.

    func TestExample(t *testing.T) { 
        // ... setup recorder and handler ...
        g := goldie.New(t)
        g.Assert(t, "example", recorder.Body.Bytes())
    }
  8. Configure Diff Engine output modes

    master

    Goldie supports three diff output modes to help you identify differences in failed tests. Use WithDiffEngine to select one:

    • goldie.ClassicDiff: The default mode.
    • goldie.ColoredDiff: Provides colored output for better visibility.
    • goldie.Simple: A simplified diff view.
    g := goldie.New(
        t,
        goldie.WithDiffEngine(goldie.ColoredDiff), // Options: goldie.Simple, goldie.ColoredDiff, goldie.ClassicDiff
    )
  9. Handle missing template keys

    master

    When using assertions that involve templates, if a required key is missing from the data provided to the template, goldie returns an error indicating the missing key.

    Note: The error type errMissingKey is internal, but the error message will describe which key or value is missing.

  10. Handle fixture directory conflicts

    master

    If the path configured to hold your golden fixtures is actually a file instead of a directory, goldie will return an error.

    While the specific type errFixtureDirectoryIsFile is internal, you can detect this issue via the error message format: "fixture folder is a file: <path>".

  11. Handle missing golden fixtures

    master

    If a test fails because a golden fixture file is missing, goldie returns an error that indicates the file could not be found. The error message suggests running the test with the -update flag to generate the missing fixture.

    Note: The error type errFixtureNotFound is internal to the package, but you can identify this state by the error message: "Golden fixture not found. Try running with -update flag."