summaryrefslogtreecommitdiff
path: root/source/Felix/Test/Unit/HtmlLayout.hs
blob: a3d701f8a1c87c6856f284b1429eec4bc5647304 (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
{-# LANGUAGE OverloadedStrings #-}

module Felix.Test.Unit.HtmlLayout (unitTests) where

import Base
import Felix.Source
import Felix.Source.Graph
import Felix.Render.Html.Layout

import Control.Exception (bracket)
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Text qualified as Text
import System.Directory qualified as Directory
import System.FilePath.Posix qualified as Posix
import Test.Tasty
import Test.Tasty.HUnit


unitTests :: TestTree
unitTests =
    testGroup "HTML layout"
        [ testCase
            "encodes URL segments canonically"
            encodesUrlSegments
        , testCase
            "renders relative typed URLs"
            rendersRelativeUrls
        , testCase
            "separates mounted route namespaces"
            separatesMountedNamespaces
        , testCase
            "routes searched and exact roots identically"
            routesRootFormsIdentically
        , testCase
            "requires an explicit mount for an external root"
            requiresExternalMount
        , testCase
            "reports URL and destination collisions independently"
            reportsRouteCollisions
        , testCase
            "rejects ancestor and descendant destinations"
            rejectsNestedDestinations
        , testCase
            "is independent of graph and configuration traversal order"
            isTraversalOrderIndependent
        ]


encodesUrlSegments :: Assertion
encodesUrlSegments = do
    let accepted =
            [ ("AZaz09-._~", "AZaz09-._~")
            , ("#?% \\", "%23%3F%25%20%5C")
            , ("über", "%C3%BCber")
            , ("%2f", "%252f")
            ]
    for_ accepted \(decoded, expected) ->
        assertEqual
            ("encoded segment " <> Text.unpack decoded)
            (Right expected)
            (renderUrlSegment <$> urlSegment decoded)
    let rejected =
            [ ("", EmptyUrlSegment)
            , (".", DotUrlSegment ".")
            , ("..", DotUrlSegment "..")
            , ("a/b", UrlSegmentContainsSeparator "a/b")
            ]
    for_ rejected \(decoded, expected) ->
        assertEqual
            ("rejected segment " <> Text.unpack decoded)
            (Left expected)
            (urlSegment decoded)
    assertEqual
        "fragment encoding"
        "#name%23%C3%BC"
        (renderUrlFragment "name#ü")

rendersRelativeUrls :: Assertion
rendersRelativeUrls = do
    let cases =
            [ ( ["library", "nested", "über"]
              , ["_static", "naproche-html.js"]
              , "../../_static/naproche-html.js"
              )
            , ( ["first", "entry"]
              , ["second", "entry"]
              , "../second/entry"
              )
            , ( ["mount", "entry"]
              , ["mount", "a?b"]
              , "a%3Fb"
              )
            ]
    for_ cases \(currentSegments, targetSegments, expected) -> do
        current <- expectRight (urlPath currentSegments)
        target <- expectRight (urlPath targetSegments)
        assertEqual
            "relative URL"
            expected
            (renderRelativeUrlPath current target)
    current <- expectRight (urlPath ["mount", "entry"])
    target <- expectRight (urlPath ["mount", "ü"])
    assertEqual
        "encoded path and fragment remain separate"
        "%C3%BC#part%23%3F"
        ( renderRelativeUrlPath current target
            <> renderUrlFragment "part#?"
        )

separatesMountedNamespaces :: Assertion
separatesMountedNamespaces =
    withTemporaryDirectory "felix-html-layout-mounts" \temp -> do
        let mountSpecifications =
                [ ("project", [])
                , ("library", ["library"])
                , ("debug", ["debug"])
                , ("external", ["external"])
                ]
        roots <- for mountSpecifications \(ident, _prefix) -> do
            let root = temp Posix.</> Text.unpack ident
            Directory.createDirectory root
            writeTheory (root Posix.</> "entry.tex") []
            pure (sourceMountId ident, root)
        mounts <- expectRight =<< prepareSourceMounts roots
        routes <- for mountSpecifications \(ident, prefix) -> do
            let sourcePath =
                    temp
                        Posix.</> Text.unpack ident
                        Posix.</> "entry.tex"
            request <- expectRight =<< existingRoot sourcePath
            graph <- expectRight =<< buildResolvedSourceGraph mounts request
            layout <-
                expectRight
                    (layoutHtmlSourceGraph
                        [ (sourceMountId configuredId, configuredPrefix)
                        | (configuredId, configuredPrefix) <-
                            mountSpecifications
                        ]
                        graph)
            route <- requireRootRoute graph layout
            pure
                ( ident
                , renderUrlPath (routeUrlPath route)
                , safeRelativePathFilePath
                    (routeDestination route)
                , prefix
                )
        assertEqual
            "mount URLs"
            [ ("project", "/entry")
            , ("library", "/library/entry")
            , ("debug", "/debug/entry")
            , ("external", "/external/entry")
            ]
            [ (ident, url) | (ident, url, _destination, _prefix) <- routes ]
        assertEqual
            "mount destinations"
            [ ("project", "entry.html")
            , ("library", "library/entry.html")
            , ("debug", "debug/entry.html")
            , ("external", "external/entry.html")
            ]
            [ (ident, destination)
            | (ident, _url, destination, _prefix) <- routes
            ]

routesRootFormsIdentically :: Assertion
routesRootFormsIdentically =
    withTemporaryDirectory "felix-html-layout-root-forms" \temp -> do
        let libraryRoot = temp Posix.</> "library"
            entry = libraryRoot Posix.</> "entry.tex"
        Directory.createDirectory libraryRoot
        writeTheory entry []
        mounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "project", temp)
            , (sourceMountId "library", libraryRoot)
            ]
        searched <- expectRight (searchedRoot "library/entry.tex")
        exact <- expectRight =<< existingRoot entry
        searchedGraph <-
            expectRight =<< buildResolvedSourceGraph mounts searched
        exactGraph <-
            expectRight =<< buildResolvedSourceGraph mounts exact
        let configuration =
                [ (sourceMountId "project", [])
                , (sourceMountId "library", ["library"])
                ]
        searchedLayout <-
            expectRight
                (layoutHtmlSourceGraph configuration searchedGraph)
        exactLayout <-
            expectRight
                (layoutHtmlSourceGraph configuration exactGraph)
        searchedRoute <-
            requireRootRoute searchedGraph searchedLayout
        exactRoute <-
            requireRootRoute exactGraph exactLayout
        assertEqual "selected route" searchedRoute exactRoute
        assertEqual
            "most-specific URL"
            "/library/entry"
            (renderUrlPath (routeUrlPath searchedRoute))

requiresExternalMount :: Assertion
requiresExternalMount =
    withTemporaryDirectory "felix-html-layout-external" \temp -> do
        let projectRoot = temp Posix.</> "project"
            externalRoot = temp Posix.</> "vendor"
            externalEntry = externalRoot Posix.</> "entry.tex"
        Directory.createDirectory projectRoot
        Directory.createDirectory externalRoot
        writeTheory externalEntry []
        request <- expectRight =<< existingRoot externalEntry
        projectMounts <- expectRight =<< prepareSourceMounts
            [(sourceMountId "project", projectRoot)]
        outsideResult <-
            buildResolvedSourceGraph projectMounts request
        case outsideResult of
            Left RootOutsideConfiguredMount{} ->
                pure ()
            result ->
                assertFailure
                    ("expected external root rejection, got "
                        <> show result)
        mounted <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "project", projectRoot)
            , (sourceMountId "external", externalRoot)
            ]
        graph <- expectRight =<< buildResolvedSourceGraph mounted request
        layout <-
            expectRight
                (layoutHtmlSourceGraph
                    [ (sourceMountId "project", [])
                    , (sourceMountId "external", ["vendor"])
                    ]
                    graph)
        route <- requireRootRoute graph layout
        assertEqual
            "external URL"
            "/vendor/entry"
            (renderUrlPath (routeUrlPath route))

reportsRouteCollisions :: Assertion
reportsRouteCollisions = do
    reportsPageCollisions
    reportsAssetUrlCollision

reportsPageCollisions :: Assertion
reportsPageCollisions =
    withTemporaryDirectory "felix-html-layout-page-collision" \temp -> do
        let firstRoot = temp Posix.</> "first"
            secondRoot = temp Posix.</> "second"
            firstEntry = firstRoot Posix.</> "two" Posix.</> "a.tex"
        Directory.createDirectory firstRoot
        Directory.createDirectory secondRoot
        Directory.createDirectory (firstRoot Posix.</> "two")
        writeTheory (secondRoot Posix.</> "a.tex") []
        writeTheory firstEntry ["a.tex"]
        mounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "first", firstRoot)
            , (sourceMountId "second", secondRoot)
            ]
        request <- expectRight =<< existingRoot firstEntry
        graph <- expectRight =<< buildResolvedSourceGraph mounts request
        let configuration =
                [ (sourceMountId "first", ["one"])
                , (sourceMountId "second", ["one", "two"])
                ]
        case layoutHtmlSourceGraph configuration graph of
            Left
                (CollidingHtmlRoutes
                    [HtmlUrlRouteCollision url owners]
                    [HtmlDestinationRouteCollision destination
                        destinationOwners]) -> do
                            assertEqual
                                "canonical URL collision"
                                "/one/two/a"
                                (renderUrlPath url)
                            assertEqual
                                "URL owners"
                                (NonEmpty.toList owners)
                                (NonEmpty.toList destinationOwners)
                            assertEqual
                                "destination collision"
                                "one/two/a.html"
                                (safeRelativePathFilePath destination)
            result ->
                assertFailure
                    ("expected paired route collisions, got "
                        <> show result)

reportsAssetUrlCollision :: Assertion
reportsAssetUrlCollision =
    withTemporaryDirectory "felix-html-layout-asset-collision" \temp -> do
        let entry =
                temp
                    Posix.</> "_static"
                    Posix.</> "naproche-html.js.tex"
        Directory.createDirectory (temp Posix.</> "_static")
        writeTheory entry []
        mounts <- expectRight =<< prepareSourceMounts
            [(sourceMountId "project", temp)]
        request <-
            expectRight
                (searchedRoot "_static/naproche-html.js.tex")
        graph <- expectRight =<< buildResolvedSourceGraph mounts request
        case
            layoutHtmlSourceGraph
                [(sourceMountId "project", [])]
                graph of
            Left
                (CollidingHtmlRoutes
                    [HtmlUrlRouteCollision url _owners]
                    []) ->
                        assertEqual
                            "page/asset URL collision"
                            "/_static/naproche-html.js"
                            (renderUrlPath url)
            result ->
                assertFailure
                    ("expected URL-only asset collision, got "
                        <> show result)

rejectsNestedDestinations :: Assertion
rejectsNestedDestinations =
    withTemporaryDirectory "felix-html-layout-nested" \temp -> do
        let nestedDirectory = temp Posix.</> "a.html"
        Directory.createDirectory nestedDirectory
        writeTheory (temp Posix.</> "a.tex") []
        writeTheory (nestedDirectory Posix.</> "b.tex") []
        writeTheory
            (temp Posix.</> "entry.tex")
            ["a.tex", "a.html/b.tex"]
        mounts <- expectRight =<< prepareSourceMounts
            [(sourceMountId "project", temp)]
        request <- expectRight (searchedRoot "entry.tex")
        graph <- expectRight =<< buildResolvedSourceGraph mounts request
        case layoutHtmlSourceGraph
                [(sourceMountId "project", [])]
                graph of
            Left
                (CollidingHtmlRoutes
                    []
                    [NestedHtmlDestinationRouteCollision
                        ancestor
                        ancestorOwner
                        descendant
                        descendantOwner]) -> do
                            assertEqual
                                "ancestor destination"
                                "a.html"
                                (safeRelativePathFilePath ancestor)
                            assertEqual
                                "ancestor owner"
                                "a.tex"
                                (pageOwnerPath ancestorOwner)
                            assertEqual
                                "descendant destination"
                                "a.html/b.html"
                                (safeRelativePathFilePath descendant)
                            assertEqual
                                "descendant owner"
                                "a.html/b.tex"
                                (pageOwnerPath descendantOwner)
            result ->
                assertFailure
                    ("expected nested destination collision, got "
                        <> show result)
  where
    pageOwnerPath = \case
        HtmlPage source ->
            safeRelativePathFilePath
                (resolvedSourceRelativePath source)
        HtmlSupportScript ->
            "<support script>"

isTraversalOrderIndependent :: Assertion
isTraversalOrderIndependent =
    withTemporaryDirectory "felix-html-layout-order" \temp -> do
        writeTheory (temp Posix.</> "a.tex") []
        writeTheory (temp Posix.</> "b.tex") []
        let root = temp Posix.</> "entry.tex"
        writeTheory root ["a.tex", "b.tex"]
        mounts <- expectRight =<< prepareSourceMounts
            [(sourceMountId "project", temp)]
        request <- expectRight (searchedRoot "entry.tex")
        firstGraph <-
            expectRight =<< buildResolvedSourceGraph mounts request
        writeTheory root ["b.tex", "a.tex"]
        secondGraph <-
            expectRight =<< buildResolvedSourceGraph mounts request
        let firstConfiguration =
                [ (sourceMountId "unused", ["unused"])
                , (sourceMountId "project", [])
                ]
        firstLayout <-
            expectRight
                (layoutHtmlSourceGraph
                    firstConfiguration
                    firstGraph)
        for_
            (zip
                (cycle [firstGraph, secondGraph])
                (List.permutations firstConfiguration))
            \(orderedGraph, configuration) -> do
                layout <-
                    expectRight
                        (layoutHtmlSourceGraph
                            configuration
                            orderedGraph)
                assertEqual
                    "route table"
                    firstLayout
                    layout

        let collidingConfiguration =
                [ (sourceMountId "z", ["same"])
                , (sourceMountId "a", ["same"])
                , (sourceMountId "project", [])
                ]
            expectedCollision =
                layoutHtmlSourceGraph
                    collidingConfiguration
                    firstGraph
        for_
            (zip
                (cycle [firstGraph, secondGraph])
                (List.permutations collidingConfiguration))
            \(orderedGraph, configuration) ->
                assertEqual
                    "collision diagnostic"
                    expectedCollision
                    (layoutHtmlSourceGraph
                        configuration
                        orderedGraph)


requireRootRoute
    :: ResolvedSourceGraph
    -> HtmlLayout
    -> IO HtmlRoute
requireRootRoute graph layout =
    case htmlPageRoute layout (sourceGraphRootSource graph) of
        Just route ->
            pure route
        Nothing -> do
            assertFailure "layout omitted the root source"
            pure (impossible "requireRootRoute: assertFailure returned")

writeTheory :: FilePath -> [FilePath] -> IO ()
writeTheory path imports =
    writeFile path
        (unlines
            (["\\import{" <> imported <> "}" | imported <- imports]
                <> [ "\\begin{axiom}\\label{route_fixture}"
                   , "  $x = x$."
                   , "\\end{axiom}"
                   ]))

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