11package jsonpath
22
33import (
4+ "encoding"
45 "encoding/json"
56 "fmt"
67 "os"
@@ -21,6 +22,7 @@ func book(idx int) spec.NormalizedPath {
2122func TestParseSpecExamples (t * testing.T ) {
2223 t .Parallel ()
2324 a := assert .New (t )
25+ r := require .New (t )
2426 val := specExampleJSON (t )
2527 store , _ := val ["store" ].(map [string ]any )
2628 books , _ := store ["book" ].([]any )
@@ -126,9 +128,35 @@ func TestParseSpecExamples(t *testing.T) {
126128 } {
127129 t .Run (tc .name , func (t * testing.T ) {
128130 t .Parallel ()
131+
132+ // Test parsing.
129133 p := MustParse (tc .path )
130134 a .Equal (p .q , p .Query ())
131135 a .Equal (p .q .String (), p .String ())
136+
137+ // Test text encoding.
138+ a .Implements ((* encoding .TextMarshaler )(nil ), p )
139+ a .Implements ((* encoding .TextUnmarshaler )(nil ), p )
140+ text , err := p .MarshalText ()
141+ r .NoError (err )
142+ a .Equal (p .q .String (), string (text ))
143+ p .q = nil
144+ r .NoError (p .UnmarshalText (text ))
145+ a .Equal (p .q , p .Query ())
146+ a .Equal (p .q .String (), p .String ())
147+
148+ // Test binary encoding.
149+ a .Implements ((* encoding .BinaryMarshaler )(nil ), p )
150+ a .Implements ((* encoding .BinaryUnmarshaler )(nil ), p )
151+ data , err := p .MarshalBinary ()
152+ r .NoError (err )
153+ a .Equal (p .q .String (), string (data ))
154+ p .q = nil
155+ r .NoError (p .UnmarshalBinary (text ))
156+ a .Equal (p .q , p .Query ())
157+ a .Equal (p .q .String (), p .String ())
158+
159+ // Test execution.
132160 res := p .Select (val )
133161 loc := p .SelectLocated (val )
134162
@@ -333,6 +361,20 @@ func TestParser(t *testing.T) {
333361 a .PanicsWithError (tc .err , func () { parser .MustParse (tc .path ) })
334362 }
335363 }
364+
365+ // Test text and binary decoding.
366+ if tc .err == "" {
367+ p = & Path {}
368+ r .NoError (p .UnmarshalText ([]byte (tc .path )))
369+ a .Equal (tc .exp , p )
370+ p = & Path {}
371+ r .NoError (p .UnmarshalBinary ([]byte (tc .path )))
372+ a .Equal (tc .exp , p )
373+ } else {
374+ p = & Path {}
375+ r .EqualError (p .UnmarshalText ([]byte (tc .path )), tc .err )
376+ r .EqualError (p .UnmarshalBinary ([]byte (tc .path )), tc .err )
377+ }
336378 })
337379 }
338380}
0 commit comments