...

Source file src/github.com/launchdarkly/go-jsonstream/v3/internal/commontest/writer_test_suite.go

Documentation: github.com/launchdarkly/go-jsonstream/v3/internal/commontest

     1  package commontest
     2  
     3  import (
     4  	"regexp"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  // WriterTestSuite runs a standard set of tests against some implementation of JSON writing.
    11  // This allows us to test both jwriter.Writer and the low-level JSON formatter jwriter.tokenWriter
    12  // with many permutations of output data.
    13  type WriterTestSuite struct {
    14  	// ContextFactory must be provided by the caller to create an implementation of TestContext for
    15  	// running a writing test on some set of JSON data. This should include whatever writer object
    16  	// will be used by the Actions that the ValueTestFactory creates.
    17  	ContextFactory func() TestContext
    18  
    19  	// ValueTestFactory must be provided by the caller to create implementations of Action for
    20  	// various JSON value types.
    21  	ValueTestFactory ValueTestFactory
    22  
    23  	// EncodeAsHex must be provided by the caller to define expectations about whether this writer
    24  	// will use a \uNNNN escape sequence for the specified Unicode character. There is no single
    25  	// correct answer for all implementations, since JSON allows characters to be escaped in
    26  	// several ways and also allows unescaped multi-byte characters.
    27  	EncodeAsHex func(rune) bool
    28  }
    29  
    30  // Run runs the test suite.
    31  func (s WriterTestSuite) Run(t *testing.T) {
    32  	tf := testFactory{
    33  		valueTestFactory: s.ValueTestFactory,
    34  		encodingBehavior: encodingBehavior{
    35  			encodeAsHex: s.EncodeAsHex,
    36  		},
    37  	}
    38  	tds := tf.MakeAllValueTests()
    39  	for _, td := range tds {
    40  		t.Run(td.name, func(t *testing.T) {
    41  			c := s.ContextFactory()
    42  			t.Cleanup(func() {
    43  				if t.Failed() {
    44  					t.Logf("JSON output: `%s`", string(c.JSONData()))
    45  				}
    46  			})
    47  			require.NoError(t, td.action(c))
    48  			output := string(c.JSONData())
    49  			require.Regexp(t, makeOutputRegex(td.encoding), output)
    50  		})
    51  	}
    52  }
    53  
    54  // Make a regex that will allow any amount of whitespace between the matched substrings.
    55  func makeOutputRegex(outputParts []string) *regexp.Regexp {
    56  	regex := "\\w*"
    57  	for _, outputPart := range outputParts {
    58  		regex += regexp.QuoteMeta(outputPart)
    59  		regex += "\\w*"
    60  	}
    61  	return regexp.MustCompile(regex)
    62  }
    63  

View as plain text