Documentation
¶
Overview ¶
Package testastic provides JSON assertion utilities for Go tests. It compares API responses against expected JSON files with support for template-based matchers, semantic comparison, and automatic updates.
Index ¶
- Variables
- func AssertHTML[T any](tb testing.TB, expectedFile string, actual T, opts ...HTMLOption)
- func AssertJSON[T any](tb testing.TB, expectedFile string, actual T, opts ...Option)
- func Between[T cmp.Ordered](tb testing.TB, value, minVal, maxVal T)
- func Contains(tb testing.TB, s, substring string)
- func DeepEqual[T any](tb testing.TB, expected, actual T)
- func Empty(tb testing.TB, collection any)
- func Equal[T comparable](tb testing.TB, expected, actual T)
- func Error(tb testing.TB, err error)
- func ErrorContains(tb testing.TB, err error, substring string)
- func ErrorIs(tb testing.TB, err, target error)
- func False(tb testing.TB, value bool)
- func FormatDiff(diffs []Difference) string
- func FormatDiffInline(expected, actual any) string
- func FormatHTMLDiff(diffs []HTMLDifference) string
- func FormatHTMLDiffInline(expected, actual *HTMLNode) string
- func Greater[T cmp.Ordered](tb testing.TB, a, b T)
- func GreaterOrEqual[T cmp.Ordered](tb testing.TB, a, b T)
- func HasPrefix(tb testing.TB, s, prefix string)
- func HasSuffix(tb testing.TB, s, suffix string)
- func IsIgnore(m Matcher) bool
- func Len(tb testing.TB, collection any, expected int)
- func Less[T cmp.Ordered](tb testing.TB, a, b T)
- func LessOrEqual[T cmp.Ordered](tb testing.TB, a, b T)
- func MapEqual[K comparable, V comparable](tb testing.TB, expected, actual map[K]V)
- func MapHasKey[K comparable, V any](tb testing.TB, m map[K]V, key K)
- func MapNotHasKey[K comparable, V any](tb testing.TB, m map[K]V, key K)
- func Matches(tb testing.TB, s, pattern string)
- func Nil(tb testing.TB, value any)
- func NoError(tb testing.TB, err error)
- func NotContains(tb testing.TB, s, substring string)
- func NotEmpty(tb testing.TB, collection any)
- func NotEqual[T comparable](tb testing.TB, unexpected, actual T)
- func NotNil(tb testing.TB, value any)
- func SliceContains[T comparable](tb testing.TB, slice []T, element T)
- func SliceEqual[T comparable](tb testing.TB, expected, actual []T)
- func SliceNotContains[T comparable](tb testing.TB, slice []T, element T)
- func StringEmpty(tb testing.TB, s string)
- func StringNotEmpty(tb testing.TB, s string)
- func True(tb testing.TB, value bool)
- type Config
- type DiffType
- type Difference
- type ExpectedHTML
- type ExpectedJSON
- type HTMLConfig
- type HTMLDifference
- type HTMLNode
- type HTMLNodeType
- type HTMLOption
- func HTMLUpdate() HTMLOption
- func IgnoreAttributeAt(pathAttr string) HTMLOption
- func IgnoreAttributes(attrs ...string) HTMLOption
- func IgnoreChildOrder() HTMLOption
- func IgnoreChildOrderAt(path string) HTMLOption
- func IgnoreElements(tags ...string) HTMLOption
- func IgnoreHTMLComments() HTMLOption
- func PreserveWhitespace() HTMLOption
- type Matcher
- type Option
- type TemplateSegment
- type TemplateString
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidRegexSyntax = errors.New("invalid regex syntax") ErrInvalidOneOfSyntax = errors.New("invalid oneOf syntax") ErrUnknownMatcher = errors.New("unknown matcher") )
Matcher parsing errors.
var ErrUnknownPlaceholder = errors.New("unknown placeholder")
ErrUnknownPlaceholder is returned when a placeholder is not found in the matcher map.
var ErrUnsupportedHTMLType = errors.New("unsupported type for HTML comparison")
ErrUnsupportedHTMLType is returned when an unsupported type is passed to AssertHTML.
Functions ¶
func AssertHTML ¶
func AssertHTML[T any](tb testing.TB, expectedFile string, actual T, opts ...HTMLOption)
AssertHTML compares actual HTML against an expected HTML file. T can be: []byte, string, io.Reader, or any type implementing fmt.Stringer.
Example:
testastic.AssertHTML(t, "testdata/user.expected.html", resp.Body) testastic.AssertHTML(t, "testdata/user.expected.html", htmlBytes) testastic.AssertHTML(t, "testdata/user.expected.html", htmlString)
func AssertJSON ¶
AssertJSON compares actual JSON against an expected JSON file. T can be: []byte, string, io.Reader, or any struct (auto-marshaled).
Example:
testastic.AssertJSON(t, "testdata/user.expected.json", resp.Body) testastic.AssertJSON(t, "testdata/user.expected.json", myUser) testastic.AssertJSON(t, "testdata/user.expected.json", jsonBytes)
func DeepEqual ¶
DeepEqual asserts that expected and actual are deeply equal using reflect.DeepEqual.
func Empty ¶
Empty asserts that the collection is empty. Works with slices, maps, strings, arrays, and channels.
func Equal ¶
func Equal[T comparable](tb testing.TB, expected, actual T)
Equal asserts that expected and actual are equal.
func ErrorContains ¶
ErrorContains asserts that err contains the given substring.
func FormatDiff ¶
func FormatDiff(diffs []Difference) string
FormatDiff formats a slice of differences into a human-readable string. This is the simple format showing paths and values.
func FormatDiffInline ¶
FormatDiffInline generates a git-style inline diff between expected and actual JSON. Shows the full JSON with - prefix for removed lines and + prefix for added lines.
func FormatHTMLDiff ¶
func FormatHTMLDiff(diffs []HTMLDifference) string
FormatHTMLDiff formats a slice of HTML differences into a human-readable string.
func FormatHTMLDiffInline ¶
FormatHTMLDiffInline generates a git-style inline diff between expected and actual HTML. Uses the same format as JSON diff.
func GreaterOrEqual ¶
GreaterOrEqual asserts that a >= b.
func Len ¶
Len asserts that the collection has the expected length. Works with slices, maps, strings, arrays, and channels.
func LessOrEqual ¶
LessOrEqual asserts that a <= b.
func MapEqual ¶
func MapEqual[K comparable, V comparable](tb testing.TB, expected, actual map[K]V)
MapEqual asserts that two maps are equal.
func MapHasKey ¶
func MapHasKey[K comparable, V any](tb testing.TB, m map[K]V, key K)
MapHasKey asserts that the map contains the given key.
func MapNotHasKey ¶
func MapNotHasKey[K comparable, V any](tb testing.TB, m map[K]V, key K)
MapNotHasKey asserts that the map does not contain the given key.
func NotContains ¶
NotContains asserts that s does not contain substring.
func NotEmpty ¶
NotEmpty asserts that the collection is not empty. Works with slices, maps, strings, arrays, and channels.
func NotEqual ¶
func NotEqual[T comparable](tb testing.TB, unexpected, actual T)
NotEqual asserts that expected and actual are not equal.
func SliceContains ¶
func SliceContains[T comparable](tb testing.TB, slice []T, element T)
SliceContains asserts that slice contains element.
func SliceEqual ¶
func SliceEqual[T comparable](tb testing.TB, expected, actual []T)
SliceEqual asserts that two slices are equal (same length and elements in same order).
func SliceNotContains ¶
func SliceNotContains[T comparable](tb testing.TB, slice []T, element T)
SliceNotContains asserts that slice does not contain element.
func StringEmpty ¶
StringEmpty asserts that s is an empty string.
func StringNotEmpty ¶
StringNotEmpty asserts that s is not an empty string.
Types ¶
type Config ¶
type Config struct {
IgnoreArrayOrder bool
IgnoreArrayOrderPaths []string
IgnoredFields []string
Update bool
}
Config holds the configuration for JSON comparison.
type DiffType ¶
type DiffType int
DiffType represents the type of difference found.
const ( // DiffChanged indicates a value was modified. DiffChanged DiffType = iota // DiffAdded indicates a value was added (exists in actual but not expected). DiffAdded // DiffRemoved indicates a value was removed (exists in expected but not actual). DiffRemoved // DiffTypeMismatch indicates the types don't match. DiffTypeMismatch // DiffMatcherFailed indicates a matcher didn't match the actual value. DiffMatcherFailed )
type Difference ¶
type Difference struct {
Path string // JSON path, e.g., "$.users[0].name"
Expected any // Expected value (or matcher description)
Actual any // Actual value
Type DiffType // Type of difference
}
Difference represents a single difference between expected and actual JSON.
type ExpectedHTML ¶
ExpectedHTML represents a parsed expected HTML file with matchers.
func ParseExpectedHTMLFile ¶
func ParseExpectedHTMLFile(path string) (*ExpectedHTML, error)
ParseExpectedHTMLFile reads and parses an expected HTML file, replacing template expressions with matchers.
func ParseExpectedHTMLString ¶
func ParseExpectedHTMLString(content string) (*ExpectedHTML, error)
ParseExpectedHTMLString parses an expected HTML string with template expressions.
func (*ExpectedHTML) ExtractMatcherPositions ¶
func (e *ExpectedHTML) ExtractMatcherPositions() map[string]string
ExtractMatcherPositions returns a map of HTML paths to their original template expressions.
type ExpectedJSON ¶
type ExpectedJSON struct {
Data any // Parsed JSON with Matcher objects in place of template expressions
Matchers map[string]string // Map of placeholder to original template expression
Raw string // Original file content for update operations
}
ExpectedJSON represents a parsed expected file with matchers.
func ParseExpectedFile ¶
func ParseExpectedFile(path string) (*ExpectedJSON, error)
ParseExpectedFile reads and parses an expected file, replacing template expressions with matchers.
func ParseExpectedString ¶
func ParseExpectedString(content string) (*ExpectedJSON, error)
ParseExpectedString parses an expected JSON string with template expressions.
func (*ExpectedJSON) ExtractMatcherPositions ¶
func (e *ExpectedJSON) ExtractMatcherPositions() map[string]string
ExtractMatcherPositions returns a map of JSON paths to their original template expressions. This is used when updating expected files to preserve matchers.
type HTMLConfig ¶
type HTMLConfig struct {
IgnoreComments bool
PreserveWhitespace bool
IgnoreChildOrder bool
IgnoreChildOrderPaths []string
IgnoredElements []string
IgnoredAttributes []string
IgnoredAttributePaths []string
Update bool
}
HTMLConfig holds the configuration for HTML comparison.
type HTMLDifference ¶
HTMLDifference represents a single difference between expected and actual HTML.
type HTMLNode ¶
type HTMLNode struct {
Type HTMLNodeType
Tag string
Attributes map[string]any
Children []*HTMLNode
Text any
Path string
}
HTMLNode represents a normalized HTML node for comparison.
type HTMLNodeType ¶
type HTMLNodeType int
HTMLNodeType represents the type of an HTML node.
const ( // HTMLElement represents an HTML element node. HTMLElement HTMLNodeType = iota // HTMLText represents a text node. HTMLText // HTMLComment represents a comment node. HTMLComment // HTMLDoctype represents a doctype node. HTMLDoctype )
type HTMLOption ¶
type HTMLOption func(*HTMLConfig)
HTMLOption is a functional option for configuring HTML comparison.
func HTMLUpdate ¶
func HTMLUpdate() HTMLOption
HTMLUpdate forces updating the expected file with the actual value.
func IgnoreAttributeAt ¶
func IgnoreAttributeAt(pathAttr string) HTMLOption
IgnoreAttributeAt excludes a specific attribute at a given path. Format: "path@attribute" e.g., "html > body > div@class".
func IgnoreAttributes ¶
func IgnoreAttributes(attrs ...string) HTMLOption
IgnoreAttributes excludes the specified attribute names from comparison globally.
func IgnoreChildOrder ¶
func IgnoreChildOrder() HTMLOption
IgnoreChildOrder makes child element comparison order-insensitive globally.
func IgnoreChildOrderAt ¶
func IgnoreChildOrderAt(path string) HTMLOption
IgnoreChildOrderAt makes child comparison order-insensitive at the specified HTML path.
func IgnoreElements ¶
func IgnoreElements(tags ...string) HTMLOption
IgnoreElements excludes elements matching the specified tag names from comparison.
func IgnoreHTMLComments ¶
func IgnoreHTMLComments() HTMLOption
IgnoreHTMLComments excludes HTML comments from comparison.
func PreserveWhitespace ¶
func PreserveWhitespace() HTMLOption
PreserveWhitespace disables whitespace normalization. By default, insignificant whitespace is collapsed.
type Matcher ¶
type Matcher interface {
// Match returns true if the actual value matches the expected pattern.
Match(actual any) bool
// String returns a description of what this matcher expects.
String() string
}
Matcher defines the interface for custom value matching.
func AnyString ¶
func AnyString() Matcher
AnyString returns a matcher that matches any string value.
func AnyValue ¶
func AnyValue() Matcher
AnyValue returns a matcher that matches any value including null.
func ParseMatcher ¶
ParseMatcher creates a Matcher from a template expression. The expression is the content between {{ and }}.
type Option ¶
type Option func(*Config)
Option is a functional option for configuring JSON comparison.
func IgnoreArrayOrder ¶
func IgnoreArrayOrder() Option
IgnoreArrayOrder makes array comparison order-insensitive globally.
func IgnoreArrayOrderAt ¶
IgnoreArrayOrderAt makes array comparison order-insensitive at the specified JSON path.
func IgnoreFields ¶
IgnoreFields excludes the specified fields from comparison. Fields can be simple names or JSON paths (e.g., "$.user.id").
type TemplateSegment ¶
type TemplateSegment struct {
Literal string // Literal text (empty if Matcher is set).
Matcher Matcher // Matcher (nil if Literal is set).
}
TemplateSegment represents part of a template string.
type TemplateString ¶
type TemplateString struct {
Segments []TemplateSegment
Original string // For display: "border-left: 6px solid {{anyString}}".
}
TemplateString represents a string with embedded matchers.
func (TemplateString) Match ¶
func (t TemplateString) Match(actual string) bool
Match checks if the actual string matches the template pattern.
func (TemplateString) String ¶
func (t TemplateString) String() string
String returns the original template representation.