sydtest-webdriver 0.0.0.1 → 0.1.0.0
raw patch · API changes only · 5 files changed · hide whitespace changes · browse sydtest-webdriver-0.1.0.0
+262/−80 lines, 5 filesdep +bytestringdep +stmdep +textdep −monad-controldep −transformers-basedep ~webdriversetup-changedPVP ok
Dependencies added: bytestring, stm, text, unliftio-core
Dependencies removed: monad-control, transformers-base
Dependency ranges changed: webdriver
API changes (from Hackage documentation)
5 removed, 11 added, 6 changed
version bump matches the API change (PVP)
- Test.Syd.Webdriver: [webdriverTestEnvConfig] :: WebdriverTestEnv app -> !WDConfig
- Test.Syd.Webdriver: instance Control.Monad.Base.MonadBase GHC.Types.IO (Test.Syd.Webdriver.WebdriverTestM app)
- Test.Syd.Webdriver: instance Control.Monad.Trans.Control.MonadBaseControl GHC.Types.IO (Test.Syd.Webdriver.WebdriverTestM app)
- Test.Syd.Webdriver: instance Test.WebDriver.Class.WebDriver (Test.Syd.Webdriver.WebdriverTestM app)
- Test.Syd.Webdriver: instance Test.WebDriver.Session.WDSessionState (Test.Syd.Webdriver.WebdriverTestM app)
+ Test.Syd.Webdriver: WebdriverSessionStartFailed :: !Status -> !ByteString -> WebdriverSessionStartFailed
+ Test.Syd.Webdriver: [webdriverSessionStartFailedBody] :: WebdriverSessionStartFailed -> !ByteString
+ Test.Syd.Webdriver: [webdriverSessionStartFailedStatus] :: WebdriverSessionStartFailed -> !Status
+ Test.Syd.Webdriver: [webdriverTestEnvCapabilities] :: WebdriverTestEnv app -> !Capabilities
+ Test.Syd.Webdriver: [webdriverTestEnvDriver] :: WebdriverTestEnv app -> !Driver
+ Test.Syd.Webdriver: data WebdriverSessionStartFailed
+ Test.Syd.Webdriver: instance Control.Monad.IO.Unlift.MonadUnliftIO (Test.Syd.Webdriver.WebdriverTestM app)
+ Test.Syd.Webdriver: instance GHC.Exception.Type.Exception Test.Syd.Webdriver.WebdriverSessionStartFailed
+ Test.Syd.Webdriver: instance GHC.Show.Show Test.Syd.Webdriver.WebdriverSessionStartFailed
+ Test.Syd.Webdriver: instance Test.WebDriver.Types.SessionState (Test.Syd.Webdriver.WebdriverTestM app)
+ Test.Syd.Webdriver: instance Test.WebDriver.Types.WebDriverBase (Test.Syd.Webdriver.WebdriverTestM app)
- Test.Syd.Webdriver: SeleniumServerHandle :: PortNumber -> SeleniumServerHandle
+ Test.Syd.Webdriver: SeleniumServerHandle :: !PortNumber -> SeleniumServerHandle
- Test.Syd.Webdriver: WebdriverTestEnv :: !URI -> !WDConfig -> !app -> WebdriverTestEnv app
+ Test.Syd.Webdriver: WebdriverTestEnv :: !URI -> !Driver -> !Capabilities -> !app -> WebdriverTestEnv app
- Test.Syd.Webdriver: WebdriverTestM :: ReaderT (WebdriverTestEnv app) WD a -> WebdriverTestM app a
+ Test.Syd.Webdriver: WebdriverTestM :: ReaderT (WebdriverTestEnv app) (ReaderT Session IO) a -> WebdriverTestM app a
- Test.Syd.Webdriver: [seleniumServerHandlePort] :: SeleniumServerHandle -> PortNumber
+ Test.Syd.Webdriver: [seleniumServerHandlePort] :: SeleniumServerHandle -> !PortNumber
- Test.Syd.Webdriver: [unWebdriverTestM] :: WebdriverTestM app a -> ReaderT (WebdriverTestEnv app) WD a
+ Test.Syd.Webdriver: [unWebdriverTestM] :: WebdriverTestM app a -> ReaderT (WebdriverTestEnv app) (ReaderT Session IO) a
- Test.Syd.Webdriver: type WebdriverSpec app = TestDef '[SeleniumServerHandle, Manager] (WebdriverTestEnv app)
+ Test.Syd.Webdriver: type WebdriverSpec app = TestDef '[SeleniumServerHandle, Manager] WebdriverTestEnv app
Files
- CHANGELOG.md +12/−0
- Setup.hs +2/−0
- src/Test/Syd/Webdriver.hs +158/−72 · folded
- sydtest-webdriver.cabal +9/−5
- test/Test/Syd/WebdriverSpec.hs +81/−3 · folded
CHANGELOG.md view
@@ -1,5 +1,17 @@ # Changelog +## [0.1.0.0] - 2026-12-04++### Added++* `WebdriverSessionStartFailed`, thrown with the server's response when a session cannot be started.++### Changed++* Compatibility with `webdriver >=0.15`.+* `WebdriverTestEnv` now holds a `webdriverTestEnvDriver` and `webdriverTestEnvCapabilities` instead of a `webdriverTestEnvConfig`.+* `WebdriverTestM` now has a `MonadUnliftIO` instance instead of `MonadBaseControl IO` and `MonadBase IO`.+ ## [0.0.0.1] - 2022-11-18 * `--hide-scrollbars` for the chrome session by default.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
src/Test/Syd/Webdriver.hs view
@@ -8,10 +8,6 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-}--- Because of webdriver using dangerous constructors-{-# OPTIONS_GHC -fno-warn-incomplete-record-updates #-}--- For the undefined trick-{-# OPTIONS_GHC -fno-warn-unused-pattern-binds #-} module Test.Syd.Webdriver ( -- * Defining webdriver tests@@ -19,6 +15,7 @@ webdriverSpec, WebdriverTestM (..), runWebdriverTestM,+ WebdriverSessionStartFailed (..), WebdriverTestEnv (..), webdriverTestEnvSetupFunc, @@ -32,37 +29,45 @@ ) where -import Control.Monad.Base+import Control.Concurrent.STM (newTVarIO)+import Control.Exception (Exception, bracket, throwIO)+import Control.Monad (guard, void)+import Control.Monad.IO.Unlift import Control.Monad.Reader-import Control.Monad.Trans.Control-import Data.Aeson as JSON+import qualified Data.Aeson as JSON+import qualified Data.Aeson.Types as JSON+import qualified Data.ByteString.Lazy as LB+import Data.Text (Text)+import qualified Data.Text as T import GHC.Stack import Network.HTTP.Client as HTTP+import qualified Network.HTTP.Types as HTTP import Network.Socket import Network.Socket.Free import Network.Socket.Wait as Port import Network.URI import Path import Path.IO+import System.Environment (getEnvironment) import System.Exit import System.Process.Typed import Test.Syd import Test.Syd.Path import Test.Syd.Process.Typed import Test.Syd.Wai-import Test.WebDriver as WD hiding (setWindowSize)-import Test.WebDriver.Class (WebDriver (..))-import qualified Test.WebDriver.Commands.Internal as WD-import qualified Test.WebDriver.JSON as WD-import Test.WebDriver.Session (WDSessionState (..))+import Test.WebDriver as WD+import Test.WebDriver.Capabilities as WD+import Test.WebDriver.Types as WD -- | Type synonym for webdriver tests type WebdriverSpec app = TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) -- | A monad for webdriver tests.--- This instantiates the 'WebDriver' class, as well as the 'IsTest' class.+-- 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) WD a+ { unWebdriverTestM :: ReaderT (WebdriverTestEnv app) (ReaderT Session IO) a } deriving ( Functor,@@ -70,29 +75,30 @@ Monad, MonadIO, MonadReader (WebdriverTestEnv app),- -- We don't want 'MonadBaseControl IO' or 'MonadBase IO', but we have to- -- because webdriver uses them.- MonadBaseControl IO,- MonadBase IO+ -- 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 configuration- webdriverTestEnvConfig :: !WDConfig,+ -- | 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 WDSessionState (WebdriverTestM app) where- getSession = WebdriverTestM getSession- putSession = WebdriverTestM . putSession+instance SessionState (WebdriverTestM app) where+ getSession = WebdriverTestM $ lift ask -instance WebDriver (WebdriverTestM app) where- doCommand m p a = WebdriverTestM $ doCommand m p a+instance 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 ()) = ()@@ -104,15 +110,72 @@ type Arg2 (WebdriverTestM app (GoldenTest a)) = WebdriverTestEnv app runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc) --- | Run a webdriver test.+-- | Run a webdriver test in a new session. runWebdriverTestM :: WebdriverTestEnv app -> WebdriverTestM app a -> IO a-runWebdriverTestM env (WebdriverTestM func) = WD.runSession (webdriverTestEnvConfig env) $- WD.finallyClose $ do- setImplicitWait 10_000- setScriptTimeout 10_000- setPageLoadTimeout 10_000- runReaderT func env+runWebdriverTestM 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 Session+startWebdriverSession 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@@ -120,17 +183,19 @@ let url = show uri <> p openPage url --- We have to override this because it returns something.--- So we remove the 'noReturn'.+-- | Set the size of the current window, without moving it. setWindowSize :: (HasCallStack, WebDriver wd) => -- | (Width, Height) (Word, Word) -> wd ()-setWindowSize (w, h) =- WD.ignoreReturn $- WD.doWinCommand methodPost currentWindow "/size" $- object ["width" .= w, "height" .= h]+setWindowSize (w, h) = do+ rect <- getWindowRect+ setWindowRect $+ rect+ { rectWidth = fromIntegral w,+ rectHeight = fromIntegral h+ } webdriverSpec :: (HTTP.Manager -> SetupFunc (URI, app)) ->@@ -174,58 +239,79 @@ Nothing -> die "No chromium found on PATH." Just executable -> pure executable - userDataDir <- tempDirSetupFunc "chromium-user-data"-- let browser =- chrome- { chromeOptions =- [ "--user-data-dir=" <> fromAbsDir userDataDir,- "--headless",- -- Bypass OS security model to run on nix as well- "--no-sandbox",- -- Overcome limited resource problem- "--disable-dev-shm-usage",- "--disable-gpu",- "--use-gl=angle",- "--use-angle=swiftshader",- "--window-size=1920,1080",- -- 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"- ],- chromeBinary = Just $ fromAbsFile chromeExecutable+ 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 caps =+ let webdriverTestEnvCapabilities = WD.defaultCaps- { browser = browser- }- let webdriverTestEnvConfig =- WD.defaultConfig- { wdPort = (fromIntegral :: PortNumber -> Int) seleniumServerHandlePort,- wdHTTPManager = Just manager,- wdCapabilities = caps+ { _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+ { seleniumServerHandlePort :: !PortNumber } -- | Run, and clean up, a selenium server seleniumServerSetupFunc :: SetupFunc SeleniumServerHandle seleniumServerSetupFunc = 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 $- setWorkingDir (fromAbsDir tempDir) $- proc- "selenium-server"- [ "-port",- show portInt- ]+ 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
sydtest-webdriver.cabal view
@@ -1,11 +1,11 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.34.7.+-- This file has been generated from package.yaml by hpack version 0.38.3. -- -- see: https://github.com/sol/hpack name: sydtest-webdriver-version: 0.0.0.1+version: 0.1.0.0 synopsis: A webdriver companion library for sydtest category: Testing author: Tom Sydney Kerckhove@@ -28,20 +28,23 @@ build-depends: aeson , base >=4.7 && <5+ , bytestring , http-client- , monad-control+ , http-types , mtl , network , network-uri , path , path-io , port-utils+ , stm , sydtest , sydtest-typed-process , sydtest-wai- , transformers-base+ , text , typed-process- , webdriver+ , unliftio-core+ , webdriver >=0.15 default-language: Haskell2010 test-suite sydtest-webdriver-test@@ -64,4 +67,5 @@ , sydtest-wai , sydtest-webdriver , wai+ , webdriver default-language: Haskell2010
test/Test/Syd/WebdriverSpec.hs view
@@ -1,15 +1,93 @@+{-# LANGUAGE ScopedTypeVariables #-}+ module Test.Syd.WebdriverSpec (spec) where +import Control.Exception+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.List.NonEmpty as NE+import qualified Network.HTTP.Types as HTTP import Network.URI import Test.Syd+import Test.Syd.OptParse import Test.Syd.Wai import Test.Syd.Webdriver import Test.Syd.Webdriver.App+import Test.WebDriver (Rect (..), getWindowRect)+import Test.WebDriver.Capabilities (Capabilities (..), ChromeOptions (..)) +-- | An exception that a test throws itself, but that is classified as+-- asynchronous, as @effectful@'s @Error@ effect does.+-- See https://github.com/NorfairKing/sydtest/issues/110+data SynchronousButClassifiedAsynchronous = SynchronousButClassifiedAsynchronous+ deriving (Show, Eq)++instance Exception SynchronousButClassifiedAsynchronous where+ toException = asyncExceptionToException+ fromException = asyncExceptionFromException+ spec :: Spec-spec = exampleAppSpec $ do- it "can navigate to home" $- openPath "/"+spec = do+ describe "a test that throws an asynchronously-classified exception fails with that exception" $ do+ let settings = defaultSettings {settingRetries = 1}++ it "WebdriverTestM app ()" $ do+ specForest <-+ execTestDefM settings $+ exampleAppSpec $+ it "throws" (liftIO (throwIO SynchronousButClassifiedAsynchronous) :: WebdriverTestM () ())+ resultForest <- runSpecForestSynchronously settings specForest+ map+ (NE.map (\r -> (testRunResultStatus r, testRunResultException r >>= fromException)) . testRunReportRawResults . timedValue . testDefVal . snd)+ (flattenSpecForest (timedValue resultForest))+ `shouldBe` [(TestFailed, Just SynchronousButClassifiedAsynchronous) :| []]++ it "WebdriverTestM app (GoldenTest a)" $ do+ specForest <-+ execTestDefM settings $+ exampleAppSpec $+ it+ "throws"+ ( pure+ ( GoldenTest+ { goldenTestRead = pure (Just ()),+ goldenTestProduce = throwIO SynchronousButClassifiedAsynchronous,+ goldenTestWrite = \() -> pure (),+ goldenTestCompare = \() () -> pure Nothing+ }+ ) ::+ WebdriverTestM () (GoldenTest ())+ )+ resultForest <- runSpecForestSynchronously settings specForest+ map+ (NE.map (\r -> (testRunResultStatus r, testRunResultException r >>= fromException)) . testRunReportRawResults . timedValue . testDefVal . snd)+ (flattenSpecForest (timedValue resultForest))+ `shouldBe` [(TestFailed, Just SynchronousButClassifiedAsynchronous) :| []]++ exampleAppSpec $ do+ it "reports why a session could not be started" $ \env -> do+ let caps = webdriverTestEnvCapabilities env+ let brokenChromeOptions = (\o -> o {_chromeOptionsBinary = Just "/nonexistent/chromium"}) <$> _capabilitiesGoogChromeOptions caps+ let brokenEnv = env {webdriverTestEnvCapabilities = caps {_capabilitiesGoogChromeOptions = brokenChromeOptions}}+ result <- try $ runWebdriverTestM brokenEnv (pure ())+ case result of+ Right () -> expectationFailure "Should not have been able to start a session."+ Left (e :: SomeException) ->+ fmap webdriverSessionStartFailedStatus (fromException e) `shouldBe` Just HTTP.status500++ it "can navigate to home" $+ openPath "/"++ it "can resize the window without moving it" $ do+ openPath "/"+ rectBefore <- getWindowRect+ setWindowSize (800, 600)+ rectAfter <- getWindowRect+ liftIO $+ rectAfter+ `shouldBe` rectBefore+ { rectWidth = 800,+ rectHeight = 600+ } exampleAppSpec :: WebdriverSpec () -> Spec exampleAppSpec = webdriverSpec $ \_ -> do