forked from JohannesKaufmann/html-to-markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrom_test.go
721 lines (623 loc) · 15.1 KB
/
from_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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
package md
import (
"bytes"
"errors"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"github.com/PuerkitoBio/goquery"
)
func TestConvertReader(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
converter := NewConverter("", true, nil)
res, err := converter.ConvertReader(strings.NewReader(input))
if err != nil {
t.Error(err)
}
if !bytes.Equal(res.Bytes(), []byte(expected)) {
t.Error("the result is different that expected")
}
}
type ErrReader struct{ Error error }
// -> https://stackoverflow.com/a/57452918
func (e *ErrReader) Read([]byte) (int, error) {
return 0, e.Error
}
func TestConvertReader_Error(t *testing.T) {
reader := &ErrReader{
Error: errors.New("we got an error"),
}
converter := NewConverter("", true, nil)
res, err := converter.ConvertReader(reader)
if err != reader.Error {
t.Error("expected an error")
}
if res.Len() != 0 {
t.Error("expected an empty buffer")
}
}
func TestConvertBytes(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
converter := NewConverter("", true, nil)
res, err := converter.ConvertBytes([]byte(input))
if err != nil {
t.Error(err)
}
if !bytes.Equal(res, []byte(expected)) {
t.Error("the result is different that expected")
}
}
func TestConvertBytes_Empty(t *testing.T) {
converter := NewConverter("", true, nil)
res, err := converter.ConvertBytes(nil)
if err != nil {
t.Error(err)
}
if !bytes.Equal(res, []byte("")) {
t.Error("the result is different that expected")
}
}
func TestConvertResponse(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
converter := NewConverter("", true, nil)
res, err := converter.ConvertResponse(&http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(input)),
Request: &http.Request{},
})
if err != nil {
t.Error(err)
}
if res != expected {
t.Error("the result is different that expected")
}
}
func TestConvertResponse_Error(t *testing.T) {
expectedErr := errors.New("custom error reader")
converter := NewConverter("", true, nil)
res, err := converter.ConvertResponse(&http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(&ErrReader{
Error: expectedErr,
}),
Request: &http.Request{},
})
if err != expectedErr {
t.Error(err)
}
if res != "" {
t.Error("the result is different that expected")
}
}
func TestConvertString(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
converter := NewConverter("", true, nil)
res, err := converter.ConvertString(input)
if err != nil {
t.Error(err)
}
if res != expected {
t.Error("the result is different that expected")
}
}
func TestConvertSelection(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
doc, err := goquery.NewDocumentFromReader(strings.NewReader(input))
if err != nil {
t.Error(err)
}
converter := NewConverter("", true, nil)
res := converter.Convert(doc.Selection)
if res != expected {
t.Error("the result is different that expected")
}
}
func TestConvertURL(t *testing.T) {
input := `<strong>Bold</strong>`
expected := `**Bold**`
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(input))
}))
// Close the server when test finishes
defer server.Close()
// override the client used in `ConvertURL`
netClient = server.Client()
converter := NewConverter(server.URL, true, nil)
res, err := converter.ConvertURL(server.URL)
if err != nil {
t.Error(err)
}
if res != expected {
t.Error("the result is different that expected")
}
}
func TestConvertURL_Error(t *testing.T) {
url := "abc https://example.com"
converter := NewConverter("", true, nil)
res, err := converter.ConvertURL(url)
if err == nil {
t.Error("expected an error")
}
if res != "" {
t.Error("the result is different that expected")
}
}
func TestConvertURL_ErrorStatusCode(t *testing.T) {
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusNotFound)
rw.Write([]byte("404 Not Found"))
}))
// Close the server when test finishes
defer server.Close()
// override the client used in `ConvertURL`
netClient = server.Client()
converter := NewConverter(server.URL, true, nil)
res, err := converter.ConvertURL(server.URL)
if err == nil {
t.Error("expected an error")
}
if res != "" {
t.Error("the result is different that expected")
}
}
// - - - - - - - - - - - - //
func TestNewConverter_NoRules(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
log.SetFlags(0)
defer func() {
// reset the options back to the defaults
log.SetOutput(os.Stderr)
log.SetFlags(3)
}()
input := `<strong>Bold</strong>`
expected := ``
// disable commonmark
converter := NewConverter("", false, nil)
res, err := converter.ConvertString(input)
if err != nil {
t.Error(err)
}
if res != expected {
t.Error("the result is different that expected")
}
if strings.TrimSuffix(buf.String(), "\n") != "you have added no rules. either enable commonmark or add you own." {
t.Error("expected a different log message")
}
}
func TestNewConverter_ValidateOptions(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
log.SetFlags(0)
defer func() {
// reset the options back to the defaults
log.SetOutput(os.Stderr)
log.SetFlags(3)
}()
input := `<strong>Bold</strong>`
expected := `====Bold====`
converter := NewConverter("", true, &Options{
StrongDelimiter: "====",
})
res, err := converter.ConvertString(input)
if err != nil {
t.Error(err)
}
if res != expected {
t.Error("the result is different that expected")
}
if strings.TrimSuffix(buf.String(), "\n") != "markdown options is not valid: field must be one of [** __] but got ====" {
t.Error("expected a different log message")
}
}
func TestNewConverter_ValidateOptions_All(t *testing.T) {
var tests = []struct {
name string
options *Options
input string
expected string
}{
{
name: "HeadingStyle",
options: &Options{
HeadingStyle: "invalid",
},
input: `<h1>Heading</h1>`,
expected: `# Heading`,
},
{
name: "HorizontalRule",
options: &Options{
HorizontalRule: "--",
},
input: `<hr />`,
expected: `--`,
},
{
name: "BulletListMarker",
options: &Options{
BulletListMarker: "^",
},
input: `<ul><li>Test</li></ul>`,
expected: `^ Test`,
},
{
name: "CodeBlockStyle",
options: &Options{
CodeBlockStyle: "invalid",
},
input: `<code>test</code>`,
expected: "`test`",
},
{
name: "Fence",
options: &Options{
Fence: "^^^",
},
input: `<pre>test</pre>`,
expected: "^^^\ntest\n^^^",
},
{
name: "EmDelimiter",
options: &Options{
EmDelimiter: "-",
},
input: `<i>test</i>`,
expected: "-test-",
},
{
name: "LinkStyle",
options: &Options{
LinkStyle: "invalid",
},
input: `<a href="example.com">link</a>`,
expected: `[link][1]
[1]: example.com`,
},
{
name: "LinkReferenceStyle",
options: &Options{
LinkReferenceStyle: "invalid",
},
input: `<a href="example.com">link</a>`,
expected: "[link](example.com)",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
log.SetFlags(0)
defer func() {
// reset the options back to the defaults
log.SetOutput(os.Stderr)
log.SetFlags(3)
}()
converter := NewConverter("", true, test.options)
res, err := converter.ConvertString(test.input)
if err != nil {
t.Error(err)
}
if res != test.expected {
t.Errorf("expected '%s' but got '%s'", test.expected, res)
}
logOutput := strings.TrimSuffix(buf.String(), "\n")
if !strings.Contains(logOutput, "markdown options is not valid: ") {
t.Errorf("expected a different log message but got '%s'", logOutput)
}
})
}
}
func BenchmarkFromString(b *testing.B) {
converter := NewConverter("www.google.com", true, nil)
strongRule := Rule{
Filter: []string{"strong"},
Replacement: func(content string, selec *goquery.Selection, opt *Options) *string {
return nil
},
}
var wg sync.WaitGroup
convert := func(html string) {
defer wg.Done()
_, err := converter.ConvertString(html)
if err != nil {
b.Error(err)
}
}
add := func() {
defer wg.Done()
converter.AddRules(strongRule)
}
for n := 0; n < b.N; n++ {
wg.Add(2)
go add()
go convert("<strong>Bold</strong>")
}
wg.Wait()
}
func TestAddRules_ChangeContent(t *testing.T) {
expected := "Some other Content"
var wasCalled bool
rule := Rule{
Filter: []string{"p"},
Replacement: func(content string, selec *goquery.Selection, opt *Options) *string {
wasCalled = true
if content != "Some Content" {
t.Errorf("got wrong `content`: '%s'", content)
}
if !selec.Is("p") {
t.Error("selec is not p")
}
return String(expected)
},
}
conv := NewConverter("", true, nil)
conv.AddRules(rule)
md, err := conv.ConvertString(`<p>Some Content</p>`)
if err != nil {
t.Error(err)
}
if md != expected {
t.Errorf("wanted '%s' but got '%s'", expected, md)
}
if !wasCalled {
t.Error("rule was not called")
}
}
func TestAddRules_Fallback(t *testing.T) {
// firstExpected := "Some other Content"
expected := "Totally different Content"
var firstWasCalled bool
var secondWasCalled bool
firstRule := Rule{
Filter: []string{"p"},
Replacement: func(content string, selec *goquery.Selection, opt *Options) *string {
firstWasCalled = true
if secondWasCalled {
t.Error("expected first rule to be called before second rule. second is already called")
}
if content != "Some Content" {
t.Errorf("got wrong `content`: '%s'", content)
}
if !selec.Is("p") {
t.Error("selec is not p")
}
return nil
},
}
secondRule := Rule{
Filter: []string{"p"},
Replacement: func(content string, selec *goquery.Selection, opt *Options) *string {
secondWasCalled = true
if !firstWasCalled {
t.Error("expected first rule to be called before second rule. first is not called yet")
}
if content != "Some Content" {
t.Errorf("got wrong `content`: '%s'", content)
}
if !selec.Is("p") {
t.Error("selec is not p")
}
return String(expected)
},
}
conv := NewConverter("", true, nil)
conv.AddRules(secondRule, firstRule)
md, err := conv.ConvertString(`<p>Some Content</p>`)
if err != nil {
t.Error(err)
}
if md != expected {
t.Errorf("wanted '%s' but got '%s'", expected, md)
}
if !firstWasCalled {
t.Error("first rule was not called")
}
if !secondWasCalled {
t.Error("second rule was not called")
}
}
func TestAddRules_NoRules(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
log.SetFlags(0)
defer func() {
// reset the options back to the defaults
log.SetOutput(os.Stderr)
log.SetFlags(3)
}()
var wasCalled bool
rule := Rule{
Filter: []string{ /* nothing */ },
Replacement: func(content string, selec *goquery.Selection, opt *Options) *string {
wasCalled = true
return nil
},
}
conv := NewConverter("", true, nil)
conv.AddRules(rule)
md, err := conv.ConvertString(`<p>Some Content</p>`)
if err != nil {
t.Error(err)
}
if md != "Some Content" {
t.Error("got different markdown result")
}
logOutput := strings.TrimSuffix(buf.String(), "\n")
if logOutput != "you need to specify at least one filter for your rule" {
t.Errorf("expected a different log message but got '%s'", logOutput)
}
if wasCalled {
t.Error("the rule should not have been called")
}
}
func TestBefore(t *testing.T) {
var firstWasCalled bool
var secondWasCalled bool
firstHook := func(selec *goquery.Selection) {
firstWasCalled = true
if secondWasCalled {
t.Error("the second hook should not be called yet")
}
}
secondHook := func(selec *goquery.Selection) {
secondWasCalled = true
if !firstWasCalled {
t.Error("the first hook should already be called")
}
}
conv := NewConverter("", true, nil)
conv.Before(firstHook, secondHook)
_, err := conv.ConvertString(`<a href="https://test.com">Link</a>`)
if err != nil {
t.Error(err)
}
if !firstWasCalled || !secondWasCalled {
t.Error("not all hooks were called")
}
}
func TestAfter(t *testing.T) {
var firstWasCalled bool
var secondWasCalled bool
firstHook := func(md string) string {
firstWasCalled = true
if secondWasCalled {
t.Error("the second hook should not be called yet")
}
return md + " first"
}
secondHook := func(md string) string {
secondWasCalled = true
if !firstWasCalled {
t.Error("the first hook should already be called")
}
return md + " second"
}
conv := NewConverter("", true, nil)
conv.After(firstHook, secondHook)
md, err := conv.ConvertString(`<span>base</span>`)
if err != nil {
t.Error(err)
}
if md != `base first second` {
t.Errorf("expected different markdown result but got '%s'", md)
}
if !firstWasCalled || !secondWasCalled {
t.Error("not all hooks were called")
}
}
func TestClearBefore(t *testing.T) {
var wasCalled bool
hook := func(selec *goquery.Selection) {
wasCalled = true
}
conv := NewConverter("", true, nil)
conv.ClearBefore()
if len(conv.before) != 0 {
t.Error("the before hook array should be of length 0")
}
conv.Before(hook)
_, err := conv.ConvertString(`<a href="https://test.com">Link</a>`)
if err != nil {
t.Error(err)
}
if !wasCalled {
t.Error("the hook should have been called")
}
}
func TestClearAfter(t *testing.T) {
var wasCalled bool
hook := func(markdown string) string {
wasCalled = true
return "my new value"
}
conv := NewConverter("", true, nil)
conv.ClearAfter()
if len(conv.after) != 0 {
t.Error("the after hook array should be of length 0")
}
conv.After(hook)
md, err := conv.ConvertString(`<a href="https://test.com">Link</a>`)
if err != nil {
t.Error(err)
}
if md != "my new value" {
t.Error("the result was different then expected")
}
if !wasCalled {
t.Error("the hook should have been called")
}
}
func TestDomainFromURL(t *testing.T) {
var tests = []struct {
input string
expected string
}{
{
input: "example.com",
expected: "example.com",
},
{
input: "https://example.com",
expected: "example.com",
},
{
input: "https://www.example.com",
expected: "www.example.com",
},
{
input: "http://example.com/index.html",
expected: "example.com",
},
{
input: "http://example.com?page=home",
expected: "example.com",
},
{
input: "http://example.com#page",
expected: "example.com",
},
{
input: "http://example.com:3000",
expected: "example.com:3000",
},
{
// not so happy about this :(
input: "example",
expected: "example",
},
{
input: "https://developer.mozilla.org/en-US/docs/Web/API/URL/host",
expected: "developer.mozilla.org",
},
{
input: " http://example.com",
expected: "example.com",
},
{
// invalid url
input: "abc http://example.com",
expected: "",
},
}
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
res := DomainFromURL(test.input)
if res != test.expected {
t.Errorf("for '%s' expected '%s' but got '%s'", test.input, test.expected, res)
}
})
}
}