summaryrefslogtreecommitdiff
path: root/source/Test/Unit/HtmlOutput.hs
blob: 0087f828741a8f096cd468e75e21e80bb87fd49e (plain)
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
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}

module Test.Unit.HtmlOutput (unitTests) where

import Base
import Felix.Parse qualified as Parse
import Felix.Source
import Felix.Source.Graph qualified as SourceGraph
import Render.Html qualified as Html
import Render.Html.Export
import Render.Html.Output

import Control.Exception (bracket)
import Data.ByteString qualified as ByteString
import Data.List qualified as List
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TextEncoding
import System.Directory qualified as Directory
import System.FilePath.Posix ((</>))
import System.Posix.Files qualified as PosixFiles
import Test.Tasty
import Test.Tasty.HUnit


unitTests :: TestTree
unitTests =
    testGroup "HTML output"
        [ testCase
            "publishes a mounted multi-page UTF-8 export"
            publishesMountedExport
        , testCase
            "writes prepared strict bytes"
            writesPreparedBytes
        , testCase
            "attaches bytes only to reserved routes"
            attachesBytesToReservedRoutes
        , testCase
            "rejects a final symlink before publication"
            rejectsFinalSymlink
        , testCase
            "replaces hard-linked targets without changing peers"
            replacesHardLinkedTarget
        , testCase
            "rejects a FIFO before publication"
            rejectsFifo
        , testCase
            "reports and cleans the source-order publication prefix"
            reportsIncompletePublication
        ]


publishesMountedExport :: Assertion
publishesMountedExport =
    withTemporaryDirectory "felix-html-export" \temp -> do
        let projectRoot = temp </> "project"
            libraryRoot = temp </> "library"
            projectDirectory = projectRoot </> "docs"
            libraryDirectory = libraryRoot </> "shared"
            rootSource = projectDirectory </> "über #.tex"
            importedSource =
                libraryDirectory </> "sets #.tex"
            outputRoot = temp </> "html"
            rootPage = outputRoot </> "docs" </> "über #.html"
            importedPage =
                outputRoot
                    </> "library"
                    </> "shared"
                    </> "sets #.html"
            supportAsset =
                outputRoot
                    </> "_static"
                    </> "naproche-html.js"
            configuration =
                [ (sourceMountId "project", [])
                , (sourceMountId "library", ["library"])
                ]
            hints =
                "relation\teq\t0\t<mo>=</mo>\n"
        Directory.createDirectory projectRoot
        Directory.createDirectory libraryRoot
        Directory.createDirectory projectDirectory
        Directory.createDirectory libraryDirectory
        writeImportedTheory importedSource
        writeRootTheory rootSource
        mounts <-
            expectRight =<<
                prepareSourceMounts
                    [ (sourceMountId "project", projectRoot)
                    , (sourceMountId "library", libraryRoot)
                    ]
        searched <-
            expectRight
                (searchedRoot "docs/über #.tex")
        exact <-
            expectRight =<< existingRoot rootSource
        searchedExport <-
            expectRight =<<
                prepareTestHtmlExport
                    configuration
                    mounts
                    searched
                    hints
        exactExport <-
            expectRight =<<
                prepareTestHtmlExport
                    configuration
                    mounts
                    exact
                    hints
        assertEqual
            "root-form-independent destinations"
            (preparedHtmlArtifactDestination <$> searchedExport)
            (preparedHtmlArtifactDestination <$> exactExport)

        let artifacts = searchedExport
        rejectsArtifactEscape temp artifacts

        plan <-
            requirePlan =<<
                planHtmlOutput outputRoot artifacts
        outputExistsBeforePublication <-
            Directory.doesPathExist outputRoot
        assertBool
            "preflight created the output root"
            (not outputExistsBeforePublication)
        requirePublication =<< writeHtmlOutput plan

        rootText <- readUtf8 rootPage
        importedText <- readUtf8 importedPage
        supportText <- readUtf8 supportAsset
        assertContains
            "root heading"
            "<h1>project:docs/über #.tex</h1>"
            rootText
        assertContains
            "imported heading"
            "<h1>library:shared/sets #.tex</h1>"
            importedText
        assertContains
            "encoded imported reference"
            "href=\"../library/shared/sets%20%23#imported_prop\""
            rootText
        assertContains
            "encoded imported source link"
            "href=\"../library/shared/sets%20%23\"><code>library:shared/sets #.tex</code>"
            rootText
        assertContains
            "root support route"
            "src=\"../_static/naproche-html.js\""
            rootText
        assertContains
            "imported support route"
            "src=\"../../_static/naproche-html.js\""
            importedText
        for_ [rootText, importedText] \document ->
            assertContains
                "UTF-8 declaration"
                "<meta charset=\"utf-8\">"
                document
        assertEqual
            "support asset"
            Html.supportScriptAssetContents
            supportText

rejectsArtifactEscape
    :: FilePath
    -> [PreparedHtmlArtifact]
    -> Assertion
rejectsArtifactEscape temp artifacts = do
    let outputRoot = temp </> "escape-html"
        outsideRoot = temp </> "outside"
        outsideMarker = outsideRoot </> "unchanged"
    Directory.createDirectory outputRoot
    Directory.createDirectory outsideRoot
    ByteString.writeFile outsideMarker "outside"
    Directory.createDirectoryLink
        outsideRoot
        (outputRoot </> "docs")
    result <- planHtmlOutput outputRoot artifacts
    case result of
        Left
            (HtmlOutputParentEscapesRoot
                _parent
                canonicalParent) -> do
                    expectedOutside <-
                        Directory.canonicalizePath outsideRoot
                    assertEqual
                        "escaping route target"
                        expectedOutside
                        canonicalParent
        other ->
            assertFailure
                ("expected output-root escape rejection, got "
                    <> showPlanResult other)
    outsideBytes <- ByteString.readFile outsideMarker
    assertEqual
        "escape planning changed the outside tree"
        "outside"
        outsideBytes
    supportExists <-
        Directory.doesPathExist
            (outputRoot </> "_static")
    assertBool
        "escape preflight created another destination"
        (not supportExists)

writesPreparedBytes :: Assertion
writesPreparedBytes =
    withTemporaryDirectory "felix-html-output-bytes" \temp -> do
        let outputRoot = temp </> "html"
            pageText = "∀ café"
            supportText = "const π = 3;"
            expectedPageBytes =
                ByteString.pack
                    [ 0xe2, 0x88, 0x80
                    , 0x20
                    , 0x63, 0x61, 0x66
                    , 0xc3, 0xa9
                    ]
        artifacts <-
            makeArtifacts
                [ ( "nested/über.html"
                  , TextEncoding.encodeUtf8 pageText
                  )
                , ( "_static/naproche-html.js"
                  , TextEncoding.encodeUtf8 supportText
                  )
                ]
        publishArtifacts outputRoot artifacts
        pageBytes <-
            ByteString.readFile
                (outputRoot </> "nested" </> "über.html")
        supportBytes <-
            ByteString.readFile
                (outputRoot
                    </> "_static"
                    </> "naproche-html.js")
        assertEqual
            "exact page UTF-8 bytes"
            expectedPageBytes
            pageBytes
        assertEqual
            "exact support bytes"
            (TextEncoding.encodeUtf8 supportText)
            supportBytes

attachesBytesToReservedRoutes :: Assertion
attachesBytesToReservedRoutes =
    withTemporaryDirectory "felix-html-output-routes" \temp -> do
        let outputRoot = temp </> "html"
        reserved <- expectRight
            (traverse safeRelativePath
                ["page.html", "_static/naproche-html.js"])
        routes <- requireRoutePlan =<<
            planHtmlRoutes outputRoot reserved
        matching <- makeArtifacts
            [ ("page.html", "page")
            , ("_static/naproche-html.js", "support")
            ]
        case planHtmlOutputAgainst routes matching of
            Right _ ->
                pure ()
            Left failure ->
                assertFailure (show failure)
        mismatched <- makeArtifacts
            [ ("other.html", "other")
            , ("_static/naproche-html.js", "support")
            ]
        case planHtmlOutputAgainst routes mismatched of
            Left HtmlOutputRouteMismatch{} ->
                pure ()
            Left failure ->
                assertFailure
                    ("unexpected route mismatch: " <> show failure)
            Right _ ->
                assertFailure "unreserved HTML route was accepted"

rejectsFinalSymlink :: Assertion
rejectsFinalSymlink =
    withTemporaryDirectory "felix-html-output-final-link" \temp -> do
        let outputRoot = temp </> "html"
            supportDirectory = outputRoot </> "_static"
            page = outputRoot </> "page.html"
            support =
                supportDirectory </> "naproche-html.js"
            outsideAsset = temp </> "outside.js"
        Directory.createDirectory outputRoot
        Directory.createDirectory supportDirectory
        ByteString.writeFile page "old page"
        ByteString.writeFile outsideAsset "outside asset"
        Directory.createFileLink outsideAsset support
        artifacts <-
            makeArtifacts
                [ ("page.html", "new page")
                , ("_static/naproche-html.js", "new support")
                ]
        result <- planHtmlOutput outputRoot artifacts
        case result of
            Left (HtmlOutputTargetIsSymbolicLink target) ->
                assertEqual "rejected target" support target
            other ->
                assertFailure
                    ("expected final symlink rejection, got "
                        <> showPlanResult other)
        pageBytes <- ByteString.readFile page
        outsideBytes <- ByteString.readFile outsideAsset
        supportIsLink <-
            Directory.pathIsSymbolicLink support
        assertEqual
            "page changed before complete preflight"
            "old page"
            pageBytes
        assertEqual
            "symlink referent changed"
            "outside asset"
            outsideBytes
        assertBool "final symlink was replaced" supportIsLink

replacesHardLinkedTarget :: Assertion
replacesHardLinkedTarget =
    withTemporaryDirectory "felix-html-output-hard-link" \temp -> do
        let outputRoot = temp </> "html"
            page = outputRoot </> "page.html"
            outsidePage = temp </> "outside.html"
        Directory.createDirectory outputRoot
        ByteString.writeFile outsidePage "outside page"
        PosixFiles.createLink outsidePage page
        artifacts <-
            makeArtifacts [("page.html", "new page")]
        publishArtifacts outputRoot artifacts
        outsideBytes <- ByteString.readFile outsidePage
        pageBytes <- ByteString.readFile page
        assertEqual
            "outside hard-link peer changed"
            "outside page"
            outsideBytes
        assertEqual "page was not replaced" "new page" pageBytes

rejectsFifo :: Assertion
rejectsFifo =
    withTemporaryDirectory "felix-html-output-fifo" \temp -> do
        let outputRoot = temp </> "html"
            page = outputRoot </> "page.html"
        Directory.createDirectory outputRoot
        PosixFiles.createNamedPipe page PosixFiles.ownerModes
        artifacts <-
            makeArtifacts [("page.html", "page")]
        result <- planHtmlOutput outputRoot artifacts
        case result of
            Left (HtmlOutputTargetNotRegularFile target) ->
                assertEqual "rejected target" page target
            other ->
                assertFailure
                    ("expected FIFO rejection, got "
                        <> showPlanResult other)
        pageStatus <-
            PosixFiles.getSymbolicLinkStatus page
        assertBool
            "FIFO target was replaced"
            (PosixFiles.isNamedPipe pageStatus)

reportsIncompletePublication :: Assertion
reportsIncompletePublication =
    withTemporaryDirectory "felix-html-output-incomplete" \temp -> do
        let outputRoot = temp </> "html"
            first = outputRoot </> "z.html"
            blocked = outputRoot </> "b.html"
            unpublished = outputRoot </> "a.html"
        artifacts <-
            makeArtifacts
                [ ("z.html", "first")
                , ("b.html", "blocked")
                , ("a.html", "unpublished")
                ]
        plan <-
            requirePlan =<<
                planHtmlOutput outputRoot artifacts
        Directory.createDirectory outputRoot
        Directory.createDirectory blocked
        result <- writeHtmlOutput plan
        case result of
            Left
                IncompleteHtmlPublication
                    { committedHtmlDestinations
                    , failedHtmlDestination
                    } -> do
                        expectedFirst <-
                            expectRight
                                (safeRelativePath "z.html")
                        expectedBlocked <-
                            expectRight
                                (safeRelativePath "b.html")
                        assertEqual
                            "committed destinations"
                            [expectedFirst]
                            committedHtmlDestinations
                        assertEqual
                            "failed destination"
                            expectedBlocked
                            failedHtmlDestination
            Right () ->
                assertFailure
                    "expected incomplete publication"
        firstBytes <- ByteString.readFile first
        unpublishedExists <-
            Directory.doesPathExist unpublished
        blockedIsDirectory <-
            Directory.doesDirectoryExist blocked
        outputEntries <-
            Directory.listDirectory outputRoot
        assertEqual "first artifact" "first" firstBytes
        assertBool
            "later artifact was published"
            (not unpublishedExists)
        assertBool
            "injected blocker was replaced"
            blockedIsDirectory
        assertBool
            "unpublished temporary files remain"
            (not
                (any
                    (List.isInfixOf ".tmp")
                    outputEntries))


publishArtifacts
    :: FilePath
    -> [PreparedHtmlArtifact]
    -> IO ()
publishArtifacts outputRoot artifacts = do
    plan <-
        requirePlan =<< planHtmlOutput outputRoot artifacts
    requirePublication =<< writeHtmlOutput plan

makeArtifacts
    :: [(FilePath, ByteString.ByteString)]
    -> IO [PreparedHtmlArtifact]
makeArtifacts artifacts =
    for artifacts \(path, bytes) -> do
        relative <- expectRight (safeRelativePath path)
        pure (preparedHtmlArtifact relative (Right bytes))

requirePlan
    :: Either HtmlOutputError HtmlOutputPlan
    -> IO HtmlOutputPlan
requirePlan =
    expectRight

requireRoutePlan
    :: Either HtmlOutputError HtmlRoutePlan
    -> IO HtmlRoutePlan
requireRoutePlan =
    expectRight

requirePublication
    :: Either HtmlPublicationError ()
    -> IO ()
requirePublication =
    expectRight

showPlanResult
    :: Either HtmlOutputError HtmlOutputPlan
    -> String
showPlanResult = \case
    Left err ->
        show err
    Right _plan ->
        "successful output plan"

readUtf8 :: FilePath -> IO Text
readUtf8 path = do
    bytes <- ByteString.readFile path
    case TextEncoding.decodeUtf8' bytes of
        Left err ->
            assertFailure
                ("invalid UTF-8 output: " <> show err)
        Right text ->
            pure text

prepareTestHtmlExport
    :: [(SourceMountId, [Text])]
    -> SourceMounts
    -> RootRequest
    -> Text
    -> IO (Either HtmlExportError [PreparedHtmlArtifact])
prepareTestHtmlExport configuration mounts request hints = do
    graph <-
        expectRight =<<
            SourceGraph.buildResolvedSourceGraph mounts request
    workspace <-
        expectRight =<< Parse.parseResolvedSourceGraph graph
    pure
        (prepareHtmlExport
            configuration
            (htmlPresentationFromParsedWorkspace workspace)
            hints)

writeImportedTheory :: FilePath -> IO ()
writeImportedTheory path =
    writeFile path
        (unlines
            [ "\\begin{proposition}\\label{imported_prop}"
            , "  $i = i$."
            , "\\end{proposition}"
            ])

writeRootTheory :: FilePath -> IO ()
writeRootTheory path =
    writeFile path
        (unlines
            [ "\\import{shared/sets #.tex}"
            , "\\begin{proposition}\\label{local_prop}"
            , "  $a = a$."
            , "\\end{proposition}"
            , "\\begin{proposition}\\label{uses_import}"
            , "  $b = b$."
            , "\\end{proposition}"
            , "\\begin{proof}"
            , "  Follows by \\cref{imported_prop}."
            , "\\end{proof}"
            ])

assertContains
    :: String
    -> Text
    -> Text
    -> Assertion
assertContains description needle haystack =
    assertBool
        (description <> ": missing " <> show needle)
        (needle `Text.isInfixOf` haystack)

expectRight
    :: (Show e, HasCallStack)
    => Either e a
    -> IO a
expectRight = \case
    Left err ->
        assertFailure
            ("expected Right, got Left " <> show err)
    Right value ->
        pure value

withTemporaryDirectory
    :: String
    -> (FilePath -> IO a)
    -> IO a
withTemporaryDirectory template =
    bracket create Directory.removePathForcibly
  where
    create = do
        systemTemp <-
            Directory.getTemporaryDirectory
        (path, handle) <-
            openTempFile systemTemp template
        hClose handle
        Directory.removeFile path
        Directory.createDirectory path
        pure path