This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
epub_test.go
856 lines (726 loc) · 24.4 KB
/
epub_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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
package epub
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"testing"
"time"
)
const (
// Set this to false to not delete the generated test EPUB file
doCleanup = true
testAuthorTemplate = `<dc:creator id="creator">%s</dc:creator>`
testContainerContents = `<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml" />
</rootfiles>
</container>`
testCoverCSSFilename = "cover.css"
testCoverCSSSource = "testdata/cover.css"
testCoverContentTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
<link rel="stylesheet" type="text/css" href="%s"></link>
</head>
<body>
<img src="%s" alt="Cover Image" />
</body>
</html>`
testCSSLinkTemplate = `<link rel="stylesheet" type="text/css" href="%s"></link>`
testDirPerm = 0775
testEpubAuthor = "Hingle McCringleberry"
testEpubcheckJarfile = "epubcheck.jar"
testEpubcheckPrefix = "epubcheck"
testEpubFilename = "My EPUB.epub"
testEpubIdentifier = "urn:uuid:51b7c9ea-b2a2-49c6-9d8c-522790786d15"
testEpubLang = "fr"
testEpubPpd = "rtl"
testEpubTitle = "My title"
testEpubDescription = "My description"
testFontCSSFilename = "font.css"
testFontCSSSource = "testdata/font.css"
testFontFromFileSource = "testdata/redacted-script-regular.ttf"
testIdentifierTemplate = `<dc:identifier id="pub-id">%s</dc:identifier>`
testImageFromFileFilename = "testfromfile.png"
testImageFromFileSource = "testdata/gophercolor16x16.png"
testNumberFilenameStart = "01filenametest.png"
testSpaceInFilename = "filename with space.png"
testImageFromURLSource = "https://golang.org/doc/gopher/gophercolor16x16.png"
testLangTemplate = `<dc:language>%s</dc:language>`
testDescTemplate = `<dc:description>%s</dc:description>`
testPpdTemplate = `page-progression-direction="%s"`
testMimetypeContents = "application/epub+zip"
testPkgContentTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="pub-id" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:identifier id="pub-id">%s</dc:identifier>
<dc:title>%s</dc:title>
<dc:language>en</dc:language>
<meta property="dcterms:modified">%s</meta>
</metadata>
<manifest>
<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"></item>
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"></item>
</manifest>
<spine toc="ncx"></spine>
</package>`
testSectionBody = ` <h1>Section 1</h1>
<p>This is a paragraph.</p>`
testSectionContentTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
</head>
<body>
%s
</body>
</html>`
testSectionFilename = "section0001.xhtml"
testSectionTitle = "Section 1"
testTempDirPrefix = "go-epub"
testTitleTemplate = `<dc:title>%s</dc:title>`
)
func TestEpubWrite(t *testing.T) {
e := NewEpub(testEpubTitle)
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
// Check the contents of the package file
// NOTE: This is tested first because it contains a timestamp; testing it later may result in a different timestamp
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testPkgContents := fmt.Sprintf(testPkgContentTemplate, e.Identifier(), testEpubTitle, time.Now().UTC().Format("2006-01-02T15:04:05Z"))
if trimAllSpace(string(contents)) != trimAllSpace(testPkgContents) {
t.Errorf(
"Package file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testPkgContents)
}
// Check the contents of the mimetype file
contents, err = ioutil.ReadFile(filepath.Join(tempDir, mimetypeFilename))
if err != nil {
t.Errorf("Unexpected error reading mimetype file: %s", err)
}
if trimAllSpace(string(contents)) != trimAllSpace(testMimetypeContents) {
t.Errorf(
"Mimetype file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testMimetypeContents)
}
// Check the contents of the container file
contents, err = ioutil.ReadFile(filepath.Join(tempDir, metaInfFolderName, containerFilename))
if err != nil {
t.Errorf("Unexpected error reading container file: %s", err)
}
if trimAllSpace(string(contents)) != trimAllSpace(testContainerContents) {
t.Errorf(
"Container file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testContainerContents)
}
cleanup(testEpubFilename, tempDir)
}
func TestAddCSS(t *testing.T) {
e := NewEpub(testEpubTitle)
testCSS1Path, err := e.AddCSS(testCoverCSSSource, testCoverCSSFilename)
if err != nil {
t.Errorf("Error adding CSS: %s", err)
}
testCSS2Path, err := e.AddCSS(testCoverCSSSource, "")
if err != nil {
t.Errorf("Error adding CSS: %s", err)
}
// Add a section with CSS to make sure the stylesheet link for a section is properly created
testSectionPath, err := e.AddSection(testSectionBody, testSectionTitle, testSectionFilename, testCSS1Path)
if err != nil {
t.Errorf("Error adding section with CSS: %s", err)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
// The CSS file path is relative to the XHTML folder
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testCSS1Path))
if err != nil {
t.Errorf("Unexpected error reading CSS file: %s", err)
}
testCSSContents, err := ioutil.ReadFile(testCoverCSSSource)
if err != nil {
t.Errorf("Unexpected error reading CSS file: %s", err)
}
if trimAllSpace(string(contents)) != trimAllSpace(string(testCSSContents)) {
t.Errorf(
"CSS file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testCSSContents)
}
contents, err = ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testCSS2Path))
if err != nil {
t.Errorf("Unexpected error reading CSS file: %s", err)
}
if trimAllSpace(string(contents)) != trimAllSpace(string(testCSSContents)) {
t.Errorf(
"CSS file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testCSSContents)
}
contents, err = ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testSectionPath))
if err != nil {
t.Errorf("Unexpected error reading section file: %s", err)
}
testCSSLinkElement := fmt.Sprintf(testCSSLinkTemplate, testCSS1Path)
if !strings.Contains(string(contents), testCSSLinkElement) {
t.Errorf(
"CSS link doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testCSSLinkElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestAddFont(t *testing.T) {
e := NewEpub(testEpubTitle)
testFontFromFilePath, err := e.AddFont(testFontFromFileSource, "")
if err != nil {
t.Errorf("Error adding font: %s", err)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
// The font path is relative to the XHTML folder
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testFontFromFilePath))
if err != nil {
t.Errorf("Unexpected error reading font file from EPUB: %s", err)
}
testFontContents, err := ioutil.ReadFile(testFontFromFileSource)
if err != nil {
t.Errorf("Unexpected error reading testdata font file: %s", err)
}
if bytes.Compare(contents, testFontContents) != 0 {
t.Errorf("Font file contents don't match")
}
cleanup(testEpubFilename, tempDir)
}
func TestAddImage(t *testing.T) {
e := NewEpub(testEpubTitle)
testImageFromFilePath, err := e.AddImage(testImageFromFileSource, testImageFromFileFilename)
if err != nil {
t.Errorf("Error adding image: %s", err)
}
testImageFromURLPath, err := e.AddImage(testImageFromURLSource, "")
if err != nil {
t.Errorf("Error adding image: %s", err)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
// The image path is relative to the XHTML folder
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testImageFromFilePath))
if err != nil {
t.Errorf("Unexpected error reading image file from EPUB: %s", err)
}
testImageContents, err := ioutil.ReadFile(testImageFromFileSource)
if err != nil {
t.Errorf("Unexpected error reading testdata image file: %s", err)
}
if bytes.Compare(contents, testImageContents) != 0 {
t.Errorf("Image file contents don't match")
}
contents, err = ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testImageFromURLPath))
if err != nil {
t.Errorf("Unexpected error reading image file from EPUB: %s", err)
}
resp, err := http.Get(testImageFromURLSource)
if err != nil {
t.Errorf("Unexpected error response from test image URL: %s", err)
}
testImageContents, err = ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("Unexpected error reading test image file from URL: %s", err)
}
if bytes.Compare(contents, testImageContents) != 0 {
t.Errorf("Image file contents don't match")
}
cleanup(testEpubFilename, tempDir)
}
func TestAddSection(t *testing.T) {
e := NewEpub(testEpubTitle)
testSection1Path, err := e.AddSection(testSectionBody, testSectionTitle, testSectionFilename, "")
if err != nil {
t.Errorf("Error adding section: %s", err)
}
testSection2Path, err := e.AddSection(testSectionBody, testSectionTitle, "", "")
if err != nil {
t.Errorf("Error adding section: %s", err)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testSection1Path))
if err != nil {
t.Errorf("Unexpected error reading section file: %s", err)
}
testSectionContents := fmt.Sprintf(testSectionContentTemplate, testSectionTitle, testSectionBody)
if trimAllSpace(string(contents)) != trimAllSpace(testSectionContents) {
t.Errorf(
"Section file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testSectionContents)
}
contents, err = ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testSection2Path))
if err != nil {
t.Errorf("Unexpected error reading section file: %s", err)
}
if trimAllSpace(string(contents)) != trimAllSpace(testSectionContents) {
t.Errorf(
"Section file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testSectionContents)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubAuthor(t *testing.T) {
e := NewEpub(testEpubTitle)
e.SetAuthor(testEpubAuthor)
if e.Author() != testEpubAuthor {
t.Errorf(
"Author doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Author(),
testEpubAuthor)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testAuthorElement := fmt.Sprintf(testAuthorTemplate, testEpubAuthor)
if !strings.Contains(string(contents), testAuthorElement) {
t.Errorf(
"Author doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testAuthorElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubLang(t *testing.T) {
e := NewEpub(testEpubTitle)
e.SetLang(testEpubLang)
if e.Lang() != testEpubLang {
t.Errorf(
"Language doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Lang(),
testEpubLang)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testLangElement := fmt.Sprintf(testLangTemplate, testEpubLang)
if !strings.Contains(string(contents), testLangElement) {
t.Errorf(
"Language doesn't match\n"+
"Got: %s"+
"Expected: %s",
contents,
testLangElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubPpd(t *testing.T) {
e := NewEpub(testEpubTitle)
e.SetPpd(testEpubPpd)
if e.Ppd() != testEpubPpd {
t.Errorf(
"Ppd doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Ppd(),
testEpubPpd)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testPpdElement := fmt.Sprintf(testPpdTemplate, testEpubPpd)
if !strings.Contains(string(contents), testPpdElement) {
t.Errorf(
"Ppd doesn't match\n"+
"Got: %s"+
"Expected: %s",
contents,
testPpdElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubTitle(t *testing.T) {
// First, test the title we provide when creating the epub
e := NewEpub(testEpubTitle)
if e.Title() != testEpubTitle {
t.Errorf(
"Title doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Title(),
testEpubTitle)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testTitleElement := fmt.Sprintf(testTitleTemplate, testEpubTitle)
if !strings.Contains(string(contents), testTitleElement) {
t.Errorf(
"Title doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testTitleElement)
}
cleanup(testEpubFilename, tempDir)
// Now test changing the title
e.SetTitle(testEpubAuthor)
if e.Title() != testEpubAuthor {
t.Errorf(
"Title doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Title(),
testEpubAuthor)
}
tempDir = writeAndExtractEpub(t, e, testEpubFilename)
contents, err = ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testTitleElement = fmt.Sprintf(testTitleTemplate, testEpubAuthor)
if !strings.Contains(string(contents), testTitleElement) {
t.Errorf(
"Title doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testTitleElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubDescription(t *testing.T) {
e := NewEpub(testEpubTitle)
e.SetDescription(testEpubDescription)
if e.Description() != testEpubDescription {
t.Errorf(
"Description doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Lang(),
testEpubDescription)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testLangElement := fmt.Sprintf(testDescTemplate, testEpubDescription)
if !strings.Contains(string(contents), testLangElement) {
t.Errorf(
"Description doesn't match\n"+
"Got: %s"+
"Expected: %s",
contents,
testLangElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestEpubIdentifier(t *testing.T) {
e := NewEpub(testEpubTitle)
e.SetIdentifier(testEpubIdentifier)
if e.Identifier() != testEpubIdentifier {
t.Errorf(
"Identifier doesn't match\n"+
"Got: %s\n"+
"Expected: %s",
e.Identifier(),
testEpubIdentifier)
}
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
testIdentifierElement := fmt.Sprintf(testIdentifierTemplate, testEpubIdentifier)
if !strings.Contains(string(contents), testIdentifierElement) {
t.Errorf(
"Identifier doesn't match\n"+
"Got: %s"+
"Expected: %s",
contents,
testIdentifierElement)
}
cleanup(testEpubFilename, tempDir)
}
func TestSetCover(t *testing.T) {
e := NewEpub(testEpubTitle)
testImagePath, _ := e.AddImage(testImageFromFileSource, testImageFromFileFilename)
testCSSPath, _ := e.AddCSS(testCoverCSSSource, testCoverCSSFilename)
e.SetCover(testImagePath, testCSSPath)
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
contents, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, xhtmlFolderName, defaultCoverXhtmlFilename))
if err != nil {
t.Errorf("Unexpected error reading cover XHTML file: %s", err)
}
testCoverContents := fmt.Sprintf(testCoverContentTemplate, testEpubTitle, testCSSPath, testImagePath)
if trimAllSpace(string(contents)) != trimAllSpace(testCoverContents) {
t.Errorf(
"Cover file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testCoverContents)
}
cleanup(testEpubFilename, tempDir)
}
func TestManifestItems(t *testing.T) {
testManifestItems := []string{`id="filenamewithspace.png" href="images/filename with space.png" media-type="image/png"></item>`,
`id="gophercolor16x16.png" href="images/gophercolor16x16.png" media-type="image/png"></item>`,
`id="id01filenametest.png" href="images/01filenametest.png" media-type="image/png"></item>`,
`id="image0005.png" href="images/image0005.png" media-type="image/png"></item>`,
`id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"></item>`,
`id="testfromfile.png" href="images/testfromfile.png" media-type="image/png"></item>`,
}
e := NewEpub(testEpubTitle)
e.AddImage(testImageFromFileSource, testImageFromFileFilename)
e.AddImage(testImageFromFileSource, "")
// In particular, we want to test these next two, which will be modified by fixXMLId()
e.AddImage(testImageFromFileSource, testNumberFilenameStart)
e.AddImage(testImageFromFileSource, testSpaceInFilename)
e.AddImage(testImageFromURLSource, "")
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
pkgFileContent, err := ioutil.ReadFile(filepath.Join(tempDir, contentFolderName, pkgFilename))
if err != nil {
t.Errorf("Unexpected error reading package file: %s", err)
}
// Get just the manifest portion of the package file
manifestContentFromFile := string(pkgFileContent)[strings.Index(string(pkgFileContent), "<manifest>"):strings.Index(string(pkgFileContent), "</manifest>")]
// Convert the manifest portion of the package file to a slice
pkgFileManifestItems := strings.Split(manifestContentFromFile, "<item")
// Drop the <manifest> and </manifest>
pkgFileManifestItems = pkgFileManifestItems[1 : len(pkgFileManifestItems)-1]
// Trim whitespace for each item
for i := range pkgFileManifestItems {
pkgFileManifestItems[i] = strings.TrimSpace(pkgFileManifestItems[i])
}
// Sort the manifest items from the package file (they will be in a random order)
sort.Strings(pkgFileManifestItems)
// Compare the slices by converting them to strings
if strings.Join(pkgFileManifestItems[:], ",") != strings.Join(testManifestItems[:], ",") {
t.Errorf(
"Package file manifest items don't match\n"+
"Got: \n%s\n\n"+
"Expected: \n%s\n",
strings.Join(pkgFileManifestItems[:], "\n"),
strings.Join(testManifestItems[:], "\n"))
}
cleanup(testEpubFilename, tempDir)
}
func TestFilenameAlreadyUsedError(t *testing.T) {
e := NewEpub(testEpubTitle)
_, err := e.AddCSS(testCoverCSSSource, testCoverCSSFilename)
if err != nil {
t.Errorf("Error adding CSS: %s", err)
}
_, err = e.AddCSS(testCoverCSSSource, testCoverCSSFilename)
if _, ok := err.(*FilenameAlreadyUsedError); !ok {
t.Errorf("Expected error FilenameAlreadyUsedError not returned. Returned instead: %+v", err)
}
}
func TestFileRetrievalError(t *testing.T) {
e := NewEpub(testEpubTitle)
_, err := e.AddCSS("/sbin/thisShouldFail", testCoverCSSFilename)
if _, ok := err.(*FileRetrievalError); !ok {
t.Errorf("Expected error FileRetrievalError not returned. Returned instead: %+v", err)
}
}
func TestUnableToCreateEpubError(t *testing.T) {
e := NewEpub(testEpubTitle)
err := e.Write("/sbin/thisShouldFail")
if _, ok := err.(*UnableToCreateEpubError); !ok {
t.Errorf("Expected error UnableToCreateEpubError not returned. Returned instead: %+v", err)
}
}
func TestEpubValidity(t *testing.T) {
e := NewEpub(testEpubTitle)
testCoverCSSPath, _ := e.AddCSS(testCoverCSSSource, testCoverCSSFilename)
e.AddCSS(testCoverCSSSource, "")
e.AddSection(testSectionBody, testSectionTitle, testSectionFilename, testCoverCSSPath)
e.AddFont(testFontFromFileSource, "")
// Add CSS referencing the font in order to validate the font MIME type
testFontCSSPath, _ := e.AddCSS(testFontCSSSource, testFontCSSFilename)
e.AddSection(testSectionBody, testSectionTitle, "", testFontCSSPath)
testImagePath, _ := e.AddImage(testImageFromFileSource, testImageFromFileFilename)
e.AddImage(testImageFromFileSource, testImageFromFileFilename)
e.AddImage(testImageFromURLSource, "")
e.AddImage(testImageFromFileSource, testNumberFilenameStart)
e.SetAuthor(testEpubAuthor)
e.SetCover(testImagePath, "")
e.SetDescription(testEpubDescription)
e.SetIdentifier(testEpubIdentifier)
e.SetLang(testEpubLang)
e.SetPpd(testEpubPpd)
e.SetTitle(testEpubAuthor)
tempDir := writeAndExtractEpub(t, e, testEpubFilename)
output, err := validateEpub(t, testEpubFilename)
if err != nil {
t.Errorf("EPUB validation failed")
}
// Always print the output so we can see warnings as well
fmt.Println(string(output))
if doCleanup {
cleanup(testEpubFilename, tempDir)
} else {
// Always remove the files in tempDir; they can still be extracted from the test epub as needed
os.RemoveAll(tempDir)
}
}
func cleanup(epubFilename string, tempDir string) {
os.Remove(epubFilename)
os.RemoveAll(tempDir)
}
// TrimAllSpace trims all space from each line of the string and removes empty
// lines for easier comparison
func trimAllSpace(s string) string {
trimmedLines := []string{}
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line != "" {
trimmedLines = append(trimmedLines, line)
}
}
return strings.Join(trimmedLines, "\n")
}
// UnzipFile unzips a file located at sourceFilePath to the provided destination directory
func unzipFile(sourceFilePath string, destDirPath string) error {
// First, make sure the destination exists and is a directory
info, err := os.Stat(destDirPath)
if err != nil {
return err
}
if !info.Mode().IsDir() {
return errors.New("destination is not a directory")
}
r, err := zip.OpenReader(sourceFilePath)
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()
// Iterate through each file in the archive
for _, f := range r.File {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()
destFilePath := filepath.Join(destDirPath, f.Name)
// Create destination subdirectories if necessary
destBaseDirPath, _ := filepath.Split(destFilePath)
os.MkdirAll(destBaseDirPath, testDirPerm)
// Create the destination file
w, err := os.Create(destFilePath)
if err != nil {
return err
}
defer func() {
if err := w.Close(); err != nil {
panic(err)
}
}()
// Copy the contents of the source file
_, err = io.Copy(w, rc)
if err != nil {
return err
}
}
return nil
}
// This function requires EPUBCheck to work; see README.md for more information
func validateEpub(t *testing.T, epubFilename string) ([]byte, error) {
cwd, err := os.Getwd()
if err != nil {
t.Error("Error getting working directory")
}
items, err := ioutil.ReadDir(cwd)
if err != nil {
t.Error("Error getting contents of working directory")
}
pathToEpubcheck := ""
for _, i := range items {
if i.Name() == testEpubcheckJarfile {
pathToEpubcheck = i.Name()
break
} else if strings.HasPrefix(i.Name(), testEpubcheckPrefix) {
if i.Mode().IsDir() {
pathToEpubcheck = filepath.Join(i.Name(), testEpubcheckJarfile)
if _, err := os.Stat(pathToEpubcheck); err == nil {
break
} else {
pathToEpubcheck = ""
}
}
}
}
if pathToEpubcheck == "" {
fmt.Println("Epubcheck tool not installed, skipping EPUB validation.")
return []byte{}, nil
}
cmd := exec.Command("java", "-jar", pathToEpubcheck, epubFilename)
return cmd.CombinedOutput()
}
func writeAndExtractEpub(t *testing.T, e *Epub, epubFilename string) string {
tempDir, err := ioutil.TempDir("", tempDirPrefix)
if err != nil {
t.Errorf("Unexpected error creating temp dir: %s", err)
}
err = e.Write(epubFilename)
if err != nil {
t.Errorf("Unexpected error writing EPUB: %s", err)
}
err = unzipFile(epubFilename, tempDir)
if err != nil {
t.Errorf("Unexpected error extracting EPUB: %s", err)
}
return tempDir
}