@@ -2,7 +2,10 @@ package matcher
22
33import (
44 "fmt"
5+ "github.com/antchfx/xmlquery"
56 "github.com/pmezard/go-difflib/difflib"
7+ "github.com/tidwall/gjson"
8+ "log"
69 "strings"
710)
811
@@ -15,6 +18,8 @@ const (
1518 Equal = "equal"
1619 // Not contains matcher type
1720 NotContains = "notcontains"
21+ JSON = "json"
22+ XML = "xml"
1823)
1924
2025// NewMatcher creates a new matcher by type
@@ -28,6 +33,10 @@ func NewMatcher(matcher string) Matcher {
2833 return EqualMatcher {}
2934 case NotContains :
3035 return NotContainsMatcher {}
36+ case JSON :
37+ return JSONMatcher {}
38+ case XML :
39+ return XMLMatcher {}
3140 default :
3241 panic (fmt .Sprintf ("Validator '%s' does not exist!" , matcher ))
3342 }
@@ -51,6 +60,7 @@ type TextMatcher struct {
5160// Match matches both texts
5261func (m TextMatcher ) Match (got interface {}, expected interface {}) MatcherResult {
5362 result := true
63+
5464 if got != expected {
5565 result = false
5666 }
@@ -150,3 +160,83 @@ to not contain
150160 Diff : diff ,
151161 }
152162}
163+
164+ type JSONMatcher struct {
165+ }
166+
167+ func (m JSONMatcher ) Match (got interface {}, expected interface {}) MatcherResult {
168+ result := MatcherResult {
169+ Success : true ,
170+ Diff : "" ,
171+ }
172+
173+ json := expected .(map [string ]string )
174+ for q , e := range json {
175+ r := gjson .Get (got .(string ), q )
176+ if r .Value () == nil {
177+ result .Success = false
178+ result .Diff = fmt .Sprintf (`Query "%s" did not match a path` , q )
179+ break
180+ }
181+
182+ if fmt .Sprintf ("%v" , r .Value ()) != e {
183+ result .Success = false
184+ result .Diff = fmt .Sprintf (`Expected json path "%s" with result
185+
186+ %s
187+
188+ to be equal to
189+
190+ %s` , q , e , r .Value ())
191+ break
192+ }
193+ }
194+
195+ return result
196+ }
197+
198+ type XMLMatcher struct {
199+ }
200+
201+ func (m XMLMatcher ) Match (got interface {}, expected interface {}) MatcherResult {
202+ result := MatcherResult {
203+ Success : true ,
204+ Diff : "" ,
205+ }
206+
207+ xml := expected .(map [string ]string )
208+ for q , e := range xml {
209+ doc , err := xmlquery .Parse (strings .NewReader (got .(string )))
210+ if err != nil {
211+ log .Fatal (err )
212+ }
213+
214+ node , err := xmlquery .Query (doc , q )
215+ if err != nil {
216+ return MatcherResult {
217+ Success : false ,
218+ Diff : fmt .Sprintf ("Error occured: %s" , err ),
219+ }
220+ }
221+
222+ if node == nil {
223+ return MatcherResult {
224+ Success : false ,
225+ Diff : fmt .Sprintf (`Query "%s" did not match a path` , q ),
226+ }
227+ }
228+
229+ if node .InnerText () != e {
230+ result .Success = false
231+ result .Diff = fmt .Sprintf (`Expected xml path "%s" with result
232+
233+ %s
234+
235+ to be equal to
236+
237+ %s` , q , e , node .InnerText ())
238+ }
239+ }
240+
241+ return result
242+ }
0 commit comments