Documentation
¶
Overview ¶
Package golden provides standard way to write tests with golden files.
Index ¶
- Variables
- func Assert(t T, data string) bool
- func EqualWithDiff(t T, expected, actual string, msgAndArgs ...interface{}) (ok bool)
- func NoError(t T, err error, msg string)
- func ParseRecreateFromEnv(t T) bool
- func PrettyJSON(t T, data string) string
- func Request(t T, client Client, req *http.Request, expectedStatusCode int) (*http.Response, bool)
- func TestNameToFilePath(t T) string
- type Client
- type FileHandler
- type T
Constants ¶
This section is empty.
Variables ¶
var DefaultHandler = &FileHandler{ FileName: TestNameToFilePath, ShouldRecreate: ParseRecreateFromEnv, Equal: EqualWithDiff, ProcessContent: nil, }
Functions ¶
func EqualWithDiff ¶
EqualWithDiff compares two strings and returns true if they are equal. If they are not equal, test will be marked as failed and the diff will be logged.
func ParseRecreateFromEnv ¶
ParseRecreateFromEnv checks if the environment variable GOLDEN_FILES_RECREATE is set to true.
func PrettyJSON ¶ added in v0.1.0
PrettyJSON formats the JSON string using the pretty package. This is useful for making the JSON more readable in the golden file also provides cleaner diffs when comparing JSON files.
func Request ¶
Request sends the request and asserts that the response status code is equal to the expectedStatusCode. It also asserts that the response body is equal to the golden file content using EqualString. Example test function:
func TestAPI(t *testing.T) {
tests := []struct {
name string
method string
path string
body io.Reader
expectedCode int
}{
{
name: "create user",
method: "POST",
path: "/api/v1/user",
body: strings.NewReader(`{"name": "someone"}`),
expectedCode: 200,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(tt.method, "http://127.0.0.1:8080"+tt.path, tt.body)
require.NoError(t, err)
golden.Request(t, http.DefaultClient, req, tt.expectedCode)
})
}
}
func TestNameToFilePath ¶
TestNameToFilePath creates file name and path for the golden file using t.Name() with following rules: Top level: ./testdata/{testFuncName}/{testFuncName}.golden Subtest: ./testdata/{testFuncName}/{subTestName}.golden
Types ¶
type Client ¶
Client is an interface that allows using http.Client or any other client that implements the Do method.