// 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 (
"context"
"fmt"
"html/template"
"path/filepath"
"strings"
"testing"
"time"
"github.com/bep/clocks"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/markup/asciidocext"
"github.com/gohugoio/hugo/markup/rst"
"github.com/gohugoio/hugo/tpl"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/common/htime"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/resource"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps"
)
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]any, pageSources ...string) {
engines := []struct {
ext string
shouldExecute func() bool
}{
{"md", func() bool { return true }},
{"ad", func() bool { return asciidocext.Supports() }},
{"rst", func() bool { return rst.Supports() }},
}
for _, e := range engines {
if !e.shouldExecute() {
continue
}
t.Run(e.ext, func(t *testing.T) {
cfg := config.New()
for k, v := range settings {
cfg.Set(k, v)
}
if s := cfg.GetString("contentDir"); s != "" && s != "content" {
panic("contentDir must be set to 'content' for this test")
}
files := `
-- hugo.toml --
[security]
[security.exec]
allow = ['^python$', '^rst2html.*', '^asciidoctor$']
`
for i, source := range pageSources {
files += fmt.Sprintf("-- content/p%d.%s --\n%s\n", i, e.ext, source)
}
homePath := fmt.Sprintf("_index.%s", e.ext)
files += fmt.Sprintf("-- content/%s --\n%s\n", homePath, homePage)
b := NewIntegrationTestBuilder(
IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
BaseCfg: cfg,
},
).Build()
s := b.H.Sites[0]
b.Assert(len(s.RegularPages()), qt.Equals, len(pageSources))
assertFunc(t, e.ext, s.RegularPages())
home := s.Home()
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)
configs, err := loadTestConfigFromProvider(cfg)
c.Assert(err, qt.IsNil)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Configs: configs}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
if p.Summary(context.Background()) != template.HTML(
"
" {
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, qt.Commentf(msg))
}
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.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
---
`, "with-index-no-date/_index.md", `---
title: No Date
---
`,
// https://github.com/gohugoio/hugo/issues/5854
"with-index-date/_index.md", `---
title: Date
date: 2018-01-15
---
`, "with-index-date/p1.md", `---
title: Date
date: 2018-01-15
---
`, "with-index-date/p1.md", `---
title: Date
date: 2018-01-15
---
`)
for i := 1; i <= 20; i++ {
b.WithContent(fmt.Sprintf("main-section/p%d.md", i), `---
title: Date
date: 2012-01-12
---
`)
}
b.CreateSites().Build(BuildCfg{})
b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0]
checkDate := func(p page.Page, year int) {
b.Assert(p.Date().Year(), qt.Equals, year)
b.Assert(p.Lastmod().Year(), qt.Equals, year)
}
checkDate(s.getPage("/"), 2018)
checkDate(s.getPage("/no-index"), 2017)
b.Assert(s.getPage("/with-index-no-date").Date().IsZero(), qt.Equals, true)
checkDate(s.getPage("/with-index-date"), 2018)
b.Assert(s.Site().LastChange().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]any{}
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, "
\n"), ext)
// Summary is not Asciidoctor- or RST-compatible so don't test them
if ext != "ad" && ext != "rst" {
checkPageSummary(t, p, normalizeExpected(ext, "Page with summary parameter and a link"), ext)
}
checkPageType(t, p, "page")
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryParameter)
}
// Issue #3854
// Also see https://github.com/gohugoio/hugo/issues/3977
func TestPageWithDateFields(t *testing.T) {
c := qt.New(t)
pageWithDate := `---
title: P%d
weight: %d
%s: 2017-10-13
---
Simple Page With Some Date`
hasDate := func(p page.Page) bool {
return p.Date().Year() == 2017
}
datePage := func(field string, weight int) string {
return fmt.Sprintf(pageWithDate, weight, weight, field)
}
t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.Pages) {
c.Assert(len(pages) > 0, qt.Equals, true)
for _, p := range pages {
c.Assert(hasDate(p), qt.Equals, true)
}
}
fields := []string{"date", "publishdate", "pubdate", "published"}
pageContents := make([]string, len(fields))
for i, field := range fields {
pageContents[i] = datePage(field, i+1)
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, pageContents...)
}
func TestPageRawContent(t *testing.T) {
files := `
-- hugo.toml --
-- content/basic.md --
---
title: "basic"
---
**basic**
-- content/empty.md --
---
title: "empty"
---
-- layouts/_default/single.html --
|{{ .RawContent }}|
`
b := NewIntegrationTestBuilder(
IntegrationTestConfig{
T: t,
TxtarString: files,
},
).Build()
b.AssertFileContent("public/basic/index.html", "|**basic**|")
b.AssertFileContent("public/empty/index.html", "! title")
}
func TestPageWithShortCodeInSummary(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, "
Summary Next Line. . More text here.
Some more text
"))
checkPageSummary(t, p, "Summary Next Line. . More text here. Some more text")
checkPageType(t, p, "page")
}
testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithShortcodeInSummary)
}
func TestTableOfContents(t *testing.T) {
c := qt.New(t)
cfg, fs := newTestCfg()
configs, err := loadTestConfigFromProvider(cfg)
c.Assert(err, qt.IsNil)
writeSource(t, fs, filepath.Join("content", "tocpage.md"), pageWithToC)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Configs: configs}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
checkPageContent(t, p, "
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(context.Background()))
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
`)
}
// Issue 9383
func TestRenderStringForRegularPageTranslations(t *testing.T) {
c := qt.New(t)
b := newTestSitesBuilder(t)
b.WithLogger(loggers.NewDefault())
b.WithConfigFile("toml",
`baseurl = "https://example.org/"
title = "My Site"
defaultContentLanguage = "ru"
defaultContentLanguageInSubdir = true
[languages.ru]
contentDir = 'content/ru'
weight = 1
[languages.en]
weight = 2
contentDir = 'content/en'
[outputs]
home = ["HTML", "JSON"]`)
b.WithTemplates("index.html", `
{{- range .Site.Home.Translations -}}
{{- .RenderString "foo" -}}
{{- end -}}
{{- range .Site.Home.AllTranslations -}}