packages feed

sydtest-webdriver-0.1.0.0 / src / Test / Syd / Webdriver.hs

{-# LANGUAGE DataKinds #-}{-# LANGUAGE FlexibleContexts #-}{-# LANGUAGE FlexibleInstances #-}{-# LANGUAGE GeneralizedNewtypeDeriving #-}{-# LANGUAGE NumericUnderscores #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE RecordWildCards #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE TypeFamilies #-}{-# LANGUAGE UndecidableInstances #-}module Test.Syd.Webdriver  ( -- * Defining webdriver tests    WebdriverSpec,    webdriverSpec,    WebdriverTestM (..),    runWebdriverTestM,    WebdriverSessionStartFailed (..),    WebdriverTestEnv (..),    webdriverTestEnvSetupFunc,    -- * Writing webdriver tests    openPath,    setWindowSize,    -- * Running a selenium server    SeleniumServerHandle (..),    seleniumServerSetupFunc,  )whereimport Control.Concurrent.STM (newTVarIO)import Control.Exception (Exception, bracket, throwIO)import Control.Monad (guard, void)import Control.Monad.IO.Unliftimport Control.Monad.Readerimport qualified Data.Aeson as JSONimport qualified Data.Aeson.Types as JSONimport qualified Data.ByteString.Lazy as LBimport Data.Text (Text)import qualified Data.Text as Timport GHC.Stackimport Network.HTTP.Client as HTTPimport qualified Network.HTTP.Types as HTTPimport Network.Socketimport Network.Socket.Freeimport Network.Socket.Wait as Portimport Network.URIimport Pathimport Path.IOimport System.Environment (getEnvironment)import System.Exitimport System.Process.Typedimport Test.Sydimport Test.Syd.Pathimport Test.Syd.Process.Typedimport Test.Syd.Waiimport Test.WebDriver as WDimport Test.WebDriver.Capabilities as WDimport Test.WebDriver.Types as WD-- | Type synonym for webdriver teststype WebdriverSpec app = TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app)-- | A monad for webdriver tests.-- This satisfies the 'WebDriver' constraint, and instantiates the 'IsTest' class.---- Every test runs in its own webdriver 'Session'.newtype WebdriverTestM app a = WebdriverTestM  { unWebdriverTestM :: ReaderT (WebdriverTestEnv app) (ReaderT Session IO) a  }  deriving    ( Functor,      Applicative,      Monad,      MonadIO,      MonadReader (WebdriverTestEnv app),      -- We don't want 'MonadUnliftIO', but we have to because webdriver uses      -- it.      MonadUnliftIO    )data WebdriverTestEnv app = WebdriverTestEnv  { -- | The base url of the app we test, so that we can test external sites just like local ones.    webdriverTestEnvURI :: !URI,    -- | The webdriver server to start a session on for every test    webdriverTestEnvDriver :: !Driver,    -- | The capabilities to request for every session    webdriverTestEnvCapabilities :: !Capabilities,    -- | The app that we'll test.    --    -- You can put any piece of data here. In the case of yesod tests, we'll put an @App@ here.    webdriverTestEnvApp :: !app  }instance SessionState (WebdriverTestM app) where  getSession = WebdriverTestM $ lift askinstance WebDriverBase (WebdriverTestM app) where  doCommandBase driver method urlPath args =    liftIO $ HTTP.httpLbs (mkDriverRequest driver method urlPath args) (_driverManager driver)instance IsTest (WebdriverTestM app ()) where  type Arg1 (WebdriverTestM app ()) = ()  type Arg2 (WebdriverTestM app ()) = WebdriverTestEnv app  runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc)instance IsTest (WebdriverTestM app (GoldenTest a)) where  type Arg1 (WebdriverTestM app (GoldenTest a)) = ()  type Arg2 (WebdriverTestM app (GoldenTest a)) = WebdriverTestEnv app  runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc)-- | Run a webdriver test in a new session.runWebdriverTestM :: WebdriverTestEnv app -> WebdriverTestM app a -> IO arunWebdriverTestM env (WebdriverTestM func) = do  let start = startWebdriverSession (webdriverTestEnvDriver env) (webdriverTestEnvCapabilities env)  bracket start closeWebdriverSession $    runReaderT $      flip runReaderT env $ do        unWebdriverTestM $ do          setImplicitWait 10_000          setScriptTimeout (Just 10_000)          setPageLoadTimeout 10_000        func-- | Thrown when the webdriver server does not start a session, for example-- because it could not launch the browser.data WebdriverSessionStartFailed = WebdriverSessionStartFailed  { webdriverSessionStartFailedStatus :: !HTTP.Status,    -- | The server's explanation    webdriverSessionStartFailedBody :: !LB.ByteString  }  deriving (Show)instance Exception WebdriverSessionStartFailed-- | Start a webdriver session.---- We don't use webdriver's 'startSession'' because it reports every failure-- as 'SessionNameAlreadyExists' and discards the server's explanation.startWebdriverSession :: Driver -> Capabilities -> IO SessionstartWebdriverSession driver capabilities = do  let sessionRequest =        mkDriverRequest driver methodPost "/session" $          JSON.object ["capabilities" JSON..= JSON.object ["alwaysMatch" JSON..= capabilities]]  response <- HTTP.httpLbs sessionRequest (_driverManager driver)  let webdriverSessionStartFailedStatus = HTTP.responseStatus response  let webdriverSessionStartFailedBody = HTTP.responseBody response  let parseSessionId :: JSON.Value -> JSON.Parser Text      parseSessionId = JSON.withObject "response" $ \o -> do        value <- o JSON..: "value"        JSON.withObject "value" (JSON..: "sessionId") value  let mSessionId = do        guard $ HTTP.statusIsSuccessful webdriverSessionStartFailedStatus        JSON.decode webdriverSessionStartFailedBody >>= JSON.parseMaybe parseSessionId  case mSessionId of    Nothing -> throwIO WebdriverSessionStartFailed {..}    Just sessionIdText -> do      -- Webdriver starts counting at one, see 'startSession''.      idCounter <- newTVarIO 1      pure        Session          { sessionDriver = driver,            sessionId = SessionId sessionIdText,            sessionName = "sydtest-webdriver",            -- We do not request the webSocketUrl capability.            sessionWebSocketUrl = Nothing,            sessionIdCounter = idCounter          }-- | Close a webdriver session that was started with 'startWebdriverSession'.closeWebdriverSession :: Session -> IO ()closeWebdriverSession session = do  let SessionId sessionIdText = sessionId session  let driver = sessionDriver session  let urlPath = T.pack $ concat ["/session/", T.unpack sessionIdText]  void $ HTTP.httpLbs (mkDriverRequest driver methodDelete urlPath JSON.Null) (_driverManager driver)-- | Open a page on the URI in the 'WebdriverTestEnv'.openPath :: String -> WebdriverTestM app ()openPath p = do  uri <- asks webdriverTestEnvURI  let url = show uri <> p  openPage url-- | Set the size of the current window, without moving it.setWindowSize ::  (HasCallStack, WebDriver wd) =>  -- | (Width, Height)  (Word, Word) ->  wd ()setWindowSize (w, h) = do  rect <- getWindowRect  setWindowRect $    rect      { rectWidth = fromIntegral w,        rectHeight = fromIntegral h      }webdriverSpec ::  (HTTP.Manager -> SetupFunc (URI, app)) ->  WebdriverSpec app ->  SpecwebdriverSpec appSetupFunc =  managerSpec    . modifyMaxSuccess (`div` 50)    . setupAroundWith' (\man () -> appSetupFunc man)    . setupAroundAll seleniumServerSetupFunc    . webdriverTestEnvSpecwebdriverTestEnvSpec ::  TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) ->  TestDef '[SeleniumServerHandle, HTTP.Manager] (URI, app)webdriverTestEnvSpec = setupAroundWith' go2 . setupAroundWith' go1  where    go1 ::      SeleniumServerHandle ->      (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app)) ->      SetupFunc (WebdriverTestEnv app)    go1 ssh func = func ssh    go2 ::      HTTP.Manager ->      (URI, app) ->      SetupFunc (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app))    go2 man (uri, app) = pure $ \ssh -> webdriverTestEnvSetupFunc ssh man uri app-- | Set up a 'WebdriverTestEnv' for your app by readying a webdriver sessionwebdriverTestEnvSetupFunc ::  SeleniumServerHandle ->  HTTP.Manager ->  URI ->  app ->  SetupFunc (WebdriverTestEnv app)webdriverTestEnvSetupFunc SeleniumServerHandle {..} manager uri app = do  chromeExecutable <- liftIO $ do    chromeFile <- parseRelFile "chromium"    mExecutable <- findExecutable chromeFile    case mExecutable of      Nothing -> die "No chromium found on PATH."      Just executable -> pure executable  let chromeOptions =        defaultChromeOptions          { _chromeOptionsArgs =              Just                [ -- We don't set the --user-data-dir because it makes the                  -- chromedriver timeout for unknown reasons.                  -- "--user-data-dir=" <> fromAbsDir tempDir,                  "--headless",                  -- Bypass OS security model to run on nix as well                  "--no-sandbox",                  -- No need for a GPU in headless mode(?)                  "--disable-gpu",                  -- Overcome limited resource problem                  "--disable-dev-shm-usage",                  -- Normalise setup for screenshots                  "--use-gl=angle",                  "--use-angle=swiftshader",                  -- 1080 + 87, the height of the bar that says "Chrome is Being Controlled by Automated Test Software".                  "--window-size=1920,1167",                  -- Toke                  "--disable-infobars",                  -- So that screenshots tests don't start failing when something new is added at the bottom of the page that isn't even on the screen                  "--hide-scrollbars"                ],            _chromeOptionsBinary = Just $ fromAbsFile chromeExecutable          }  let webdriverTestEnvCapabilities =        WD.defaultCaps          { _capabilitiesBrowserName = Just "chrome",            _capabilitiesGoogChromeOptions = Just chromeOptions          }  seleniumDriver <-    mkManualDriver      "127.0.0.1"      ((fromIntegral :: PortNumber -> Int) seleniumServerHandlePort)      -- [check:tag SeleniumVersion] Selenium 3 serves the webdriver protocol under      -- this path, and takes its port as a single-dash flag.      -- Selenium 4 does neither, so update both when nixpkgs upgrades it.      "/wd/hub"      []  let webdriverTestEnvDriver = seleniumDriver {_driverManager = manager}  let webdriverTestEnvURI = uri      webdriverTestEnvApp = app  pure WebdriverTestEnv {..}data SeleniumServerHandle = SeleniumServerHandle  { seleniumServerHandlePort :: !PortNumber  }-- | Run, and clean up, a selenium serverseleniumServerSetupFunc :: SetupFunc SeleniumServerHandleseleniumServerSetupFunc = do  tempDir <- tempDirSetupFunc "selenium-server"  environment <- liftIO getEnvironment  configDir <- liftIO $ resolveDir tempDir "config"  cacheDir <- liftIO $ resolveDir tempDir "cache"  let newEnvironment =        environment          ++ [ ("XDG_CONFIG_HOME", fromAbsDir configDir),               ("XDG_CACHE_HOME", fromAbsDir cacheDir)             ]  portInt <- liftIO getFreePort  -- [check:ref SeleniumVersion]  let processConfig =        setStdout nullStream $          setStderr nullStream $            setEnv newEnvironment $              setWorkingDir (fromAbsDir tempDir) $                proc                  "selenium-server"                  [ "-port",                    show portInt                  ]  _ <- typedProcessSetupFunc processConfig  liftIO $ Port.wait "127.0.0.1" portInt  let seleniumServerHandlePort = fromIntegral portInt  pure SeleniumServerHandle {..}