sandwich-webdriver 0.5.0.0 → 0.6.0.0
raw patch · 9 files changed
+123/−57 lines, 9 files
Files
- CHANGELOG.md +6/−0
- LICENSE +1/−1
- sandwich-webdriver.cabal +3/−3
- src/Test/Sandwich/WebDriver.hs +1/−1
- src/Test/Sandwich/WebDriver/Config.hs +1/−0
- src/Test/Sandwich/WebDriver/Internal/Action.hs +43/−24
- src/Test/Sandwich/WebDriver/Internal/Types.hs +23/−8
- src/Test/Sandwich/WebDriver/Types.hs +40/−15
- test/Spec.hs +5/−5
CHANGELOG.md view
@@ -1,5 +1,11 @@ # Changelog for sandwich-webdriver +# 0.6.0.0++* Add `webDriverResponseMaxLogLength` to `WdOptions`, to limit how much of each WebDriver request and response body is logged. Defaults to 300 characters; `Just 0` turns this logging off and `Nothing` logs bodies in full.+* BREAKING CHANGE: the `WebDriverBase (ExampleT context m)` instance now requires `HasTestWebDriverContext context`. Code that runs WebDriver commands with only `HasWebDriverSessionContext` in scope needs to add it (or use `WebDriverSessionMonad`).+* Fix a `wdSessionMap` desync in `closeSession`/`closeAllSessionsExcept`: drop a session from the map only once its WebDriver-side close succeeds, and bound each close with a timeout. Previously an interrupted close could leave `wdSessionMap` out of sync with the driver's session map, causing `SessionNameAlreadyExists` on a later create of the same session name.+ # 0.5.0.0 * Support `webdriver-0.15.0.0`.
LICENSE view
@@ -1,4 +1,4 @@-Copyright Tom McLaughlin (c) 2025+Copyright Tom McLaughlin (c) 2026 All rights reserved.
sandwich-webdriver.cabal view
@@ -1,11 +1,11 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.38.0.+-- This file has been generated from package.yaml by hpack version 0.39.1. -- -- see: https://github.com/sol/hpack name: sandwich-webdriver-version: 0.5.0.0+version: 0.6.0.0 synopsis: Sandwich integration with Selenium WebDriver description: Please see the <https://codedownio.github.io/sandwich/docs/extensions/sandwich-webdriver documentation>. category: Testing@@ -13,7 +13,7 @@ bug-reports: https://github.com/codedownio/sandwich/issues author: Tom McLaughlin maintainer: tom@codedown.io-copyright: 2025 Tom McLaughlin+copyright: 2026 Tom McLaughlin license: BSD3 license-file: LICENSE build-type: Simple
src/Test/Sandwich/WebDriver.hs view
@@ -271,7 +271,7 @@ -- | Clean up the given WebDriver. cleanupWebDriver :: (BaseMonad m context) => TestWebDriverContext -> ExampleT context m ()-cleanupWebDriver sess = do+cleanupWebDriver sess = pushContext webdriver sess $ do closeAllSessions sess stopWebDriver sess
src/Test/Sandwich/WebDriver/Config.hs view
@@ -7,6 +7,7 @@ , defaultWdOptions , runMode , httpRetryCount+ , webDriverResponseMaxLogLength , geckodriverExtraFlags , chromedriverExtraFlags , modifyCapabilities
src/Test/Sandwich/WebDriver/Internal/Action.hs view
@@ -5,49 +5,68 @@ import Control.Monad import Control.Monad.Logger import qualified Data.Map as M+import Data.Maybe (catMaybes) import Data.String.Interpolate import GHC.Stack import Test.Sandwich import Test.Sandwich.WebDriver.Internal.Types-import Test.Sandwich.WebDriver.Internal.Util import Test.Sandwich.WebDriver.Types import qualified Test.WebDriver as W import UnliftIO.Concurrent import UnliftIO.Directory import UnliftIO.Exception+import UnliftIO.Timeout +-- | How long to wait for a single session's WebDriver-side close before giving up and leaving it in+-- the session map (still tracked, still consistent with W's _webDriverSessions).+sessionCloseTimeoutUs :: Int+sessionCloseTimeoutUs = 30 * 1000000 -- 30s+ -- | Close the given session. closeSession :: (MonadLogger m, W.WebDriverBase m) => SessionName -> TestWebDriverContext -> m ()-closeSession session (TestWebDriverContext {wdSessionMap, wdContext}) = do- toClose <- modifyMVar wdSessionMap $ \sessionMap ->+closeSession session (TestWebDriverContext {wdSessionMap, wdContext}) =+ modifyMVar_ wdSessionMap $ \sessionMap -> case M.lookup session sessionMap of- Nothing -> return (sessionMap, Nothing)- Just x -> return (M.delete session sessionMap, Just x)-- whenJust toClose $ \(SessionMapEntry {..}) -> do- W.closeSession wdContext sessionMapEntrySession-- info [i|Closing session: #{sessionMapEntrySession}. sessionMapEntryDirsToRemove: #{sessionMapEntryDirsToRemove}|]-- forM_ sessionMapEntryDirsToRemove $ \dirToRemove -> do- debug [i|Removing session-specific directory: #{dirToRemove}|]- catch (removePathForcibly dirToRemove)- (\(e :: SomeException) -> warn [i|Failed to remove session directory '#{dirToRemove}': '#{e}'|])+ Nothing -> return sessionMap+ Just (SessionMapEntry {..}) ->+ tryAny (timeout sessionCloseTimeoutUs (W.closeSession wdContext sessionMapEntrySession)) >>= \case+ Right (Just ()) -> do+ info [i|Closed session: #{sessionMapEntrySession}|]+ forM_ sessionMapEntryDirsToRemove $ \dirToRemove -> do+ debug [i|Removing session-specific directory: #{dirToRemove}|]+ catch (removePathForcibly dirToRemove)+ (\(e :: SomeException) -> warn [i|Failed to remove session directory '#{dirToRemove}': '#{e}'|])+ return (M.delete session sessionMap)+ Right Nothing -> do+ warn [i|Timed out after #{sessionCloseTimeoutUs `div` 1000000}s closing session '#{session}'. Leaving session in map.|]+ return sessionMap+ Left e -> do+ warn [i|Failed to destroy session '#{session}': '#{e}'. Leaving session in map.|]+ return sessionMap -- | Close all sessions except those listed. closeAllSessionsExcept :: (HasCallStack, MonadLogger m, W.WebDriverBase m) => [SessionName] -> TestWebDriverContext -> m ()-closeAllSessionsExcept toKeep (TestWebDriverContext {wdSessionMap, wdContext}) = do- toClose <- modifyMVar wdSessionMap $ return . M.partitionWithKey (\name _ -> name `elem` toKeep)+closeAllSessionsExcept toKeep (TestWebDriverContext {wdSessionMap, wdContext}) =+ modifyMVar_ wdSessionMap $ \sessionMap -> do+ let (toKeepMap, toCloseMap) = M.partitionWithKey (\name _ -> name `elem` toKeep) sessionMap - forM_ (M.toList toClose) $ \(name, SessionMapEntry {..}) -> do- catch (W.closeSession wdContext sessionMapEntrySession)- (\(e :: SomeException) -> warn [i|Failed to destroy session '#{name}': '#{e}'|])+ stillOpen <- fmap (M.fromList . catMaybes) $ forM (M.toList toCloseMap) $ \(name, entry@(SessionMapEntry {..})) ->+ tryAny (timeout sessionCloseTimeoutUs (W.closeSession wdContext sessionMapEntrySession)) >>= \case+ Right (Just ()) -> do+ forM_ sessionMapEntryDirsToRemove $ \dirToRemove -> do+ debug [i|Removing session-specific directory: #{dirToRemove}|]+ catch (removePathForcibly dirToRemove)+ (\(e :: SomeException) -> warn [i|Failed to remove session directory '#{dirToRemove}': '#{e}'|])+ return Nothing+ Right Nothing -> do+ warn [i|Timed out after #{sessionCloseTimeoutUs `div` 1000000}s closing session '#{name}'|]+ return (Just (name, entry))+ Left e -> do+ warn [i|Failed to destroy session '#{name}': '#{e}'|]+ return (Just (name, entry)) - forM_ sessionMapEntryDirsToRemove $ \dirToRemove -> do- debug [i|Removing session-specific directory: #{dirToRemove}|]- catch (removePathForcibly dirToRemove)- (\(e :: SomeException) -> warn [i|Failed to remove session directory '#{dirToRemove}': '#{e}'|])+ return (toKeepMap <> stillOpen) -- | Close all sessions. closeAllSessions :: (HasCallStack, MonadLogger m, W.WebDriverBase m) => TestWebDriverContext -> m ()
src/Test/Sandwich/WebDriver/Internal/Types.hs view
@@ -33,17 +33,19 @@ data WhenToSave = Always | OnException | Never deriving (Show, Eq) --- | Headless and Xvfb modes are useful because they allow you to run tests in the background, without popping up browser windows.--- This is useful for development or for running on a CI server, and is also more reproducible since the screen resolution can be fixed.--- In addition, Xvfb mode allows videos to be recorded of tests.+-- | Headless and Xvfb modes are useful because they allow you to run tests in+-- the background, without popping up browser windows. This is useful for+-- development or for running on a CI server, and is also more reproducible+-- since the screen resolution can be fixed. In addition, Xvfb mode allows+-- videos to be recorded of tests. data RunMode = Normal -- ^ Normal Selenium behavior; will pop up a web browser. | RunHeadless HeadlessConfig -- ^ Run with a headless browser. Supports screenshots but videos will be black. | RunInXvfb XvfbConfig- -- ^ Run inside <https://en.wikipedia.org/wiki/Xvfb Xvfb> so that tests run in their own X11 display.- -- The @Xvfb@ binary must be installed and on the PATH.+ -- ^ Run inside <https://en.wikipedia.org/wiki/Xvfb Xvfb> so that tests run in+ -- their own X11 display. The @Xvfb@ binary must be installed and on the PATH. data WdOptions = WdOptions { -- | How to handle opening the browser (in a popup window, headless, etc.).@@ -52,7 +54,19 @@ -- | Number of times to retry an HTTP request if it times out. , httpRetryCount :: Int - -- | Pass the --no-sandbox flag to Chrome (useful in GitHub Actions when installing Chrome via Nix).+ -- | We include WebDriver requests and responses in debug logs. This can+ -- create a lot of logs if they aren't truncated, especially if you do things+ -- like save screenshots.+ --+ -- This option defines the maximum number of characters of WebDriver HTTP+ -- bodies to include.+ --+ -- Set to 'Just 0' to skip this logging.+ -- Set to 'Nothing' to not truncate at all.+ , webDriverResponseMaxLogLength :: Maybe Int++ -- | Pass the --no-sandbox flag to Chrome (useful in GitHub Actions when+ -- installing Chrome via Nix). , chromeNoSandbox :: Bool -- | Extra flags to pass to chromedriver.@@ -65,8 +79,8 @@ , modifyCapabilities :: W.Capabilities -> IO W.Capabilities } --- | How to obtain certain binaries "on demand". These may or not be needed based on 'WdOptions', so--- they will be obtained as needed.+-- | How to obtain certain binaries "on demand". These may or not be needed+-- based on 'WdOptions', so they will be obtained as needed. data OnDemandOptions = OnDemandOptions { -- | How to obtain ffmpeg binary. ffmpegToUse :: FfmpegToUse@@ -108,6 +122,7 @@ defaultWdOptions = WdOptions { runMode = Normal , httpRetryCount = 0+ , webDriverResponseMaxLogLength = Just 300 , chromeNoSandbox = False , chromedriverExtraFlags = [] , geckodriverExtraFlags = []
src/Test/Sandwich/WebDriver/Types.hs view
@@ -24,15 +24,18 @@ -- , getXvfbSession ) where +import Control.Monad import Control.Monad.Catch (MonadMask) import Control.Monad.IO.Class import Control.Monad.IO.Unlift import Control.Monad.Reader import qualified Data.Aeson as A-import Data.ByteString import qualified Data.ByteString.Lazy as BL import Data.String.Interpolate import Data.Text (Text)+import qualified Data.Text as T+import Data.Text.Encoding (decodeUtf8With)+import Data.Text.Encoding.Error (lenientDecode) import GHC.Stack import qualified Network.HTTP.Client as HC import Network.HTTP.Types.Status as N@@ -66,30 +69,52 @@ return sess -- This implementation of 'W.WebDriverBase' provides logging for the requests/responses.-instance (MonadUnliftIO m) => W.WebDriverBase (ExampleT context m) where+instance (MonadUnliftIO m, HasTestWebDriverContext context) => W.WebDriverBase (ExampleT context m) where doCommandBase driver method path args = do+ truncationLength <- (webDriverResponseMaxLogLength . wdOptions) <$> getContext webdriver+ let req = W.mkDriverRequest driver method path args- debug [i|--> #{HC.method req} #{HC.path req}#{HC.queryString req} (#{showRequestBody (HC.requestBody req)})|]++ when (truncationLength /= Just 0) $+ debug [i|--> #{HC.method req} #{HC.path req}#{HC.queryString req} (#{truncateForLogging truncationLength (showRequestBody (HC.requestBody req))})|]+ response <- tryAny (liftIO $ HC.httpLbs req (W._driverManager driver)) >>= either throwIO return let (N.Status code _) = HC.responseStatus response - -- TODO: truncate the response body. We're currently logging entire screenshot responses.+ when (truncationLength /= Just 0) $+ if | code >= 200 && code < 300 -> case A.eitherDecode (HC.responseBody response) of+ -- For successful responses, try to pull out the "value" and show it+ Right (A.Object (aesonLookup "value" -> Just value)) -> debug [i|<-- #{code} #{truncateForLogging truncationLength (A.encode value)}|]+ _ -> debug [i|<-- #{code} #{truncateForLogging truncationLength (HC.responseBody response)}|]+ -- For non-successful responses, log the entire response.+ -- Reading the WebDriver spec, it would probably be sufficient to just show the "value" as above,+ -- plus the HTTP status message.+ | otherwise -> debug [i|<-- #{code} #{truncateTextForLogging truncationLength (T.pack (show response))}|] - if | code >= 200 && code < 300 -> case A.eitherDecode (HC.responseBody response) of- -- For successful responses, try to pull out the "value" and show it- Right (A.Object (aesonLookup "value" -> Just value)) -> debug [i|<-- #{code} #{A.encode value}|]- _ -> debug [i|<-- #{code} #{HC.responseBody response}|]- -- For non-successful responses, log the entire response.- -- Reading the WebDriver spec, it would probably be sufficient to just show the "value" as above,- -- plus the HTTP status message.- | otherwise -> debug [i|<-- #{code} #{response}|] return response where- showRequestBody :: HC.RequestBody -> ByteString- showRequestBody (HC.RequestBodyLBS bytes) = BL.toStrict bytes- showRequestBody (HC.RequestBodyBS bytes) = bytes+ showRequestBody :: HC.RequestBody -> BL.ByteString+ showRequestBody (HC.RequestBodyLBS bytes) = bytes+ showRequestBody (HC.RequestBodyBS bytes) = BL.fromStrict bytes showRequestBody _ = "<request body>"++ -- Measure and slice on the raw bytes (both O(1)) and only decode the retained prefix,+ -- so large bodies (e.g. base64 screenshots) aren't decoded in full.+ truncateForLogging :: Maybe Int -> BL.ByteString -> Text+ truncateForLogging maxLen bytes = case maxLen of+ Just n | len > fromIntegral n ->+ decodeUtf8With lenientDecode (BL.toStrict (BL.take (fromIntegral n) bytes))+ <> [i| ... (#{len - fromIntegral n} more bytes)|]+ _ -> decodeUtf8With lenientDecode (BL.toStrict bytes)+ where+ len = BL.length bytes++ -- Like 'truncateForLogging', but for a value that's already 'Text' (truncates by character).+ truncateTextForLogging :: Maybe Int -> Text -> Text+ truncateTextForLogging maxLen t = case maxLen of+ Just n | T.length t > n -> T.take n t <> [i| ... (#{T.length t - n} more characters)|]+ _ -> t type HasTestWebDriverContext context = HasLabel context "webdriver" TestWebDriverContext type HasWebDriverSessionContext context = HasLabel context "webdriverSession" WebDriverSession
test/Spec.hs view
@@ -15,13 +15,13 @@ import qualified Data.ByteString.Lazy as BL --- We use nixpkgsRelease2405 here, because Chrome/chromedriver > 131 seems to have a bug where we get--- a message like this in CI:------ session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir+-- We use nixpkgsMaster rather than a release pin because google-chrome is unfree, so it isn't in+-- the Nix binary cache and has to be downloaded from Google. Google only serves the current couple+-- of Chrome releases, so the google-chrome in an older pin fails to fetch with a 404. Bump+-- nixpkgsMaster whenever that happens. spec :: TopSpecWithOptions-spec = introduceNixContext (nixpkgsRelease2505 { nixpkgsDerivationAllowUnfree = True }) $+spec = introduceNixContext (nixpkgsMaster { nixpkgsDerivationAllowUnfree = True }) $ introduceWebDriverViaNix defaultWdOptions $ do it "opens Xkcd and presses the prev button" $ withSession1 $ do openPage [i|https://www.xkcd.com|]