Documentation
¶
Overview ¶
Package testutility provides utility functions for tests.
Index ¶
- Variables
- func CleanSnapshots(m *testing.M)
- func CreateTestDir(t *testing.T) string
- func GetCurrentWorkingDirectory(t *testing.T) string
- func IsAcceptanceTesting() bool
- func LoadJSONFixture[V any](t *testing.T, path string) V
- func LoadJSONFixtureWithWindowsReplacements[V any](t *testing.T, path string, replacements map[string]string) V
- func LoadVulnMapFixture(t *testing.T, path string) map[string]*osvschema.Vulnerability
- func ReplaceJSONInput(t *testing.T, jsonInput string, path string, ...) string
- func Skip(t *testing.T, args ...any)
- func SkipIfNotAcceptanceTesting(t *testing.T, reason string)
- func SkipIfShort(t *testing.T)
- func ValueIfOnWindows(win, or string) string
- type JSONReplaceRule
- type MockHTTPServer
- func (m *MockHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *MockHTTPServer) SetAuthorization(t *testing.T, auth string)
- func (m *MockHTTPServer) SetResponse(t *testing.T, path string, response []byte)
- func (m *MockHTTPServer) SetResponseFromFile(t *testing.T, path string, filename string)
- type Snapshot
Constants ¶
This section is empty.
Variables ¶
var ( // OnlyIDVulnsRule simplifies vulnerabilities to only their ID OnlyIDVulnsRule = JSONReplaceRule{ Path: "results.#.packages.#.vulnerabilities", ReplaceFunc: func(toReplace gjson.Result) any { return toReplace.Get("#.id").Value() }, } // GroupsAsArrayLen replaces the groups array with its length GroupsAsArrayLen = JSONReplaceRule{ Path: "results.#.packages.#.groups", ReplaceFunc: func(toReplace gjson.Result) any { if toReplace.IsArray() { return len(toReplace.Array()) } return 0 }, } // OnlyFirstBaseImage simplifies the array of base images to only the first one OnlyFirstBaseImage = JSONReplaceRule{ Path: "image_metadata.base_images.#", ReplaceFunc: func(toReplace gjson.Result) any { if toReplace.IsArray() && len(toReplace.Array()) >= 1 { return toReplace.Array()[0].Value() } return struct{}{} }, } // AnyDiffID truncates diff ids in image layer metadata to just `sha256:...` AnyDiffID = JSONReplaceRule{ Path: "image_metadata.layer_metadata.#.diff_id", ReplaceFunc: func(toReplace gjson.Result) any { if len(toReplace.String()) > 7 { return toReplace.String()[:7] + "..." } return "" }, } // ShortenHistoryCommandLength truncates COMMAND data to 28 characters ShortenHistoryCommandLength = JSONReplaceRule{ Path: "image_metadata.layer_metadata.#.command", ReplaceFunc: func(toReplace gjson.Result) any { if len(toReplace.String()) > 28 { return toReplace.String()[:25] + "..." } return toReplace.String() }, } // NormalizeHistoryCommand replaces COMMAND data to be consistent // across different versions of docker NormalizeHistoryCommand = JSONReplaceRule{ Path: "image_metadata.layer_metadata.#.command", ReplaceFunc: func(toReplace gjson.Result) any { str := toReplace.String() nopMatcher := cachedregexp.MustCompile(`^/bin/sh -c #\(nop\)\s+`) runMatcher := cachedregexp.MustCompile(`^/bin/sh -c\s+`) str = nopMatcher.ReplaceAllLiteralString(str, "") str = runMatcher.ReplaceAllString(str, "RUN \\0") return str }, } // NormalizeCreateDateSPDX replaces the created date with a placeholder date NormalizeCreateDateSPDX = JSONReplaceRule{ Path: "creationInfo.created", ReplaceFunc: func(_ gjson.Result) any { return "2025-01-01T01:01:01Z" }, } ReplacePartialFingerprintHash = JSONReplaceRule{ Path: "runs.#.results.#.partialFingerprints.primaryLocationLineHash", ReplaceFunc: func(toReplace gjson.Result) any { if len(toReplace.String()) > 0 { return "[line-hash]" } return "[empty]" }, } )
Functions ¶
func CleanSnapshots ¶
CleanSnapshots ensures that snapshots are relevant and sorted for consistency
func CreateTestDir ¶
CreateTestDir makes a temporary directory for use in testing that involves writing and reading files from disk, which is automatically cleaned up when testing finishes
func GetCurrentWorkingDirectory ¶ added in v2.1.0
GetCurrentWorkingDirectory returns the current working directory, raising a fatal error if it cannot be retrieved for some reason
func IsAcceptanceTesting ¶
func IsAcceptanceTesting() bool
IsAcceptanceTesting returns true if the test suite is being run with acceptance tests enabled
func LoadJSONFixture ¶
LoadJSONFixture returns the contents of the fixture file parsed as JSON
func LoadJSONFixtureWithWindowsReplacements ¶
func LoadJSONFixtureWithWindowsReplacements[V any]( t *testing.T, path string, replacements map[string]string, ) V
LoadJSONFixtureWithWindowsReplacements returns the contents of the fixture file parsed as JSON after applying any replacements if running on Windows
func LoadVulnMapFixture ¶ added in v2.3.0
LoadVulnMapFixture returns the contents of the fixture file parsed as a map of vulnerability IDs to vulnerabilities
func ReplaceJSONInput ¶ added in v2.3.1
func ReplaceJSONInput(t *testing.T, jsonInput string, path string, replacer func(toReplace gjson.Result) any) string
ReplaceJSONInput takes a gjson path and replaces all elements the path matches with the output of matcher
func Skip ¶
Skip is equivalent to t.Log followed by t.SkipNow, but allows tracking of what snapshots are skipped so that they're not marked as obsolete
func SkipIfNotAcceptanceTesting ¶
SkipIfNotAcceptanceTesting marks the test as skipped unless the test suite is being run with acceptance tests enabled, as indicated by IsAcceptanceTesting, or the test is being run specifically with the -run flag This is used to skip tests that could require external dependencies other than go
func SkipIfShort ¶ added in v2.3.1
SkipIfShort marks the test as skipped if the short flag is set or the test is being run specifically with the -run flag
func ValueIfOnWindows ¶
Types ¶
type JSONReplaceRule ¶
type MockHTTPServer ¶
func NewMockHTTPServer ¶
func NewMockHTTPServer(t *testing.T) *MockHTTPServer
NewMockHTTPServer starts and returns a new simple HTTP Server for mocking basic requests. The Server will automatically be shut down with Close() in the test Cleanup function.
Use the SetResponse / SetResponseFromFile to set the responses for specific URL paths.
func (*MockHTTPServer) ServeHTTP ¶
func (m *MockHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the http.Handler for the underlying httptest.Server.
func (*MockHTTPServer) SetAuthorization ¶
func (m *MockHTTPServer) SetAuthorization(t *testing.T, auth string)
SetAuthorization sets the contents of the 'Authorization' header the server expects for all endpoints.
The incoming requests' headers must match the auth string exactly, otherwise the server will respond with 401 Unauthorized. If authorization is unset or empty, the server will not require authorization.
func (*MockHTTPServer) SetResponse ¶
func (m *MockHTTPServer) SetResponse(t *testing.T, path string, response []byte)
SetResponse sets the Server's response for the URL path to be response bytes.
func (*MockHTTPServer) SetResponseFromFile ¶
func (m *MockHTTPServer) SetResponseFromFile(t *testing.T, path string, filename string)
SetResponseFromFile sets the Server's response for the URL path to be the contents of the file at filename.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
func NewSnapshot ¶
func NewSnapshot() Snapshot
NewSnapshot creates a snapshot that can be passed around within tests
func (Snapshot) MatchJSON ¶
MatchJSON asserts the existing snapshot matches what was gotten in the test, after being marshalled as JSON
func (Snapshot) MatchText ¶
MatchText asserts the existing snapshot matches what was gotten in the test
func (Snapshot) WithCRLFReplacement ¶
WithCRLFReplacement adds a Windows replacement for "\r\n" to "\n". This should be called after WithWindowsReplacements if used together.