github.com/crowdsecurity/crowdsec@v1.6.1/pkg/exprhelpers/xml_test.go (about) 1 package exprhelpers 2 3 import ( 4 "log" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestXMLGetAttributeValue(t *testing.T) { 11 if err := Init(nil); err != nil { 12 log.Fatal(err) 13 } 14 15 tests := []struct { 16 name string 17 xmlString string 18 path string 19 attribute string 20 expectResult string 21 }{ 22 { 23 name: "XMLGetAttributeValue", 24 xmlString: `<root><child attr="value"/></root>`, 25 path: "/root/child", 26 attribute: "attr", 27 expectResult: "value", 28 }, 29 { 30 name: "Non existing attribute for XMLGetAttributeValue", 31 xmlString: `<root><child attr="value"/></root>`, 32 path: "/root/child", 33 attribute: "asdasd", 34 expectResult: "", 35 }, 36 { 37 name: "Non existing path for XMLGetAttributeValue", 38 xmlString: `<root><child attr="value"/></root>`, 39 path: "/foo/bar", 40 attribute: "asdasd", 41 expectResult: "", 42 }, 43 { 44 name: "Invalid XML for XMLGetAttributeValue", 45 xmlString: `<root><`, 46 path: "/foo/bar", 47 attribute: "asdasd", 48 expectResult: "", 49 }, 50 { 51 name: "Invalid path for XMLGetAttributeValue", 52 xmlString: `<root><child attr="value"/></root>`, 53 path: "/foo/bar[@", 54 attribute: "asdasd", 55 expectResult: "", 56 }, 57 } 58 59 for _, test := range tests { 60 result, _ := XMLGetAttributeValue(test.xmlString, test.path, test.attribute) 61 isOk := assert.Equal(t, test.expectResult, result) 62 if !isOk { 63 t.Fatalf("test '%s' failed", test.name) 64 } 65 log.Printf("test '%s' : OK", test.name) 66 } 67 68 } 69 func TestXMLGetNodeValue(t *testing.T) { 70 if err := Init(nil); err != nil { 71 log.Fatal(err) 72 } 73 74 tests := []struct { 75 name string 76 xmlString string 77 path string 78 expectResult string 79 }{ 80 { 81 name: "XMLGetNodeValue", 82 xmlString: `<root><child>foobar</child></root>`, 83 path: "/root/child", 84 expectResult: "foobar", 85 }, 86 { 87 name: "Non existing path for XMLGetNodeValue", 88 xmlString: `<root><child>foobar</child></root>`, 89 path: "/foo/bar", 90 expectResult: "", 91 }, 92 { 93 name: "Invalid XML for XMLGetNodeValue", 94 xmlString: `<root><`, 95 path: "/foo/bar", 96 expectResult: "", 97 }, 98 { 99 name: "Invalid path for XMLGetNodeValue", 100 xmlString: `<root><child>foobar</child></root>`, 101 path: "/foo/bar[@", 102 expectResult: "", 103 }, 104 } 105 106 for _, test := range tests { 107 result, _ := XMLGetNodeValue(test.xmlString, test.path) 108 isOk := assert.Equal(t, test.expectResult, result) 109 if !isOk { 110 t.Fatalf("test '%s' failed", test.name) 111 } 112 log.Printf("test '%s' : OK", test.name) 113 } 114 115 }