elm-pages-v3-beta/tests/BetaStaticHttpRequestsTests.elm

387 lines
13 KiB
Elm
Raw Normal View History

module BetaStaticHttpRequestsTests exposing (all)
import Codec
2020-12-07 19:41:10 +03:00
import Dict
import Expect
import Html
import Json.Decode as JD
import Json.Encode as Encode
import OptimizedDecoder as Decode exposing (Decoder)
import Pages.ContentCache as ContentCache
import Pages.Document as Document
import Pages.ImagePath as ImagePath
2021-04-03 00:44:40 +03:00
import Pages.Internal.Platform.Cli exposing (..)
import Pages.Internal.Platform.Effect as Effect exposing (Effect)
2020-12-07 19:41:10 +03:00
import Pages.Internal.Platform.ToJsPayload as ToJsPayload
import Pages.Internal.StaticHttpBody as StaticHttpBody
import Pages.Manifest as Manifest
import Pages.PagePath as PagePath
import Pages.StaticHttp as StaticHttp
import Pages.StaticHttp.Request as Request
import PagesHttp
import ProgramTest exposing (ProgramTest)
import Secrets
import SimulatedEffect.Cmd
import SimulatedEffect.Http as Http
import SimulatedEffect.Ports
import SimulatedEffect.Task
2020-12-07 19:41:10 +03:00
import Test exposing (Test, describe, test)
all : Test
all =
describe "Beta Static Http Requests"
[ test "port is sent out once all requests are finished" <|
\() ->
start
[ ( [ "elm-pages" ]
, StaticHttp.get (Secrets.succeed "https://api.github.com/repos/dillonkearns/elm-pages") starDecoder
)
]
|> ProgramTest.simulateHttpOk
"GET"
"https://api.github.com/repos/dillonkearns/elm-pages"
"""{ "stargazer_count": 86 }"""
|> expectSuccess
[ ( "elm-pages"
, [ ( get "https://api.github.com/repos/dillonkearns/elm-pages"
, """{"stargazer_count":86}"""
)
]
)
]
, test "two pages" <|
\() ->
start
[ ( [ "elm-pages" ]
, StaticHttp.get (Secrets.succeed "https://api.github.com/repos/dillonkearns/elm-pages") starDecoder
)
, ( [ "elm-pages-starter" ]
, StaticHttp.get (Secrets.succeed "https://api.github.com/repos/dillonkearns/elm-pages-starter") starDecoder
)
]
|> ProgramTest.simulateHttpOk
"GET"
"https://api.github.com/repos/dillonkearns/elm-pages"
"""{ "stargazer_count": 86 }"""
|> ProgramTest.simulateHttpOk
"GET"
"https://api.github.com/repos/dillonkearns/elm-pages-starter"
"""{ "stargazer_count": 49 }"""
|> expectSuccess
[ ( "elm-pages"
, [ ( get "https://api.github.com/repos/dillonkearns/elm-pages"
, """{"stargazer_count":86}"""
)
]
)
, ( "elm-pages-starter"
, [ ( get "https://api.github.com/repos/dillonkearns/elm-pages-starter"
, """{"stargazer_count":49}"""
)
]
)
]
]
2021-04-03 00:44:40 +03:00
start : List ( List String, StaticHttp.Request a ) -> ProgramTest (Model PathKey ()) Msg (Effect PathKey)
start pages =
startWithHttpCache (Ok ()) [] pages
startWithHttpCache :
Result String ()
-> List ( Request.Request, String )
-> List ( List String, StaticHttp.Request a )
2021-04-03 00:44:40 +03:00
-> ProgramTest (Model PathKey ()) Msg (Effect PathKey)
startWithHttpCache =
startLowLevel (StaticHttp.succeed [])
startLowLevel :
StaticHttp.Request
(List
2021-04-01 05:55:28 +03:00
(Result
String
{ path : List String
, content : String
}
)
)
-> Result String ()
-> List ( Request.Request, String )
-> List ( List String, StaticHttp.Request a )
2021-04-03 00:44:40 +03:00
-> ProgramTest (Model PathKey ()) Msg (Effect PathKey)
startLowLevel generateFiles documentBodyResult staticHttpCache pages =
let
document =
Document.fromList
[ Document.parser
{ extension = "md"
, metadata = JD.succeed ()
, body = \_ -> documentBodyResult
}
]
content =
pages
|> List.map
(\( path, _ ) ->
( path, { extension = "md", frontMatter = "null", body = Just "" } )
)
contentCache =
ContentCache.init document content Nothing
siteMetadata =
contentCache
|> Result.map
(\cache -> cache |> ContentCache.extractMetadata PathKey)
|> Result.mapError (List.map Tuple.second)
config =
{ toJsPort = toJsPort
, fromJsPort = fromJsPort
, manifest = manifest
, generateFiles = \_ -> generateFiles
, init = \_ -> ( (), Cmd.none )
, update = \_ _ -> ( (), Cmd.none )
, view =
2021-04-03 00:44:40 +03:00
\_ page ->
let
thing =
pages
|> Dict.fromList
|> Dict.get
(page.path
|> PagePath.toString
|> String.split "/"
|> List.filter (\pathPart -> pathPart /= "")
)
in
case thing of
Just request ->
request
|> StaticHttp.map
2021-04-03 00:44:40 +03:00
(\_ -> { view = \_ _ -> { title = "Title", body = Html.text "" }, head = [] })
Nothing ->
Debug.todo "Couldn't find page"
2020-10-26 21:50:06 +03:00
, subscriptions = \_ _ _ -> Sub.none
, document = document
, content =
[ ( [ "elm-pages" ]
, { extension = "md", frontMatter = "{}", body = Nothing }
)
]
2020-10-21 06:48:21 +03:00
, canonicalSiteUrl = canonicalSiteUrl
, pathKey = PathKey
, onPageChange = Just (\_ -> ())
}
encodedFlags =
--{"secrets":
-- {"API_KEY": "ABCD1234","BEARER": "XYZ789"}, "mode": "prod", "staticHttpCache": {}
-- }
Encode.object
[ ( "secrets"
, [ ( "API_KEY", "ABCD1234" )
, ( "BEARER", "XYZ789" )
]
|> Dict.fromList
|> Encode.dict identity Encode.string
)
, ( "mode", Encode.string "elm-to-html-beta" )
, ( "staticHttpCache", encodedStaticHttpCache )
]
encodedStaticHttpCache =
staticHttpCache
|> List.map
(\( request, httpResponseString ) ->
( Request.hash request, Encode.string httpResponseString )
)
|> Encode.object
in
{-
(Model -> model)
-> ContentCache.ContentCache metadata view
-> Result (List BuildError) (List ( PagePath pathKey, metadata ))
-> Config pathKey userMsg userModel metadata view
-> Decode.Value
-> ( model, Effect pathKey )
-}
ProgramTest.createDocument
2021-04-03 00:44:40 +03:00
{ init = init identity contentCache siteMetadata config
, update = update contentCache siteMetadata config
, view = \_ -> { title = "", body = [] }
}
|> ProgramTest.withSimulatedEffects simulateEffects
|> ProgramTest.start (flags (Encode.encode 0 encodedFlags))
2020-10-21 06:48:21 +03:00
canonicalSiteUrl =
""
flags : String -> JD.Value
flags jsonString =
case JD.decodeString JD.value jsonString of
Ok value ->
value
Err _ ->
Debug.todo "Invalid JSON value."
2021-04-03 00:44:40 +03:00
simulateEffects : Effect PathKey -> ProgramTest.SimulatedEffect Msg
simulateEffects effect =
case effect of
Effect.NoEffect ->
SimulatedEffect.Cmd.none
Effect.SendJsData value ->
2020-10-21 06:48:21 +03:00
SimulatedEffect.Ports.send "toJsPort" (value |> Codec.encoder (ToJsPayload.toJsCodec canonicalSiteUrl))
-- toJsPort value |> Cmd.map never
Effect.Batch list ->
list
|> List.map simulateEffects
|> SimulatedEffect.Cmd.batch
2021-04-03 00:44:40 +03:00
Effect.FetchHttp ({ unmasked } as requests) ->
Http.request
{ method = unmasked.method
, url = unmasked.url
, headers = unmasked.headers |> List.map (\( key, value ) -> Http.header key value)
, body =
case unmasked.body of
StaticHttpBody.EmptyBody ->
Http.emptyBody
StaticHttpBody.StringBody contentType string ->
Http.stringBody contentType string
StaticHttpBody.JsonBody value ->
Http.jsonBody value
, expect =
PagesHttp.expectString
(\response ->
GotStaticHttpResponse
{ request = requests
, response = response
}
)
, timeout = Nothing
, tracker = Nothing
}
Effect.SendSinglePage info ->
2020-10-14 07:02:12 +03:00
SimulatedEffect.Cmd.batch
[ info
2020-10-20 03:41:27 +03:00
|> Codec.encoder (ToJsPayload.successCodecNew2 "" "")
2020-10-14 07:02:12 +03:00
|> SimulatedEffect.Ports.send "toJsPort"
, SimulatedEffect.Task.succeed ()
2021-04-03 00:44:40 +03:00
|> SimulatedEffect.Task.perform (\_ -> Continue)
2020-10-14 07:02:12 +03:00
]
Effect.Continue ->
2020-10-14 07:02:12 +03:00
SimulatedEffect.Cmd.none
2021-04-03 00:44:40 +03:00
Effect.ReadFile _ ->
2021-04-01 05:55:28 +03:00
SimulatedEffect.Cmd.none
2021-04-03 00:44:40 +03:00
Effect.GetGlob _ ->
2021-04-01 05:55:28 +03:00
SimulatedEffect.Cmd.none
2020-10-14 07:02:12 +03:00
--SimulatedEffect.Task.succeed ()
-- |> SimulatedEffect.Task.perform (\_ -> Main.Continue)
2021-04-03 00:49:18 +03:00
toJsPort _ =
Cmd.none
fromJsPort =
Sub.none
type PathKey
= PathKey
manifest : Manifest.Config PathKey
manifest =
{ backgroundColor = Nothing
, categories = []
, displayMode = Manifest.Standalone
, orientation = Manifest.Portrait
, description = "elm-pages - A statically typed site generator."
, iarcRatingId = Nothing
, name = "elm-pages docs"
, themeColor = Nothing
, startUrl = PagePath.external ""
, shortName = Just "elm-pages"
, sourceIcon = ImagePath.external ""
2020-10-21 05:38:51 +03:00
, icons = []
}
starDecoder : Decoder Int
starDecoder =
Decode.field "stargazer_count" Decode.int
expectSuccess : List ( String, List ( Request.Request, String ) ) -> ProgramTest model msg effect -> Expect.Expectation
expectSuccess expectedRequests previous =
previous
|> ProgramTest.expectOutgoingPortValues
"toJsPort"
2020-10-20 03:41:27 +03:00
(Codec.decoder (ToJsPayload.successCodecNew2 "" ""))
2020-10-11 19:25:37 +03:00
(\portPayloads ->
portPayloads
2020-10-18 04:58:17 +03:00
|> List.filterMap
(\portPayload ->
case portPayload of
ToJsPayload.PageProgress value ->
Just ( value.route, value.contentJson )
2021-04-03 00:44:40 +03:00
ToJsPayload.InitialData _ ->
2020-10-18 04:58:17 +03:00
Nothing
2021-04-01 05:55:28 +03:00
2021-04-03 00:44:40 +03:00
ToJsPayload.ReadFile _ ->
2021-04-01 05:55:28 +03:00
Nothing
2021-04-03 00:44:40 +03:00
ToJsPayload.Glob _ ->
2021-04-01 05:55:28 +03:00
Nothing
2020-10-18 04:58:17 +03:00
)
2020-10-11 19:25:37 +03:00
|> Dict.fromList
|> Expect.equalDicts
(expectedRequests
|> List.map
(\( url, requests ) ->
( url
, requests
|> List.map
(\( request, response ) ->
( Request.hash request, response )
)
2020-10-11 19:25:37 +03:00
|> Dict.fromList
)
2020-10-11 19:21:49 +03:00
)
2020-10-11 19:25:37 +03:00
|> Dict.fromList
)
)
get : String -> Request.Request
get url =
{ method = "GET"
, url = url
, headers = []
, body = StaticHttp.emptyBody
}