match_xml_matcher.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package matchers
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "reflect"
  9. "sort"
  10. "strings"
  11. "github.com/onsi/gomega/format"
  12. "golang.org/x/net/html/charset"
  13. )
  14. type MatchXMLMatcher struct {
  15. XMLToMatch interface{}
  16. }
  17. func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err error) {
  18. actualString, expectedString, err := matcher.formattedPrint(actual)
  19. if err != nil {
  20. return false, err
  21. }
  22. aval, err := parseXmlContent(actualString)
  23. if err != nil {
  24. return false, fmt.Errorf("Actual '%s' should be valid XML, but it is not.\nUnderlying error:%s", actualString, err)
  25. }
  26. eval, err := parseXmlContent(expectedString)
  27. if err != nil {
  28. return false, fmt.Errorf("Expected '%s' should be valid XML, but it is not.\nUnderlying error:%s", expectedString, err)
  29. }
  30. return reflect.DeepEqual(aval, eval), nil
  31. }
  32. func (matcher *MatchXMLMatcher) FailureMessage(actual interface{}) (message string) {
  33. actualString, expectedString, _ := matcher.formattedPrint(actual)
  34. return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString)
  35. }
  36. func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  37. actualString, expectedString, _ := matcher.formattedPrint(actual)
  38. return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString)
  39. }
  40. func (matcher *MatchXMLMatcher) formattedPrint(actual interface{}) (actualString, expectedString string, err error) {
  41. var ok bool
  42. actualString, ok = toString(actual)
  43. if !ok {
  44. return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))
  45. }
  46. expectedString, ok = toString(matcher.XMLToMatch)
  47. if !ok {
  48. return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.XMLToMatch, 1))
  49. }
  50. return actualString, expectedString, nil
  51. }
  52. func parseXmlContent(content string) (*xmlNode, error) {
  53. allNodes := []*xmlNode{}
  54. dec := newXmlDecoder(strings.NewReader(content))
  55. for {
  56. tok, err := dec.Token()
  57. if err != nil {
  58. if err == io.EOF {
  59. break
  60. }
  61. return nil, fmt.Errorf("failed to decode next token: %v", err) // untested section
  62. }
  63. lastNodeIndex := len(allNodes) - 1
  64. var lastNode *xmlNode
  65. if len(allNodes) > 0 {
  66. lastNode = allNodes[lastNodeIndex]
  67. } else {
  68. lastNode = &xmlNode{}
  69. }
  70. switch tok := tok.(type) {
  71. case xml.StartElement:
  72. attrs := attributesSlice(tok.Attr)
  73. sort.Sort(attrs)
  74. allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr})
  75. case xml.EndElement:
  76. if len(allNodes) > 1 {
  77. allNodes[lastNodeIndex-1].Nodes = append(allNodes[lastNodeIndex-1].Nodes, lastNode)
  78. allNodes = allNodes[:lastNodeIndex]
  79. }
  80. case xml.CharData:
  81. lastNode.Content = append(lastNode.Content, tok.Copy()...)
  82. case xml.Comment:
  83. lastNode.Comments = append(lastNode.Comments, tok.Copy()) // untested section
  84. case xml.ProcInst:
  85. lastNode.ProcInsts = append(lastNode.ProcInsts, tok.Copy())
  86. }
  87. }
  88. if len(allNodes) == 0 {
  89. return nil, errors.New("found no nodes")
  90. }
  91. firstNode := allNodes[0]
  92. trimParentNodesContentSpaces(firstNode)
  93. return firstNode, nil
  94. }
  95. func newXmlDecoder(reader io.Reader) *xml.Decoder {
  96. dec := xml.NewDecoder(reader)
  97. dec.CharsetReader = charset.NewReaderLabel
  98. return dec
  99. }
  100. func trimParentNodesContentSpaces(node *xmlNode) {
  101. if len(node.Nodes) > 0 {
  102. node.Content = bytes.TrimSpace(node.Content)
  103. for _, childNode := range node.Nodes {
  104. trimParentNodesContentSpaces(childNode)
  105. }
  106. }
  107. }
  108. type xmlNode struct {
  109. XMLName xml.Name
  110. Comments []xml.Comment
  111. ProcInsts []xml.ProcInst
  112. XMLAttr []xml.Attr
  113. Content []byte
  114. Nodes []*xmlNode
  115. }