Debian Codegraph @

resources/page/permalinks_test.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package page
15
16 import (
17 "fmt"
18 "regexp"
19 "strings"
20 "sync"
21 "testing"
22 "time"
23
24 qt "github.com/frankban/quicktest"
25 "github.com/gohugoio/hugo/source"
26 )
27
28 // testdataPermalinks is used by a couple of tests; the expandsTo content is
29 // subject to the data in simplePageJSON.
30 var testdataPermalinks = []struct {
31 spec string
32 valid bool
33 withPage func(p *testPage)
34 expandsTo string
35 }{
36 {":title", true, nil, "spf13-vim-3.0-release-and-new-website"},
37 {"/:year-:month-:title", true, nil, "/2012-04-spf13-vim-3.0-release-and-new-website"},
38 {"/:year/:yearday/:month/:monthname/:day/:weekday/:weekdayname/", true, nil, "/2012/97/04/April/06/5/Friday/"}, // Dates
39 {"/:section/", true, nil, "/blue/"}, // Section
40 {"/:title/", true, nil, "/spf13-vim-3.0-release-and-new-website/"}, // Title
41 {"/:slug/", true, nil, "/the-slug/"}, // Slug
42 {"/:slugorfilename/", true, nil, "/the-slug/"}, // Slug or filename
43 {"/:filename/", true, nil, "/test-page/"}, // Filename
44 {"/:06-:1-:2-:Monday", true, nil, "/12-4-6-Friday"}, // Dates with Go formatting
45 {"/:2006_01_02_15_04_05.000", true, nil, "/2012_04_06_03_01_59.000"}, // Complicated custom date format
46 {"/:sections/", true, nil, "/a/b/c/"}, // Sections
47 {"/:sections[last]/", true, nil, "/c/"}, // Sections
48 {"/:sections[0]/:sections[last]/", true, nil, "/a/c/"}, // Sections
49 {"/\\:filename", true, nil, "/:filename"}, // Escape sequence
50 {"/special\\::slug/", true, nil, "/special:the-slug/"},
51 // contentbasename. // Escape sequence
52 {"/:contentbasename/", true, nil, "/test-page/"},
53 // slug, contentbasename. // Content base name
54 {"/:slugorcontentbasename/", true, func(p *testPage) {
55 p.slug = ""
56 }, "/test-page/"},
57 {"/:slugorcontentbasename/", true, func(p *testPage) {
58 p.slug = "myslug"
59 }, "/myslug/"},
60 {"/:slugorcontentbasename/", true, func(p *testPage) {
61 p.slug = ""
62 p.title = "mytitle"
63 p.file = source.NewContentFileInfoFrom("/", "_index.md")
64 }, "/test-page/"},
65 // slug, title. // Section slug
66 {"/:sectionslug/", true, func(p *testPage) {
67 p.currentSection = &testPage{slug: "my-slug"}
68 }, "/my-slug/"},
69 // slug, title. // Section slugs
70 {"/:sectionslugs/", true, func(p *testPage) {
71 // Set up current section with ancestors
72 currentSection := &testPage{
73 slug: "c-slug",
74 kind: "section",
75 ancestors: Pages{
76 &testPage{slug: "b-slug", kind: "section"},
77 &testPage{slug: "a-slug", kind: "section"},
78 },
79 }
80 p.currentSection = currentSection
81 }, "/a-slug/b-slug/c-slug/"},
82 // slice: slug, title.
83 {"/:sectionslugs[0]/:sectionslugs[last]/", true, func(p *testPage) {
84 currentSection := &testPage{
85 slug: "c-slug",
86 kind: "section",
87 ancestors: Pages{
88 &testPage{slug: "b-slug", kind: "section"},
89 &testPage{slug: "a-slug", kind: "section"},
90 },
91 }
92 p.currentSection = currentSection
93 }, "/a-slug/c-slug/"},
94 // slice: slug, title.
95 {"/:sectionslugs[last]/", true, func(p *testPage) {
96 currentSection := &testPage{
97 slug: "c-slug",
98 kind: "section",
99 ancestors: Pages{
100 &testPage{slug: "b-slug", kind: "section"},
101 &testPage{slug: "a-slug", kind: "section"},
102 },
103 }
104 p.currentSection = currentSection
105 }, "/c-slug/"},
106 // Failures
107 {"/blog/:fred", false, nil, ""},
108 {"/:year//:title", false, nil, ""},
109 {"/:TITLE", false, nil, ""}, // case is not normalized
110 {"/:2017", false, nil, ""}, // invalid date format
111 {"/:2006-01-02", false, nil, ""}, // valid date format but invalid attribute name
112 }
113
114 func urlize(uri string) string {
115 // This is just an approximation of the real urlize function.
116 return strings.ToLower(strings.ReplaceAll(uri, " ", "-"))
117 }
118
119 func TestPermalinkExpansion(t *testing.T) {
120 t.Parallel()
121
122 c := qt.New(t)
123
124 newPage := func() *testPage {
125 page := newTestPageWithFile("/test-page/index.md")
126 page.title = "Spf13 Vim 3.0 Release and new website"
127 d, _ := time.Parse("2006-01-02 15:04:05", "2012-04-06 03:01:59")
128 page.date = d
129 page.section = "blue"
130 page.slug = "The Slug"
131 page.kind = "page"
132 page.path = "/posts/test-page"
133 return page
134 }
135
136 for i, item := range testdataPermalinks {
137 if !item.valid {
138 continue
139 }
140
141 page := newPage()
142 if item.withPage != nil {
143 item.withPage(page)
144 }
145
146 specNameCleaner := regexp.MustCompile(`[\:\/\[\]]`)
147 name := fmt.Sprintf("[%d] %s", i, specNameCleaner.ReplaceAllString(item.spec, "_"))
148
149 c.Run(name, func(c *qt.C) {
150 configs := PermalinksConfig{
151 {Target: PageMatcher{Kind: "page", Path: "/posts/**"}, Pattern: item.spec},
152 }
153 expander, err := NewPermalinkExpander(urlize, configs)
154 c.Assert(err, qt.IsNil)
155 expanded, err := expander.Expand(page)
156 c.Assert(err, qt.IsNil)
157 c.Assert(expanded, qt.Equals, item.expandsTo)
158
159 expanded, err = expander.ExpandPattern(item.spec, page)
160 c.Assert(err, qt.IsNil)
161 c.Assert(expanded, qt.Equals, item.expandsTo)
162 })
163
164 }
165 }
166
167 func TestPermalinkExpansionMultiSection(t *testing.T) {
168 t.Parallel()
169
170 c := qt.New(t)
171
172 page := newTestPage()
173 page.title = "Page Title"
174 d, _ := time.Parse("2006-01-02", "2012-04-06")
175 page.date = d
176 page.section = "blue"
177 page.slug = "The Slug"
178 page.kind = "page"
179 page.path = "/posts/my-page"
180
181 pageSlugFallback := newTestPageWithFile("/page-filename/index.md")
182 pageSlugFallback.title = "Page Title"
183 pageSlugFallback.kind = "page"
184
185 configs := PermalinksConfig{
186 {Target: PageMatcher{Kind: "page", Path: "/posts/**"}, Pattern: "/:slug"},
187 {Target: PageMatcher{Kind: "page", Path: "/blog/**"}, Pattern: "/:section/:year"},
188 {Target: PageMatcher{Kind: "page", Path: "/recipes/**"}, Pattern: "/:slugorfilename"},
189 {Target: PageMatcher{Kind: "page", Path: "/special/**"}, Pattern: "/special\\::slug"},
190 }
191 expander, err := NewPermalinkExpander(urlize, configs)
192 c.Assert(err, qt.IsNil)
193
194 expanded, err := expander.Expand(page)
195 c.Assert(err, qt.IsNil)
196 c.Assert(expanded, qt.Equals, "/the-slug")
197
198 page.path = "/blog/my-page"
199 expanded, err = expander.Expand(page)
200 c.Assert(err, qt.IsNil)
201 c.Assert(expanded, qt.Equals, "/blue/2012")
202
203 pageSlugFallback.path = "/posts/my-page"
204 expanded, err = expander.Expand(pageSlugFallback)
205 c.Assert(err, qt.IsNil)
206 c.Assert(expanded, qt.Equals, "/page-title")
207
208 pageSlugFallback.path = "/recipes/my-page"
209 expanded, err = expander.Expand(pageSlugFallback)
210 c.Assert(err, qt.IsNil)
211 c.Assert(expanded, qt.Equals, "/page-filename")
212
213 page.path = "/special/my-page"
214 expanded, err = expander.Expand(page)
215 c.Assert(err, qt.IsNil)
216 c.Assert(expanded, qt.Equals, "/special:the-slug")
217 }
218
219 // https://github.com/gohugoio/hugo/issues/3577
220 func TestPermalinkExpansionTitleSlash(t *testing.T) {
221 t.Parallel()
222
223 c := qt.New(t)
224
225 configs := PermalinksConfig{
226 {Target: PageMatcher{Kind: "page"}, Pattern: "/:slug/"},
227 {Target: PageMatcher{Kind: "term"}, Pattern: "/:slug/"},
228 }
229 expander, err := NewPermalinkExpander(urlize, configs)
230 c.Assert(err, qt.IsNil)
231
232 // A page with no explicit slug and a title containing a "/" must not
233 // silently introduce an extra, unintended path segment.
234 page := newTestPage()
235 page.kind = "page"
236 page.title = "Watch/listen to this"
237 page.slug = ""
238
239 expanded, err := expander.Expand(page)
240 c.Assert(err, qt.IsNil)
241 c.Assert(expanded, qt.Equals, "/watch-listen-to-this/")
242
243 // An explicit slug is left as-is; the user is in control of it.
244 pageWithSlug := newTestPage()
245 pageWithSlug.kind = "page"
246 pageWithSlug.slug = "explicit/slug"
247
248 expanded, err = expander.Expand(pageWithSlug)
249 c.Assert(err, qt.IsNil)
250 c.Assert(expanded, qt.Equals, "/explicit/slug/")
251
252 // Taxonomy term pages are allowed to preserve "/" in their title
253 // (the term itself) to build multi-level taxonomy hierarchies.
254 // See https://github.com/gohugoio/hugo/issues/5571.
255 term := newTestPage()
256 term.kind = "term"
257 term.title = "country/region/city"
258 term.slug = ""
259
260 expanded, err = expander.Expand(term)
261 c.Assert(err, qt.IsNil)
262 c.Assert(expanded, qt.Equals, "/country/region/city/")
263 }
264
265 func TestPermalinkExpansionConcurrent(t *testing.T) {
266 t.Parallel()
267
268 c := qt.New(t)
269
270 configs := PermalinksConfig{
271 {Target: PageMatcher{Kind: "page", Path: "/posts/**"}, Pattern: "/:slug/"},
272 }
273
274 expander, err := NewPermalinkExpander(urlize, configs)
275 c.Assert(err, qt.IsNil)
276
277 var wg sync.WaitGroup
278
279 for i := 1; i < 20; i++ {
280 wg.Add(1)
281 go func(i int) {
282 defer wg.Done()
283 page := newTestPage()
284 page.kind = "page"
285 page.path = "/posts/my-page"
286 for j := 1; j < 20; j++ {
287 page.slug = fmt.Sprintf("slug%d", i+j)
288 expanded, err := expander.Expand(page)
289 c.Assert(err, qt.IsNil)
290 c.Assert(expanded, qt.Equals, fmt.Sprintf("/%s/", page.slug))
291 }
292 }(i)
293 }
294
295 wg.Wait()
296 }
297
298 func TestPermalinkExpansionSliceSyntax(t *testing.T) {
299 t.Parallel()
300
301 c := qt.New(t)
302 exp, err := NewPermalinkExpander(urlize, PermalinksConfig{})
303 c.Assert(err, qt.IsNil)
304 slice4 := []string{"a", "b", "c", "d"}
305 fn4 := func(s string) []string {
306 return exp.toSliceFunc(s)(slice4)
307 }
308
309 slice1 := []string{"a"}
310 fn1 := func(s string) []string {
311 return exp.toSliceFunc(s)(slice1)
312 }
313
314 c.Run("Basic", func(c *qt.C) {
315 c.Assert(fn4("[1:3]"), qt.DeepEquals, []string{"b", "c"})
316 c.Assert(fn4("[1:]"), qt.DeepEquals, []string{"b", "c", "d"})
317 c.Assert(fn4("[:2]"), qt.DeepEquals, []string{"a", "b"})
318 c.Assert(fn4("[0:2]"), qt.DeepEquals, []string{"a", "b"})
319 c.Assert(fn4("[:]"), qt.DeepEquals, []string{"a", "b", "c", "d"})
320 c.Assert(fn4(""), qt.DeepEquals, []string{"a", "b", "c", "d"})
321 c.Assert(fn4("[last]"), qt.DeepEquals, []string{"d"})
322 c.Assert(fn4("[:last]"), qt.DeepEquals, []string{"a", "b", "c"})
323 c.Assert(fn1("[last]"), qt.DeepEquals, []string{"a"})
324 c.Assert(fn1("[:last]"), qt.DeepEquals, []string{})
325 c.Assert(fn1("[1:last]"), qt.DeepEquals, []string{})
326 c.Assert(fn1("[1]"), qt.DeepEquals, []string{})
327 })
328
329 c.Run("Out of bounds", func(c *qt.C) {
330 c.Assert(fn4("[1:5]"), qt.DeepEquals, []string{"b", "c", "d"})
331 c.Assert(fn4("[-1:5]"), qt.DeepEquals, []string{"a", "b", "c", "d"})
332 c.Assert(fn4("[5:]"), qt.DeepEquals, []string{})
333 c.Assert(fn4("[5:]"), qt.DeepEquals, []string{})
334 c.Assert(fn4("[5:32]"), qt.DeepEquals, []string{})
335 c.Assert(exp.toSliceFunc("[:1]")(nil), qt.DeepEquals, []string(nil))
336 c.Assert(exp.toSliceFunc("[:1]")([]string{}), qt.DeepEquals, []string(nil))
337
338 // These all return nil
339 c.Assert(fn4("[]"), qt.IsNil)
340 c.Assert(fn4("[1:}"), qt.IsNil)
341 c.Assert(fn4("foo"), qt.IsNil)
342 })
343 }
344
345 func BenchmarkPermalinkExpand(b *testing.B) {
346 page := newTestPage()
347 page.title = "Hugo Rocks"
348 d, _ := time.Parse("2006-01-02", "2019-02-28")
349 page.date = d
350 page.kind = "page"
351 page.path = "/posts/my-page"
352
353 configs := PermalinksConfig{
354 {Target: PageMatcher{Kind: "page", Path: "/posts/**"}, Pattern: "/:year-:month-:title"},
355 }
356 expander, err := NewPermalinkExpander(urlize, configs)
357 if err != nil {
358 b.Fatal(err)
359 }
360
361 for b.Loop() {
362 s, err := expander.Expand(page)
363 if err != nil {
364 b.Fatal(err)
365 }
366 if s != "/2019-02-hugo-rocks" {
367 b.Fatal(s)
368 }
369
370 }
371 }