forked from gocolly/colly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunmarshal_test.go
58 lines (53 loc) · 1.6 KB
/
unmarshal_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package colly
import (
"bytes"
"testing"
"github.com/PuerkitoBio/goquery"
)
var basicTestData = []byte(`<ul><li class="x">list <span>item</span> 1</li><li>list item 2</li><li>3</li></ul>`)
var nestedTestData = []byte(`<div><p>a</p><div><p>b</p><div><p>c</p></div></div></div>`)
func TestBasicUnmarshal(t *testing.T) {
doc, _ := goquery.NewDocumentFromReader(bytes.NewBuffer(basicTestData))
e := &HTMLElement{
DOM: doc.First(),
}
s := struct {
String string `selector:"li:first-child" attr:"class"`
Items []string `selector:"li"`
Struct struct {
String string `selector:"li:last-child"`
}
}{}
if err := e.Unmarshal(&s); err != nil {
t.Error("Cannot unmarshal struct: " + err.Error())
}
if s.String != "x" {
t.Errorf(`Invalid data for String: %q, expected "x"`, s.String)
}
if s.Struct.String != "3" {
t.Errorf(`Invalid data for Struct.String: %q, expected "3"`, s.Struct.String)
}
}
func TestNestedUnmarshal(t *testing.T) {
doc, _ := goquery.NewDocumentFromReader(bytes.NewBuffer(nestedTestData))
e := &HTMLElement{
DOM: doc.First(),
}
type nested struct {
String string `selector:"div > p"`
Struct *nested `selector:"div > div"`
}
s := nested{}
if err := e.Unmarshal(&s); err != nil {
t.Error("Cannot unmarshal struct: " + err.Error())
}
if s.String != "a" {
t.Errorf(`Invalid data for String: %q, expected "a"`, s.String)
}
if s.Struct.String != "b" {
t.Errorf(`Invalid data for Struct.String: %q, expected "b"`, s.Struct.String)
}
if s.Struct.Struct.String != "c" {
t.Errorf(`Invalid data for Struct.Struct.String: %q, expected "c"`, s.Struct.Struct.String)
}
}