-
Notifications
You must be signed in to change notification settings - Fork 0
/
unmarshal_test.go
88 lines (74 loc) · 2.43 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package crepe_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/mkfsn/crepe"
"github.com/stretchr/testify/suite"
)
type UnmarshalSuite struct {
suite.Suite
}
func (suite *UnmarshalSuite) TestFirstQuery() {
html := suite.loadHTML("page1.html")
var data struct {
Employees []*struct {
Id string `crepe:"attr=data-id"`
Name string `crepe:"td,:eq(0),text"`
Gender string `crepe:"td,:eq(1),text"`
Age int `crepe:"td,:eq(2),text"`
Role string `crepe:"attr=role"`
} `crepe:"table,:eq(1),tbody>tr,:first"`
}
err := crepe.Unmarshal([]byte(html), &data)
suite.Require().NoError(err)
b, err := json.Marshal(data)
suite.Require().NoError(err)
suite.Require().Equal(`{"Employees":[{"Id":"aaaa","Name":"Tony","Gender":"Male","Age":20,"Role":"engineer"}]}`, string(b))
}
func (suite *UnmarshalSuite) TestLastQuery() {
html := suite.loadHTML("page1.html")
var data struct {
Employees []*struct {
Id string `crepe:"attr=data-id"`
Name string `crepe:"td,:eq(0),text"`
Gender string `crepe:"td,:eq(1),text"`
Age int `crepe:"td,:eq(2),text"`
Role string `crepe:"attr=role"`
} `crepe:"table,:eq(1),tbody>tr,:last"`
}
err := crepe.Unmarshal([]byte(html), &data)
suite.Require().NoError(err)
b, err := json.Marshal(data)
suite.Require().NoError(err)
suite.Require().Equal(`{"Employees":[{"Id":"bbbb","Name":"Mary","Gender":"Female","Age":23,"Role":"manager"}]}`, string(b))
}
func (suite *UnmarshalSuite) TestSliceOfPtrToStruct() {
html := suite.loadHTML("page1.html")
var data struct {
Employees []*struct {
Id string `crepe:"attr=data-id"`
Name string `crepe:"td,:eq(0),text"`
Gender string `crepe:"td,:eq(1),text"`
Age int `crepe:"td,:eq(2),text"`
Role string `crepe:"attr=role"`
} `crepe:"table,:eq(1),tbody>tr"`
}
err := crepe.Unmarshal([]byte(html), &data)
suite.Require().NoError(err)
b, err := json.Marshal(data)
suite.Require().NoError(err)
suite.Require().Equal(`{"Employees":[{"Id":"aaaa","Name":"Tony","Gender":"Male","Age":20,"Role":"engineer"},{"Id":"bbbb","Name":"Mary","Gender":"Female","Age":23,"Role":"manager"}]}`, string(b))
}
func (suite *UnmarshalSuite) loadHTML(filename string) []byte {
f, err := os.Open(fmt.Sprintf("./testdata/%s", filename))
suite.Require().NoError(err)
b, err := ioutil.ReadAll(f)
suite.Require().NoError(err)
return b
}
func TestUnmarshal(t *testing.T) {
suite.Run(t, new(UnmarshalSuite))
}