Skip to content

Commit

Permalink
Improve golden tests
Browse files Browse the repository at this point in the history
  • Loading branch information
glrf committed May 9, 2022
1 parent 3360093 commit 0e4c020
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ test: test-go ## All-in-one test
test-go: ## Run unit tests against code
go test -race -coverprofile cover.out -covermode atomic ./...

.PHONY: gen-golden
gen-golden:
go test ./description_templates/... -update

.PHONY: fmt
fmt: ## Run 'go fmt' against code
go fmt ./...
Expand Down
28 changes: 25 additions & 3 deletions description_templates/golden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,32 @@ package descriptiontemplates_test

import (
"context"
"flag"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"

"github.com/appuio/appuio-cloud-reporting/pkg/invoice"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vshn/appuio-odoo-adapter/invoice/desctmpl"
)

const extension = ".gotmpl"

var (
updateGolden = flag.Bool("update", false, "update the golden files of this test")
)

func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}

func TestGenerateGolden(t *testing.T) {
os.RemoveAll("golden")
os.Mkdir("golden", os.ModePerm)

templateFS := os.DirFS(".")
Expand Down Expand Up @@ -72,10 +83,21 @@ func TestGenerateGolden(t *testing.T) {
t.Run(key, func(t *testing.T) {
item := baseItem
item.ProductRef.Source = key
rendered, err := r.RenderItemDescription(context.Background(), item)
actual, err := r.RenderItemDescription(context.Background(), item)
require.NoError(t, err)

os.WriteFile(filepath.Join("golden", key+".txt"), []byte(rendered), os.ModePerm)
fileName := filepath.Join("golden", key+".txt")
if *updateGolden {
require.NoError(t, os.WriteFile(fileName, []byte(actual), os.ModePerm))
return
}
f, err := os.OpenFile(fileName, os.O_RDONLY, 0644)
require.NoErrorf(t, err, "failed to open golden file %s", fileName)
defer f.Close()
expected, err := io.ReadAll(f)
require.NoErrorf(t, err, "failed to read golden file %s", fileName)

assert.Equal(t, string(expected), actual)
})
}
}

0 comments on commit 0e4c020

Please sign in to comment.