Documentation
¶
Overview ¶
Package jman provides fast, minimal helpers for building, querying and asserting JSON objects (Obj) and arrays (Arr) in tests.
Core Types ¶
- Obj — JSON object implemented as `map[string]any`.
- Arr — JSON array implemented as `[]any`.
Testing Interface ¶
- T — interface for testing, e.g. `*testing.T`. Only Implements Fatalf() method.
Both types satisfy the JSONEqual interface and can be created:
// Literal
user := jman.Obj{"id": 1, "name": "alice"}
tags := jman.Arr{"go", "test", 42}
// Parse / normalise
user := jman.New[jman.Obj](t, `{"id":1,"name":"alice"}`)
tags := jman.New[jman.Arr](t, []byte(`["go","test",42]`))
Path-based Getters & Setters ¶
Paths use JSON-Path–like dot syntax and must start with `$`.
id := user.GetNumber(t, "$.id") user.Set(t, "$.settings.theme", "dark") tags.Set(t, "$.1", "unit")
There are diffferent getters for each type expected to be returned ¶
Setter can set any type as a value, however the value will be normalized into either: bool, string, float64, Obj, or Arr.
Deep Equality ¶
expected := jman.Obj{
"id": "{{uuid}}",
"name": "{{nonEmpty}}",
"roles": jman.Arr{"admin", "editor"},
"addresses": jman.Arr{
jman.Obj{"street": "High", "no": 1},
jman.Obj{"street": "Low", "no": 9},
},
}
actual := `{
"id":"9b74c989-7cdf-41fa-9a49-5290f31e59d3",
"name":"alice",
"roles":["editor","admin"],
"addresses":[
{"street":"High","no":1},
{"street":"Low","no":9}
]}`
expected.Equal(t, actual,
jman.WithIgnoreArrayOrder("$.roles", "$.addresses"),
jman.WithDefaultMatchers(jman.Matchers{
jman.IsUUID("{{uuid}}"),
jman.NotEmpty("{{nonEmpty}}"),
}),
)
Inequality Report ¶
For each difference the path and problem is returned, e.g.:
expected not equal to actual: $.roles expected 2 items - got 3 items $.name expected "alice" - got "bob" $.extra unexpected key
Matchers ¶
Matchers allow placeholders in the *expected* JSON that are resolved at comparison time:
jman.IsUUID("{{uuid}}") // any valid UUID
jman.NotEmpty("{{nonEmpty}}") // non-empty string/array/object
jman.EqualMatcher("{{id}}", 99) // equals specific value
Write your own with `jman.Custom`. A placeholder is a string that when found in the expected as a value, will find the corresponding value in the actual JSON and compare it using the matcher.
Options ¶
- WithIgnoreArrayOrder(paths...) — compare arrays as sets for given paths.
- WithDefaultMatchers(ms) — register Matchers once per comparison.
Index ¶
- Variables
- func Equal(t T, expected, actual any, optFuncs ...optsFunc)
- func New[E JSONEqual](t T, data any) E
- func NewFromFile[E JSONEqual](t T, path string) E
- func WithDefaultMatchers(matchers Matchers) optsFunc
- func WithIgnoreArrayOrder(keys ...string) optsFunc
- func WithMatchers(matchers ...Matcher) optsFunc
- type Arr
- func (a Arr) Equal(t T, other any, optFuncs ...optsFunc)
- func (a Arr) Get(t T, path string) any
- func (a Arr) GetArray(t T, path string) Arr
- func (a Arr) GetBool(t T, path string) bool
- func (a Arr) GetNumber(t T, path string) float64
- func (a Arr) GetObject(t T, path string) Obj
- func (a Arr) GetString(t T, path string) string
- func (a Arr) MustBytes(t T) []byte
- func (a Arr) Set(t T, path string, value any)
- func (a Arr) String(t T) string
- func (a *Arr) UnmarshalJSON(data []byte) error
- type JSONEqual
- type Matcher
- type MatcherFunc
- type Matchers
- type Obj
- func (ob Obj) Bytes(t T) []byte
- func (ob Obj) Equal(t T, other any, optFuncs ...optsFunc)
- func (o Obj) Get(t T, path string) any
- func (o Obj) GetArray(t T, path string) Arr
- func (o Obj) GetBool(t T, path string) bool
- func (o Obj) GetNumber(t T, path string) float64
- func (o Obj) GetObject(t T, path string) Obj
- func (o Obj) GetString(t T, path string) string
- func (ob Obj) MustBytes() []byte
- func (ob Obj) MustString() string
- func (o Obj) Set(t T, path string, value any)
- func (ob Obj) String(t T) string
- func (o *Obj) UnmarshalJSON(data []byte) error
- type T
Constants ¶
This section is empty.
Variables ¶
Functions ¶
func Equal ¶ added in v0.4.3
Equal compares two JSON values where each value can be Obj, Arr, JSON string/bytes, or any value that can be marshaled into a JSON object/array.
func New ¶
New creates a new instance of type T from the provided data. The data can be a JSON string, a byte slice, or an instance of type T. It fails the test via t.Fatalf if data cannot be parsed or normalized into type T.
func NewFromFile ¶ added in v0.4.3
NewFromFile creates a new instance of type E from a JSON file path. It fails the test via t.Fatalf if the file can't be read or JSON can't be parsed.
func WithDefaultMatchers ¶
func WithDefaultMatchers(matchers Matchers) optsFunc
WithDefaultMatchers allows you to set the default matchers for the comparison options. Useful if defining a set of matchers that should be used in most comparisons.
func WithIgnoreArrayOrder ¶
func WithIgnoreArrayOrder(keys ...string) optsFunc
WithIgnoreArrayOrder allows you to specify keys for which the order of array elements should be ignored during comparison. each key should be a valid JSON path, and the order of elements in arrays at those paths will not be considered during comparison. the path must start with $. For ignoring order of the base array, use "$" as the key.
func WithMatchers ¶
func WithMatchers(matchers ...Matcher) optsFunc
WithMatchers allows you to add matchers to the comparison options.
Types ¶
type Arr ¶
type Arr []any
Arr represents a JSON array. It implements the Equaler interface for deep equality checks.
func (Arr) Equal ¶
Equal checks if the Arr is equal to another value, which can be either a JSON string, byte slice, or another Arr. It uses the provided options to customize the equality check, such as ignoring array order. If the actual value is not a valid JSON array, it returns an error.
func (Arr) Get ¶
Get retrieves a value from the Arr at the specified path. The path is a JSONPath-like string that specifies the location of the value. If the path is invalid or the value cannot be retrieved, it calls t.Fatal
func (Arr) GetArray ¶ added in v0.4.0
GetArray functions like Get but attempts to convert to Arr. Fails if the value at the path is not an array.
func (Arr) GetBool ¶ added in v0.4.0
GetBool functions like Get but attempts to convert to bool. Fails if the value at the path is not a boolean.
func (Arr) GetNumber ¶ added in v0.4.0
GetNumber functions like Get but attempts to convert to float64. Fails if the value at the path is not a number.
func (Arr) GetObject ¶ added in v0.4.0
GetObject functions like Get but attempts to convert to Obj. Fails if the value at the path is not an object.
func (Arr) GetString ¶ added in v0.4.0
GetString functions like Get but attempts to convert to string. Fails if the value at the path is not a string.
func (Arr) MustBytes ¶
Bytes returns the JSON representation of the Arr as a byte slice. It fails if there is an error during marshaling.
func (Arr) Set ¶
Set sets a value at the specified path in the Arr. The path is a JSONPath-like string that specifies the location of the value. If the path is invalid or the value cannot be set, it fails. After setting the value, it normalizes the Arr to ensure it is valid JSON. If normalization fails, it calls Fatalf on T. If successful, it updates the Arr in place. The value can be of any type, but it will be normalized to one of the supported JSON types: bool, string, float64, Obj, or Arr.
func (Arr) String ¶ added in v0.4.0
String returns the JSON representation of the Arr as a string. It fails if there is an error during marshaling.
func (*Arr) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for Arr. Any items in the array of type []any or map[string]any will be converted to Arr or Obj, and other simple types will be converted to their corresponding types (bool, string, float64).
type JSONEqual ¶
JSONEqual is an interface that defines a method for comparing JSON objects. It requires the implementation to provide an Equal method that checks interface equality between two JSON objects, allowing for custom options via OptsFunc.
type Matcher ¶
type Matcher struct {
Placeholder string
MatcherFunc
}
Matcher represents a matcher that can be used to validate values against certain conditions. It contains a placeholder for identification and a function that defines the matching logic. It will be checked whenever a string value is encountered in the expected value. If a matcher with the same placeholder is found, it will be used to validate the actual value.
func Custom ¶
func Custom(placeholder string, matcherFunc MatcherFunc) Matcher
Custom creates a matcher with a custom matching function.
func EqualMatcher ¶
EqualMatcher checks if the value matches the expected value.
func IsUUID ¶
IsUUID creates a matcher that checks if the value is a valid UUID against a uuid regular expression.
type MatcherFunc ¶
MatcherFunc is a function type that defines the matching logic. It takes a value of any type and returns true if the value matches the expected condition, false otherwise. the value passed into the MatcherFunc can be of any type, including nil and is taken from the actual value in the JSON.
type Obj ¶
Obj represents a JSON object. It implements the Equaler interface for deep equality checks.
func (Obj) Bytes ¶ added in v0.4.0
Bytes returns the JSON representation of the Obj as a byte slice. It fails if the marshaling fails.
func (Obj) Equal ¶
Equal checks if the Obj is equal to another value, which can be either a JSON string, byte slice, or another Obj.
func (Obj) Get ¶
Get retrieves a value from the Obj at the specified path. The path is a JSONPath-like string that specifies the location of the value. If the path is invalid or the value cannot be retrieved, it calls t.Fatal
func (Obj) GetArray ¶ added in v0.4.0
GetArray functions like Get but attempts to convert to Arr. Fails if the value at the path is not an array.
func (Obj) GetBool ¶ added in v0.4.0
GetBool functions like Get but attempts to convert to bool. Fails if the value at the path is not a boolean.
func (Obj) GetNumber ¶ added in v0.4.0
GetNumber functions like Get but attempts to convert to float64. Fails if the value at the path is not a number.
func (Obj) GetObject ¶ added in v0.4.0
GetObject functions like Get but attempts to convert to Obj. Fails if the value at the path is not an object.
func (Obj) GetString ¶ added in v0.4.0
GetString functions like Get but attempts to convert to string. Fails if the value at the path is not a string.
func (Obj) MustBytes ¶
MustBytes returns the JSON representation of the Obj as a byte slice. It panics if the marshaling fails, which is useful for tests where you want to ensure the JSON is valid without handling errors.
func (Obj) MustString ¶
MustString returns the JSON representation of the Obj as a string. It panics if the marshaling fails, which is useful for tests where you want to
func (Obj) Set ¶
Set sets a value at the specified path in the Obj. The path is a JSONPath-like string that specifies the location of the value. If the path is invalid or the value cannot be set, it fails. After setting the value, it normalizes the Arr to ensure it is valid JSON. If normalization fails, it calls Fatalf on T. If successful, it updates the Arr in place. The value can be of any type, but it will be normalized to one of the supported JSON types: bool, string, float64, Obj, or Arr.
func (Obj) String ¶ added in v0.4.0
String returns the JSON representation of the Obj as a string. It fails if the marshaling fails.
func (*Obj) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for Obj. Any nested fields with values of type []any or map[string]any will be converted to Arr or Obj, and other simple types will be converted to their corresponding types (bool, string, float64).