@@ -7,8 +7,12 @@ package etree
7
7
import (
8
8
"bytes"
9
9
"encoding/xml"
10
+ "errors"
10
11
"io"
12
+ "io/fs"
11
13
"math/rand"
14
+ "os"
15
+ "path"
12
16
"strings"
13
17
"testing"
14
18
)
@@ -1540,19 +1544,46 @@ func TestValidateInput(t *testing.T) {
1540
1544
{`<root><child>x</child></root1>` , `XML syntax error on line 1: element <root> closed by </root1>` },
1541
1545
}
1542
1546
1543
- for i , test := range tests {
1544
- doc := NewDocument ()
1545
- doc .ReadSettings .ValidateInput = true
1546
- err := doc .ReadFromString (test .s )
1547
- if err == nil {
1548
- if test .err != "" {
1549
- t .Errorf ("etree: test #%d:\n Expected error:\n %s\n Received error:\n nil" , i , test .err )
1550
- }
1551
- } else {
1552
- te := err .Error ()
1553
- if te != test .err {
1554
- t .Errorf ("etree: test #%d:\n Expected error;\n %s\n Received error:\n %s" , i , test .err , te )
1547
+ type readFunc func (doc * Document , s string ) error
1548
+ runTests := func (t * testing.T , read readFunc ) {
1549
+ for i , test := range tests {
1550
+ doc := NewDocument ()
1551
+ doc .ReadSettings .ValidateInput = true
1552
+ err := read (doc , test .s )
1553
+ if err == nil {
1554
+ if test .err != "" {
1555
+ t .Errorf ("etree: test #%d:\n Expected error:\n %s\n Received error:\n nil" , i , test .err )
1556
+ }
1557
+ root := doc .Root ()
1558
+ if root == nil || root .Tag != "root" {
1559
+ t .Errorf ("etree: test #%d: failed to read document after input validation" , i )
1560
+ }
1561
+ } else {
1562
+ te := err .Error ()
1563
+ if te != test .err {
1564
+ t .Errorf ("etree: test #%d:\n Expected error;\n %s\n Received error:\n %s" , i , test .err , te )
1565
+ }
1555
1566
}
1556
1567
}
1557
1568
}
1569
+
1570
+ readFromString := func (doc * Document , s string ) error {
1571
+ return doc .ReadFromString (s )
1572
+ }
1573
+ t .Run ("ReadFromString" , func (t * testing.T ) { runTests (t , readFromString ) })
1574
+
1575
+ readFromBytes := func (doc * Document , s string ) error {
1576
+ return doc .ReadFromBytes ([]byte (s ))
1577
+ }
1578
+ t .Run ("ReadFromBytes" , func (t * testing.T ) { runTests (t , readFromBytes ) })
1579
+
1580
+ readFromFile := func (doc * Document , s string ) error {
1581
+ pathtmp := path .Join (t .TempDir (), "etree-test" )
1582
+ err := os .WriteFile (pathtmp , []byte (s ), fs .ModePerm )
1583
+ if err != nil {
1584
+ return errors .New ("unable to write tmp file for input validation" )
1585
+ }
1586
+ return doc .ReadFromFile (pathtmp )
1587
+ }
1588
+ t .Run ("ReadFromFile" , func (t * testing.T ) { runTests (t , readFromFile ) })
1558
1589
}
0 commit comments