Debian Codegraph @

main_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 main
15
16 import (
17 "bytes"
18 "encoding/base64"
19 "encoding/json"
20 "fmt"
21 "io"
22 "io/fs"
23 "log"
24 "net/http"
25 "os"
26 "path/filepath"
27 "regexp"
28 "runtime"
29 "strconv"
30 "strings"
31 "sync"
32 "testing"
33 "time"
34
35 "github.com/bep/helpers/envhelpers"
36 "github.com/gohugoio/hugo/commands"
37 "github.com/gohugoio/hugo/htesting"
38 "github.com/rogpeppe/go-internal/testscript"
39 )
40
41 func TestCommands(t *testing.T) {
42 p := commonTestScriptsParam
43 p.Dir = "testscripts/commands"
44 testscript.Run(t, p)
45 }
46
47 func TestServer(t *testing.T) {
48 // See issue #14439
49 htesting.SkipSlowTestUnlessCI(t)
50 p := commonTestScriptsParam
51 p.Dir = "testscripts/server"
52 testscript.Run(t, p)
53 }
54
55 // Tests in development can be put in "testscripts/unfinished".
56 // Also see the watch_testscripts.sh script.
57 func TestUnfinished(t *testing.T) {
58 if os.Getenv("CI") != "" {
59 t.Skip("skip unfinished tests on CI")
60 }
61
62 p := commonTestScriptsParam
63 p.Dir = "testscripts/unfinished"
64 // p.UpdateScripts = true
65 // p.TestWork = true
66
67 testscript.Run(t, p)
68 }
69
70 func TestMain(m *testing.M) {
71 testscript.Main(m, map[string]func(){
72 // The main program.
73 "hugo": func() {
74 err := commands.Execute(os.Args[1:])
75 if err != nil {
76 fmt.Fprintln(os.Stderr, err)
77 os.Exit(1)
78 }
79 },
80 })
81 }
82
83 var isCaseInsensitiveFs = sync.OnceValues(func() (bool, error) {
84 return htesting.IsCaseInsensitiveFs(os.TempDir())
85 })
86
87 var commonTestScriptsParam = testscript.Params{
88 Setup: func(env *testscript.Env) error {
89 return testSetupFunc()(env)
90 },
91 Condition: func(cond string) (bool, error) {
92 switch cond {
93 case "caseinsensitivefs":
94 return isCaseInsensitiveFs()
95 default:
96 return false, fmt.Errorf("unknown condition %q", cond)
97 }
98 },
99 Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
100 // log prints to stderr.
101 "log": func(ts *testscript.TestScript, neg bool, args []string) {
102 log.Println(args)
103 },
104 // cat prints a file to stdout.
105 "cat": func(ts *testscript.TestScript, neg bool, args []string) {
106 filename := ts.MkAbs(args[0])
107 b, err := os.ReadFile(filename)
108 if err != nil {
109 ts.Fatalf("%v", err)
110 }
111 fmt.Print(string(b))
112 },
113 // sleep sleeps for a second.
114 "sleep": func(ts *testscript.TestScript, neg bool, args []string) {
115 i := 1
116 if len(args) > 0 {
117 var err error
118 i, err = strconv.Atoi(args[0])
119 if err != nil {
120 i = 1
121 }
122 }
123 time.Sleep(time.Duration(i) * time.Second)
124 },
125 // tree lists a directory recursively to stdout as a simple tree.
126 "tree": func(ts *testscript.TestScript, neg bool, args []string) {
127 dirname := ts.MkAbs(args[0])
128
129 err := filepath.WalkDir(dirname, func(path string, d fs.DirEntry, err error) error {
130 if err != nil {
131 return err
132 }
133 rel, err := filepath.Rel(dirname, path)
134 if err != nil {
135 return err
136 }
137 if rel == "." {
138 fmt.Fprintln(ts.Stdout(), ".")
139 return nil
140 }
141 depth := strings.Count(rel, string(os.PathSeparator))
142 prefix := strings.Repeat(" ", depth) + "└─"
143 if d.IsDir() {
144 fmt.Fprintf(ts.Stdout(), "%s%s/\n", prefix, d.Name())
145 } else {
146 fmt.Fprintf(ts.Stdout(), "%s%s\n", prefix, d.Name())
147 }
148 return nil
149 })
150 if err != nil {
151 ts.Fatalf("%v", err)
152 }
153 },
154 // ls lists a directory to stdout.
155 "ls": func(ts *testscript.TestScript, neg bool, args []string) {
156 dirname := ts.MkAbs(args[0])
157
158 dir, err := os.Open(dirname)
159 if err != nil {
160 ts.Fatalf("%v", err)
161 }
162 fis, err := dir.Readdir(-1)
163 if err != nil {
164 ts.Fatalf("%v", err)
165 }
166 if len(fis) == 0 {
167 // To simplify empty dir checks.
168 fmt.Fprintln(ts.Stdout(), "Empty dir")
169 return
170 }
171 for _, fi := range fis {
172 fmt.Fprintf(ts.Stdout(), "%s %04o %s %s\n", fi.Mode(), fi.Mode().Perm(), fi.ModTime().Format(time.RFC3339), fi.Name())
173 }
174 },
175 // lsr lists a directory recursively to stdout.
176 "lsr": func(ts *testscript.TestScript, neg bool, args []string) {
177 dirname := ts.MkAbs(args[0])
178
179 err := filepath.WalkDir(dirname, func(path string, d fs.DirEntry, err error) error {
180 if err != nil {
181 return err
182 }
183 if d.IsDir() {
184 return nil
185 }
186
187 fi, err := d.Info()
188 if err != nil {
189 return err
190 }
191
192 rel, err := filepath.Rel(dirname, path)
193 if err != nil {
194 return err
195 }
196
197 fmt.Fprintf(ts.Stdout(), "%s %04o %s\n", fi.Mode(), fi.Mode().Perm(), filepath.ToSlash(rel))
198 return nil
199 })
200 if err != nil {
201 ts.Fatalf("%v", err)
202 }
203 },
204 // append appends to a file with a leading newline.
205 "append": func(ts *testscript.TestScript, neg bool, args []string) {
206 if len(args) < 2 {
207 ts.Fatalf("usage: append FILE TEXT")
208 }
209
210 filename := ts.MkAbs(args[0])
211 words := args[1:]
212 for i, word := range words {
213 words[i] = strings.Trim(word, "\"")
214 }
215 text := strings.Join(words, " ")
216
217 _, err := os.Stat(filename)
218 if err != nil {
219 if os.IsNotExist(err) {
220 ts.Fatalf("file does not exist: %s", filename)
221 }
222 ts.Fatalf("failed to stat file: %v", err)
223 }
224
225 f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o644)
226 if err != nil {
227 ts.Fatalf("failed to open file: %v", err)
228 }
229 defer f.Close()
230
231 _, err = f.WriteString("\n" + text)
232 if err != nil {
233 ts.Fatalf("failed to write to file: %v", err)
234 }
235 },
236 // replace replaces a string in a file.
237 "replace": func(ts *testscript.TestScript, neg bool, args []string) {
238 if len(args) < 3 {
239 ts.Fatalf("usage: replace FILE OLD NEW")
240 }
241 filename := ts.MkAbs(args[0])
242 oldContent, err := os.ReadFile(filename)
243 if err != nil {
244 ts.Fatalf("failed to read file %v", err)
245 }
246 old, new := args[1], args[2]
247
248 newContent := bytes.Replace(oldContent, []byte(old), []byte(new), -1)
249 err = os.WriteFile(filename, newContent, 0o644)
250 if err != nil {
251 ts.Fatalf("failed to write file: %v", err)
252 }
253 },
254 // ln creates a symlink, but throws an error on Windows.
255 "ln": func(ts *testscript.TestScript, neg bool, args []string) {
256 if runtime.GOOS == "windows" {
257 ts.Fatalf("ln is not supported on Windows")
258 }
259 if len(args) != 2 {
260 ts.Fatalf("usage: ln TARGET LINKNAME")
261 }
262 target := ts.MkAbs(args[0])
263 linkname := ts.MkAbs(args[1])
264 err := os.Symlink(target, linkname)
265 if err != nil {
266 ts.Fatalf("failed to create symlink: %v", err)
267 }
268 },
269 // base64decode decodes a base64-encoded file into a binary file.
270 "base64decode": func(ts *testscript.TestScript, neg bool, args []string) {
271 if len(args) != 2 {
272 ts.Fatalf("usage: base64decode src_base64_file dest_binary_file")
273 }
274
275 // Resolve paths relative to the test sandbox's current directory
276 src := ts.MkAbs(args[0])
277 dest := ts.MkAbs(args[1])
278
279 // Read the base64 text
280 base64Data, err := os.ReadFile(src)
281 if err != nil {
282 ts.Fatalf("failed to read base64 file: %v", err)
283 }
284
285 // Decode base64 back to raw bytes.
286 binaryBytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(base64Data)))
287 if err != nil {
288 ts.Fatalf("failed to decode base64 data: %v", err)
289 }
290
291 // Write the binary file.
292 err = os.WriteFile(dest, binaryBytes, 0o644)
293 if err != nil {
294 ts.Fatalf("failed to write binary file: %v", err)
295 }
296 },
297
298 // httpget checks that a HTTP resource's body matches (if it compiles as a regexp) or contains all of the strings given as arguments.
299 "httpget": func(ts *testscript.TestScript, neg bool, args []string) {
300 if len(args) < 2 {
301 ts.Fatalf("usage: httpget URL STRING...")
302 }
303
304 tryget := func() error {
305 resp, err := http.Get(args[0])
306 if err != nil {
307 return fmt.Errorf("failed to get URL %q: %v", args[0], err)
308 }
309
310 defer resp.Body.Close()
311 body, err := io.ReadAll(resp.Body)
312 if err != nil {
313 return fmt.Errorf("failed to read response body: %v", err)
314 }
315 for _, s := range args[1:] {
316 re, err := regexp.Compile(s)
317 if err == nil {
318 ok := re.Match(body)
319 if ok != !neg {
320 return fmt.Errorf("response body %q for URL %q does not match %q", body, args[0], s)
321 }
322 } else {
323 ok := bytes.Contains(body, []byte(s))
324 if ok != !neg {
325 return fmt.Errorf("response body %q for URL %q does not contain %q", body, args[0], s)
326 }
327 }
328 }
329 return nil
330 }
331
332 // The timing on server rebuilds can be a little tricky to get right,
333 // so we try again a few times until the server is ready.
334 // There may be smarter ways to do this, but this works.
335 start := time.Now()
336 for {
337 time.Sleep(200 * time.Millisecond)
338 err := tryget()
339 if err == nil {
340 return
341 }
342 if time.Since(start) > 6*time.Second {
343 ts.Fatalf("timeout waiting for %q: %v", args[0], err)
344 }
345 }
346 },
347 // checkfile checks that a file exists and is not empty.
348 "checkfile": func(ts *testscript.TestScript, neg bool, args []string) {
349 var readonly, exec bool
350 loop:
351 for len(args) > 0 {
352 switch args[0] {
353 case "-readonly":
354 readonly = true
355 args = args[1:]
356 case "-exec":
357 exec = true
358 args = args[1:]
359 default:
360 break loop
361 }
362 }
363 if len(args) == 0 {
364 ts.Fatalf("usage: checkfile [-readonly] [-exec] file...")
365 }
366
367 for _, filename := range args {
368 filename = ts.MkAbs(filename)
369 fi, err := os.Stat(filename)
370 ok := err == nil != neg
371 if !ok {
372 ts.Fatalf("stat %s: %v", filename, err)
373 }
374 if ok && neg {
375 // OK.
376 continue
377 }
378 if fi.Size() == 0 {
379 ts.Fatalf("%s is empty", filename)
380 }
381 if readonly && fi.Mode()&0o222 != 0 {
382 ts.Fatalf("%s is writable", filename)
383 }
384 if exec && runtime.GOOS != "windows" && fi.Mode()&0o111 == 0 {
385 ts.Fatalf("%s is not executable", filename)
386 }
387 }
388 },
389
390 // checkfilecount checks that the number of files in a directory is equal to the given count.
391 "checkfilecount": func(ts *testscript.TestScript, neg bool, args []string) {
392 if len(args) != 2 {
393 ts.Fatalf("usage: checkfilecount count dir")
394 }
395 count, err := strconv.Atoi(args[0])
396 if err != nil {
397 ts.Fatalf("invalid count: %v", err)
398 }
399 if count < 0 {
400 ts.Fatalf("count must be non-negative")
401 }
402 dir := args[1]
403 dir = ts.MkAbs(dir)
404
405 found := 0
406
407 filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
408 if err != nil {
409 return err
410 }
411 if d.IsDir() {
412 return nil
413 }
414 found++
415 return nil
416 })
417
418 ok := found == count != neg
419 if !ok {
420 ts.Fatalf("found %d files, want %d", found, count)
421 }
422 },
423 // waitServer waits for the .ready file to be created by the server.
424 "waitServer": func(ts *testscript.TestScript, neg bool, args []string) {
425 type testInfo struct {
426 BaseURLs []string
427 }
428
429 // The server will write a .ready file when ready.
430 // We wait for that.
431 readyFilename := ts.MkAbs(".ready")
432 limit := time.Now().Add(10 * time.Second)
433 for {
434 _, err := os.Stat(readyFilename)
435 if err != nil {
436 time.Sleep(500 * time.Millisecond)
437 if time.Now().After(limit) {
438 ts.Fatalf("timeout waiting for .ready file")
439 }
440 continue
441 }
442 var info testInfo
443 // Read the .ready file's JSON into info.
444 f, err := os.Open(readyFilename)
445 if err != nil {
446 ts.Fatalf("failed to open .ready file: %v", err)
447 }
448 err = json.NewDecoder(f).Decode(&info)
449 if err != nil {
450 ts.Fatalf("error decoding json: %v", err)
451 }
452 f.Close()
453
454 for i, s := range info.BaseURLs {
455 ts.Setenv(fmt.Sprintf("HUGOTEST_BASEURL_%d", i), s)
456 }
457
458 return
459 }
460 },
461 "stopServer": func(ts *testscript.TestScript, neg bool, args []string) {
462 baseURL := ts.Getenv("HUGOTEST_BASEURL_0")
463 if baseURL == "" {
464 ts.Fatalf("HUGOTEST_BASEURL_0 not set")
465 }
466 if !strings.HasSuffix(baseURL, "/") {
467 baseURL += "/"
468 }
469 resp, err := http.Head(baseURL + "__stop")
470 if err != nil {
471 ts.Fatalf("failed to shutdown server: %v", err)
472 }
473 resp.Body.Close()
474 // Allow some time for the server to shut down.
475 time.Sleep(2 * time.Second)
476 },
477 },
478 }
479
480 func testSetupFunc() func(env *testscript.Env) error {
481 sourceDir, _ := os.Getwd()
482 return func(env *testscript.Env) error {
483 var keyVals []string
484 keyVals = append(keyVals, "HUGO_TESTRUN", "true")
485 keyVals = append(keyVals, "HUGO_CACHEDIR", filepath.Join(env.WorkDir, "hugocache"))
486 xdghome := filepath.Join(env.WorkDir, "xdgcachehome")
487 keyVals = append(keyVals, "XDG_CACHE_HOME", xdghome)
488 home := filepath.Join(env.WorkDir, "home")
489 keyVals = append(keyVals, "HOME", home)
490
491 if runtime.GOOS == "darwin" {
492 if err := os.MkdirAll(filepath.Join(home, "Library", "Caches"), 0o777); err != nil {
493 return err
494 }
495 }
496
497 if runtime.GOOS == "linux" {
498 if err := os.MkdirAll(xdghome, 0o777); err != nil {
499 return err
500 }
501 }
502
503 keyVals = append(keyVals, "SOURCE", sourceDir)
504
505 goVersion := runtime.Version()
506
507 goVersion = strings.TrimPrefix(goVersion, "go")
508 if strings.HasPrefix(goVersion, "1.20") {
509 // Strip patch version.
510 goVersion = goVersion[:strings.LastIndex(goVersion, ".")]
511 }
512
513 goModVersion := goVersion
514 // From Go 1.26.0 on, the version used in go.mod on go mod init is the current version minus one.
515 // This was reverted in Go 1.26.1.
516 if goVersion == "1.26.0" {
517 goModVersion = "1.25.0"
518 }
519
520 keyVals = append(keyVals, "GOVERSION", goVersion)
521 keyVals = append(keyVals, "GOMODVERSION", goModVersion)
522 envhelpers.SetEnvVars(&env.Vars, keyVals...)
523
524 return nil
525 }
526 }