Debian Codegraph @

helpers/path_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 helpers_test
15
16 import (
17 "fmt"
18 "os"
19 "path/filepath"
20 "runtime"
21 "strconv"
22 "strings"
23 "testing"
24 "time"
25
26 qt "github.com/frankban/quicktest"
27 "github.com/gohugoio/hugo/helpers"
28 "github.com/spf13/afero"
29 )
30
31 func TestMakePath(t *testing.T) {
32 tests := []struct {
33 input string
34 expected string
35 removeAccents bool
36 }{
37 {"dot.slash/backslash\\underscore_pound#plus+hyphen-", "dot.slash/backslash\\underscore_pound#plus+hyphen-", true},
38 {"abcXYZ0123456789", "abcXYZ0123456789", true},
39 {"%20 %2", "%20-2", true},
40 {"foo- bar", "foo-bar", true},
41 {" Foo bar ", "Foo-bar", true},
42 {"Foo.Bar/foo_Bar-Foo", "Foo.Bar/foo_Bar-Foo", true},
43 {"fOO,bar:foobAR", "fOObarfoobAR", true},
44 {"FOo/BaR.html", "FOo/BaR.html", true},
45 {"трям/трям", "трям/трям", true},
46 {"은행", "은행", true},
47 {"Банковский кассир", "Банковскии-кассир", true},
48 // Issue #1488
49 {"संस्कृत", "संस्कृत", false},
50 {"a%C3%B1ame", "a%C3%B1ame", false}, // Issue #1292
51 {"this+is+a+test", "this+is+a+test", false}, // Issue #1290
52 {"~foo", "~foo", false}, // Issue #2177
53 {"foo--bar", "foo--bar", true}, // Issue #7288
54 {"foo@bar", "foo@bar", true}, // Issue #10548
55 }
56
57 for _, test := range tests {
58 p := newTestPathSpec("removePathAccents", test.removeAccents)
59 output := p.MakePath(test.input)
60 if output != test.expected {
61 t.Errorf("Expected %#v, got %#v\n", test.expected, output)
62 }
63 }
64 }
65
66 func TestMakePathSanitized(t *testing.T) {
67 p := newTestPathSpec()
68
69 tests := []struct {
70 input string
71 expected string
72 }{
73 {" FOO bar ", "foo-bar"},
74 {"Foo.Bar/fOO_bAr-Foo", "foo.bar/foo_bar-foo"},
75 {"FOO,bar:FooBar", "foobarfoobar"},
76 {"foo/BAR.HTML", "foo/bar.html"},
77 {"трям/трям", "трям/трям"},
78 {"은행", "은행"},
79 }
80
81 for _, test := range tests {
82 output := p.MakePathSanitized(test.input)
83 if output != test.expected {
84 t.Errorf("Expected %#v, got %#v\n", test.expected, output)
85 }
86 }
87 }
88
89 func TestMakePathSanitizedDisablePathToLower(t *testing.T) {
90 p := newTestPathSpec("disablePathToLower", true)
91
92 tests := []struct {
93 input string
94 expected string
95 }{
96 {" FOO bar ", "FOO-bar"},
97 {"Foo.Bar/fOO_bAr-Foo", "Foo.Bar/fOO_bAr-Foo"},
98 {"FOO,bar:FooBar", "FOObarFooBar"},
99 {"foo/BAR.HTML", "foo/BAR.HTML"},
100 {"трям/трям", "трям/трям"},
101 {"은행", "은행"},
102 }
103
104 for _, test := range tests {
105 output := p.MakePathSanitized(test.input)
106 if output != test.expected {
107 t.Errorf("Expected %#v, got %#v\n", test.expected, output)
108 }
109 }
110 }
111
112 func TestGetDottedRelativePath(t *testing.T) {
113 for _, f := range []func(string) string{filepath.FromSlash, func(s string) string { return s }} {
114 doTestGetDottedRelativePath(f, t)
115 }
116 }
117
118 func doTestGetDottedRelativePath(urlFixer func(string) string, t *testing.T) {
119 type test struct {
120 input, expected string
121 }
122 data := []test{
123 {"", "./"},
124 {urlFixer("/"), "./"},
125 {urlFixer("post"), "../"},
126 {urlFixer("/post"), "../"},
127 {urlFixer("post/"), "../"},
128 {urlFixer("tags/foo.html"), "../"},
129 {urlFixer("/tags/foo.html"), "../"},
130 {urlFixer("/post/"), "../"},
131 {urlFixer("////post/////"), "../"},
132 {urlFixer("/foo/bar/index.html"), "../../"},
133 {urlFixer("/foo/bar/foo/"), "../../../"},
134 {urlFixer("/foo/bar/foo"), "../../../"},
135 {urlFixer("foo/bar/foo/"), "../../../"},
136 {urlFixer("foo/bar/foo/bar"), "../../../../"},
137 {"404.html", "./"},
138 {"404.xml", "./"},
139 {"/404.html", "./"},
140 }
141 for i, d := range data {
142 output := helpers.GetDottedRelativePath(d.input)
143 if d.expected != output {
144 t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output)
145 }
146 }
147 }
148
149 func TestDirExists(t *testing.T) {
150 type test struct {
151 input string
152 expected bool
153 }
154
155 data := []test{
156 {".", true},
157 {"./", true},
158 {"..", true},
159 {"../", true},
160 {"./..", true},
161 {"./../", true},
162 {os.TempDir(), true},
163 {os.TempDir() + helpers.FilePathSeparator, true},
164 {"/", true},
165 {"/some-really-random-directory-name", false},
166 {"/some/really/random/directory/name", false},
167 {"./some-really-random-local-directory-name", false},
168 {"./some/really/random/local/directory/name", false},
169 }
170
171 for i, d := range data {
172 exists, _ := helpers.DirExists(filepath.FromSlash(d.input), new(afero.OsFs))
173 if d.expected != exists {
174 t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
175 }
176 }
177 }
178
179 func TestIsDir(t *testing.T) {
180 type test struct {
181 input string
182 expected bool
183 }
184 data := []test{
185 {"./", true},
186 {"/", true},
187 {"./this-directory-does-not-existi", false},
188 {"/this-absolute-directory/does-not-exist", false},
189 }
190
191 for i, d := range data {
192
193 exists, _ := helpers.IsDir(d.input, new(afero.OsFs))
194 if d.expected != exists {
195 t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
196 }
197 }
198 }
199
200 func createZeroSizedFileInTempDir(t *testing.T) *os.File {
201 t.Helper()
202
203 filePrefix := "_path_test_"
204 f, err := os.CreateTemp(t.TempDir(), filePrefix)
205 if err != nil {
206 t.Error(err)
207 }
208 if err := f.Close(); err != nil {
209 t.Error(err)
210 }
211 return f
212 }
213
214 func createNonZeroSizedFileInTempDir(t *testing.T) *os.File {
215 t.Helper()
216
217 f := createZeroSizedFileInTempDir(t)
218 byteString := []byte("byteString")
219 err := os.WriteFile(f.Name(), byteString, 0o644)
220 if err != nil {
221 t.Error(err)
222 }
223 return f
224 }
225
226 func TestExists(t *testing.T) {
227 zeroSizedFile := createZeroSizedFileInTempDir(t)
228 nonZeroSizedFile := createNonZeroSizedFileInTempDir(t)
229 emptyDirectory := t.TempDir()
230 nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
231 nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/"
232
233 type test struct {
234 input string
235 expectedResult bool
236 expectedErr error
237 }
238
239 data := []test{
240 {zeroSizedFile.Name(), true, nil},
241 {nonZeroSizedFile.Name(), true, nil},
242 {emptyDirectory, true, nil},
243 {nonExistentFile, false, nil},
244 {nonExistentDir, false, nil},
245 }
246 for i, d := range data {
247 exists, err := helpers.Exists(d.input, new(afero.OsFs))
248 if d.expectedResult != exists {
249 t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
250 }
251 if d.expectedErr != err {
252 t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
253 }
254 }
255 }
256
257 func TestAbsPathify(t *testing.T) {
258 type test struct {
259 inPath, workingDir, expected string
260 }
261 data := []test{
262 {os.TempDir(), filepath.FromSlash("/work"), filepath.Clean(os.TempDir())}, // TempDir has trailing slash
263 {"dir", filepath.FromSlash("/work"), filepath.FromSlash("/work/dir")},
264 }
265
266 windowsData := []test{
267 {"c:\\banana\\..\\dir", "c:\\foo", "c:\\dir"},
268 {"\\dir", "c:\\foo", "c:\\foo\\dir"},
269 {"c:\\", "c:\\foo", "c:\\"},
270 }
271
272 unixData := []test{
273 {"/banana/../dir/", "/work", "/dir"},
274 }
275
276 for i, d := range data {
277 // todo see comment in AbsPathify
278 ps := newTestPathSpec("workingDir", d.workingDir)
279
280 expected := ps.AbsPathify(d.inPath)
281 if d.expected != expected {
282 t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
283 }
284 }
285 t.Logf("Running platform specific path tests for %s", runtime.GOOS)
286 if runtime.GOOS == "windows" {
287 for i, d := range windowsData {
288 ps := newTestPathSpec("workingDir", d.workingDir)
289
290 expected := ps.AbsPathify(d.inPath)
291 if d.expected != expected {
292 t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
293 }
294 }
295 } else {
296 for i, d := range unixData {
297 ps := newTestPathSpec("workingDir", d.workingDir)
298
299 expected := ps.AbsPathify(d.inPath)
300 if d.expected != expected {
301 t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
302 }
303 }
304 }
305 }
306
307 func TestExtractAndGroupRootPaths(t *testing.T) {
308 c := qt.New(t)
309
310 t.Run("Basic grouping", func(t *testing.T) {
311 in := []string{
312 filepath.FromSlash("/a/b/c/d"),
313 filepath.FromSlash("/a/b/c/e"),
314 filepath.FromSlash("/a/b/e/f"),
315 filepath.FromSlash("/a/b"),
316 filepath.FromSlash("/a/b/c/b/g"),
317 filepath.FromSlash("/c/d/e"),
318 }
319
320 result := helpers.ExtractAndGroupRootPaths(in)
321 c.Assert(result, qt.DeepEquals, []string{"/a/b/{c,e}", "/c/d/e"})
322 })
323
324 t.Run("Limits number of root groups", func(t *testing.T) {
325 in := []string{}
326 // Create 15 different root paths to exceed maxRootGroups (10)
327 for i := range 15 {
328 in = append(in, filepath.FromSlash(fmt.Sprintf("/path%d/subdir", i)))
329 }
330
331 result := helpers.ExtractAndGroupRootPaths(in)
332 // Should have 10 paths + 1 "... and X more" message
333 c.Assert(len(result), qt.Equals, 11)
334 c.Assert(result[10], qt.Matches, `\.\.\. and \d+ more`)
335 })
336 }
337
338 func BenchmarkExtractAndGroupRootPaths(b *testing.B) {
339 in := []string{}
340 for i := range 10 {
341 for j := range 1000 {
342 in = append(in, fmt.Sprintf("/a/b/c/s%d/p%d", i, j))
343 }
344 }
345
346 b.ResetTimer()
347 for i := 0; i < b.N; i++ {
348 helpers.ExtractAndGroupRootPaths(in)
349 }
350 }
351
352 func TestWriteToDisk(t *testing.T) {
353 emptyFile := createZeroSizedFileInTempDir(t)
354 tmpDir := t.TempDir()
355
356 randomString := "This is a random string!"
357 reader := strings.NewReader(randomString)
358
359 type test struct {
360 filename string
361 expectedErr error
362 }
363
364 now := time.Now().Unix()
365 nowStr := strconv.FormatInt(now, 10)
366 data := []test{
367 {emptyFile.Name(), nil},
368 {tmpDir + "/" + nowStr, nil},
369 }
370
371 for i, d := range data {
372 e := helpers.WriteToDisk(d.filename, reader, new(afero.OsFs))
373 if d.expectedErr != e {
374 t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
375 }
376 contents, e := os.ReadFile(d.filename)
377 if e != nil {
378 t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
379 }
380 if randomString != string(contents) {
381 t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
382 }
383 reader.Seek(0, 0)
384 }
385 }
386
387 func TestGetTempDir(t *testing.T) {
388 dir := os.TempDir()
389 if helpers.FilePathSeparator != dir[len(dir)-1:] {
390 dir = dir + helpers.FilePathSeparator
391 }
392 testDir := "hugoTestFolder" + helpers.FilePathSeparator
393 tests := []struct {
394 input string
395 expected string
396 }{
397 {"", dir},
398 {testDir + " Foo bar ", dir + testDir + " Foo bar " + helpers.FilePathSeparator},
399 {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + helpers.FilePathSeparator},
400 {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + helpers.FilePathSeparator},
401 {testDir + "fOO,bar:foobAR", dir + testDir + "fOObarfoobAR" + helpers.FilePathSeparator},
402 {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + helpers.FilePathSeparator},
403 {testDir + "трям/трям", dir + testDir + "трям/трям" + helpers.FilePathSeparator},
404 {testDir + "은행", dir + testDir + "은행" + helpers.FilePathSeparator},
405 {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + helpers.FilePathSeparator},
406 }
407
408 for _, test := range tests {
409 output := helpers.GetTempDir(test.input, new(afero.MemMapFs))
410 if output != test.expected {
411 t.Errorf("Expected %#v, got %#v\n", test.expected, output)
412 }
413 }
414 }