// Copyright 2019 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"
"os"
"github.com/gohugoio/hugo/markup/rst"
"github.com/gohugoio/hugo/markup/asciidoc"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/common/loggers"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/resource"
"github.com/spf13/afero"
"github.com/spf13/viper"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers"
)
const (
homePage = "---\ntitle: Home\n---\nHome Page Content\n"
simplePage = "---\ntitle: Simple\n---\nSimple Page\n"
simplePageRFC3339Date = "---\ntitle: RFC3339 Date\ndate: \"2013-05-17T16:59:30Z\"\n---\nrfc3339 content"
simplePageWithoutSummaryDelimiter = `---
title: SimpleWithoutSummaryDelimiter
---
[Lorem ipsum](https://lipsum.com/) dolor sit amet, consectetur adipiscing 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.
Additional text.
Further text.
`
simplePageWithSummaryDelimiter = `---
title: Simple
---
Summary Next Line
Some more text
`
simplePageWithSummaryParameter = `---
title: SimpleWithSummaryParameter
summary: "Page with summary parameter and [a link](http://www.example.com/)"
---
Some text.
Some more text.
`
simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder = `---
title: Simple
---
The [best static site generator][hugo].[^1]
[hugo]: http://gohugo.io/
[^1]: Many people say so.
`
simplePageWithShortcodeInSummary = `---
title: Simple
---
Summary Next Line. {{
")
expected := ""
for _, para := range paragraphs {
if para == "" {
continue
}
expected += fmt.Sprintf("
\n%s
\n", para)
}
return expected
case "rst":
return fmt.Sprintf("
\n\n\n%s
", str)
}
}
func testAllMarkdownEnginesForPages(t *testing.T,
assertFunc func(t *testing.T, ext string, pages page.Pages), settings map[string]interface{}, pageSources ...string) {
engines := []struct {
ext string
shouldExecute func() bool
}{
{"md", func() bool { return true }},
{"mmark", func() bool { return true }},
{"ad", func() bool { return asciidoc.Supports() }},
{"rst", func() bool { return rst.Supports() }},
}
for _, e := range engines {
if !e.shouldExecute() {
continue
}
cfg, fs := newTestCfg(func(cfg config.Provider) error {
for k, v := range settings {
cfg.Set(k, v)
}
return nil
})
contentDir := "content"
if s := cfg.GetString("contentDir"); s != "" {
contentDir = s
}
var fileSourcePairs []string
for i, source := range pageSources {
fileSourcePairs = append(fileSourcePairs, fmt.Sprintf("p%d.%s", i, e.ext), source)
}
for i := 0; i < len(fileSourcePairs); i += 2 {
writeSource(t, fs, filepath.Join(contentDir, fileSourcePairs[i]), fileSourcePairs[i+1])
}
// Add a content page for the home page
homePath := fmt.Sprintf("_index.%s", e.ext)
writeSource(t, fs, filepath.Join(contentDir, homePath), homePage)
b := newTestSitesBuilderFromDepsCfg(t, deps.DepsCfg{Fs: fs, Cfg: cfg}).WithNothingAdded()
b.Build(BuildCfg{SkipRender: true})
s := b.H.Sites[0]
b.Assert(len(s.RegularPages()), qt.Equals, len(pageSources))
assertFunc(t, e.ext, s.RegularPages())
home, err := s.Info.Home()
b.Assert(err, qt.IsNil)
b.Assert(home, qt.Not(qt.IsNil))
b.Assert(home.File().Path(), qt.Equals, homePath)
b.Assert(content(home), qt.Contains, "Home Page Content")
}
}
// Issue #1076
func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) {
t.Parallel()
cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
if p.Summary() != template.HTML(
"
\n\n" {
t.Fatalf("Got content:\n%q", cnt)
}
}
func TestPageDatesAllKinds(t *testing.T) {
t.Parallel()
pageContent := `
---
title: Page
date: 2017-01-15
tags: ["hugo"]
categories: ["cool stuff"]
---
`
b := newTestSitesBuilder(t)
b.WithSimpleConfigFile().WithContent("page.md", pageContent)
b.WithContent("blog/page.md", pageContent)
b.CreateSites().Build(BuildCfg{})
b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0]
checkDate := func(t time.Time, msg string) {
b.Assert(t.Year(), qt.Equals, 2017)
}
checkDated := func(d resource.Dated, msg string) {
checkDate(d.Date(), "date: "+msg)
checkDate(d.Lastmod(), "lastmod: "+msg)
}
for _, p := range s.Pages() {
checkDated(p, p.Kind())
}
checkDate(s.Info.LastChange(), "site")
}
func TestPageDatesSections(t *testing.T) {
t.Parallel()
b := newTestSitesBuilder(t)
b.WithSimpleConfigFile().WithContent("no-index/page.md", `
---
title: Page
date: 2017-01-15
---
`)
b.WithSimpleConfigFile().WithContent("with-index-no-date/_index.md", `---
title: No Date
---
`)
// https://github.com/gohugoio/hugo/issues/5854
b.WithSimpleConfigFile().WithContent("with-index-date/_index.md", `---
title: Date
date: 2018-01-15
---
`)
b.CreateSites().Build(BuildCfg{})
b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0]
b.Assert(s.getPage("/").Date().Year(), qt.Equals, 2017)
b.Assert(s.getPage("/no-index").Date().Year(), qt.Equals, 2017)
b.Assert(s.getPage("/with-index-no-date").Date().IsZero(), qt.Equals, true)
b.Assert(s.getPage("/with-index-date").Date().Year(), qt.Equals, 2018)
}
func TestCreateNewPage(t *testing.T) {
t.Parallel()
c := qt.New(t)
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
// issue #2290: Path is relative to the content dir and will continue to be so.
c.Assert(p.File().Path(), qt.Equals, fmt.Sprintf("p0.%s", ext))
c.Assert(p.IsHome(), qt.Equals, false)
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "
Simple Page
\n"))
checkPageSummary(t, p, "Simple Page")
checkPageType(t, p, "page")
}
settings := map[string]interface{}{
"contentDir": "mycontent",
}
testAllMarkdownEnginesForPages(t, assertFunc, settings, simplePage)
}
func TestPageSummary(t *testing.T) {
t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
checkPageTitle(t, p, "SimpleWithoutSummaryDelimiter")
// Source is not Asciidoctor- or RST-compatible so don't test them
if ext != "ad" && ext != "rst" {
checkPageContent(t, p, normalizeExpected(ext, "
Lorem ipsum dolor sit amet, consectetur adipiscing 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.
\n\n
Additional text.
\n\n
Further text.
\n"), ext)
checkPageSummary(t, p, normalizeExpected(ext, "Lorem ipsum dolor sit amet, consectetur adipiscing 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. Additional text."), ext)
}
checkPageType(t, p, "page")
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithoutSummaryDelimiter)
}
func TestPageWithDelimiter(t *testing.T) {
t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "
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.”
"))
checkPageType(t, p, "page")
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryDelimiterSameLine)
}
// #2973
func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
c := qt.New(t)
p := pages[0]
s := string(p.Summary())
c.Assert(s, qt.Contains, "Happy new year everyone!")
c.Assert(s, qt.Not(qt.Contains), "User interface")
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, `---
title: Simple
---
Happy new year everyone!
Here is the last report for commits in the year 2016. It covers hrev50718-hrev50829.
User interface
`)
}
func TestPageWithDate(t *testing.T) {
t.Parallel()
cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageRFC3339Date)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
d, _ := time.Parse(time.RFC3339, "2013-05-17T16:59:30Z")
checkPageDate(t, p, d)
}
func TestPageWithLastmodFromGitInfo(t *testing.T) {
c := qt.New(t)
// We need to use the OS fs for this.
cfg := viper.New()
fs := hugofs.NewFrom(hugofs.Os, cfg)
fs.Destination = &afero.MemMapFs{}
wd, err := os.Getwd()
c.Assert(err, qt.IsNil)
cfg.Set("frontmatter", map[string]interface{}{
"lastmod": []string{":git", "lastmod"},
})
cfg.Set("defaultContentLanguage", "en")
langConfig := map[string]interface{}{
"en": map[string]interface{}{
"weight": 1,
"languageName": "English",
"contentDir": "content",
},
"nn": map[string]interface{}{
"weight": 2,
"languageName": "Nynorsk",
"contentDir": "content_nn",
},
}
cfg.Set("languages", langConfig)
cfg.Set("enableGitInfo", true)
cfg.Set("workingDir", filepath.Join(wd, "testsite"))
b := newTestSitesBuilderFromDepsCfg(t, deps.DepsCfg{Fs: fs, Cfg: cfg}).WithNothingAdded()
b.Build(BuildCfg{SkipRender: true})
h := b.H
c.Assert(len(h.Sites), qt.Equals, 2)
enSite := h.Sites[0]
c.Assert(len(enSite.RegularPages()), qt.Equals, 1)
// 2018-03-11 is the Git author date for testsite/content/first-post.md
c.Assert(enSite.RegularPages()[0].Lastmod().Format("2006-01-02"), qt.Equals, "2018-03-11")
nnSite := h.Sites[1]
c.Assert(len(nnSite.RegularPages()), qt.Equals, 1)
// 2018-08-11 is the Git author date for testsite/content_nn/first-post.md
c.Assert(nnSite.RegularPages()[0].Lastmod().Format("2006-01-02"), qt.Equals, "2018-08-11")
}
func TestPageWithFrontMatterConfig(t *testing.T) {
for _, dateHandler := range []string{":filename", ":fileModTime"} {
dateHandler := dateHandler
t.Run(fmt.Sprintf("dateHandler=%q", dateHandler), func(t *testing.T) {
t.Parallel()
c := qt.New(t)
cfg, fs := newTestCfg()
pageTemplate := `
---
title: Page
weight: %d
lastMod: 2018-02-28
%s
---
Content
`
cfg.Set("frontmatter", map[string]interface{}{
"date": []string{dateHandler, "date"},
})
c1 := filepath.Join("content", "section", "2012-02-21-noslug.md")
c2 := filepath.Join("content", "section", "2012-02-22-slug.md")
writeSource(t, fs, c1, fmt.Sprintf(pageTemplate, 1, ""))
writeSource(t, fs, c2, fmt.Sprintf(pageTemplate, 2, "slug: aslug"))
c1fi, err := fs.Source.Stat(c1)
c.Assert(err, qt.IsNil)
c2fi, err := fs.Source.Stat(c2)
c.Assert(err, qt.IsNil)
b := newTestSitesBuilderFromDepsCfg(t, deps.DepsCfg{Fs: fs, Cfg: cfg}).WithNothingAdded()
b.Build(BuildCfg{SkipRender: true})
s := b.H.Sites[0]
c.Assert(len(s.RegularPages()), qt.Equals, 2)
noSlug := s.RegularPages()[0]
slug := s.RegularPages()[1]
c.Assert(noSlug.Lastmod().Day(), qt.Equals, 28)
switch strings.ToLower(dateHandler) {
case ":filename":
c.Assert(noSlug.Date().IsZero(), qt.Equals, false)
c.Assert(slug.Date().IsZero(), qt.Equals, false)
c.Assert(noSlug.Date().Year(), qt.Equals, 2012)
c.Assert(slug.Date().Year(), qt.Equals, 2012)
c.Assert(noSlug.Slug(), qt.Equals, "noslug")
c.Assert(slug.Slug(), qt.Equals, "aslug")
case ":filemodtime":
c.Assert(noSlug.Date().Year(), qt.Equals, c1fi.ModTime().Year())
c.Assert(slug.Date().Year(), qt.Equals, c2fi.ModTime().Year())
fallthrough
default:
c.Assert(noSlug.Slug(), qt.Equals, "")
c.Assert(slug.Slug(), qt.Equals, "aslug")
}
})
}
}
func TestWordCountWithAllCJKRunesWithoutHasCJKLanguage(t *testing.T) {
t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
if p.WordCount() != 8 {
t.Fatalf("[%s] incorrect word count. expected %v, got %v", ext, 8, p.WordCount())
}
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithAllCJKRunes)
}
func TestWordCountWithAllCJKRunesHasCJKLanguage(t *testing.T) {
t.Parallel()
settings := map[string]interface{}{"hasCJKLanguage": true}
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
if p.WordCount() != 15 {
t.Fatalf("[%s] incorrect word count, expected %v, got %v", ext, 15, p.WordCount())
}
}
testAllMarkdownEnginesForPages(t, assertFunc, settings, simplePageWithAllCJKRunes)
}
func TestWordCountWithMainEnglishWithCJKRunes(t *testing.T) {
t.Parallel()
settings := map[string]interface{}{"hasCJKLanguage": true}
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0]
if p.WordCount() != 74 {
t.Fatalf("[%s] incorrect word count, expected %v, got %v", ext, 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, settings, simplePageWithMainEnglishWithCJKRunes)
}
func TestWordCountWithIsCJKLanguageFalse(t *testing.T) {
t.Parallel()
settings := map[string]interface{}{
"hasCJKLanguage": true,
}
assertFunc := func(t *testing.T, ext string, pages page.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, settings, simplePageWithIsCJKLanguageFalse)
}
func TestWordCount(t *testing.T) {
t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.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.FuzzyWordCount())
}
if p.ReadingTime() != 3 {
t.Fatalf("[%s] incorrect min read. expected %v, got %v", ext, 3, p.ReadingTime())
}
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithLongContent)
}
func TestPagePaths(t *testing.T) {
t.Parallel()
c := qt.New(t)
siteParmalinksSetting := map[string]string{
"post": ":year/:month/:day/:title/",
}
tests := []struct {
content string
path string
hasPermalink bool
expected string
}{
{simplePage, "post/x.md", false, "post/x.html"},
{simplePageWithURL, "post/x.md", false, "simple/url/index.html"},
{simplePageWithSlug, "post/x.md", false, "post/simple-slug.html"},
{simplePageWithDate, "post/x.md", true, "2013/10/15/simple/index.html"},
{UTF8Page, "post/x.md", false, "post/x.html"},
{UTF8PageWithURL, "post/x.md", false, "ラーメン/url/index.html"},
{UTF8PageWithSlug, "post/x.md", false, "post/ラーメン-slug.html"},
{UTF8PageWithDate, "post/x.md", true, "2013/10/15/ラーメン/index.html"},
}
for _, test := range tests {
cfg, fs := newTestCfg()
if test.hasPermalink {
cfg.Set("permalinks", siteParmalinksSetting)
}
writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.path)), test.content)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
}
}
func TestTranslationKey(t *testing.T) {
t.Parallel()
c := qt.New(t)
cfg, fs := newTestCfg()
writeSource(t, fs, filepath.Join("content", filepath.FromSlash("sect/simple.no.md")), "---\ntitle: \"A1\"\ntranslationKey: \"k1\"\n---\nContent\n")
writeSource(t, fs, filepath.Join("content", filepath.FromSlash("sect/simple.en.md")), "---\ntitle: \"A2\"\n---\nContent\n")
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 2)
home, _ := s.Info.Home()
c.Assert(home, qt.Not(qt.IsNil))
c.Assert(home.TranslationKey(), qt.Equals, "home")
c.Assert(s.RegularPages()[0].TranslationKey(), qt.Equals, "page/k1")
p2 := s.RegularPages()[1]
c.Assert(p2.TranslationKey(), qt.Equals, "page/sect/simple")
}
func TestChompBOM(t *testing.T) {
t.Parallel()
c := qt.New(t)
const utf8BOM = "\xef\xbb\xbf"
cfg, fs := newTestCfg()
writeSource(t, fs, filepath.Join("content", "simple.md"), utf8BOM+simplePage)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
checkPageTitle(t, p, "Simple")
}
func TestPageWithEmoji(t *testing.T) {
for _, enableEmoji := range []bool{true, false} {
v := viper.New()
v.Set("enableEmoji", enableEmoji)
b := newTestSitesBuilder(t).WithViper(v)
b.WithContent("page-emoji.md", `---
title: "Hugo Smile"
---
This is a :smile:.
Another :smile: This is :not: :an: :emoji:.
O :christmas_tree:
Write me an :e-mail: or :email:?
Too many colons: :: ::: :::: :?: :!: :.:
If you dislike this video, you can hit that :-1: button :stuck_out_tongue_winking_eye:,
but if you like it, hit :+1: and get subscribed!
`)
b.CreateSites().Build(BuildCfg{})
if enableEmoji {
b.AssertFileContent("public/page-emoji/index.html",
"This is a 😄",
"Another 😄",
"This is :not: :an: :emoji:.",
"O 🎄",
"Write me an 📧 or ✉️?",
"Too many colons: :: ::: :::: :?: :!: :.:",
"you can hit that 👎 button 😜,",
"hit 👍 and get subscribed!",
)
} else {
b.AssertFileContent("public/page-emoji/index.html",
"This is a :smile:",
"Another :smile:",
"This is :not: :an: :emoji:.",
"O :christmas_tree:",
"Write me an :e-mail: or :email:?",
"Too many colons: :: ::: :::: :?: :!: :.:",
"you can hit that :-1: button :stuck_out_tongue_winking_eye:,",
"hit :+1: and get subscribed!",
)
}
}
}
func TestPageHTMLContent(t *testing.T) {
b := newTestSitesBuilder(t)
b.WithSimpleConfigFile()
frontmatter := `---
title: "HTML Content"
---
`
b.WithContent("regular.html", frontmatter+`