Debian Codegraph @

hugolib/integrationtest_builder.go

raw
1 package hugolib
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "image"
9 "io"
10 "math/rand"
11 "os"
12 "path/filepath"
13 "regexp"
14 "runtime"
15 "sort"
16 "strings"
17 "sync"
18 "testing"
19
20 "github.com/bep/logg"
21 "github.com/yuin/goldmark/util"
22
23 qt "github.com/frankban/quicktest"
24 "github.com/fsnotify/fsnotify"
25 "github.com/gohugoio/hugo/common/herrors"
26 "github.com/gohugoio/hugo/common/hexec"
27 "github.com/gohugoio/hugo/common/himage"
28 "github.com/gohugoio/hugo/common/hmaps"
29 "github.com/gohugoio/hugo/common/loggers"
30 "github.com/gohugoio/hugo/common/types"
31 "github.com/gohugoio/hugo/config"
32 "github.com/gohugoio/hugo/config/allconfig"
33 "github.com/gohugoio/hugo/config/security"
34 "github.com/gohugoio/hugo/deps"
35 "github.com/gohugoio/hugo/helpers"
36 "github.com/gohugoio/hugo/htesting"
37 "github.com/gohugoio/hugo/hugofs"
38 "github.com/gohugoio/hugo/hugofs/hglob"
39 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
40 "github.com/gohugoio/hugo/identity"
41 "github.com/gohugoio/hugo/media"
42 "github.com/spf13/afero"
43 "golang.org/x/text/unicode/norm"
44 "golang.org/x/tools/txtar"
45 )
46
47 type TestOpt func(*IntegrationTestConfig)
48
49 // TestOptRunning will enable running in integration tests.
50 func TestOptRunning() TestOpt {
51 return func(c *IntegrationTestConfig) {
52 c.Running = true
53 }
54 }
55
56 // TestOptWatching will enable watching in integration tests.
57 func TestOptWatching() TestOpt {
58 return func(c *IntegrationTestConfig) {
59 c.Watching = true
60 }
61 }
62
63 // Enable tracing in integration tests.
64 // THis should only be used during development and not committed to the repo.
65 func TestOptTrace() TestOpt {
66 return func(c *IntegrationTestConfig) {
67 c.LogLevel = logg.LevelTrace
68 }
69 }
70
71 // TestOptDebug will enable debug logging in integration tests.
72 func TestOptDebug() TestOpt {
73 return func(c *IntegrationTestConfig) {
74 c.LogLevel = logg.LevelDebug
75 }
76 }
77
78 // TestOptInfo will enable info logging in integration tests.
79 func TestOptInfo() TestOpt {
80 return func(c *IntegrationTestConfig) {
81 c.LogLevel = logg.LevelInfo
82 }
83 }
84
85 // TestOptWarn will enable warn logging in integration tests.
86 func TestOptWarn() TestOpt {
87 return func(c *IntegrationTestConfig) {
88 c.LogLevel = logg.LevelWarn
89 }
90 }
91
92 // TestOptSkipRender will skip the render phase in integration tests.
93 func TestOptSkipRender() TestOpt {
94 return func(c *IntegrationTestConfig) {
95 c.BuildCfg = BuildCfg{
96 SkipRender: true,
97 }
98 }
99 }
100
101 // TestOptOsFs will enable the real file system in integration tests.
102 func TestOptOsFs() TestOpt {
103 return func(c *IntegrationTestConfig) {
104 c.NeedsOsFS = true
105 }
106 }
107
108 // TestOptWithNpmInstall will enable npm install in integration tests.
109 func TestOptWithNpmInstall() TestOpt {
110 return func(c *IntegrationTestConfig) {
111 c.NeedsNpmInstall = true
112 }
113 }
114
115 // TestOptWithNpmInstallGlobal enables global npm package installation in integration tests.
116 // This mutates the host environment and is therefore restricted to real CI.
117 func TestOptWithNpmInstallGlobal(packages ...string) TestOpt {
118 return func(c *IntegrationTestConfig) {
119 c.NeedsNpmGlobalInstall = packages
120 }
121 }
122
123 // TestOptWithNFDOnDarwin will normalize the Unicode filenames to NFD on Darwin.
124 func TestOptWithNFDOnDarwin() TestOpt {
125 return func(c *IntegrationTestConfig) {
126 c.NFDFormOnDarwin = true
127 }
128 }
129
130 // TestOptWithOSFs enables the real file system.
131 func TestOptWithOSFs() TestOpt {
132 return func(c *IntegrationTestConfig) {
133 c.NeedsOsFS = true
134 }
135 }
136
137 func TestOptWithPrintAndKeepTempDir(b bool) TestOpt {
138 return func(c *IntegrationTestConfig) {
139 c.PrintAndKeepTempDir = b
140 }
141 }
142
143 // TestOptWithWorkingDir allows setting any config optiona as a function al option.
144 func TestOptWithConfig(fn func(c *IntegrationTestConfig)) TestOpt {
145 return func(c *IntegrationTestConfig) {
146 fn(c)
147 }
148 }
149
150 // Test is a convenience method to create a new IntegrationTestBuilder from some files and run a build.
151 func Test(t testing.TB, files string, opts ...TestOpt) *IntegrationTestBuilder {
152 cfg := IntegrationTestConfig{T: t, TxtarString: files}
153 for _, o := range opts {
154 o(&cfg)
155 }
156 return NewIntegrationTestBuilder(cfg).Build()
157 }
158
159 // TestE is the same as Test, but returns an error instead of failing the test.
160 func TestE(t testing.TB, files string, opts ...TestOpt) (*IntegrationTestBuilder, error) {
161 cfg := IntegrationTestConfig{T: t, TxtarString: files}
162 for _, o := range opts {
163 o(&cfg)
164 }
165 return NewIntegrationTestBuilder(cfg).BuildE()
166 }
167
168 // TestRunning is a convenience method to create a new IntegrationTestBuilder from some files with Running set to true and run a build.
169 // Deprecated: Use Test with TestOptRunning instead.
170 func TestRunning(t testing.TB, files string, opts ...TestOpt) *IntegrationTestBuilder {
171 cfg := IntegrationTestConfig{T: t, TxtarString: files, Running: true}
172 for _, o := range opts {
173 o(&cfg)
174 }
175 return NewIntegrationTestBuilder(cfg).Build()
176 }
177
178 // In most cases you should not use this function directly, but the Test or TestRunning function.
179 func NewIntegrationTestBuilder(conf IntegrationTestConfig) *IntegrationTestBuilder {
180 // Code fences.
181 conf.TxtarString = strings.ReplaceAll(conf.TxtarString, "§§§", "```")
182 // Multiline strings.
183 conf.TxtarString = strings.ReplaceAll(conf.TxtarString, "§§", "`")
184
185 data := txtar.Parse([]byte(conf.TxtarString))
186
187 if conf.FileContentPrefix != "" {
188 for i, f := range data.Files {
189 data.Files[i].Data = append([]byte(conf.FileContentPrefix), f.Data...)
190 }
191 }
192
193 if conf.NFDFormOnDarwin {
194 for i, f := range data.Files {
195 data.Files[i].Name = norm.NFD.String(f.Name)
196 }
197 }
198
199 c, ok := conf.T.(*qt.C)
200 if !ok {
201 c = qt.New(conf.T)
202 }
203
204 if conf.NeedsOsFS {
205 if !filepath.IsAbs(conf.WorkingDir) {
206 tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
207 c.Assert(err, qt.IsNil)
208 conf.WorkingDir = filepath.Join(tempDir, conf.WorkingDir)
209 if !conf.PrintAndKeepTempDir {
210 c.Cleanup(clean)
211 } else {
212 fmt.Println("\nUsing WorkingDir dir:", conf.WorkingDir)
213 }
214 }
215 } else if conf.WorkingDir == "" {
216 conf.WorkingDir = helpers.FilePathSeparator
217 }
218
219 return &IntegrationTestBuilder{
220 Cfg: conf,
221 C: c,
222 data: data,
223 }
224 }
225
226 // IntegrationTestBuilder is a (partial) rewrite of sitesBuilder.
227 // The main problem with the "old" one was that it was that the test data was often a little hidden,
228 // so it became hard to look at a test and determine what it should do, especially coming back to the
229 // test after a year or so.
230 type IntegrationTestBuilder struct {
231 *qt.C
232
233 data *txtar.Archive
234
235 fs *hugofs.Fs
236 H *HugoSites
237
238 Cfg IntegrationTestConfig
239
240 changedFiles []string
241 createdFiles []string
242 removedFiles []string
243 renamedFiles []string
244 atomicSavedFiles []string
245 renamedDirs []string
246
247 buildCount int
248 GCCount int
249 counters *buildCounters
250 logBuff lockingBuffer
251 lastBuildLog string
252
253 builderInit sync.Once
254 }
255
256 type IntegrationTestSiteHelper struct {
257 *qt.C
258 b *IntegrationTestBuilder
259 S *Site
260 }
261
262 type IntegrationTestPageHelper struct {
263 *qt.C
264 b *IntegrationTestBuilder
265 p *pageState
266 }
267
268 func (s *IntegrationTestPageHelper) siteIntsToMap(matrix, complements sitesmatrix.VectorStore) map[string]map[string][]string {
269 dconf := s.p.s.Conf.ConfiguredDimensions()
270 intSetsToMap := func(intSets sitesmatrix.VectorStore) map[string][]string {
271 var languages, versions, roles []string
272
273 keys1, keys2, keys3 := intSets.KeysSorted()
274
275 for _, v := range keys1 {
276 languages = append(languages, dconf.ConfiguredLanguages.ResolveName(v))
277 }
278 for _, v := range keys2 {
279 versions = append(versions, dconf.ConfiguredVersions.ResolveName(v))
280 }
281 for _, v := range keys3 {
282 roles = append(roles, dconf.ConfiguredRoles.ResolveName(v))
283 }
284
285 return map[string][]string{
286 "languages": languages,
287 "versions": versions,
288 "roles": roles,
289 }
290 }
291
292 return map[string]map[string][]string{
293 "matrix": intSetsToMap(matrix),
294 "complements": intSetsToMap(complements),
295 }
296 }
297
298 func (s *IntegrationTestPageHelper) MatrixFromPageConfig() map[string]map[string][]string {
299 pc := s.p.m.pageConfigSource
300 return s.siteIntsToMap(pc.SitesMatrix, pc.SitesComplements)
301 }
302
303 func (s *IntegrationTestPageHelper) MatrixFromFile() map[string]map[string][]string {
304 if s.p.m.f == nil {
305 return nil
306 }
307 m := s.p.m.f.FileInfo().Meta()
308 return s.siteIntsToMap(m.SitesMatrix, m.SitesComplements)
309 }
310
311 func (s *IntegrationTestSiteHelper) PageHelper(path string) *IntegrationTestPageHelper {
312 p, err := s.S.GetPage(path)
313 s.Assert(err, qt.IsNil)
314 s.Assert(p, qt.Not(qt.IsNil), qt.Commentf("Page not found: %s", path))
315 ps, ok := p.(*pageState)
316 s.Assert(ok, qt.IsTrue, qt.Commentf("Expected pageState, got %T", p))
317 return &IntegrationTestPageHelper{
318 C: s.C,
319 b: s.b,
320 p: ps,
321 }
322 }
323
324 func (s *IntegrationTestSiteHelper) DimensionNames() types.Strings3 {
325 return types.Strings3{
326 s.S.Language().Name(),
327 s.S.Version().Name(),
328 s.S.Role().Name(),
329 }
330 }
331
332 type lockingBuffer struct {
333 sync.Mutex
334 buf bytes.Buffer
335 }
336
337 func (b *lockingBuffer) String() string {
338 b.Lock()
339 defer b.Unlock()
340 return b.buf.String()
341 }
342
343 func (b *lockingBuffer) Reset() {
344 b.Lock()
345 defer b.Unlock()
346 b.buf.Reset()
347 }
348
349 func (b *lockingBuffer) ReadFrom(r io.Reader) (n int64, err error) {
350 b.Lock()
351 n, err = b.buf.ReadFrom(r)
352 b.Unlock()
353 return
354 }
355
356 func (b *lockingBuffer) Write(p []byte) (n int, err error) {
357 b.Lock()
358 n, err = b.buf.Write(p)
359 b.Unlock()
360 return
361 }
362
363 // SiteHelper returns a helper for the given language, version and role.
364 // Note that a blank value for an argument will use the default value for that dimension.
365 func (s *IntegrationTestBuilder) SiteHelper(language, version, role string) *IntegrationTestSiteHelper {
366 s.Helper()
367 if s.H == nil {
368 s.Fatal("SiteHelper: no sites available")
369 }
370 v := s.H.Conf.ConfiguredDimensions().ResolveVector(types.Strings3{language, version, role})
371 site, found := s.H.sitesVersionsRolesMap[v]
372 if !found {
373 s.Fatalf("SiteHelper: no site found for vector %v", v)
374 }
375
376 return &IntegrationTestSiteHelper{
377 C: s.C,
378 b: s,
379 S: site,
380 }
381 }
382
383 // AssertLogContains asserts that the last build log contains the given strings.
384 // Each string can be negated with a hglob.NegationPrefix prefix.
385 func (s *IntegrationTestBuilder) AssertLogContains(els ...string) {
386 s.Helper()
387 for _, el := range els {
388 var negate bool
389 el, negate = s.negate(el)
390 check := qt.Contains
391 if negate {
392 check = qt.Not(qt.Contains)
393 }
394 s.Assert(s.lastBuildLog, check, el)
395 }
396 }
397
398 // AssertLogMatches asserts that the last build log matches the given regular expressions.
399 // The regular expressions can be negated with a hglob.NegationPrefix prefix.
400 func (s *IntegrationTestBuilder) AssertLogMatches(expression string) {
401 s.Helper()
402 var negate bool
403 expression, negate = s.negate(expression)
404 re := regexp.MustCompile(expression)
405 checker := qt.IsTrue
406 if negate {
407 checker = qt.IsFalse
408 }
409
410 s.Assert(re.MatchString(s.lastBuildLog), checker, qt.Commentf(s.lastBuildLog))
411 }
412
413 func (s *IntegrationTestBuilder) AssertFileCount(dirname string, expected int) {
414 s.Helper()
415 fs := s.fs.WorkingDirReadOnly
416 count := 0
417 afero.Walk(fs, dirname, func(path string, info os.FileInfo, err error) error {
418 if err != nil {
419 return err
420 }
421 if info.IsDir() {
422 return nil
423 }
424 count++
425 return nil
426 })
427 s.Assert(count, qt.Equals, expected)
428 }
429
430 func (s *IntegrationTestBuilder) negate(match string) (string, bool) {
431 var negate bool
432 if strings.HasPrefix(match, hglob.NegationPrefix) {
433 negate = true
434 match = strings.TrimPrefix(match, hglob.NegationPrefix)
435 }
436 return match, negate
437 }
438
439 // AssertFileContentStartsWith asserts that the content of the given file starts with s.
440 func (s *IntegrationTestBuilder) AssertFileContentStartsWith(filename, prefix string) {
441 s.Helper()
442 content := strings.TrimSpace(s.FileContent(filename))
443 cm := qt.Commentf("File: %s Expect:\n%s Got:\n%s\nWith Space Visuals:\n%s", filename, prefix, content, util.VisualizeSpaces([]byte(content)))
444 var negate bool
445 prefix, negate = s.negate(prefix)
446 s.Assert(strings.HasPrefix(content, prefix), qt.Equals, !negate, cm)
447 }
448
449 func (s *IntegrationTestBuilder) AssertFileContent(filename string, matches ...string) {
450 s.Helper()
451 content := strings.TrimSpace(s.FileContent(filename))
452
453 for _, m := range matches {
454 cm := qt.Commentf("File: %s Expect:\n%s Got:\n%s\nWith Space Visuals:\n%s", filename, m, content, util.VisualizeSpaces([]byte(content)))
455 lines := strings.SplitSeq(m, "\n")
456 for match := range lines {
457 match = strings.TrimSpace(match)
458 if match == "" || strings.HasPrefix(match, "#") {
459 continue
460 }
461 var negate bool
462 match, negate = s.negate(match)
463 if negate {
464 s.Assert(content, qt.Not(qt.Contains), match, cm)
465 continue
466 }
467 s.Assert(content, qt.Contains, match, cm)
468 }
469 }
470 }
471
472 func (s *IntegrationTestBuilder) AssertFileContentEquals(filename string, match string) {
473 s.Helper()
474 content := s.FileContent(filename)
475 s.Assert(content, qt.Equals, match, qt.Commentf(match))
476 }
477
478 func (s *IntegrationTestBuilder) AssertFileContentExact(filename string, matches ...string) {
479 s.Helper()
480 content := s.FileContent(filename)
481 for _, m := range matches {
482 cm := qt.Commentf("File: %s Match %s\nContent:\n%s", filename, m, content)
483 s.Assert(content, qt.Contains, m, cm)
484 }
485 }
486
487 func (s *IntegrationTestBuilder) AssertNoRenderShortcodesArtifacts() {
488 s.Helper()
489 s.AssertStringPublished("! __hugo_ctx")
490 }
491
492 func (s *IntegrationTestBuilder) AssertStringPublished(match string) {
493 s.Helper()
494 var negate bool
495 match, negate = s.negate(match)
496 afero.Walk(s.fs.PublishDir, "", func(path string, info os.FileInfo, err error) error {
497 if err != nil || info.IsDir() {
498 return err
499 }
500 ext := strings.TrimPrefix(filepath.Ext(path), ".")
501 if !s.H.Conf.GetConfigSection("mediaTypes").(media.Types).IsTextSuffix(ext) {
502 return nil
503 }
504 content, err := afero.ReadFile(s.fs.PublishDir, path)
505 s.Assert(err, qt.IsNil)
506 comment := qt.Commentf("File: %s\n%s", path, string(content))
507 s.Assert(strings.Contains(string(content), match), qt.Equals, !negate, comment)
508 return nil
509 })
510 }
511
512 type IntegrationTestImageHelper struct {
513 *qt.C
514 b *IntegrationTestBuilder
515
516 img image.Image
517 formatName string
518 congig image.Config
519 }
520
521 func (h *IntegrationTestImageHelper) AssertFormat(formatName string) *IntegrationTestImageHelper {
522 h.Assert(h.formatName, qt.Equals, formatName, qt.Commentf("Expected format %q, got %q", formatName, h.formatName))
523 return h
524 }
525
526 func (h *IntegrationTestImageHelper) AssertFrameDurations(expect []int) *IntegrationTestImageHelper {
527 anim, ok := h.img.(himage.AnimatedImage)
528 h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated"))
529 h.Assert(anim.GetFrameDurations(), qt.DeepEquals, expect, qt.Commentf("Frame durations do not match"))
530 return h
531 }
532
533 func (h *IntegrationTestImageHelper) AssertLoopCount(expect int) *IntegrationTestImageHelper {
534 anim, ok := h.img.(himage.AnimatedImage)
535 h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated"))
536 h.Assert(anim.GetLoopCount(), qt.Equals, expect, qt.Commentf("Loop count does not match"))
537 return h
538 }
539
540 func (h *IntegrationTestImageHelper) AssertIsAnimated(b bool) *IntegrationTestImageHelper {
541 _, ok := h.img.(himage.AnimatedImage)
542 if b {
543 h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated"))
544 return h
545 }
546 h.Assert(ok, qt.IsFalse, qt.Commentf("Image is animated"))
547 return h
548 }
549
550 func (s *IntegrationTestBuilder) ImageHelper(filename string) *IntegrationTestImageHelper {
551 filename = filepath.Clean(filename)
552 fs := s.fs.WorkingDirReadOnly
553 b, err := afero.ReadFile(fs, filename)
554 s.Assert(err, qt.IsNil)
555 conf, format, err := s.H.ResourceSpec.Imaging.Codec.DecodeConfig(0, bytes.NewReader(b))
556 s.Assert(err, qt.IsNil)
557 img, err := s.H.ResourceSpec.Imaging.Codec.Decode(bytes.NewReader(b))
558 s.Assert(err, qt.IsNil)
559
560 return &IntegrationTestImageHelper{
561 C: s.C,
562 b: s,
563 img: img,
564 formatName: format,
565 congig: conf,
566 }
567 }
568
569 func (s *IntegrationTestBuilder) AssertPublishDir(matches ...string) {
570 s.AssertFs(s.fs.PublishDir, matches...)
571 }
572
573 func (s *IntegrationTestBuilder) AssertFs(fs afero.Fs, matches ...string) {
574 s.Helper()
575 var buff bytes.Buffer
576 if err := s.printAndCheckFs(fs, "", &buff); err != nil {
577 // E.g. public not created, treat that as an empty dir.
578 if !errors.Is(err, os.ErrNotExist) {
579 s.Fatal(err)
580 }
581 }
582 printFsLines := strings.Split(buff.String(), "\n")
583 sort.Strings(printFsLines)
584 content := strings.TrimSpace(strings.Join(printFsLines, "\n"))
585 for _, m := range matches {
586 cm := qt.Commentf("Match: %q\nIn:\n%s", m, content)
587 lines := strings.SplitSeq(m, "\n")
588 for match := range lines {
589 match = strings.TrimSpace(match)
590 var negate bool
591 if strings.HasPrefix(match, hglob.NegationPrefix) {
592 negate = true
593 match = strings.TrimPrefix(match, hglob.NegationPrefix)
594 }
595 if negate {
596 s.Assert(content, qt.Not(qt.Contains), match, cm)
597 continue
598 }
599 s.Assert(content, qt.Contains, match, cm)
600 }
601 }
602 }
603
604 func (s *IntegrationTestBuilder) printAndCheckFs(fs afero.Fs, path string, w io.Writer) error {
605 if fs == nil {
606 return nil
607 }
608
609 return afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
610 if err != nil {
611 return err
612 }
613 path = filepath.ToSlash(path)
614 if path == "" {
615 path = "."
616 }
617 var size int64
618 if !info.IsDir() {
619 size = info.Size()
620 f, err := fs.Open(path)
621 if err != nil {
622 return fmt.Errorf("error: path %q: %s", path, err)
623 }
624 defer f.Close()
625 // This will panic if the file is a directory.
626 var buf [1]byte
627 io.ReadFull(f, buf[:])
628 }
629 fmt.Fprintf(w, "%06d %s %t\n", size, path, info.IsDir())
630 return nil
631 })
632 }
633
634 func (s *IntegrationTestBuilder) AssertFileExists(filename string, b bool) {
635 checker := qt.IsNil
636 if !b {
637 checker = qt.IsNotNil
638 }
639
640 _, err := s.fs.WorkingDirReadOnly.Stat(filename)
641 if err != nil && !herrors.IsNotExist(err) {
642 s.Assert(err, qt.IsNil)
643 return
644 }
645 s.Assert(err, checker)
646 }
647
648 func (s *IntegrationTestBuilder) AssertRenderCountContent(count int) {
649 s.Helper()
650 s.Assert(s.counters.contentRenderCounter.Load(), qt.Equals, uint64(count))
651 }
652
653 func (s *IntegrationTestBuilder) AssertRenderCountPage(count int) {
654 s.Helper()
655 s.Assert(s.counters.pageRenderCounter.Load(), qt.Equals, uint64(count))
656 }
657
658 func (s *IntegrationTestBuilder) AssertRenderCountPageBetween(from, to int) {
659 s.Helper()
660 i := int(s.counters.pageRenderCounter.Load())
661 s.Assert(i >= from && i <= to, qt.IsTrue)
662 }
663
664 func (s *IntegrationTestBuilder) Build() *IntegrationTestBuilder {
665 s.Helper()
666 _, err := s.BuildE()
667
668 if err != nil && strings.Contains(err.Error(), "error(s)") {
669 err = fmt.Errorf("%w: %s", err, s.lastBuildLog)
670 }
671
672 if s.Cfg.Verbose || err != nil {
673 if s.H != nil && err == nil {
674 for s := range s.H.allSites(nil) {
675 m := s.pageMap
676 var buff bytes.Buffer
677 fmt.Fprintf(&buff, "======= PageMap for site %q =======\n\n", s.resolveDimensionNames())
678 m.debugPrint("", 999, &buff)
679 fmt.Println(buff.String())
680 }
681 }
682 } else if s.Cfg.LogLevel <= logg.LevelDebug {
683 fmt.Println(s.lastBuildLog)
684 }
685 s.Assert(err, qt.IsNil)
686 if s.Cfg.RunGC {
687 s.GCCount, err = s.H.GC()
688 s.Assert(err, qt.IsNil)
689 }
690
691 s.Cleanup(func() {
692 if h := s.H; h != nil {
693 s.Assert(h.Close(), qt.IsNil)
694 }
695 })
696
697 return s
698 }
699
700 func (s *IntegrationTestBuilder) BuildPartial(urls ...string) *IntegrationTestBuilder {
701 if _, err := s.BuildPartialE(urls...); err != nil {
702 s.Fatal(err)
703 }
704 return s
705 }
706
707 func (s *IntegrationTestBuilder) BuildPartialE(urls ...string) (*IntegrationTestBuilder, error) {
708 if s.buildCount == 0 {
709 panic("BuildPartial can only be used after a full build")
710 }
711 if !s.Cfg.Running {
712 panic("BuildPartial can only be used in server mode")
713 }
714 visited := types.NewEvictingQueue[string](len(urls))
715 for _, url := range urls {
716 visited.Add(url)
717 }
718 buildCfg := BuildCfg{RecentlyTouched: visited, PartialReRender: true}
719 return s, s.build(buildCfg)
720 }
721
722 func (s *IntegrationTestBuilder) Close() {
723 s.Helper()
724 s.Assert(s.H.Close(), qt.IsNil)
725 }
726
727 func (s *IntegrationTestBuilder) LogString() string {
728 return s.lastBuildLog
729 }
730
731 func (s *IntegrationTestBuilder) BuildE() (*IntegrationTestBuilder, error) {
732 s.Helper()
733 if err := s.initBuilder(); err != nil {
734 return s, err
735 }
736
737 err := s.build(s.Cfg.BuildCfg)
738 return s, err
739 }
740
741 func (s *IntegrationTestBuilder) Init() *IntegrationTestBuilder {
742 if err := s.initBuilder(); err != nil {
743 s.Fatalf("Failed to init builder: %s", err)
744 }
745 s.lastBuildLog = s.logBuff.String()
746 return s
747 }
748
749 type IntegrationTestDebugConfig struct {
750 Out io.Writer
751
752 PrintDestinationFs bool
753 PrintPagemap bool
754
755 PrefixDestinationFs string
756 PrefixPagemap string
757 }
758
759 func (s *IntegrationTestBuilder) EditFileReplaceAll(filename, old, new string) *IntegrationTestBuilder {
760 return s.EditFileReplaceFunc(filename, func(s string) string {
761 return strings.ReplaceAll(s, old, new)
762 })
763 }
764
765 // EditFileAtomicReplaceAll edits a file and simulates an editor atomic save by
766 // emitting a fsnotify.Remove event for an existing path (see changeEvents).
767 func (s *IntegrationTestBuilder) EditFileAtomicReplaceAll(filename, old, new string) *IntegrationTestBuilder {
768 return s.EditFileAtomicReplaceFunc(filename, func(s string) string {
769 return strings.ReplaceAll(s, old, new)
770 })
771 }
772
773 func (s *IntegrationTestBuilder) EditFileReplaceFunc(filename string, replacementFunc func(s string) string) *IntegrationTestBuilder {
774 absFilename := s.absFilename(filename)
775 b, err := afero.ReadFile(s.fs.Source, absFilename)
776 s.Assert(err, qt.IsNil)
777 s.changedFiles = append(s.changedFiles, absFilename)
778 oldContent := string(b)
779 s.writeSource(absFilename, replacementFunc(oldContent))
780 return s
781 }
782
783 func (s *IntegrationTestBuilder) EditFileAtomicReplaceFunc(filename string, replacementFunc func(s string) string) *IntegrationTestBuilder {
784 absFilename := s.absFilename(filename)
785 b, err := afero.ReadFile(s.fs.Source, absFilename)
786 s.Assert(err, qt.IsNil)
787 s.atomicSavedFiles = append(s.atomicSavedFiles, absFilename)
788 oldContent := string(b)
789 s.writeSource(absFilename, replacementFunc(oldContent))
790 return s
791 }
792
793 func (s *IntegrationTestBuilder) EditFileAppend(filename, contnt string) *IntegrationTestBuilder {
794 absFilename := s.absFilename(filename)
795 b, err := afero.ReadFile(s.fs.Source, absFilename)
796 s.Assert(err, qt.IsNil)
797 s.changedFiles = append(s.changedFiles, absFilename)
798 oldContent := string(b)
799 s.writeSource(absFilename, oldContent+contnt)
800 return s
801 }
802
803 func (s *IntegrationTestBuilder) EditFiles(filenameContent ...string) *IntegrationTestBuilder {
804 for i := 0; i < len(filenameContent); i += 2 {
805 filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1]
806 absFilename := s.absFilename(filename)
807 s.changedFiles = append(s.changedFiles, absFilename)
808 s.writeSource(absFilename, content)
809 }
810 return s
811 }
812
813 func (s *IntegrationTestBuilder) AddFiles(filenameContent ...string) *IntegrationTestBuilder {
814 for i := 0; i < len(filenameContent); i += 2 {
815 filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1]
816 absFilename := s.absFilename(filename)
817 s.createdFiles = append(s.createdFiles, absFilename)
818 s.writeSource(absFilename, content)
819 }
820 return s
821 }
822
823 func (s *IntegrationTestBuilder) CreateDirs(dirnames ...string) *IntegrationTestBuilder {
824 for _, dirname := range dirnames {
825 absDir := s.absFilename(filepath.FromSlash(dirname))
826 s.Assert(s.fs.Source.MkdirAll(absDir, 0o777), qt.IsNil)
827 s.createdFiles = append(s.createdFiles, absDir)
828 }
829 return s
830 }
831
832 func (s *IntegrationTestBuilder) RemoveFiles(filenames ...string) *IntegrationTestBuilder {
833 for _, filename := range filenames {
834 absFilename := s.absFilename(filename)
835 s.removedFiles = append(s.removedFiles, absFilename)
836 s.Assert(s.fs.Source.Remove(absFilename), qt.IsNil)
837
838 }
839
840 return s
841 }
842
843 func (s *IntegrationTestBuilder) RemovePublishDir() *IntegrationTestBuilder {
844 s.Helper()
845 if err := s.fs.PublishDir.RemoveAll(""); err != nil && !herrors.IsNotExist(err) {
846 s.Fatalf("Failed to remove publish dir: %s", err)
847 }
848
849 return s
850 }
851
852 func (s *IntegrationTestBuilder) RenameFile(old, new string) *IntegrationTestBuilder {
853 absOldFilename := s.absFilename(old)
854 absNewFilename := s.absFilename(new)
855 s.renamedFiles = append(s.renamedFiles, absOldFilename)
856 s.createdFiles = append(s.createdFiles, absNewFilename)
857 s.Assert(s.fs.Source.MkdirAll(filepath.Dir(absNewFilename), 0o777), qt.IsNil)
858 s.Assert(s.fs.Source.Rename(absOldFilename, absNewFilename), qt.IsNil)
859 return s
860 }
861
862 func (s *IntegrationTestBuilder) RenameDir(old, new string) *IntegrationTestBuilder {
863 absOldFilename := s.absFilename(old)
864 absNewFilename := s.absFilename(new)
865 s.renamedDirs = append(s.renamedDirs, absOldFilename)
866 s.changedFiles = append(s.changedFiles, absNewFilename)
867 afero.Walk(s.fs.Source, absOldFilename, func(path string, info os.FileInfo, err error) error {
868 if err != nil {
869 return err
870 }
871 if info.IsDir() {
872 return nil
873 }
874 s.createdFiles = append(s.createdFiles, strings.Replace(path, absOldFilename, absNewFilename, 1))
875 return nil
876 })
877 s.Assert(s.fs.Source.MkdirAll(filepath.Dir(absNewFilename), 0o777), qt.IsNil)
878 s.Assert(s.fs.Source.Rename(absOldFilename, absNewFilename), qt.IsNil)
879 return s
880 }
881
882 func (s *IntegrationTestBuilder) FileContent(filename string) string {
883 s.Helper()
884 return s.readWorkingDir(s, s.fs, filepath.FromSlash(filename))
885 }
886
887 func (s *IntegrationTestBuilder) initBuilder() error {
888 var initErr error
889 s.builderInit.Do(func() {
890 var afs afero.Fs
891 if s.Cfg.NeedsOsFS {
892 afs = afero.NewOsFs()
893 } else {
894 afs = afero.NewMemMapFs()
895 }
896
897 if s.Cfg.LogLevel == 0 {
898 s.Cfg.LogLevel = logg.LevelError
899 }
900
901 isBinaryRe := regexp.MustCompile(`^(.*)(\.png|\.jpg)$`)
902
903 const dataSourceFilenamePrefix = "sourcefilename:"
904
905 for _, f := range s.data.Files {
906 filename := filepath.Join(s.Cfg.WorkingDir, f.Name)
907 data := bytes.TrimSuffix(f.Data, []byte("\n"))
908 datastr := strings.TrimSpace(string(data))
909 if strings.HasPrefix(datastr, dataSourceFilenamePrefix) {
910 // Read from file relative to the current dir.
911 var err error
912 wd, _ := os.Getwd()
913 filename := filepath.Join(wd, strings.TrimSpace(strings.TrimPrefix(datastr, dataSourceFilenamePrefix)))
914 data, err = os.ReadFile(filename)
915 s.Assert(err, qt.IsNil)
916 } else if isBinaryRe.MatchString(filename) {
917 var err error
918 data, err = base64.StdEncoding.DecodeString(string(data))
919 s.Assert(err, qt.IsNil)
920
921 }
922 s.Assert(afs.MkdirAll(filepath.Dir(filename), 0o777), qt.IsNil)
923 s.Assert(afero.WriteFile(afs, filename, data, 0o666), qt.IsNil)
924 }
925
926 configDir := "config"
927 if _, err := afs.Stat(filepath.Join(s.Cfg.WorkingDir, "config")); err != nil {
928 configDir = ""
929 }
930
931 var flags config.Provider
932 if s.Cfg.BaseCfg != nil {
933 flags = s.Cfg.BaseCfg
934 } else {
935 flags = config.New()
936 }
937
938 if s.Cfg.Running {
939 flags.Set("internal", hmaps.Params{
940 "running": s.Cfg.Running,
941 "watch": s.Cfg.Running,
942 "fastRenderMode": s.Cfg.FastRenderMode,
943 })
944 } else if s.Cfg.Watching {
945 flags.Set("internal", hmaps.Params{
946 "watch": s.Cfg.Watching,
947 })
948 }
949
950 if s.Cfg.WorkingDir != "" {
951 flags.Set("workingDir", s.Cfg.WorkingDir)
952 }
953
954 var w io.Writer
955 if s.Cfg.Verbose || s.Cfg.LogLevel == logg.LevelTrace {
956 w = io.MultiWriter(os.Stdout, &s.logBuff)
957 } else {
958 w = &s.logBuff
959 }
960
961 var logHookLast func(e *logg.Entry) error
962 if s.Cfg.PanicOnWarning {
963 logHookLast = loggers.PanicOnWarningHook
964 }
965
966 logger := loggers.New(
967 loggers.Options{
968 StdOut: w,
969 StdErr: w,
970 Level: s.Cfg.LogLevel,
971 DistinctLevel: logg.LevelWarn,
972 HandlerPost: logHookLast,
973 },
974 )
975
976 res, err := allconfig.LoadConfig(
977 allconfig.ConfigSourceDescriptor{
978 Flags: flags,
979 ConfigDir: configDir,
980 Fs: afs,
981 Logger: logger,
982 Environ: s.Cfg.Environ,
983 },
984 )
985 if err != nil {
986 initErr = err
987 return
988 }
989
990 fs := hugofs.NewFrom(afs, res.LoadingInfo.BaseConfig)
991
992 s.Assert(err, qt.IsNil)
993
994 // changes received from Hugo in watch mode.
995 // In the full setup, this channel is created in the commands package.
996 changesFromBuild := make(chan []identity.Identity, 10)
997
998 depsCfg := deps.DepsCfg{Configs: res, Fs: fs, LogLevel: logger.Level(), StdErr: logger.StdErr(), ChangesFromBuild: changesFromBuild, IsIntegrationTest: true, TestCfg: deps.TestConfig{WarpcMemory: s.Cfg.WarpcMemory}}
999 sites, err := NewHugoSites(depsCfg)
1000 if err != nil {
1001 initErr = err
1002 return
1003 }
1004 if sites == nil {
1005 initErr = errors.New("no sites")
1006 return
1007 }
1008
1009 go func() {
1010 for id := range changesFromBuild {
1011 whatChanged := &WhatChanged{}
1012 for _, v := range id {
1013 whatChanged.Add(v)
1014 }
1015 bcfg := s.Cfg.BuildCfg
1016 bcfg.WhatChanged = whatChanged
1017 if err := s.build(bcfg); err != nil {
1018 s.Fatalf("Build failed after change: %s", err)
1019 }
1020 }
1021 }()
1022
1023 s.H = sites
1024 s.fs = fs
1025
1026 if s.Cfg.NeedsNpmInstall || len(s.Cfg.NeedsNpmGlobalInstall) > 0 {
1027 if s.Cfg.NeedsNpmInstall {
1028 wd, _ := os.Getwd()
1029 s.Assert(os.Chdir(s.Cfg.WorkingDir), qt.IsNil)
1030 s.C.Cleanup(func() { os.Chdir(wd) })
1031 }
1032 sc := security.DefaultConfig
1033 sc.Exec.Allow, err = security.NewWhitelist("npm")
1034 s.Assert(err, qt.IsNil)
1035 ex := hexec.New(sc, s.Cfg.WorkingDir, loggers.NewDefault())
1036
1037 if len(s.Cfg.NeedsNpmGlobalInstall) > 0 {
1038 if !htesting.IsRealCI() && !htesting.IsGitHubAction() {
1039 panic("NeedsNpmGlobalInstall is restricted to real CI because it performs global npm installs")
1040 }
1041 for _, pkg := range s.Cfg.NeedsNpmGlobalInstall {
1042 command, err := ex.New("npm", "install", "-g", pkg)
1043 s.Assert(err, qt.IsNil)
1044 s.Assert(command.Run(), qt.IsNil)
1045
1046 }
1047 s.C.Cleanup(func() {
1048 for _, pkg := range s.Cfg.NeedsNpmGlobalInstall {
1049 ex.New("npm", "uninstall", "-g", pkg)
1050 }
1051 })
1052 } else {
1053 command, err := ex.New("npm", "install")
1054 s.Assert(err, qt.IsNil)
1055 s.Assert(command.Run(), qt.IsNil)
1056 }
1057 }
1058 })
1059
1060 return initErr
1061 }
1062
1063 func (s *IntegrationTestBuilder) absFilename(filename string) string {
1064 filename = filepath.FromSlash(filename)
1065 if filepath.IsAbs(filename) {
1066 return filename
1067 }
1068 if s.Cfg.WorkingDir != "" && !strings.HasPrefix(filename, s.Cfg.WorkingDir) {
1069 filename = filepath.Join(s.Cfg.WorkingDir, filename)
1070 }
1071 return filename
1072 }
1073
1074 func (s *IntegrationTestBuilder) reset() {
1075 s.changedFiles = nil
1076 s.createdFiles = nil
1077 s.removedFiles = nil
1078 s.renamedFiles = nil
1079 s.atomicSavedFiles = nil
1080 }
1081
1082 func (s *IntegrationTestBuilder) build(cfg BuildCfg) error {
1083 s.Helper()
1084 defer func() {
1085 s.reset()
1086 s.lastBuildLog = s.logBuff.String()
1087 s.logBuff.Reset()
1088 }()
1089
1090 changeEvents := s.changeEvents()
1091 s.counters = &buildCounters{}
1092 cfg.testCounters = s.counters
1093
1094 s.buildCount++
1095
1096 err := s.H.Build(cfg, changeEvents...)
1097 if err != nil {
1098 return err
1099 }
1100
1101 return nil
1102 }
1103
1104 // We simulate the fsnotify events.
1105 // See the test output in https://github.com/bep/fsnotifyeventlister for what events gets produced
1106 // by the different OSes.
1107 func (s *IntegrationTestBuilder) changeEvents() []fsnotify.Event {
1108 var (
1109 events []fsnotify.Event
1110 isLinux = runtime.GOOS == "linux"
1111 isMacOs = runtime.GOOS == "darwin"
1112 isWindows = runtime.GOOS == "windows"
1113 )
1114
1115 for _, v := range s.removedFiles {
1116 events = append(events, fsnotify.Event{
1117 Name: v,
1118 Op: fsnotify.Remove,
1119 })
1120 }
1121 for _, v := range s.renamedFiles {
1122 events = append(events, fsnotify.Event{
1123 Name: v,
1124 Op: fsnotify.Rename,
1125 })
1126 }
1127
1128 for _, v := range s.atomicSavedFiles {
1129 events = append(events, fsnotify.Event{
1130 Name: v,
1131 // The watcher was watching the inode that got replaced by the rename,
1132 // so we get a Remove for a file that's still on disk.
1133 Op: fsnotify.Remove,
1134 })
1135 }
1136
1137 for _, v := range s.renamedDirs {
1138 events = append(events, fsnotify.Event{
1139 Name: v,
1140 // This is what we get on MacOS.
1141 Op: fsnotify.Remove | fsnotify.Rename,
1142 })
1143 }
1144
1145 for _, v := range s.changedFiles {
1146 events = append(events, fsnotify.Event{
1147 Name: v,
1148 Op: fsnotify.Write,
1149 })
1150 if isLinux || isWindows {
1151 // Duplicate write events, for some reason.
1152 events = append(events, fsnotify.Event{
1153 Name: v,
1154 Op: fsnotify.Write,
1155 })
1156 }
1157 if isMacOs {
1158 events = append(events, fsnotify.Event{
1159 Name: v,
1160 Op: fsnotify.Chmod,
1161 })
1162 }
1163 }
1164 for _, v := range s.createdFiles {
1165 events = append(events, fsnotify.Event{
1166 Name: v,
1167 Op: fsnotify.Create,
1168 })
1169 if isLinux || isWindows {
1170 events = append(events, fsnotify.Event{
1171 Name: v,
1172 Op: fsnotify.Write,
1173 })
1174 }
1175
1176 }
1177
1178 // Shuffle events.
1179 for i := range events {
1180 j := rand.Intn(i + 1)
1181 events[i], events[j] = events[j], events[i]
1182 }
1183
1184 return events
1185 }
1186
1187 func (s *IntegrationTestBuilder) readWorkingDir(t testing.TB, fs *hugofs.Fs, filename string) string {
1188 t.Helper()
1189 return s.readFileFromFs(t, fs.WorkingDirReadOnly, filename)
1190 }
1191
1192 func (s *IntegrationTestBuilder) readFileFromFs(t testing.TB, fs afero.Fs, filename string) string {
1193 t.Helper()
1194 filename = filepath.Clean(filename)
1195 b, err := afero.ReadFile(fs, filename)
1196 s.Assert(err, qt.IsNil)
1197 return string(b)
1198 }
1199
1200 func (s *IntegrationTestBuilder) writeSource(filename, content string) {
1201 s.Helper()
1202 s.writeToFs(s.fs.Source, filename, content)
1203 }
1204
1205 func (s *IntegrationTestBuilder) writeToFs(fs afero.Fs, filename, content string) {
1206 s.Helper()
1207 if err := afero.WriteFile(fs, filepath.FromSlash(filename), []byte(content), 0o755); err != nil {
1208 s.Fatalf("Failed to write file: %s", err)
1209 }
1210 }
1211
1212 type IntegrationTestConfig struct {
1213 T testing.TB
1214
1215 // The files to use on txtar format, see
1216 // https://pkg.go.dev/golang.org/x/exp/cmd/txtar
1217 // There are some contentions used in this test setup.
1218 // - §§§ can be used to wrap code fences.
1219 // - §§ can be used to wrap multiline strings.
1220 // - filenames prefixed with sourcefilename: will be read from the file system relative to the current dir.
1221 // - filenames with a .png or .jpg extension will be treated as binary and base64 decoded.
1222 TxtarString string
1223
1224 // Prefix to add to all file contents, e.g. BOM.
1225 FileContentPrefix string
1226
1227 // COnfig to use as the base. We will also read the config from the txtar.
1228 BaseCfg config.Provider
1229
1230 // Environment variables passed to the config loader.
1231 Environ []string
1232
1233 // Whether to simulate server mode.
1234 Running bool
1235
1236 // Whether to simulate the server's fast render mode.
1237 // Only used when Running is set.
1238 FastRenderMode bool
1239
1240 // Watch for changes.
1241 // This is (currently) always set to true when Running is set.
1242 // Note that the CLI for the server does allow for --watch=false, but that is not used in these test.
1243 Watching bool
1244
1245 // Enable verbose logging.
1246 Verbose bool
1247
1248 // The log level to use.
1249 LogLevel logg.Level
1250
1251 // Whether to panic on warnings.
1252 PanicOnWarning bool
1253
1254 // Whether it needs the real file system (e.g. for js.Build tests).
1255 NeedsOsFS bool
1256
1257 // Whether to run GC after each build.
1258 RunGC bool
1259
1260 // Do not remove the temp dir after the test.
1261 PrintAndKeepTempDir bool
1262
1263 // Whether to run npm install before Build.
1264 NeedsNpmInstall bool
1265
1266 // Global npm packages to install before Build. This is used for testing the npm integration in the Hugo Pipes.
1267 // Only used on CI.
1268 NeedsNpmGlobalInstall []string
1269
1270 // Whether to normalize the Unicode filenames to NFD on Darwin.
1271 NFDFormOnDarwin bool
1272
1273 // The working dir to use. If not absolute, a temp dir will be created.
1274 WorkingDir string
1275
1276 // The config to pass to Build.
1277 BuildCfg BuildCfg
1278
1279 // WarpcMemory, if set, overrides the memory limit in MiB for the WASM based
1280 // image processors (WebP and AVIF). Used to provoke memory allocation failures.
1281 WarpcMemory int
1282 }