assertjson

package module
v1.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 23, 2023 License: MIT Imports: 11 Imported by: 17

README

JSON assertions

Build Status Coverage Status GoDevDoc time tracker

This library extends awesome github.com/stretchr/testify/assert with nice JSON equality assertions built with github.com/yudai/gojsondiff.

Also it provides JSON marshaler with compact indentation.

Usage

Default comparer is set up to ignore difference against "<ignore-diff>" values. It is accessible with package functions Equal and EqualMarshal.

package my_test

import (
	"testing"

	"github.com/swaggest/assertjson"
)

func Test(t *testing.T) {
	assertjson.Equal(t,
		[]byte(`{"a": [1, {"val": "<ignore-diff>"}, 3], "b": 2, "c": 3}`),
		[]byte(`{"a": [1, {"val": 123}, 3], "c": 2, "b": 3}`),
	)

	// Output:
	// Error Trace:	....
	//	Error:      	Not equal:
	//	            	 {
	//	            	   "a": [
	//	            	     1,
	//	            	     {
	//	            	       "val": "<ignore-diff>"
	//	            	     },
	//	            	     3
	//	            	   ],
	//	            	-  "b": 2,
	//	            	+  "b": 3,
	//	            	-  "c": 3
	//	            	+  "c": 2
	//	            	 }
}

Custom Comparer can be created and used to control ignore behavior and formatter options.

Variables

Custom Comparer also supports shared.Vars to collect or check variables. This can be helpful in case of asserting equality of dynamic data in different payloads.

v := &shared.Vars{}
v.Set("$varB", []int{1, 2, 3})
v.Set("$varC", "abc")

// Properties "b" and "c" are checked against values defined in vars.
// Properties "a" and "d" are not checked, but their values are assigned to missing vars.
expected := []byte(`{"a": "$varA", "b": "$varB", "c": "$varC", "d": "$varD"}`)
actual := []byte(`{"a": 1.23, "b": [1, 2, 3], "c": "abc", "d": 4}`)

c := assertjson.Comparer{Vars: v}

c.Equal(t, expected, actual)

Variable reference should look like double quote enclosed name of variable, e.g. "$var1".

  • Variables that were set before JSON comparison will be used by their value in equality check.
  • Variables that were not set before JSON comparison will be assigned with values from actual JSON, equality check will be skipped.
Compact Indentation

Often json.MarshalIndent produces result, that is not easy to comprehend due to high count of lines that requires massive scrolling effort to read.

This library provides an alternative assertjson.MarshalIndentCompact which keeps indentation and line breaks only for major part of JSON document, while compacting smaller pieces.

j, err := assertjson.MarshalIndentCompact(v, "", "  ", 100) // 100 is line width limit.
{
  "openapi":"3.0.2","info":{"title":"","version":""},
  "paths":{
    "/test/{in-path}":{
      "post":{
        "summary":"Title","description":"","operationId":"name",
        "x-some-array":[
          "abc","def",123456,7890123456,[],{"foo":"bar"},
          "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!"
        ],
        "parameters":[
          {"name":"in_query","in":"query","schema":{"type":"integer"}},
          {"name":"in-path","in":"path","required":true,"schema":{"type":"boolean"}},
          {"name":"in_cookie","in":"cookie","schema":{"type":"number"}},
          {"name":"X-In-Header","in":"header","schema":{"type":"string"}}
        ],
        "requestBody":{
          "content":{
            "application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/FormDataOpenapiTestInput"}}
          }
        },
        "responses":{"200":{"description":"OK","content":{"application/json":{"schema":{}}}}},
        "deprecated":true
      }
    }
  },
  "components":{
    "schemas":{"FormDataOpenapiTestInput":{"type":"object","properties":{"in_form_data":{"type":"string"}}}}
  }
}
CLI Tool

Available as jsoncompact CLI tool.

go get github.com/swaggest/assertjson/cmd/jsoncompact

You can invoke the tool against one or more JSON files, for example:

jsoncompact some-*.json path/to/another/*.json

Or paste JSON into stdin.

jsoncompact -

Additional flags.

Usage of jsoncompact:
  -indent string
        Set indent. (default " ")
  -len int
        Line length limit. (default 100)
  -output string
        Path to output json file, if not specified input file is used.
  -prefix string
        Set prefix.
  -v    Verbose mode.
  -version
        Print version and exit.

Documentation

Overview

Package assertjson implements JSON equality assertion for tests.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
)

var t = testingT(func(format string, args ...interface{}) {
	fmt.Printf(format, args...)
})

func main() {
	assertjson.Equal(t,
		[]byte(`{"a": [1, {"val": "<ignore-diff>"}, 3], "b": 2, "c": 3}`),
		[]byte(`{"a": [1, {"val": 123}, 3], "c": 2, "b": 3}`),
	)

}
Output:

Error Trace:	equal.go:88
	            				equal.go:63
	            				example_test.go:14
	Error:      	Not equal:
	            	 {
	            	   "a": [
	            	     1,
	            	     {
	            	       "val": "<ignore-diff>"
	            	     },
	            	     3
	            	   ],
	            	-  "b": 2,
	            	+  "b": 3,
	            	-  "c": 3
	            	+  "c": 2
	            	 }

Index

Examples

Constants

View Source
const IgnoreDiff = "<ignore-diff>"

IgnoreDiff is a marker to ignore difference in JSON.

Variables

This section is empty.

Functions

func EqMarshal added in v1.9.0

func EqMarshal(t TestingT, expected string, actualValue interface{}, msgAndArgs ...interface{}) bool

EqMarshal marshals actual value and compares two JSON documents ignoring string values "<ignore-diff>".

func Equal

func Equal(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool

Equal compares two JSON documents ignoring string values "<ignore-diff>".

func EqualMarshal added in v1.4.0

func EqualMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool

EqualMarshal marshals actual value and compares two JSON documents ignoring string values "<ignore-diff>".

func FailMismatch added in v1.8.0

func FailMismatch(expected, actual []byte) error

FailMismatch returns error if expected JSON payload does not match actual JSON payload, nil otherwise. It ignores added fields in actual JSON payload.

func FailMismatchMarshal added in v1.8.0

func FailMismatchMarshal(expected []byte, actualValue interface{}) error

FailMismatchMarshal returns error if expected JSON payload does not match marshaled actual value, nil otherwise. It ignores added fields in actual JSON payload.

func FailNotEqual added in v1.1.0

func FailNotEqual(expected, actual []byte) error

FailNotEqual returns error if JSON payloads are different, nil otherwise.

func FailNotEqualMarshal added in v1.7.0

func FailNotEqualMarshal(expected []byte, actualValue interface{}) error

FailNotEqualMarshal returns error if expected JSON payload is not equal to marshaled actual value.

func MarshalIndentCompact added in v1.2.0

func MarshalIndentCompact(v interface{}, prefix, indent string, lineLen int) ([]byte, error)

MarshalIndentCompact applies indentation for large chunks of JSON and uses compact format for smaller ones.

Line length limits indented width of JSON structure, does not apply to long distinct scalars. This function is not optimized for performance, so it might be not a good fit for high load scenarios.

func Matches added in v1.8.0

func Matches(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool

Matches compares two JSON documents ignoring string values "<ignore-diff>". It ignores added fields in actual JSON payload.

func MatchesMarshal added in v1.8.0

func MatchesMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool

MatchesMarshal marshals actual value and compares two JSON documents ignoring string values "<ignore-diff>". It ignores added fields in actual JSON payload.

Types

type Comparer

type Comparer struct {
	// IgnoreDiff is a value in expected document to ignore difference with actual document.
	IgnoreDiff string

	// Vars keeps state of found variables.
	Vars *shared.Vars

	// FormatterConfig controls diff formatter configuration.
	FormatterConfig formatter.AsciiFormatterConfig

	// KeepFullDiff shows full diff in error message.
	KeepFullDiff bool

	// FullDiffMaxLines is a maximum number of lines to show without reductions, default 50.
	// Ignored if KeepFullDiff is true.
	FullDiffMaxLines int

	// DiffSurroundingLines is a number of lines to add before and after diff line, default 5.
	// Ignored if KeepFullDiff is true.
	DiffSurroundingLines int
}

Comparer compares JSON documents.

func (Comparer) Equal

func (c Comparer) Equal(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool

Equal compares two JSON payloads.

func (Comparer) EqualMarshal added in v1.4.0

func (c Comparer) EqualMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool

EqualMarshal marshals actual JSON payload and compares it with expected payload.

func (Comparer) FailMismatch added in v1.8.0

func (c Comparer) FailMismatch(expected, actual []byte) error

FailMismatch returns error if expected JSON payload does not match actual JSON payload, nil otherwise. It ignores added fields in actual JSON payload.

func (Comparer) FailMismatchMarshal added in v1.8.0

func (c Comparer) FailMismatchMarshal(expected []byte, actualValue interface{}) error

FailMismatchMarshal returns error if expected JSON payload does not match marshaled actual value, nil otherwise. It ignores added fields in actual JSON payload.

func (Comparer) FailNotEqual added in v1.1.0

func (c Comparer) FailNotEqual(expected, actual []byte) error

FailNotEqual returns error if JSON payloads are different, nil otherwise.

func (Comparer) FailNotEqualMarshal added in v1.7.0

func (c Comparer) FailNotEqualMarshal(expected []byte, actualValue interface{}) error

FailNotEqualMarshal returns error if expected JSON payload is not equal to marshaled actual value.

func (Comparer) Matches added in v1.8.0

func (c Comparer) Matches(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool

Matches compares two JSON payloads. It ignores added fields in actual JSON payload.

func (Comparer) MatchesMarshal added in v1.8.0

func (c Comparer) MatchesMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool

MatchesMarshal marshals actual JSON payload and compares it with expected payload. It ignores added fields in actual JSON payload.

type TestingT

type TestingT interface {
	Errorf(format string, args ...interface{})
}

TestingT is an interface wrapper around *testing.T.

Directories

Path Synopsis
cmd
jsoncompact
Package main provides a tool to compact JSON.
Package main provides a tool to compact JSON.
Package json5 provides JSON5 decoder.
Package json5 provides JSON5 decoder.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL