-
Notifications
You must be signed in to change notification settings - Fork 90
/
parser_test.go
279 lines (232 loc) · 7.44 KB
/
parser_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package readability
import (
"encoding/json"
"fmt"
"net/url"
"os"
fp "path/filepath"
"strings"
"testing"
"time"
"github.com/go-shiori/dom"
"github.com/sergi/go-diff/diffmatchpatch"
"golang.org/x/net/html"
)
var (
fakeHostURL, _ = url.ParseRequestURI("http://fakehost/test/page.html")
)
type ExpectedMetadata struct {
Title string `json:"title,omitempty"`
Byline string `json:"byline,omitempty"`
Excerpt string `json:"excerpt,omitempty"`
Language string `json:"language,omitempty"`
SiteName string `json:"siteName,omitempty"`
Readerable bool `json:"readerable"`
PublishedTime string `json:"publishedTime,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty"`
}
func Test_parser(t *testing.T) {
testDir := "test-pages"
testItems, err := os.ReadDir(testDir)
if err != nil {
t.Errorf("\nfailed to read test directory")
}
for _, item := range testItems {
if !item.IsDir() {
continue
}
itemName := item.Name()
t.Run(itemName, func(t1 *testing.T) {
// Prepare path
sourcePath := fp.Join(testDir, itemName, "source.html")
expectedPath := fp.Join(testDir, itemName, "expected.html")
expectedMetaPath := fp.Join(testDir, itemName, "expected-metadata.json")
// Extract source file
article, originalDoc, extractedDoc, err := extractSourceFile(sourcePath)
if err != nil {
t1.Error(err)
}
// Decode expected file
expectedDoc, err := decodeExpectedFile(expectedPath)
if err != nil {
t1.Error(err)
}
// Decode expected metadata
metadata, err := decodeExpectedMetadata(expectedMetaPath)
if err != nil {
t1.Error(err)
}
// Compare extraction result
err = compareArticleContent(extractedDoc, expectedDoc)
if err != nil {
t1.Error(err)
}
// Check metadata
if metadata.Byline != article.Byline {
t1.Errorf("byline, want %q got %q\n", metadata.Byline, article.Byline)
}
if metadata.Excerpt != article.Excerpt {
t1.Errorf("excerpt, want %q got %q\n", metadata.Excerpt, article.Excerpt)
}
if metadata.SiteName != article.SiteName {
t1.Errorf("sitename, want %q got %q\n", metadata.SiteName, article.SiteName)
}
if metadata.Title != article.Title {
t1.Errorf("title, want %q got %q\n", metadata.Title, article.Title)
}
if isReaderable := CheckDocument(originalDoc); metadata.Readerable != isReaderable {
t1.Errorf("readerable, want %v got %v\n", metadata.Readerable, isReaderable)
}
if metadata.Language != article.Language {
t1.Errorf("language, want %q got %q\n", metadata.Language, article.Language)
}
if !timesAreEqual(metadata.PublishedTime, article.PublishedTime) {
t1.Errorf("date published, want %q got %q\n", metadata.PublishedTime, article.PublishedTime)
}
if !timesAreEqual(metadata.ModifiedTime, article.ModifiedTime) {
t1.Errorf("date modified, want %q got %q\n", metadata.ModifiedTime, article.ModifiedTime)
}
})
}
}
func extractSourceFile(path string) (Article, *html.Node, *html.Node, error) {
// Open source file
f, err := os.Open(path)
if err != nil {
return Article{}, nil, nil, fmt.Errorf("failed to open source: %v", err)
}
defer f.Close()
// Decode to HTML
originalDoc, err := dom.Parse(f)
if err != nil {
return Article{}, nil, nil, fmt.Errorf("failed to decode source: %v", err)
}
// Extract readable article
article, err := FromDocument(originalDoc, fakeHostURL)
if err != nil {
return Article{}, nil, nil, fmt.Errorf("failed to extract source: %v", err)
}
// Parse article into HTML
extractedDoc, err := dom.Parse(strings.NewReader(article.Content))
if err != nil {
return Article{}, nil, nil, fmt.Errorf("failed to parse exytract to HTML: %v", err)
}
return article, originalDoc, extractedDoc, nil
}
func decodeExpectedFile(path string) (*html.Node, error) {
// Open expected file
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open expected: %v", err)
}
defer f.Close()
// Parse file into HTML document
doc, err := dom.Parse(f)
if err != nil {
return nil, fmt.Errorf("failed to parse expected to HTML: %v", err)
}
return doc, nil
}
func decodeExpectedMetadata(path string) (ExpectedMetadata, error) {
var zero ExpectedMetadata
// Open expected file
f, err := os.Open(path)
if err != nil {
return zero, fmt.Errorf("failed to open metadata: %v", err)
}
defer f.Close()
// Parse file into map
var result ExpectedMetadata
err = json.NewDecoder(f).Decode(&result)
return result, err
}
func compareArticleContent(result, expected *html.Node) error {
// Make sure number of nodes is same
resultNodesCount := len(dom.Children(result))
expectedNodesCount := len(dom.Children(expected))
if resultNodesCount != expectedNodesCount {
return fmt.Errorf("number of nodes is different, want %d got %d",
expectedNodesCount, resultNodesCount)
}
resultNode := result
expectedNode := expected
for resultNode != nil && expectedNode != nil {
// Get node excerpt
resultExcerpt := getNodeExcerpt(resultNode)
expectedExcerpt := getNodeExcerpt(expectedNode)
// Compare tag name
resultTagName := dom.TagName(resultNode)
expectedTagName := dom.TagName(expectedNode)
if resultTagName != expectedTagName {
return fmt.Errorf("tag name is different\n"+
"want : %s (%s)\n"+
"got : %s (%s)",
expectedTagName, expectedExcerpt,
resultTagName, resultExcerpt)
}
// Compare attributes
resultAttrCount := len(resultNode.Attr)
expectedAttrCount := len(expectedNode.Attr)
if resultAttrCount != expectedAttrCount {
return fmt.Errorf("number of attributes is different\n"+
"want : %d (%s)\n"+
"got : %d (%s)",
expectedAttrCount, expectedExcerpt,
resultAttrCount, resultExcerpt)
}
for _, resultAttr := range resultNode.Attr {
expectedAttrVal := dom.GetAttribute(expectedNode, resultAttr.Key)
switch resultAttr.Key {
case "href", "src":
resultAttr.Val = strings.TrimSuffix(resultAttr.Val, "/")
expectedAttrVal = strings.TrimSuffix(expectedAttrVal, "/")
}
if resultAttr.Val != expectedAttrVal {
return fmt.Errorf("attribute %s is different\n"+
"want : %s (%s)\n"+
"got : %s (%s)",
resultAttr.Key, expectedAttrVal, expectedExcerpt,
resultAttr.Val, resultExcerpt)
}
}
// Compare text content
resultText := strings.TrimSpace(dom.TextContent(resultNode))
expectedText := strings.TrimSpace(dom.TextContent(expectedNode))
resultText = strings.Join(strings.Fields(resultText), " ")
expectedText = strings.Join(strings.Fields(expectedText), " ")
comparator := diffmatchpatch.New()
diffs := comparator.DiffMain(resultText, expectedText, false)
if len(diffs) > 1 {
return fmt.Errorf("text content is different\n"+
"want : %s\n"+
"got : %s\n"+
"diffs : %s",
expectedExcerpt, resultExcerpt,
comparator.DiffPrettyText(diffs))
}
// Move to next node
ps := Parser{}
resultNode = ps.getNextNode(resultNode, false)
expectedNode = ps.getNextNode(expectedNode, false)
}
return nil
}
func getNodeExcerpt(node *html.Node) string {
outer := dom.OuterHTML(node)
outer = strings.Join(strings.Fields(outer), " ")
if len(outer) < 120 {
return outer
}
return outer[:120]
}
func timesAreEqual(metadataTimeString string, parsedTime *time.Time) bool {
if metadataTimeString == "" && parsedTime == nil {
return true
}
if metadataTimeString == "" || parsedTime == nil {
return false
}
ps := Parser{}
metadataTime := ps.getParsedDate(metadataTimeString)
return metadataTime.Equal(*parsedTime)
}