Debian Codegraph @

hugolib/integrationtest_builder.go

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