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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
|
// Copyright 2015 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"fmt"
"html/template"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/spf13/cast"
"github.com/spf13/hugo/helpers"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var emptyPage = ""
const (
simplePage = "---\ntitle: Simple\n---\nSimple Page\n"
invalidFrontMatterMissing = "This is a test"
renderNoFrontmatter = "<!doctype><html><head></head><body>This is a test</body></html>"
contentWithCommentedFrontmatter = "<!--\n+++\ntitle = \"Network configuration\"\ndescription = \"Docker networking\"\nkeywords = [\"network\"]\n[menu.main]\nparent= \"smn_administrate\"\n+++\n-->\n\n# Network configuration\n\n##\nSummary"
contentWithCommentedTextFrontmatter = "<!--[metaData]>\n+++\ntitle = \"Network configuration\"\ndescription = \"Docker networking\"\nkeywords = [\"network\"]\n[menu.main]\nparent= \"smn_administrate\"\n+++\n<![end-metadata]-->\n\n# Network configuration\n\n##\nSummary"
contentWithCommentedLongFrontmatter = "<!--[metaData123456789012345678901234567890]>\n+++\ntitle = \"Network configuration\"\ndescription = \"Docker networking\"\nkeywords = [\"network\"]\n[menu.main]\nparent= \"smn_administrate\"\n+++\n<![end-metadata]-->\n\n# Network configuration\n\n##\nSummary"
contentWithCommentedLong2Frontmatter = "<!--[metaData]>\n+++\ntitle = \"Network configuration\"\ndescription = \"Docker networking\"\nkeywords = [\"network\"]\n[menu.main]\nparent= \"smn_administrate\"\n+++\n<![end-metadata123456789012345678901234567890]-->\n\n# Network configuration\n\n##\nSummary"
invalidFrontmatterShortDelim = `
--
title: Short delim start
---
Short Delim
`
invalidFrontmatterShortDelimEnding = `
---
title: Short delim ending
--
Short Delim
`
invalidFrontmatterLadingWs = `
---
title: Leading WS
---
Leading
`
simplePageJSON = `
{
"title": "spf13-vim 3.0 release and new website",
"description": "spf13-vim is a cross platform distribution of vim plugins and resources for Vim.",
"tags": [ ".vimrc", "plugins", "spf13-vim", "VIm" ],
"date": "2012-04-06",
"categories": [
"Development",
"VIM"
],
"slug": "-spf13-vim-3-0-release-and-new-website-"
}
Content of the file goes Here
`
simplePageJSONLoose = `
{
"title": "spf13-vim 3.0 release and new website"
"description": "spf13-vim is a cross platform distribution of vim plugins and resources for Vim."
"tags": [ ".vimrc", "plugins", "spf13-vim", "VIm" ]
"date": "2012-04-06"
"categories": [
"Development"
"VIM"
],
"slug": "spf13-vim-3-0-release-and-new-website"
}
Content of the file goes Here
`
simplePageRFC3339Date = "---\ntitle: RFC3339 Date\ndate: \"2013-05-17T16:59:30Z\"\n---\nrfc3339 content"
simplePageJSONMultiple = `
{
"title": "foobar",
"customData": { "foo": "bar" },
"date": "2012-08-06"
}
Some text
`
simplePageNoLayout = `---
title: simple_no_layout
---
No Layout called out`
simplePageLayoutFoobar = `---
title: simple layout foobar
layout: foobar
---
Layout foobar`
simplePageTypeFoobar = `---
type: foobar
---
type foobar`
simplePageTypeLayout = `---
type: barfoo
layout: buzfoo
---
type and layout set`
simplePageWithSummaryDelimiter = `---
title: Simple
---
Summary Next Line
<!--more-->
Some more text
`
simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder = `---
title: Simple
---
The [best static site generator][hugo].[^1]
<!--more-->
[hugo]: http://gohugo.io/
[^1]: Many people say so.
`
simplePageWithShortcodeInSummary = `---
title: Simple
---
Summary Next Line. {{<figure src="/not/real" >}}.
More text here.
Some more text
`
simplePageWithEmbeddedScript = `---
title: Simple
---
<script type='text/javascript'>alert('the script tags are still there, right?');</script>
`
simplePageWithSummaryDelimiterSameLine = `---
title: Simple
---
Summary Same Line<!--more-->
Some more text
`
simplePageWithAllCJKRunes = `---
title: Simple
---
€ € € € €
你好
도형이
カテゴリー
`
simplePageWithMainEnglishWithCJKRunes = `---
title: Simple
---
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
In Chinese, 好 means good. In Chinese, 好 means good.
More then 70 words.
`
simplePageWithMainEnglishWithCJKRunesSummary = "In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good. " +
"In Chinese, 好 means good. In Chinese, 好 means good."
simplePageWithIsCJKLanguageFalse = `---
title: Simple
isCJKLanguage: false
---
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀 means good.
In Chinese, 好的啊 means good. In Chinese, 好的呀呀 means good enough.
More then 70 words.
`
simplePageWithIsCJKLanguageFalseSummary = "In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. " +
"In Chinese, 好的啊 means good. In Chinese, 好的呀呀 means good enough."
simplePageWithLongContent = `---
title: Simple
---
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim
id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem
ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.`
pageWithToC = `---
title: TOC
---
For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke.
## AA
I have no idea, of course, how long it took me to reach the limit of the plain,
but at last I entered the foothills, following a pretty little canyon upward
toward the mountains. Beside me frolicked a laughing brooklet, hurrying upon
its noisy way down to the silent sea. In its quieter pools I discovered many
small fish, of four-or five-pound weight I should imagine. In appearance,
except as to size and color, they were not unlike the whale of our own seas. As
I watched them playing about I discovered, not only that they suckled their
young, but that at intervals they rose to the surface to breathe as well as to
feed upon certain grasses and a strange, scarlet lichen which grew upon the
rocks just above the water line.
### AAA
I remember I felt an extraordinary persuasion that I was being played with,
that presently, when I was upon the very verge of safety, this mysterious
death--as swift as the passage of light--would leap after me from the pit about
the cylinder and strike me down. ## BB
### BBB
"You're a great Granser," he cried delightedly, "always making believe them little marks mean something."
`
simplePageWithAdditionalExtension = `+++
[blackfriday]
extensions = ["hardLineBreak"]
+++
first line.
second line.
fourth line.
`
simplePageWithURL = `---
title: Simple
url: simple/url/
---
Simple Page With URL`
simplePageWithSlug = `---
title: Simple
slug: simple-slug
---
Simple Page With Slug`
simplePageWithDate = `---
title: Simple
date: '2013-10-15T06:16:13'
---
Simple Page With Date`
UTF8Page = `---
title: ラーメン
---
UTF8 Page`
UTF8PageWithURL = `---
title: ラーメン
url: ラーメン/url/
---
UTF8 Page With URL`
UTF8PageWithSlug = `---
title: ラーメン
slug: ラーメン-slug
---
UTF8 Page With Slug`
UTF8PageWithDate = `---
title: ラーメン
date: '2013-10-15T06:16:13'
---
UTF8 Page With Date`
)
var pageWithVariousFrontmatterTypes = `+++
a_string = "bar"
an_integer = 1
a_float = 1.3
a_bool = false
a_date = 1979-05-27T07:32:00Z
[a_table]
a_key = "a_value"
+++
Front Matter with various frontmatter types`
var pageWithCalendarYAMLFrontmatter = `---
type: calendar
weeks:
-
start: "Jan 5"
days:
- activity: class
room: EN1000
- activity: lab
- activity: class
- activity: lab
- activity: class
-
start: "Jan 12"
days:
- activity: class
- activity: lab
- activity: class
- activity: lab
- activity: exam
---
Hi.
`
var pageWithCalendarJSONFrontmatter = `{
"type": "calendar",
"weeks": [
{
"start": "Jan 5",
"days": [
{ "activity": "class", "room": "EN1000" },
{ "activity": "lab" },
{ "activity": "class" },
{ "activity": "lab" },
{ "activity": "class" }
]
},
{
"start": "Jan 12",
"days": [
{ "activity": "class" },
{ "activity": "lab" },
{ "activity": "class" },
{ "activity": "lab" },
{ "activity": "exam" }
]
}
]
}
Hi.
`
var pageWithCalendarTOMLFrontmatter = `+++
type = "calendar"
[[weeks]]
start = "Jan 5"
[[weeks.days]]
activity = "class"
room = "EN1000"
[[weeks.days]]
activity = "lab"
[[weeks.days]]
activity = "class"
[[weeks.days]]
activity = "lab"
[[weeks.days]]
activity = "class"
[[weeks]]
start = "Jan 12"
[[weeks.days]]
activity = "class"
[[weeks.days]]
activity = "lab"
[[weeks.days]]
activity = "class"
[[weeks.days]]
activity = "lab"
[[weeks.days]]
activity = "exam"
+++
Hi.
`
func checkError(t *testing.T, err error, expected string) {
if err == nil {
t.Fatalf("err is nil. Expected: %s", expected)
}
if err.Error() != expected {
t.Errorf("err.Error() returned: '%s'. Expected: '%s'", err.Error(), expected)
}
}
func TestDegenerateEmptyPageZeroLengthName(t *testing.T) {
_, err := NewPage("")
if err == nil {
t.Fatalf("A zero length page name must return an error")
}
checkError(t, err, "Zero length page name")
}
func TestDegenerateEmptyPage(t *testing.T) {
_, err := NewPageFrom(strings.NewReader(emptyPage), "test")
if err != nil {
t.Fatalf("Empty files should not trigger an error. Should be able to touch a file while watching without erroring out.")
}
}
func checkPageTitle(t *testing.T, page *Page, title string) {
if page.Title != title {
t.Fatalf("Page title is: %s. Expected %s", page.Title, title)
}
}
func checkPageContent(t *testing.T, page *Page, content string, msg ...interface{}) {
a := normalizeContent(content)
b := normalizeContent(string(page.Content))
if a != b {
t.Fatalf("Page content is:\n%q\nExpected:\n%q (%q)", b, a, msg)
}
}
func normalizeContent(c string) string {
norm := c
norm = strings.Replace(norm, "\n", " ", -1)
norm = strings.Replace(norm, " ", " ", -1)
norm = strings.Replace(norm, " ", " ", -1)
norm = strings.Replace(norm, " ", " ", -1)
norm = strings.Replace(norm, "p> ", "p>", -1)
norm = strings.Replace(norm, "> <", "> <", -1)
return strings.TrimSpace(norm)
}
func checkPageTOC(t *testing.T, page *Page, toc string) {
if page.TableOfContents != template.HTML(toc) {
t.Fatalf("Page TableOfContents is: %q.\nExpected %q", page.TableOfContents, toc)
}
}
func checkPageSummary(t *testing.T, page *Page, summary string, msg ...interface{}) {
a := normalizeContent(string(page.Summary))
b := normalizeContent(summary)
if a != b {
t.Fatalf("Page summary is:\n%q.\nExpected\n%q (%q)", a, b, msg)
}
}
func checkPageType(t *testing.T, page *Page, pageType string) {
if page.Type() != pageType {
t.Fatalf("Page type is: %s. Expected: %s", page.Type(), pageType)
}
}
func checkPageLayout(t *testing.T, page *Page, layout ...string) {
if !listEqual(page.layouts(), layout) {
t.Fatalf("Page layout is: %s. Expected: %s", page.layouts(), layout)
}
}
func checkPageDate(t *testing.T, page *Page, time time.Time) {
if page.Date != time {
t.Fatalf("Page date is: %s. Expected: %s", page.Date, time)
}
}
func checkTruncation(t *testing.T, page *Page, shouldBe bool, msg string) {
if page.Summary == "" {
t.Fatal("page has no summary, can not check truncation")
}
if page.Truncated != shouldBe {
if shouldBe {
t.Fatalf("page wasn't truncated: %s", msg)
} else {
t.Fatalf("page was truncated: %s", msg)
}
}
}
func normalizeExpected(ext, str string) string {
str = normalizeContent(str)
switch ext {
default:
return str
case "html":
return strings.Trim(helpers.StripHTML(str), " ")
case "ad":
paragraphs := strings.Split(str, "</p>")
expected := ""
for _, para := range paragraphs {
if para == "" {
continue
}
expected += fmt.Sprintf("<div class=\"paragraph\">\n%s</p></div>\n", para)
}
return expected
case "rst":
return fmt.Sprintf("<div class=\"document\">\n\n\n%s</div>", str)
}
}
func testAllMarkdownEnginesForPages(t *testing.T,
assertFunc func(t *testing.T, ext string, pages Pages), pageSources ...string) {
engines := []struct {
ext string
shouldExecute func() bool
}{
{"md", func() bool { return true }},
{"mmark", func() bool { return true }},
{"ad", func() bool { return helpers.HasAsciidoc() }},
// TODO(bep) figure a way to include this without too much work.{"html", func() bool { return true }},
{"rst", func() bool { return helpers.HasRst() }},
}
for _, e := range engines {
if !e.shouldExecute() {
continue
}
var fileSourcePair []string
for i, source := range pageSources {
fileSourcePair = append(fileSourcePair, fmt.Sprintf("p%d.%s", i, e.ext), source)
}
s := newSiteFromSources(fileSourcePair...)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, len(pageSources))
assertFunc(t, e.ext, s.Pages)
}
}
func TestCreateNewPage(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
assert.False(t, p.IsHome)
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "<p>Simple Page</p>\n"))
checkPageSummary(t, p, "Simple Page")
checkPageType(t, p, "page")
checkPageLayout(t, p, "page/single.html", "_default/single.html", "theme/page/single.html", "theme/_default/single.html")
checkTruncation(t, p, false, "simple short page")
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePage)
}
func TestSplitSummaryAndContent(t *testing.T) {
for i, this := range []struct {
markup string
content string
expectedSummary string
expectedContent string
expectedContentWithoutSummary string
}{
{"markdown", `<p>Summary Same LineHUGOMORE42</p>
<p>Some more text</p>`, "<p>Summary Same Line</p>", "<p>Summary Same Line</p>\n\n<p>Some more text</p>", "<p>Some more text</p>"},
{"asciidoc", `<div class="paragraph"><p>sn</p></div><div class="paragraph"><p>HUGOMORE42Some more text</p></div>`,
"<div class=\"paragraph\"><p>sn</p></div>",
"<div class=\"paragraph\"><p>sn</p></div><div class=\"paragraph\"><p>Some more text</p></div>",
"<div class=\"paragraph\"><p>Some more text</p></div>"},
{"rst",
"<div class=\"document\"><p>Summary Next Line</p><p>HUGOMORE42Some more text</p></div>",
"<div class=\"document\"><p>Summary Next Line</p></div>",
"<div class=\"document\"><p>Summary Next Line</p><p>Some more text</p></div>",
"<div class=\"document\"><p>Some more text</p></div>"},
{"markdown", "<p>a</p><p>b</p><p>HUGOMORE42c</p>", "<p>a</p><p>b</p>", "<p>a</p><p>b</p><p>c</p>", "<p>c</p>"},
{"markdown", "<p>a</p><p>b</p><p>cHUGOMORE42</p>", "<p>a</p><p>b</p><p>c</p>", "<p>a</p><p>b</p><p>c</p>", ""},
{"markdown", "<p>a</p><p>bHUGOMORE42</p><p>c</p>", "<p>a</p><p>b</p>", "<p>a</p><p>b</p><p>c</p>", "<p>c</p>"},
{"markdown", "<p>aHUGOMORE42</p><p>b</p><p>c</p>", "<p>a</p>", "<p>a</p><p>b</p><p>c</p>", "<p>b</p><p>c</p>"},
{"markdown", " HUGOMORE42 ", "", "", ""},
{"markdown", "HUGOMORE42", "", "", ""},
{"markdown", "<p>HUGOMORE42", "<p>", "<p>", ""},
{"markdown", "HUGOMORE42<p>", "", "<p>", "<p>"},
{"markdown", "\n\n<p>HUGOMORE42</p>\n", "<p></p>", "<p></p>", ""},
// Issue #2586
// Note: Hugo will not split mid-sentence but will look for the closest
// paragraph end marker. This may be a change from Hugo 0.16, but it makes sense.
{"markdown", `<p>this is an example HUGOMORE42of the issue.</p>`,
"<p>this is an example of the issue.</p>",
"<p>this is an example of the issue.</p>", ""},
// Issue: #2538
{"markdown", fmt.Sprintf(` <p class="lead">%s</p>HUGOMORE42<p>%s</p>
`,
strings.Repeat("A", 10), strings.Repeat("B", 31)),
fmt.Sprintf(`<p class="lead">%s</p>`, strings.Repeat("A", 10)),
fmt.Sprintf(`<p class="lead">%s</p><p>%s</p>`, strings.Repeat("A", 10), strings.Repeat("B", 31)),
fmt.Sprintf(`<p>%s</p>`, strings.Repeat("B", 31)),
},
} {
sc, err := splitUserDefinedSummaryAndContent(this.markup, []byte(this.content))
require.NoError(t, err)
require.NotNil(t, sc, fmt.Sprintf("[%d] Nil %s", i, this.markup))
require.Equal(t, this.expectedSummary, string(sc.summary), fmt.Sprintf("[%d] Summary markup %s", i, this.markup))
require.Equal(t, this.expectedContent, string(sc.content), fmt.Sprintf("[%d] Content markup %s", i, this.markup))
require.Equal(t, this.expectedContentWithoutSummary, string(sc.contentWithoutSummary), fmt.Sprintf("[%d] Content without summary, markup %s", i, this.markup))
}
}
func TestPageWithDelimiter(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Next Line</p>\n\n<p>Some more text</p>\n"), ext)
checkPageSummary(t, p, normalizeExpected(ext, "<p>Summary Next Line</p>"), ext)
checkPageType(t, p, "page")
checkPageLayout(t, p, "page/single.html", "_default/single.html", "theme/page/single.html", "theme/_default/single.html")
checkTruncation(t, p, true, "page with summary delimiter")
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithSummaryDelimiter)
}
// Issue #1076
func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) {
s := newSiteFromSources("simple.md", simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, 1)
p := s.Pages[0]
if p.Summary != template.HTML("<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup class=\"footnote-ref\" id=\"fnref:1\"><a rel=\"footnote\" href=\"#fn:1\">1</a></sup>\n</p>") {
t.Fatalf("Got summary:\n%q", p.Summary)
}
if p.Content != template.HTML("<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup class=\"footnote-ref\" id=\"fnref:1\"><a rel=\"footnote\" href=\"#fn:1\">1</a></sup>\n</p>\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:1\">Many people say so.\n <a class=\"footnote-return\" href=\"#fnref:1\"><sup>[return]</sup></a></li>\n</ol>\n</div>") {
t.Fatalf("Got content:\n%q", p.Content)
}
}
func TestPageWithShortCodeInSummary(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Next Line. \n<figure >\n \n <img src=\"/not/real\" />\n \n \n</figure>\n.\nMore text here.</p>\n\n<p>Some more text</p>\n"))
checkPageSummary(t, p, "Summary Next Line. . More text here. Some more text")
checkPageType(t, p, "page")
checkPageLayout(t, p, "page/single.html", "_default/single.html", "theme/page/single.html", "theme/_default/single.html")
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithShortcodeInSummary)
}
func TestPageWithEmbeddedScriptTag(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if ext == "ad" || ext == "rst" {
// TOD(bep)
return
}
checkPageContent(t, p, "<script type='text/javascript'>alert('the script tags are still there, right?');</script>\n", ext)
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithEmbeddedScript)
}
func TestPageWithAdditionalExtension(t *testing.T) {
s := newSiteFromSources("simple.md", simplePageWithAdditionalExtension)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, 1)
p := s.Pages[0]
checkPageContent(t, p, "<p>first line.<br />\nsecond line.</p>\n\n<p>fourth line.</p>\n")
}
func TestTableOfContents(t *testing.T) {
s := newSiteFromSources("tocpage.md", pageWithToC)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, 1)
p := s.Pages[0]
checkPageContent(t, p, "\n\n<p>For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke.</p>\n\n<h2 id=\"aa\">AA</h2>\n\n<p>I have no idea, of course, how long it took me to reach the limit of the plain,\nbut at last I entered the foothills, following a pretty little canyon upward\ntoward the mountains. Beside me frolicked a laughing brooklet, hurrying upon\nits noisy way down to the silent sea. In its quieter pools I discovered many\nsmall fish, of four-or five-pound weight I should imagine. In appearance,\nexcept as to size and color, they were not unlike the whale of our own seas. As\nI watched them playing about I discovered, not only that they suckled their\nyoung, but that at intervals they rose to the surface to breathe as well as to\nfeed upon certain grasses and a strange, scarlet lichen which grew upon the\nrocks just above the water line.</p>\n\n<h3 id=\"aaa\">AAA</h3>\n\n<p>I remember I felt an extraordinary persuasion that I was being played with,\nthat presently, when I was upon the very verge of safety, this mysterious\ndeath–as swift as the passage of light–would leap after me from the pit about\nthe cylinder and strike me down. ## BB</p>\n\n<h3 id=\"bbb\">BBB</h3>\n\n<p>“You’re a great Granser,” he cried delightedly, “always making believe them little marks mean something.”</p>\n")
checkPageTOC(t, p, "<nav id=\"TableOfContents\">\n<ul>\n<li>\n<ul>\n<li><a href=\"#aa\">AA</a>\n<ul>\n<li><a href=\"#aaa\">AAA</a></li>\n<li><a href=\"#bbb\">BBB</a></li>\n</ul></li>\n</ul></li>\n</ul>\n</nav>")
}
func TestPageWithMoreTag(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>\n\n<p>Some more text</p>\n"))
checkPageSummary(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>"))
checkPageType(t, p, "page")
checkPageLayout(t, p, "page/single.html", "_default/single.html", "theme/page/single.html", "theme/_default/single.html")
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithSummaryDelimiterSameLine)
}
func TestPageWithDate(t *testing.T) {
s := newSiteFromSources("simple.md", simplePageRFC3339Date)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, 1)
p := s.Pages[0]
d, _ := time.Parse(time.RFC3339, "2013-05-17T16:59:30Z")
checkPageDate(t, p, d)
}
func TestWordCountWithAllCJKRunesWithoutHasCJKLanguage(t *testing.T) {
testCommonResetState()
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if p.WordCount() != 8 {
t.Fatalf("[%s] incorrect word count for content '%s'. expected %v, got %v", ext, p.plain, 8, p.WordCount())
}
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithAllCJKRunes)
}
func TestWordCountWithAllCJKRunesHasCJKLanguage(t *testing.T) {
testCommonResetState()
viper.Set("hasCJKLanguage", true)
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if p.WordCount() != 15 {
t.Fatalf("[%s] incorrect word count for content '%s'. expected %v, got %v", ext, p.plain, 15, p.WordCount())
}
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithAllCJKRunes)
}
func TestWordCountWithMainEnglishWithCJKRunes(t *testing.T) {
testCommonResetState()
viper.Set("hasCJKLanguage", true)
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if p.WordCount() != 74 {
t.Fatalf("[%s] incorrect word count for content '%s'. expected %v, got %v", ext, p.plain, 74, p.WordCount())
}
if p.Summary != simplePageWithMainEnglishWithCJKRunesSummary {
t.Fatalf("[%s] incorrect Summary for content '%s'. expected %v, got %v", ext, p.plain,
simplePageWithMainEnglishWithCJKRunesSummary, p.Summary)
}
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithMainEnglishWithCJKRunes)
}
func TestWordCountWithIsCJKLanguageFalse(t *testing.T) {
testCommonResetState()
viper.Set("hasCJKLanguage", true)
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if p.WordCount() != 75 {
t.Fatalf("[%s] incorrect word count for content '%s'. expected %v, got %v", ext, p.plain, 74, p.WordCount())
}
if p.Summary != simplePageWithIsCJKLanguageFalseSummary {
t.Fatalf("[%s] incorrect Summary for content '%s'. expected %v, got %v", ext, p.plain,
simplePageWithIsCJKLanguageFalseSummary, p.Summary)
}
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithIsCJKLanguageFalse)
}
func TestWordCount(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages Pages) {
p := pages[0]
if p.WordCount() != 483 {
t.Fatalf("[%s] incorrect word count. expected %v, got %v", ext, 483, p.WordCount())
}
if p.FuzzyWordCount() != 500 {
t.Fatalf("[%s] incorrect word count. expected %v, got %v", ext, 500, p.WordCount())
}
if p.ReadingTime() != 3 {
t.Fatalf("[%s] incorrect min read. expected %v, got %v", ext, 3, p.ReadingTime())
}
checkTruncation(t, p, true, "long page")
}
testAllMarkdownEnginesForPages(t, assertFunc, simplePageWithLongContent)
}
func TestCreatePage(t *testing.T) {
var tests = []struct {
r string
}{
{simplePageJSON},
{simplePageJSONLoose},
{simplePageJSONMultiple},
//{strings.NewReader(SIMPLE_PAGE_JSON_COMPACT)},
}
for _, test := range tests {
p, _ := NewPage("page")
if _, err := p.ReadFrom(strings.NewReader(test.r)); err != nil {
t.Errorf("Unable to parse page: %s", err)
}
}
}
func TestDegenerateInvalidFrontMatterShortDelim(t *testing.T) {
var tests = []struct {
r string
err string
}{
{invalidFrontmatterShortDelimEnding, "unable to read frontmatter at filepos 45: EOF"},
}
for _, test := range tests {
p, _ := NewPage("invalid/front/matter/short/delim")
_, err := p.ReadFrom(strings.NewReader(test.r))
checkError(t, err, test.err)
}
}
func TestShouldRenderContent(t *testing.T) {
var tests = []struct {
text string
render bool
}{
{invalidFrontMatterMissing, true},
// TODO how to deal with malformed frontmatter. In this case it'll be rendered as markdown.
{invalidFrontmatterShortDelim, true},
{renderNoFrontmatter, false},
{contentWithCommentedFrontmatter, true},
{contentWithCommentedTextFrontmatter, true},
{contentWithCommentedLongFrontmatter, false},
{contentWithCommentedLong2Frontmatter, true},
}
for _, test := range tests {
p, _ := NewPage("render/front/matter")
_, err := p.ReadFrom(strings.NewReader(test.text))
p = pageMust(p, err)
if p.IsRenderable() != test.render {
t.Errorf("expected p.IsRenderable() == %t, got %t", test.render, p.IsRenderable())
}
}
}
// Issue #768
func TestCalendarParamsVariants(t *testing.T) {
pageJSON, _ := NewPage("test/fileJSON.md")
_, _ = pageJSON.ReadFrom(strings.NewReader(pageWithCalendarJSONFrontmatter))
pageYAML, _ := NewPage("test/fileYAML.md")
_, _ = pageYAML.ReadFrom(strings.NewReader(pageWithCalendarYAMLFrontmatter))
pageTOML, _ := NewPage("test/fileTOML.md")
_, _ = pageTOML.ReadFrom(strings.NewReader(pageWithCalendarTOMLFrontmatter))
assert.True(t, compareObjects(pageJSON.Params, pageYAML.Params))
assert.True(t, compareObjects(pageJSON.Params, pageTOML.Params))
}
func TestDifferentFrontMatterVarTypes(t *testing.T) {
page, _ := NewPage("test/file1.md")
_, _ = page.ReadFrom(strings.NewReader(pageWithVariousFrontmatterTypes))
dateval, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
if page.GetParam("a_string") != "bar" {
t.Errorf("frontmatter not handling strings correctly should be %s, got: %s", "bar", page.GetParam("a_string"))
}
if page.GetParam("an_integer") != 1 {
t.Errorf("frontmatter not handling ints correctly should be %s, got: %s", "1", page.GetParam("an_integer"))
}
if page.GetParam("a_float") != 1.3 {
t.Errorf("frontmatter not handling floats correctly should be %f, got: %s", 1.3, page.GetParam("a_float"))
}
if page.GetParam("a_bool") != false {
t.Errorf("frontmatter not handling bools correctly should be %t, got: %s", false, page.GetParam("a_bool"))
}
if page.GetParam("a_date") != dateval {
t.Errorf("frontmatter not handling dates correctly should be %s, got: %s", dateval, page.GetParam("a_date"))
}
param := page.GetParam("a_table")
if param == nil {
t.Errorf("frontmatter not handling tables correctly should be type of %v, got: type of %v", reflect.TypeOf(page.Params["a_table"]), reflect.TypeOf(param))
}
if cast.ToStringMap(param)["a_key"] != "a_value" {
t.Errorf("frontmatter not handling values inside a table correctly should be %s, got: %s", "a_value", cast.ToStringMap(page.Params["a_table"])["a_key"])
}
}
func TestDegenerateInvalidFrontMatterLeadingWhitespace(t *testing.T) {
p, _ := NewPage("invalid/front/matter/leading/ws")
_, err := p.ReadFrom(strings.NewReader(invalidFrontmatterLadingWs))
if err != nil {
t.Fatalf("Unable to parse front matter given leading whitespace: %s", err)
}
}
func TestSectionEvaluation(t *testing.T) {
page, _ := NewPage(filepath.FromSlash("blue/file1.md"))
page.ReadFrom(strings.NewReader(simplePage))
if page.Section() != "blue" {
t.Errorf("Section should be %s, got: %s", "blue", page.Section())
}
}
func L(s ...string) []string {
return s
}
func TestLayoutOverride(t *testing.T) {
var (
pathContentTwoDir = filepath.Join("content", "dub", "sub", "file1.md")
pathContentOneDir = filepath.Join("content", "gub", "file1.md")
pathContentNoDir = filepath.Join("content", "file1")
pathOneDirectory = filepath.Join("fub", "file1.md")
pathNoDirectory = filepath.Join("file1.md")
)
tests := []struct {
content string
path string
expectedLayout []string
}{
{simplePageNoLayout, pathContentTwoDir, L("dub/single.html", "_default/single.html")},
{simplePageNoLayout, pathContentOneDir, L("gub/single.html", "_default/single.html")},
{simplePageNoLayout, pathContentNoDir, L("page/single.html", "_default/single.html")},
{simplePageNoLayout, pathOneDirectory, L("fub/single.html", "_default/single.html")},
{simplePageNoLayout, pathNoDirectory, L("page/single.html", "_default/single.html")},
{simplePageLayoutFoobar, pathContentTwoDir, L("dub/foobar.html", "_default/foobar.html")},
{simplePageLayoutFoobar, pathContentOneDir, L("gub/foobar.html", "_default/foobar.html")},
{simplePageLayoutFoobar, pathOneDirectory, L("fub/foobar.html", "_default/foobar.html")},
{simplePageLayoutFoobar, pathNoDirectory, L("page/foobar.html", "_default/foobar.html")},
{simplePageTypeFoobar, pathContentTwoDir, L("foobar/single.html", "_default/single.html")},
{simplePageTypeFoobar, pathContentOneDir, L("foobar/single.html", "_default/single.html")},
{simplePageTypeFoobar, pathContentNoDir, L("foobar/single.html", "_default/single.html")},
{simplePageTypeFoobar, pathOneDirectory, L("foobar/single.html", "_default/single.html")},
{simplePageTypeFoobar, pathNoDirectory, L("foobar/single.html", "_default/single.html")},
{simplePageTypeLayout, pathContentTwoDir, L("barfoo/buzfoo.html", "_default/buzfoo.html")},
{simplePageTypeLayout, pathContentOneDir, L("barfoo/buzfoo.html", "_default/buzfoo.html")},
{simplePageTypeLayout, pathContentNoDir, L("barfoo/buzfoo.html", "_default/buzfoo.html")},
{simplePageTypeLayout, pathOneDirectory, L("barfoo/buzfoo.html", "_default/buzfoo.html")},
{simplePageTypeLayout, pathNoDirectory, L("barfoo/buzfoo.html", "_default/buzfoo.html")},
}
for _, test := range tests {
p, _ := NewPage(test.path)
_, err := p.ReadFrom(strings.NewReader(test.content))
if err != nil {
t.Fatalf("Unable to parse content:\n%s\n", test.content)
}
for _, y := range test.expectedLayout {
test.expectedLayout = append(test.expectedLayout, "theme/"+y)
}
if !listEqual(p.layouts(), test.expectedLayout) {
t.Errorf("Layout mismatch. Expected: %s, got: %s", test.expectedLayout, p.layouts())
}
}
}
func TestSliceToLower(t *testing.T) {
tests := []struct {
value []string
expected []string
}{
{[]string{"a", "b", "c"}, []string{"a", "b", "c"}},
{[]string{"a", "B", "c"}, []string{"a", "b", "c"}},
{[]string{"A", "B", "C"}, []string{"a", "b", "c"}},
}
for _, test := range tests {
res := helpers.SliceToLower(test.value)
for i, val := range res {
if val != test.expected[i] {
t.Errorf("Case mismatch. Expected %s, got %s", test.expected[i], res[i])
}
}
}
}
func TestPagePaths(t *testing.T) {
testCommonResetState()
viper.Set("defaultExtension", "html")
siteParmalinksSetting := PermalinkOverrides{
"post": ":year/:month/:day/:title/",
}
tests := []struct {
content string
path string
hasPermalink bool
expected string
}{
{simplePage, "content/post/x.md", false, "content/post/x.html"},
{simplePageWithURL, "content/post/x.md", false, "simple/url/index.html"},
{simplePageWithSlug, "content/post/x.md", false, "content/post/simple-slug.html"},
{simplePageWithDate, "content/post/x.md", true, "2013/10/15/simple/index.html"},
{UTF8Page, "content/post/x.md", false, "content/post/x.html"},
{UTF8PageWithURL, "content/post/x.md", false, "ラーメン/url/index.html"},
{UTF8PageWithSlug, "content/post/x.md", false, "content/post/ラーメン-slug.html"},
{UTF8PageWithDate, "content/post/x.md", true, "2013/10/15/ラーメン/index.html"},
}
for _, test := range tests {
p, _ := NewPageFrom(strings.NewReader(test.content), filepath.FromSlash(test.path))
info := newSiteInfo(siteBuilderCfg{language: helpers.NewDefaultLanguage()})
p.Node.Site = &info
if test.hasPermalink {
p.Node.Site.Permalinks = siteParmalinksSetting
}
expectedTargetPath := filepath.FromSlash(test.expected)
expectedFullFilePath := filepath.FromSlash(test.path)
if p.TargetPath() != expectedTargetPath {
t.Errorf("%s => TargetPath expected: '%s', got: '%s'", test.content, expectedTargetPath, p.TargetPath())
}
if p.FullFilePath() != expectedFullFilePath {
t.Errorf("%s => FullFilePath expected: '%s', got: '%s'", test.content, expectedFullFilePath, p.FullFilePath())
}
}
}
var pageWithDraftAndPublished = `---
title: broken
published: false
draft: true
---
some content
`
func TestDraftAndPublishedFrontMatterError(t *testing.T) {
_, err := NewPageFrom(strings.NewReader(pageWithDraftAndPublished), "content/post/broken.md")
if err != ErrHasDraftAndPublished {
t.Errorf("expected ErrHasDraftAndPublished, was %#v", err)
}
}
var pagesWithPublishedFalse = `---
title: okay
published: false
---
some content
`
var pageWithPublishedTrue = `---
title: okay
published: true
---
some content
`
func TestPublishedFrontMatter(t *testing.T) {
p, err := NewPageFrom(strings.NewReader(pagesWithPublishedFalse), "content/post/broken.md")
if err != nil {
t.Fatalf("err during parse: %s", err)
}
if !p.Draft {
t.Errorf("expected true, got %t", p.Draft)
}
p, err = NewPageFrom(strings.NewReader(pageWithPublishedTrue), "content/post/broken.md")
if err != nil {
t.Fatalf("err during parse: %s", err)
}
if p.Draft {
t.Errorf("expected false, got %t", p.Draft)
}
}
var pagesDraftTemplate = []string{`---
title: "okay"
draft: %t
---
some content
`,
`+++
title = "okay"
draft = %t
+++
some content
`,
}
func TestDraft(t *testing.T) {
for _, draft := range []bool{true, false} {
for i, templ := range pagesDraftTemplate {
pageContent := fmt.Sprintf(templ, draft)
p, err := NewPageFrom(strings.NewReader(pageContent), "content/post/broken.md")
if err != nil {
t.Fatalf("err during parse: %s", err)
}
if p.Draft != draft {
t.Errorf("[%d] expected %t, got %t", i, draft, p.Draft)
}
}
}
}
func TestPageSimpleMethods(t *testing.T) {
for i, this := range []struct {
assertFunc func(p *Page) bool
}{
{func(p *Page) bool { return !p.IsNode() }},
{func(p *Page) bool { return p.IsPage() }},
{func(p *Page) bool { return p.Plain() == "Do Be Do Be Do" }},
{func(p *Page) bool { return strings.Join(p.PlainWords(), " ") == "Do Be Do Be Do" }},
} {
p, _ := NewPage("Test")
p.Content = "<h1>Do Be Do Be Do</h1>"
if !this.assertFunc(p) {
t.Errorf("[%d] Page method error", i)
}
}
}
func TestChompBOM(t *testing.T) {
const utf8BOM = "\xef\xbb\xbf"
s := newSiteFromSources("simple.md", utf8BOM+simplePage)
if err := buildSiteSkipRender(s); err != nil {
t.Fatalf("Failed to build site: %s", err)
}
require.Len(t, s.Pages, 1)
p := s.Pages[0]
checkPageTitle(t, p, "Simple")
}
func listEqual(left, right []string) bool {
if len(left) != len(right) {
return false
}
for i := range left {
if left[i] != right[i] {
return false
}
}
return true
}
// TODO(bep) this may be useful for other tests.
func compareObjects(a interface{}, b interface{}) bool {
aStr := strings.Split(fmt.Sprintf("%v", a), "")
sort.Strings(aStr)
bStr := strings.Split(fmt.Sprintf("%v", b), "")
sort.Strings(bStr)
return strings.Join(aStr, "") == strings.Join(bStr, "")
}
func TestShouldBuild(t *testing.T) {
var past = time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
var future = time.Date(2037, 11, 17, 20, 34, 58, 651387237, time.UTC)
var zero = time.Time{}
var publishSettings = []struct {
buildFuture bool
buildExpired bool
buildDrafts bool
draft bool
publishDate time.Time
expiryDate time.Time
out bool
}{
// publishDate and expiryDate
{false, false, false, false, zero, zero, true},
{false, false, false, false, zero, future, true},
{false, false, false, false, past, zero, true},
{false, false, false, false, past, future, true},
{false, false, false, false, past, past, false},
{false, false, false, false, future, future, false},
{false, false, false, false, future, past, false},
// buildFuture and buildExpired
{false, true, false, false, past, past, true},
{true, true, false, false, past, past, true},
{true, false, false, false, past, past, false},
{true, false, false, false, future, future, true},
{true, true, false, false, future, future, true},
{false, true, false, false, future, past, false},
// buildDrafts and draft
{true, true, false, true, past, future, false},
{true, true, true, true, past, future, true},
{true, true, true, true, past, future, true},
}
for _, ps := range publishSettings {
s := shouldBuild(ps.buildFuture, ps.buildExpired, ps.buildDrafts, ps.draft,
ps.publishDate, ps.expiryDate)
if s != ps.out {
t.Errorf("AssertShouldBuild unexpected output with params: %+v", ps)
}
}
}
|