Repository navigation
Expand file tree
/
Copy pathheaders_test.go
More file actions
1030 lines (861 loc) · 33.5 KB
/
Copy pathheaders_test.go
File metadata and controls
1030 lines (861 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package mark
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kovetskiy/mark/v17/confluence"
"github.com/kovetskiy/mark/v17/confluence/confluencetest"
"github.com/kovetskiy/mark/v17/manifest"
"github.com/kovetskiy/mark/v17/report"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPageHeaderIsPublishedAboveTheDocument(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Generated -->
Body text.
`)
config := publishConfig(server.URL, file)
config.Rendering.PageHeader = writeFile(t, dir, "header.html", `<p>Generated: {{ .Title | xmlesc }}</p>`)
require.NoError(t, Run(context.Background(), config))
body := bodyOfPageTitled(t, server, "Generated")
assert.Contains(t, body, "<p>Generated: Generated</p>")
assert.Less(t, bytes.Index([]byte(body), []byte("Generated:")), bytes.Index([]byte(body), []byte("Body text.")))
}
// TestPageHeaderSitsInsideTheArticleLayout: outside the layout, Confluence
// would show the header as a section of its own beside the sidebar.
func TestPageHeaderSitsInsideTheArticleLayout(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Article -->
<!-- Layout: article -->
Body text.
`)
config := publishConfig(server.URL, file)
config.Rendering.PageHeader = writeFile(t, dir, "header.html", `<p>Header</p>`)
require.NoError(t, Run(context.Background(), config))
assert.Contains(t, bodyOfPageTitled(t, server, "Article"), "<ac:layout-cell><p>Header</p>")
}
func TestPageHeaderIsInCompileOnlyOutput(t *testing.T) {
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", `<!-- Space: DOCS -->
<!-- Title: Compiled -->
Body text.
`)
var output bytes.Buffer
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Mode: ModeConfig{
CompileOnly: true,
},
Rendering: RenderingConfig{
Features: []string{"mention"},
PageHeader: writeFile(t, dir, "header.md", "**Generated** from {{ .Space }}\n"),
},
Output: &output,
},
Files: file,
}))
assert.Contains(t, output.String(), "<p><strong>Generated</strong> from DOCS</p>")
}
// TestPageHeaderNamesThePageInPageIDMode: --page-id discards the file's
// metadata, so the title has to come from the page being updated.
func TestPageHeaderNamesThePageInPageIDMode(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
existing := server.AddPage("DOCS", "Existing", "page", "")
file := writeFile(t, dir, "doc.md", "Just a body.\n")
config := publishConfig(server.URL, file)
config.Page.PageID = existing.ID
config.Page.Space = "DOCS"
config.Rendering.PageHeader = writeFile(t, dir, "header.html", `<p>{{ .Title | xmlesc }} in {{ .Space | xmlesc }}</p>`)
require.NoError(t, Run(context.Background(), config))
assert.Contains(t, bodyOfPageTitled(t, server, "Existing"), "<p>Existing in DOCS</p>")
}
// TestPageHeaderNamesThePageInPageIDDryRun: the dry run already looks the page
// up, so the header it prints matches the one a real run would publish.
func TestPageHeaderNamesThePageInPageIDDryRun(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
existing := server.AddPage("DOCS", "Existing", "page", "")
file := writeFile(t, dir, "doc.md", "Just a body.\n")
var output bytes.Buffer
config := publishConfig(server.URL, file)
config.Page.PageID = existing.ID
config.Page.Space = "DOCS"
config.Mode.DryRun = true
config.Output = &output
config.Rendering.PageHeader = writeFile(t, dir, "header.html", `<p>{{ .Title | xmlesc }} in {{ .Space | xmlesc }}</p>`)
require.NoError(t, Run(context.Background(), config))
assert.Contains(t, output.String(), "<p>Existing in DOCS</p>")
}
// TestPageHeaderImageThatClashesWithTheDocumentsIsRefused: one filename is one
// attachment on the page, so the second upload would replace the first.
func TestPageHeaderImageThatClashesWithTheDocumentsIsRefused(t *testing.T) {
server, _ := docsSpace(t)
docDir := t.TempDir()
headerDir := t.TempDir()
writeFile(t, docDir, "logo.png", "document logo")
writeFile(t, headerDir, "logo.png", "header logo")
file := writeFile(t, docDir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Clash -->

`)
config := publishConfig(server.URL, file)
config.Rendering.PageHeader = writeFile(t, headerDir, "header.md", "\n")
err := Run(context.Background(), config)
require.Error(t, err)
assert.Contains(t, err.Error(), "page header attachment")
}
func TestPageHeaderImageIdenticalToTheDocumentsIsAttachedOnce(t *testing.T) {
server, _ := docsSpace(t)
docDir := t.TempDir()
headerDir := t.TempDir()
writeFile(t, docDir, "logo.png", "same logo")
writeFile(t, headerDir, "logo.png", "same logo")
file := writeFile(t, docDir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Same -->

`)
config := publishConfig(server.URL, file)
config.Rendering.PageHeader = writeFile(t, headerDir, "header.md", "\n")
require.NoError(t, Run(context.Background(), config))
}
// TestPageHeaderImageThatClashesWithADeclaredAttachmentUploadsNothing: the
// clash is known before the first upload, so the document's own file is not
// sent for a page the run is about to fail on.
func TestPageHeaderImageThatClashesWithADeclaredAttachmentUploadsNothing(t *testing.T) {
server, _ := docsSpace(t)
docDir := t.TempDir()
headerDir := t.TempDir()
writeFile(t, docDir, "logo.png", "document logo")
writeFile(t, headerDir, "logo.png", "header logo")
file := writeFile(t, docDir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Declared Clash -->
<!-- Attachment: logo.png -->
Text.
`)
config := publishConfig(server.URL, file)
config.Rendering.PageHeader = writeFile(t, headerDir, "header.md", "\n")
err := Run(context.Background(), config)
require.Error(t, err)
assert.Contains(t, err.Error(), "page header attachment")
assert.Equal(t, 0, server.CountRequests("POST", "/child/attachment"))
}
// TestPageHeaderAttachmentClashFailsADryRun: a dry run that reports success
// where the real run refuses the page is not a dry run of it. Both a declared
// attachment and one the document only references are covered.
func TestPageHeaderAttachmentClashFailsADryRun(t *testing.T) {
for _, mode := range []string{"dry-run", "compile-only"} {
t.Run(mode, func(t *testing.T) {
server, _ := docsSpace(t)
docDir := t.TempDir()
headerDir := t.TempDir()
writeFile(t, docDir, "logo.png", "document logo")
writeFile(t, docDir, "chart.png", "document chart")
writeFile(t, headerDir, "logo.png", "header logo")
writeFile(t, headerDir, "chart.png", "header chart")
file := writeFile(t, docDir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Dry Clash -->
<!-- Attachment: logo.png -->

`)
for _, header := range []string{"\n", "\n"} {
config := publishConfig(server.URL, file)
config.Mode.DryRun = mode == "dry-run"
config.Mode.CompileOnly = mode == "compile-only"
config.Output = &bytes.Buffer{}
config.Rendering.PageHeader = writeFile(t, headerDir, "header.md", header)
err := Run(context.Background(), config)
require.Error(t, err, header)
assert.Contains(t, err.Error(), "page header attachment")
}
})
}
}
// propertiesFixture publishes one document and returns the server, the page id
// and the config used, so a test can republish.
func propertiesFixture(t *testing.T, doc string, config func(*Config)) (*confluencetest.Server, string, Config) {
t.Helper()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
writeFile(t, dir, "doc.md", doc)
cfg := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "doc.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}
if config != nil {
config(&cfg)
}
require.NoError(t, Run(context.Background(), cfg))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
page, err := api.FindPage(context.Background(), "DOCS", "Doc", "page")
require.NoError(t, err)
require.NotNil(t, page)
return server, page.ID, cfg
}
const propertyHeaders = "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Doc -->\n"
// TestPropertyHeaderSetsAContentProperty covers the singular, repeatable header
// form, which matches Parent, Label and Attachment.
func TestPropertyHeaderSetsAContentProperty(t *testing.T) {
server, id, _ := propertiesFixture(t,
propertyHeaders+
"<!-- Property: team=platform -->\n"+
"<!-- Property: reviewed=2026-08 -->\n\nBody.\n", nil)
require.NotNil(t, server.SpaceProperty(id, "team"))
assert.JSONEq(t, `"platform"`, string(server.SpaceProperty(id, "team").Value))
require.NotNil(t, server.SpaceProperty(id, "reviewed"))
assert.JSONEq(t, `"2026-08"`, string(server.SpaceProperty(id, "reviewed").Value))
}
// TestPropertiesFrontMatterSetsProperties covers the plural front matter form,
// which matches parents, labels and attachments -- and which, unlike the
// header, can carry a value that is not a string.
func TestPropertiesFrontMatterSetsProperties(t *testing.T) {
server, id, _ := propertiesFixture(t,
"---\n"+
"title: Doc\n"+
"space: DOCS\n"+
"parents:\n - Parent\n"+
"properties:\n"+
" team: platform\n"+
" reviewers: 3\n"+
" tags:\n - one\n - two\n"+
"---\n\nBody.\n",
func(c *Config) { c.Rendering.Features = []string{"mention", "frontmatter"} })
require.NotNil(t, server.SpaceProperty(id, "team"))
assert.JSONEq(t, `"platform"`, string(server.SpaceProperty(id, "team").Value))
require.NotNil(t, server.SpaceProperty(id, "reviewers"))
assert.JSONEq(t, `3`, string(server.SpaceProperty(id, "reviewers").Value))
require.NotNil(t, server.SpaceProperty(id, "tags"))
assert.JSONEq(t, `["one","two"]`, string(server.SpaceProperty(id, "tags").Value))
}
func TestGlobalPropertiesApplyToEveryPage(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "properties.yaml")
require.NoError(t, os.WriteFile(path, []byte("owner: docs-team\nsource: git\n"), 0o600))
server, id, _ := propertiesFixture(t, propertyHeaders+"\nBody.\n",
func(c *Config) { c.Update.GlobalProperties = path })
require.NotNil(t, server.SpaceProperty(id, "owner"))
assert.JSONEq(t, `"docs-team"`, string(server.SpaceProperty(id, "owner").Value))
require.NotNil(t, server.SpaceProperty(id, "source"))
}
// TestDocumentPropertyWinsOverGlobal: a document naming a property is being
// specific about its own page, which is the more particular statement.
func TestDocumentPropertyWinsOverGlobal(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "properties.json")
require.NoError(t, os.WriteFile(path, []byte(`{"owner": "docs-team"}`), 0o600))
server, id, _ := propertiesFixture(t,
propertyHeaders+"<!-- Property: owner=platform-team -->\n\nBody.\n",
func(c *Config) { c.Update.GlobalProperties = path })
assert.JSONEq(t, `"platform-team"`, string(server.SpaceProperty(id, "owner").Value))
}
// TestPropertyUnchangedIsNotRewritten: a property holds a version Confluence
// increments on every write, so rewriting an unchanged value would fill its
// history the way republishing an unchanged page fills the page's.
func TestPropertyUnchangedIsNotRewritten(t *testing.T) {
server, id, config := propertiesFixture(t,
propertyHeaders+"<!-- Property: team=platform -->\n\nBody.\n", nil)
first := server.SpaceProperty(id, "team").Version
require.NoError(t, Run(context.Background(), config))
assert.Equal(t, first, server.SpaceProperty(id, "team").Version,
"an unchanged property must not be written again")
}
func TestPropertyChangedIsRewritten(t *testing.T) {
server, id, config := propertiesFixture(t,
propertyHeaders+"<!-- Property: team=platform -->\n\nBody.\n", nil)
first := server.SpaceProperty(id, "team").Version
writeFile(t, filepath.Dir(config.Files), "doc.md",
propertyHeaders+"<!-- Property: team=infrastructure -->\n\nBody.\n")
require.NoError(t, Run(context.Background(), config))
assert.Greater(t, server.SpaceProperty(id, "team").Version, first)
assert.JSONEq(t, `"infrastructure"`, string(server.SpaceProperty(id, "team").Value))
}
func TestPropertyHeaderMustBeKeyValue(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
dir := t.TempDir()
writeFile(t, dir, "doc.md",
"<!-- Space: DOCS -->\n<!-- Title: Doc -->\n<!-- Property: nonsense -->\n\nBody.\n")
err := Run(context.Background(), Config{
PublishConfig: PublishConfig{
Output: io.Discard,
},
Files: filepath.Join(dir, "doc.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "key=value")
}
func TestGlobalPropertiesFileMustParse(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "properties.yaml")
require.NoError(t, os.WriteFile(path, []byte("owner: [unclosed\n"), 0o600))
writeFile(t, dir, "doc.md", "<!-- Space: DOCS -->\n<!-- Title: Doc -->\n\nBody.\n")
err := Run(context.Background(), Config{
PublishConfig: PublishConfig{
Update: UpdateConfig{
GlobalProperties: path,
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: "http://127.0.0.1:1",
Username: "user",
Password: "token",
},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "properties file")
}
// restrictedDoc is a document under Parent whose headers restrict reading to
// group, with body below them.
func restrictedDoc(group, body string) string {
return "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Restricted -->\n" +
"<!-- Restriction: read.group=" + group + " -->\n\n" + body + "\n"
}
// writesAfter reports, of the requests the server took from the index from
// on, the position of the last restriction PUT and of the content PUT.
func writesAfter(server *confluencetest.Server, from int, pageID string) (restriction, content int) {
restriction, content = -1, -1
for i, request := range server.Requests()[from:] {
if request.Method != http.MethodPut {
continue
}
switch {
case strings.HasSuffix(request.Path, "/restriction"):
restriction = i
case strings.HasSuffix(request.Path, "/content/"+pageID):
content = i
}
}
return restriction, content
}
// TestRestrictionsLoosenAfterTheContent: lifting a restriction waits until
// the content that needed it has been replaced, so a run that fails between
// the two never shows the old content to the people it was kept from.
func TestRestrictionsLoosenAfterTheContent(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", restrictedDoc("hr", "secret"))
config := trackingConfig(server, file)
require.NoError(t, Run(context.Background(), config))
id := mustFind(t, server, "Restricted")
require.Equal(t, []string{"hr"}, server.Page(id).RestrictedGroups["read"])
writeFile(t, dir, "doc.md", "---\nrestrictions:\n read: {}\n---\n"+
"<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Restricted -->\n\npublic\n")
config.Rendering.Features = append(config.Rendering.Features, "frontmatter")
from := len(server.Requests())
require.NoError(t, Run(context.Background(), config))
restriction, content := writesAfter(server, from, id)
require.NotEqual(t, -1, restriction, "the restriction is lifted")
assert.Less(t, content, restriction, "and only after the content is replaced")
assert.Empty(t, server.Page(id).RestrictedGroups["read"])
}
// TestRestrictionsChangeIsAChange: a document whose only change is to its
// restrictions is previewed as would-update and reported as published, and
// one with none left to make sends nothing.
func TestRestrictionsChangeIsAChange(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", restrictedDoc("hr", "same"))
config := trackingConfig(server, file)
config.Update.ChangesOnly = true
require.NoError(t, Run(context.Background(), config))
writeFile(t, dir, "doc.md", restrictedDoc("eng", "same"))
assert.Contains(t, previewOf(t, config, "json"), `"status": "would-update"`)
assert.Equal(t, report.StatusPublished, runReported(t, config).Status)
id := mustFind(t, server, "Restricted")
assert.Equal(t, []string{"eng"}, server.Page(id).RestrictedGroups["read"])
puts := server.CountRequests(http.MethodPut, "/restriction")
assert.Equal(t, report.StatusUnchanged, runReported(t, config).Status)
assert.Equal(t, puts, server.CountRequests(http.MethodPut, "/restriction"), "nothing left to change sends nothing")
}
// TestRestrictionsUnknownUserCreatesNothing: on Cloud, a restricted user that
// resolves to nobody fails a dry run, and fails a real run before it creates
// a page that would then stand empty and unrestricted.
func TestRestrictionsUnknownUserCreatesNothing(t *testing.T) {
server, _ := docsSpace(t)
server.SetCurrentUser(confluencetest.User{AccountID: "acct-me", FullName: "Mark Bot"})
file := writeFile(t, t.TempDir(), "doc.md", "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"+
"<!-- Title: Restricted -->\n<!-- Restriction: read.user=Nobody Known -->\n\nbody\n")
config := trackingConfig(server, file)
dry := config
dry.Mode.DryRun = true
require.ErrorContains(t, Run(context.Background(), dry), `"Nobody Known"`)
require.ErrorContains(t, Run(context.Background(), config), `"Nobody Known"`)
assert.Zero(t, countPagesTitled(t, server, "Restricted"))
}
func synchronizedServer(t *testing.T) *confluencetest.Server {
t.Helper()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
return server
}
// TestSynchronizedFalseHeaderSkipsTheFile covers the header form.
func TestSynchronizedFalseHeaderSkipsTheFile(t *testing.T) {
server := synchronizedServer(t)
dir := t.TempDir()
writeFile(t, dir, "doc.md",
"<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Draft -->\n"+
"<!-- Synchronized: false -->\n\nNot ready.\n")
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
page, err := api.FindPage(context.Background(), "DOCS", "Draft", "page")
require.NoError(t, err)
assert.Nil(t, page, "an unsynchronized document must not be published")
}
// TestSynchronizedFalseFrontMatterSkipsTheFile covers the front matter form.
func TestSynchronizedFalseFrontMatterSkipsTheFile(t *testing.T) {
server := synchronizedServer(t)
dir := t.TempDir()
writeFile(t, dir, "doc.md",
"---\ntitle: Draft\nspace: DOCS\nparents:\n - Parent\nsynchronized: false\n---\n\nNot ready.\n")
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention", "frontmatter"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
page, err := api.FindPage(context.Background(), "DOCS", "Draft", "page")
require.NoError(t, err)
assert.Nil(t, page, "an unsynchronized document must not be published")
}
// TestSynchronizedTrueAndAbsentBothPublish: opting out has to be deliberate,
// and saying nothing is the ordinary case.
func TestSynchronizedTrueAndAbsentBothPublish(t *testing.T) {
for name, header := range map[string]string{
"stated true": "<!-- Synchronized: true -->\n",
"not stated": "",
} {
t.Run(name, func(t *testing.T) {
server := synchronizedServer(t)
dir := t.TempDir()
writeFile(t, dir, "doc.md",
"<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Doc -->\n"+
header+"\nBody.\n")
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
page, err := api.FindPage(context.Background(), "DOCS", "Doc", "page")
require.NoError(t, err)
assert.NotNil(t, page)
})
}
}
// TestSynchronizedFalseKeepsTheMapping is the case that would hurt. Opting a
// document out must not read as the file being gone: mark drops the page from
// the manifest, and synchronising it again later would no longer know which
// page was already its own -- publishing a second copy beside it.
//
// A second document in the same space is what makes this bite. Skipping every
// file in a space leaves the manifest for that space unread, so nothing is
// judged missing; it takes one page that does publish to load the mapping and
// expose the skipped one as unaccounted for.
func TestSynchronizedFalseKeepsTheMapping(t *testing.T) {
server := synchronizedServer(t)
dir := t.TempDir()
draft := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Draft -->\n"
writeFile(t, dir, "draft.md", draft+"\nBody.\n")
writeFile(t, dir, "other.md",
"<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n<!-- Title: Other -->\n\nBody.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
published, err := api.FindPage(context.Background(), "DOCS", "Draft", "page")
require.NoError(t, err)
require.NotNil(t, published)
// Now the draft opts out, while its neighbour keeps publishing.
writeFile(t, dir, "draft.md", draft+"<!-- Synchronized: false -->\n\nBody.\n")
require.NoError(t, Run(context.Background(), config))
// The page is never deleted either way; a forgotten mapping is what causes
// a duplicate the next time it publishes.
require.NotNil(t, server.Page(published.ID))
entry, ok, err := manifest.NewStore(api).Lookup(context.Background(), "DOCS", filepath.Join(dir, "draft.md"))
require.NoError(t, err)
require.True(t, ok, "the page mapping must survive a document opting out")
assert.Equal(t, published.ID, entry.PageID)
}
func TestSynchronizedRejectsANonBoolean(t *testing.T) {
server := synchronizedServer(t)
dir := t.TempDir()
writeFile(t, dir, "doc.md",
"<!-- Space: DOCS -->\n<!-- Title: Doc -->\n<!-- Synchronized: maybe -->\n\nBody.\n")
err := Run(context.Background(), Config{
PublishConfig: PublishConfig{
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "true or false")
}
// folderOrderedDocument is a document that declares both a folder and a
// position among its siblings -- the combination that used to get neither.
func folderOrderedDocument(title string, order string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Folder: Manuals -->
<!-- Title: ` + title + ` -->
<!-- Order: ` + order + ` -->
# ` + title + `
Some content.
`
}
// titlesInOrder names the pages Confluence lists under a parent, in the order
// the tree shows them.
func titlesInOrder(server *confluencetest.Server, parentID string) []string {
var titles []string
for _, id := range server.ChildOrder(parentID) {
if page := server.Page(id); page != nil {
titles = append(titles, page.Title)
}
}
return titles
}
// TestOrderIsAppliedUnderAFolder pins the class of bug where a placement is
// dropped for want of a parent id. A folder is not a page, so it never appears
// among a page's expanded ancestors -- every folder-parented page therefore
// reported no parent, and OrderChildren discarded its position without a word.
func TestOrderIsAppliedUnderAFolder(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "a.md", folderOrderedDocument("Second", "2"))
writeFile(t, dir, "b.md", folderOrderedDocument("First", "1"))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
folders := server.Folders()
require.Len(t, folders, 1, "the declared folder should have been created once")
assert.Equal(t, []string{"First", "Second"}, titlesInOrder(server, folders[0].ID),
"a page under a folder must still be placed where its Order header asks")
}
// TestOrderIsAppliedUnderAPage guards the ordinary path, which resolves the
// parent from the page's own ancestors, against the folder fallback added
// beside it.
func TestOrderIsAppliedUnderAPage(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
document := func(title, order string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: ` + title + ` -->
<!-- Order: ` + order + ` -->
# ` + title + `
Some content.
`
}
writeFile(t, dir, "a.md", document("Second", "2"))
writeFile(t, dir, "b.md", document("First", "1"))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
parent, err := api.FindPage(context.Background(), "DOCS", "Parent", "page")
require.NoError(t, err)
require.NotNil(t, parent)
assert.Equal(t, []string{"First", "Second"}, titlesInOrder(server, parent.ID))
}
// TestOrderIsAppliedOnDataCenter: without the content move endpoint the
// Order header is carried out through movepage.action.
func TestOrderIsAppliedOnDataCenter(t *testing.T) {
server, api := docsSpace(t)
server.SetDataCenter()
server.SetFail(func(r *http.Request) (int, string, bool) {
if strings.Contains(r.URL.Path, "/move/") {
return http.StatusNotFound, `{"message":"no such endpoint"}`, true
}
return 0, "", false
})
dir := t.TempDir()
document := func(title, order string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: ` + title + ` -->
<!-- Order: ` + order + ` -->
# ` + title + `
Some content.
`
}
writeFile(t, dir, "a.md", document("Second", "2"))
writeFile(t, dir, "b.md", document("First", "1"))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
parent, err := api.FindPage(context.Background(), "DOCS", "Parent", "page")
require.NoError(t, err)
require.NotNil(t, parent)
assert.Equal(t, []string{"First", "Second"}, titlesInOrder(server, parent.ID))
assert.Positive(t, server.CountRequests(http.MethodPost, "/pages/movepage.action"))
}
// orderedDoc is a document asking for a position among its siblings.
func orderedDoc(title string, order int) string {
return fmt.Sprintf(`<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: %s -->
<!-- Order: %d -->
Body.
`, title, order)
}
// orderSpace builds a space and returns the parent the documents hang from.
func orderSpace(t *testing.T) (*confluencetest.Server, *confluencetest.Page) {
t.Helper()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
return server, server.AddPage("DOCS", "Parent", "page", home.ID)
}
func titlesOf(t *testing.T, server *confluencetest.Server, parentID string) []string {
t.Helper()
var titles []string
for _, id := range server.ChildOrder(parentID) {
titles = append(titles, server.Page(id).Title)
}
return titles
}
// TestOrderHeaderArrangesSiblings is the feature: documents are published in
// whatever order the glob produced them, and end up in the order they asked
// for.
func TestOrderHeaderArrangesSiblings(t *testing.T) {
server, parent := orderSpace(t)
dir := t.TempDir()
// Written so the filenames sort opposite to the requested order, which is
// what shows the ordering is doing the work.
writeFile(t, dir, "a.md", orderedDoc("Third", 30))
writeFile(t, dir, "b.md", orderedDoc("First", 10))
writeFile(t, dir, "c.md", orderedDoc("Second", 20))
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}))
assert.Equal(t, []string{"First", "Second", "Third"}, titlesOf(t, server, parent.ID))
}
// TestOrderIsIdempotent is what decides whether this can run in CI. Ordering
// happens on every publish, so a run that changes nothing must move nothing --
// otherwise every run fills page histories with churn.
func TestOrderIsIdempotent(t *testing.T) {
server, parent := orderSpace(t)
dir := t.TempDir()
writeFile(t, dir, "a.md", orderedDoc("Third", 30))
writeFile(t, dir, "b.md", orderedDoc("First", 10))
writeFile(t, dir, "c.md", orderedDoc("Second", 20))
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}
require.NoError(t, Run(context.Background(), config))
require.Equal(t, []string{"First", "Second", "Third"}, titlesOf(t, server, parent.ID))
server.ResetRequests()
require.NoError(t, Run(context.Background(), config))
assert.Equal(t, 0, countMoves(server), "a second run must not move anything")
assert.Equal(t, []string{"First", "Second", "Third"}, titlesOf(t, server, parent.ID))
}
func countMoves(server *confluencetest.Server) int {
n := 0
for _, r := range server.Requests() {
if strings.Contains(r.Path, "/move/") {
n++
}
}
return n
}
// TestOrderMovesOnlyWhatMustMove: one page changing position must not
// reshuffle the rest.
func TestOrderMovesOnlyWhatMustMove(t *testing.T) {
server, parent := orderSpace(t)
dir := t.TempDir()
for i, title := range []string{"One", "Two", "Three", "Four"} {
writeFile(t, dir, fmt.Sprintf("%d.md", i), orderedDoc(title, (i+1)*10))
}
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}
require.NoError(t, Run(context.Background(), config))
require.Equal(t, []string{"One", "Two", "Three", "Four"}, titlesOf(t, server, parent.ID))
// "Four" is asked to lead. Everything else keeps its relative order, so
// only one page needs to move.
writeFile(t, dir, "3.md", orderedDoc("Four", 5))
server.ResetRequests()
require.NoError(t, Run(context.Background(), config))
assert.Equal(t, []string{"Four", "One", "Two", "Three"}, titlesOf(t, server, parent.ID))
assert.Equal(t, 1, countMoves(server), "only the page that changed position should move")
}
// TestOrderLeavesUnorderedPagesAlone: a document that says nothing about order
// must not be dragged about by the ones that do.
func TestOrderLeavesUnorderedPagesAlone(t *testing.T) {
server, parent := orderSpace(t)
dir := t.TempDir()
writeFile(t, dir, "plain.md", markdownWithTitle("Plain"))
writeFile(t, dir, "a.md", orderedDoc("Second", 20))
writeFile(t, dir, "b.md", orderedDoc("First", 10))
require.NoError(t, Run(context.Background(), Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
}))
order := titlesOf(t, server, parent.ID)
assert.Contains(t, order, "Plain")
first, second := indexOf(order, "First"), indexOf(order, "Second")
assert.Less(t, first, second, "the ordered pages should be in the order they asked for")
}
func indexOf(values []string, want string) int {
for i, v := range values {
if v == want {
return i
}
}
return -1
}
// TestOrderIsNotAppliedOnDryRun: a dry run reports and rearranges nothing.
func TestOrderIsNotAppliedOnDryRun(t *testing.T) {