sandwich 0.3.1.0 → 0.4.0.0
raw patch · 35 files changed
+1208/−150 lines, 35 files
Files
- CHANGELOG.md +17/−0
- LICENSE +1/−1
- sandwich.cabal +12/−2
- src/Test/Sandwich.hs +59/−15
- src/Test/Sandwich/ArgParsing.hs +5/−0
- src/Test/Sandwich/Formatters/TerminalUI.hs +22/−7
- src/Test/Sandwich/Formatters/TerminalUI/CrossPlatform.hs +15/−0
- src/Test/Sandwich/Formatters/TerminalUI/Draw/TopBox.hs +7/−0
- src/Test/Sandwich/Formatters/TerminalUI/Keys.hs +1/−0
- src/Test/Sandwich/Formatters/TerminalUI/SpeedScope.hs +189/−0
- src/Test/Sandwich/Formatters/TerminalUI/Types.hs +4/−1
- src/Test/Sandwich/Internal/Inspection.hs +2/−0
- src/Test/Sandwich/Internal/Running.hs +6/−1
- src/Test/Sandwich/Interpreters/RunTree.hs +4/−3
- src/Test/Sandwich/Interpreters/RunTree/FolderNameLength.hs +74/−0
- src/Test/Sandwich/Interpreters/RunTree/Util.hs +13/−11
- src/Test/Sandwich/Interpreters/StartTree.hs +67/−31
- src/Test/Sandwich/Logging/Process.hs +17/−2
- src/Test/Sandwich/ManagedAsync.hs +10/−0
- src/Test/Sandwich/Options.hs +17/−0
- src/Test/Sandwich/ParallelN.hs +159/−31
- src/Test/Sandwich/RunTree.hs +18/−0
- src/Test/Sandwich/Shutdown.hs +9/−7
- src/Test/Sandwich/TH.hs +31/−18
- src/Test/Sandwich/TestTimer.hs +90/−12
- src/Test/Sandwich/Types/ArgParsing.hs +1/−0
- src/Test/Sandwich/Types/RunTree.hs +7/−1
- src/Test/Sandwich/Types/Spec.hs +3/−1
- src/Test/Sandwich/Types/TestTimer.hs +15/−0
- test/CancelOnLongExecution.hs +50/−0
- test/EscapedExceptions.hs +69/−0
- test/FolderPaths.hs +89/−0
- test/Main.hs +16/−6
- test/TestUtil.hs +37/−0
- test/UnicodeLabels.hs +72/−0
CHANGELOG.md view
@@ -1,5 +1,22 @@ # Changelog for sandwich +## 0.4.0.0++* TUI: be able to press 'S' to open the speedscope profile in a browser.+* `parallelN` now limits with a pool of lanes instead of a semaphore, so a run produces N test timer profiles rather than one per test. The bound still covers the whole subtree, including nested `parallel` nodes.+* BREAKING CHANGE: `parallelN` introduces `parallelLanes` instead of `parallelSemaphore`, and requires `HasBaseContext`. Claim a lane with `withParallelLane` rather than taking the `QSem` yourself; unlike the semaphore, it's re-entrant.+* Add `withParallelLanes`, `withParallelLanesFromArgs` and `takeParallelLane`, for limiting a spec tree you can't wrap with `parallelN` (such as one from `getSpecFromFolder`).+* Don't leave children running when a `parallel` node stops waiting on them early.+* Fix nodes being left `Running` or `NotStarted` forever when a subtree is cancelled, which hung the `--print-failures` formatter (and anything else that calls `waitForTree`).+* Export `optionsWarnOnLongExecutionMs` and `optionsCancelOnLongExecutionMs`, which previously could only be set from the command line.+* Keep acronyms intact in discovered folder names (#137).+* `createProcessWithLogging` and `readCreateProcessWithLogging` close the parent's copy of the logging pipe's write end and spawn with `close_fds`, so the log reader reaches EOF when the process exits (avoids hang on Windows).+* Shorten test folder names to keep paths under Windows' `MAX_PATH`, preserving the tree structure. Configure with `optionsMaxFolderPathLength`/`--max-folder-path-length` (0 disables). It defaults to 200 on Windows, leaving 59 characters for files under `MAX_PATH` (260, including the terminating NUL).+* BREAKING CHANGE: `CommandLineOptions` has a new field, `optMaxFolderPathLength`.+* Fix build with `containers` >= 0.8.1, whose `Data.Sequence` now exports `toList` (#143).+* Use UTF-8 for file paths and stdout/stderr regardless of locale, so test labels with non-ASCII characters work under e.g. `LANG=C` (#146).+* Fix a hang after an unexpected exception in a node, and rethrow `finalizeFormatter` errors once the run has shut down instead of aborting the shutdown (#145).+ ## 0.3.1.0 * Add a socket formatter (`Test.Sandwich.Formatters.Socket`) and a TUI debug socket (`Test.Sandwich.Formatters.TerminalUI.DebugSocket`).
LICENSE view
@@ -1,4 +1,4 @@-Copyright Tom McLaughlin (c) 2025+Copyright Tom McLaughlin (c) 2026 All rights reserved.
sandwich.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: sandwich-version: 0.3.1.0+version: 0.4.0.0 synopsis: Yet another test framework for Haskell description: Please see the <https://codedownio.github.io/sandwich 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@@ -72,6 +72,7 @@ Test.Sandwich.Formatters.TerminalUI.Filter Test.Sandwich.Formatters.TerminalUI.Keys Test.Sandwich.Formatters.TerminalUI.OpenInEditor+ Test.Sandwich.Formatters.TerminalUI.SpeedScope Test.Sandwich.Formatters.TerminalUI.Types Test.Sandwich.Golden.Update Test.Sandwich.Instrumentation@@ -83,6 +84,7 @@ Test.Sandwich.Interpreters.PrettyShow Test.Sandwich.Interpreters.PruneTree Test.Sandwich.Interpreters.RunTree+ Test.Sandwich.Interpreters.RunTree.FolderNameLength Test.Sandwich.Interpreters.RunTree.Logging Test.Sandwich.Interpreters.RunTree.Util Test.Sandwich.Interpreters.StartTree@@ -289,10 +291,14 @@ other-modules: Around Before+ CancelOnLongExecution Describe+ EscapedExceptions+ FolderPaths Introduce IntroduceWith TestUtil+ UnicodeLabels Paths_sandwich hs-source-dirs: test@@ -357,10 +363,14 @@ other-modules: Around Before+ CancelOnLongExecution Describe+ EscapedExceptions+ FolderPaths Introduce IntroduceWith TestUtil+ UnicodeLabels Paths_sandwich hs-source-dirs: test
src/Test/Sandwich.hs view
@@ -46,8 +46,22 @@ , aroundEach -- * Parallel nodes- , module Test.Sandwich.ParallelN+ , parallelN+ , parallelN'+ , parallelNFromArgs+ , parallelNFromArgs'+ , defaultParallelNodeOptions + -- ** Lower-level+ , withParallelLanes+ , withParallelLanesFromArgs+ , withParallelLane+ , takeParallelLane++ , ParallelLanes+ , parallelLanes+ , HasParallelLanes+ -- * Timing -- -- | For timing actions within your tests. Test tree nodes are timed by default.@@ -102,7 +116,7 @@ import System.Environment import System.Exit import System.FilePath-import System.IO (hSetBuffering, BufferMode(..), IOMode(..), openFile, hClose)+import System.IO (hSetBuffering, BufferMode(..), IOMode(..), openFile, hClose, hGetEncoding, hSetEncoding, hPutStrLn, stdout, stderr) import Test.Sandwich.ArgParsing import Test.Sandwich.Contexts import Test.Sandwich.Expectations@@ -150,6 +164,8 @@ -- The options will become available as a test context, which you can access by calling 'getCommandLineOptions'. runSandwichWithCommandLineArgs' :: forall a. (Typeable a) => Options -> Parser a -> TopSpecWithOptions' a -> IO () runSandwichWithCommandLineArgs' baseOptions userOptionsParser spec = do+ useUtf8Encodings+ (clo, individualTestParser, modulesAndShorthands) <- parseCommandLineArgs' userOptionsParser spec (options, repeatCount) <- liftIO $ addOptionsFromArgs baseOptions clo @@ -209,8 +225,12 @@ -- | Run the spec with optional custom 'CommandLineOptions'. When finished, return the exit reason, -- the number of "it" nodes which failed, and the total failed nodes (which includes "it" nodes, and -- may also include other nodes like "introduce" nodes).+--+-- If a formatter throws in 'finalizeFormatter', the exception is rethrown once the run has shut down. runSandwich' :: Maybe (CommandLineOptions ()) -> Options -> CoreSpec -> IO (ExitReason, Int, Int) runSandwich' maybeCommandLineOptions options spec' = do+ useUtf8Encodings+ let runId = optionsRunId options baseContext <- baseContextFromOptions options @@ -231,15 +251,6 @@ Just chan -> atomically $ writeTChan chan (NodeEvent now 0 "sandwich" (EventMilestone msg)) Nothing -> return () - -- To prevent weird errors saving files like "commitAndReleaseBuffer: invalid argument (invalid character)",- -- especially on Windows- -- See https://gitlab.haskell.org/ghc/ghc/issues/8118- setLocaleEncoding utf8-#ifdef mingw32_HOST_OS- -- Fix Windows console output. Makes sandwich-hedgehog unicode print properly- setConsoleOutputCP 65001-#endif- -- Wrap the spec in a finalizer for the test timer, when one is present let spec = case baseContextTestTimer baseContext of NullTestTimer -> spec'@@ -315,19 +326,25 @@ finalResults :: [Either E.SomeException ()] <- forM formatterAsyncs $ E.try . wait let failures = lefts finalResults unless (null failures) $- putStrLn [i|Some formatters failed: '#{failures}'|]+ hPutStrLn stderr [i|Some formatters failed: '#{failures}'|] milestone "formatters finished" - -- Run finalizeFormatter method on formatters+ -- Run finalizeFormatter method on formatters. A failure here shouldn't stop us from shutting+ -- down cleanly, so hold on to it and rethrow at the end. milestone [i|finalizing formatters: #{optionsFormatters options'}|]- forM_ (optionsFormatters options') $ \(SomeFormatter f) -> do+ finalizeFailures <- fmap catMaybes $ forM (optionsFormatters options') $ \(SomeFormatter f) -> do milestone [i|finalizing formatter: #{f}|] let loggingFn = case baseContextRunRoot baseContext of Nothing -> flip runLoggingT (\_ _ _ _ -> return ()) Just rootPath -> runFileLoggingT (rootPath </> (formatterName f) <.> "log") - loggingFn $ finalizeFormatter f rts baseContext+ tryAny (loggingFn $ finalizeFormatter f rts baseContext) >>= \case+ Right () -> return Nothing+ Left e -> do+ milestone [i|formatter failed to finalize: #{formatterName f}: #{e}|]+ hPutStrLn stderr [i|Formatter '#{formatterName f}' failed to finalize: #{e}|]+ return (Just e) milestone "fixing tree" fixedTree <- atomically $ mapM fixRunTree rts@@ -368,7 +385,34 @@ exitReason <- readIORef exitReasonRef let failedItBlocks = countWhere isFailedItBlock fixedTree let failedBlocks = countWhere isFailedBlock fixedTree++ -- Now that we've shut down cleanly, fail the run if a formatter failed to finalize+ forM_ (listToMaybe finalizeFailures) throwIO+ return (exitReason, failedItBlocks, failedBlocks)++-- | Use UTF-8 regardless of locale, so non-ASCII test labels work under e.g. @LANG=C@.+useUtf8Encodings :: IO ()+useUtf8Encodings = do+ -- To prevent weird errors saving files like "commitAndReleaseBuffer: invalid argument (invalid character)",+ -- especially on Windows+ -- See https://gitlab.haskell.org/ghc/ghc/issues/8118+ setLocaleEncoding utf8++#ifdef mingw32_HOST_OS+ -- Fix Windows console output. Makes sandwich-hedgehog unicode print properly+ setConsoleOutputCP 65001+#endif++#ifndef mingw32_HOST_OS+ -- ROUNDTRIP keeps paths that aren't valid UTF-8 working. (Windows paths are UTF-16.)+ setFileSystemEncoding =<< mkTextEncoding "UTF-8//ROUNDTRIP"+#endif++ -- The std handles take the locale encoding on first use, which may have been before now+ forM_ [stdout, stderr] $ \h -> hGetEncoding h >>= \case+ Just _ -> hSetEncoding h utf8+ Nothing -> return () -- | Count the it nodes
src/Test/Sandwich/ArgParsing.hs view
@@ -95,6 +95,7 @@ <*> optional (flag False True (long "dry-run" <> help "Skip actually launching the tests. This is useful if you want to see the set of the tests that would be run, or start them manually in the terminal UI.")) <*> optional (option auto (long "warn-on-long-execution-ms" <> showDefault <> help "Warn on long-running nodes by writing to a file in the run root." <> metavar "INT")) <*> optional (option auto (long "cancel-on-long-execution-ms" <> showDefault <> help "Cancel long-running nodes and write to a file in the run root." <> metavar "INT"))+ <*> optional (option auto (long "max-folder-path-length" <> help "Shorten test folder names to keep folder paths at most this long; 0 for no limit. Defaults to 200 on Windows, which leaves 59 characters for files under MAX_PATH (260, including the terminating NUL), and 0 elsewhere." <> metavar "INT")) <*> optional (strOption (long "markdown-summary" <> help "File path to write a Markdown summary of the results." <> metavar "STRING")) <*> switch (long "tui-debug" <> help "Enable TUI debug socket at <test-root>/tui-debug.sock") <*> switch (long "socket" <> help "Enable interactive socket formatter at <test-root>/socket.sock")@@ -305,6 +306,10 @@ , optionsDryRun = fromMaybe (optionsDryRun baseOptions) optDryRun , optionsWarnOnLongExecutionMs = (optionsWarnOnLongExecutionMs baseOptions) <|> optWarnOnLongExecutionMs , optionsCancelOnLongExecutionMs = (optionsCancelOnLongExecutionMs baseOptions) <|> optCancelOnLongExecutionMs+ , optionsMaxFolderPathLength = case optMaxFolderPathLength of+ Just 0 -> Nothing+ Just n -> Just n+ Nothing -> optionsMaxFolderPathLength baseOptions , optionsLogBroadcast = maybeLogBroadcast , optionsEventBroadcast = maybeEventBroadcast }
src/Test/Sandwich/Formatters/TerminalUI.hs view
@@ -45,6 +45,7 @@ import qualified Data.Set as S import Data.String.Interpolate import Data.Text (Text)+import qualified Data.Text.Encoding as TE import Data.Time import qualified Data.Vector as Vec import GHC.Stack@@ -59,6 +60,7 @@ import Test.Sandwich.Formatters.TerminalUI.Draw import Test.Sandwich.Formatters.TerminalUI.Filter import Test.Sandwich.Formatters.TerminalUI.Keys+import Test.Sandwich.Formatters.TerminalUI.SpeedScope import Test.Sandwich.Formatters.TerminalUI.Types import Test.Sandwich.Interpreters.RunTree.Util import Test.Sandwich.Interpreters.StartTree@@ -92,11 +94,14 @@ -- Create debug channel for optional debug socket server debugChan <- liftIO $ newBroadcastTChanIO- let debugFn :: Text -> IO ()- debugFn msg = do- now <- getCurrentTime+ let debugFn :: UTCTime -> Text -> IO ()+ debugFn now msg = atomically $ writeTChan debugChan (BS8.pack [i|#{formatTime defaultTimeLocale "%H:%M:%S%3Q" now} #{msg}\n|])+ let debugFnNow :: Text -> IO ()+ debugFnNow msg = getCurrentTime >>= flip debugFn msg + speedScopeServer <- liftIO $ newMVar Nothing+ let initialState = updateFilteredTree $ AppState { _appRunTreeBase = rts@@ -117,7 +122,8 @@ , _appShowVisibilityThresholds = terminalUIShowVisibilityThresholds , _appShowLogSizes = terminalUIShowLogSizes - , _appOpenInEditor = terminalUIOpenInEditor terminalUIDefaultEditor debugFn+ , _appOpenInEditor = terminalUIOpenInEditor terminalUIDefaultEditor debugFnNow+ , _appSpeedScopeServer = speedScopeServer , _appDebug = debugFn , _appCustomExceptionFormatters = terminalUICustomExceptionFormatters }@@ -129,7 +135,7 @@ currentFixedTree <- liftIO $ newTVarIO rtsFixed let eventAsync = liftIO $ forever $ do handleAny (\e -> flip runLoggingT logFn (logError [i|Got exception in event async: #{e}|]) >> threadDelay terminalUIRefreshPeriod) $ do- debugFn "eventAsync: waiting for tree change"+ debugFnNow "eventAsync: waiting for tree change" (newFixedTree, somethingRunning) <- atomically $ flip runStateT False $ do currentFixed <- lift $ readTVar currentFixedTree newFixed <- mapM fixRunTree' rts@@ -137,7 +143,7 @@ lift $ writeTVar currentFixedTree newFixed return newFixed let nodeCount = length $ concatMap getCommons newFixedTree- debugFn [i|eventAsync: tree changed, nodes=#{nodeCount} somethingRunning=#{somethingRunning}|]+ debugFnNow [i|eventAsync: tree changed, nodes=#{nodeCount} somethingRunning=#{somethingRunning}|] writeBChan eventChan (RunTreeUpdated newFixedTree somethingRunning) threadDelay terminalUIRefreshPeriod @@ -147,11 +153,13 @@ when (V.supportsMode output V.Mouse) $ liftIO $ V.setMode output V.Mouse True return v+#if !MIN_VERSION_brick(3,1,0) initialVty <- liftIO buildVty+#endif let updateCurrentTimeForever period = forever $ do now <- getCurrentTime- debugFn "CurrentTimeUpdated tick"+ debugFn now "CurrentTimeUpdated tick" writeBChan eventChan (CurrentTimeUpdated now) threadDelay period @@ -165,7 +173,11 @@ withDebugSocket $ (case terminalUIClockUpdatePeriod of Nothing -> id; Just ts -> \action -> managedWithAsync_ runId "tui-clock-update" (updateCurrentTimeForever ts) action) $ managedWithAsync_ runId "tui-event-async" eventAsync $+#if MIN_VERSION_brick(3,1,0)+ void $ customMain (Just buildVty) (Just eventChan) app initialState+#else void $ customMain initialVty buildVty (Just eventChan) app initialState+#endif app :: App AppState AppEvent ClickableName app = App {@@ -332,6 +344,9 @@ whenJust folderPath $ liftIO . openFileExplorerFolderPortable V.EvKey c [] | c == openTestRootKey -> withContinueS s $ whenJust (baseContextRunRoot (s ^. appBaseContext)) $ liftIO . openFileExplorerFolderPortable+ V.EvKey c [] | c == openSpeedScopeKey -> withContinueS s $ liftIO $+ flip runLoggingT (\_ _ _ x -> getCurrentTime >>= \now -> (s ^. appDebug) now (TE.decodeUtf8 (fromLogStr x))) $+ openSpeedScope (s ^. appSpeedScopeServer) (s ^. appBaseContext) V.EvKey c [] | c == openTestInEditorKey -> case listSelectedElement (s ^. appMainList) of Just (_i, MainListElem {node=(runTreeLoc -> Just loc)}) -> openSrcLoc s loc _ -> continue s
src/Test/Sandwich/Formatters/TerminalUI/CrossPlatform.hs view
@@ -2,6 +2,7 @@ module Test.Sandwich.Formatters.TerminalUI.CrossPlatform ( openFileExplorerFolderPortable+ , openUrlPortable ) where import Control.Monad@@ -18,12 +19,26 @@ findExecutable "explorer.exe" >>= \case Just p -> void $ readCreateProcessWithExitCode (proc p [folder]) "" Nothing -> return ()++openUrlPortable :: String -> IO ()+openUrlPortable url = do+ findExecutable "explorer.exe" >>= \case+ Just p -> void $ readCreateProcessWithExitCode (proc p [url]) ""+ Nothing -> return () #elif darwin_HOST_OS openFileExplorerFolderPortable :: String -> IO () openFileExplorerFolderPortable folder = void $ readCreateProcessWithExitCode (proc "open" [folder]) ""++openUrlPortable :: String -> IO ()+openUrlPortable url =+ void $ readCreateProcessWithExitCode (proc "open" [url]) "" #else openFileExplorerFolderPortable :: String -> IO () openFileExplorerFolderPortable folder = void $ readCreateProcessWithExitCode (proc "xdg-open" [folder]) ""++openUrlPortable :: String -> IO ()+openUrlPortable url =+ void $ readCreateProcessWithExitCode (proc "xdg-open" [url]) "" #endif
src/Test/Sandwich/Formatters/TerminalUI/Draw/TopBox.hs view
@@ -118,6 +118,13 @@ , str "] " , str "Log level"] + , hBox [str "["+ , highlightKeyIfPredicate (const True) app (str $ showKey openSpeedScopeKey)+ , str "] "+ , withAttr hotkeyMessageAttr $ str "Open "+ , highlightMessageIfPredicate (const True) app (str "speedscope")+ ]+ , keyIndicator "q" "Exit"] scrollNodeLabel :: String
src/Test/Sandwich/Formatters/TerminalUI/Keys.hs view
@@ -26,6 +26,7 @@ openTestInEditorKey = V.KChar 't' openFailureInEditorKey = V.KChar 'f' openLogsInEditorKey = V.KChar 'l'+openSpeedScopeKey = V.KChar 'S' -- Column 3 cycleVisibilityThresholdKey = V.KChar 'v'
+ src/Test/Sandwich/Formatters/TerminalUI/SpeedScope.hs view
@@ -0,0 +1,189 @@++module Test.Sandwich.Formatters.TerminalUI.SpeedScope (+ SpeedScopeServer(..)+ , openSpeedScope+ ) where++import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.IO.Unlift (MonadUnliftIO)+import Control.Monad.Logger+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import qualified Data.List as L+import Data.String.Interpolate+import qualified Data.Text as T+import Network.Socket+import Network.Socket.ByteString (recv, sendAll)+import System.Exit+import System.FilePath+import System.Process+import Test.Sandwich.Formatters.TerminalUI.CrossPlatform+import Test.Sandwich.ManagedAsync+import Test.Sandwich.TestTimer+import Test.Sandwich.Types.RunTree+import Test.Sandwich.Types.TestTimer+import UnliftIO.Async+import UnliftIO.Directory+import UnliftIO.Exception+import UnliftIO.MVar+import UnliftIO.Temporary+++speedScopeVersion :: String+speedScopeVersion = "1.25.0"++speedScopeUrl :: String+speedScopeUrl = [i|https://registry.npmjs.org/speedscope/-/speedscope-#{speedScopeVersion}.tgz|]++profilePath :: String+profilePath = "/speedscope.json"++data SpeedScopeServer = SpeedScopeServer {+ speedScopeServerSocket :: Socket+ , speedScopeServerAsync :: Async ()+ , speedScopeServerUrl :: String+ }++openSpeedScope :: (MonadLoggerIO m, MonadUnliftIO m) => MVar (Maybe SpeedScopeServer) -> BaseContext -> m ()+openSpeedScope serverVar (BaseContext {..}) = handle logException $+ modifyMVar_ serverVar $ \maybeServer -> do+ server <- case maybeServer of+ Just server -> return server+ Nothing -> do+ bundleDir <- ensureSpeedScopeBundle+ server <- liftIO $ startServer baseContextRunId baseContextTestTimer bundleDir+ logDebugN [i|Serving speedscope at #{speedScopeServerUrl server}|]+ return server++ liftIO $ openUrlPortable (speedScopeServerUrl server)+ return $ Just server+ where+ logException (e :: SomeException) = logDebugN [i|Failed to open speedscope: #{e}|]++-- * Bundle++ensureSpeedScopeBundle :: (MonadLoggerIO m, MonadUnliftIO m) => m (Maybe FilePath)+ensureSpeedScopeBundle = flip catch logException $ do+ cacheDir <- getXdgDirectory XdgCache ("sandwich" </> ("speedscope-" <> speedScopeVersion))+ doesFileExist (cacheDir </> "index.html") >>= \case+ True -> return $ Just cacheDir+ False -> withSystemTempDirectory "sandwich-speedscope" $ \tmpDir -> do+ let tarball = tmpDir </> "speedscope.tgz"+ logDebugN [i|Downloading #{speedScopeUrl}|]+ run "curl" ["-sSL", speedScopeUrl, "-o", tarball]+ run "tar" ["xzf", tarball, "-C", tmpDir]++ -- The npm tarball puts the self-contained app in package/dist/release.+ let releaseDir = tmpDir </> "package" </> "dist" </> "release"+ doesFileExist (releaseDir </> "index.html") >>= \case+ False -> do+ logDebugN [i|No index.html in the speedscope tarball; falling back to speedscope.app|]+ return Nothing+ True -> do+ createDirectoryIfMissing True cacheDir+ files <- listDirectory releaseDir+ forM_ files $ \file -> copyFile (releaseDir </> file) (cacheDir </> file)+ logDebugN [i|Unpacked speedscope to #{cacheDir}|]+ return $ Just cacheDir+ where+ logException (e :: SomeException) = do+ logDebugN [i|Couldn't fetch speedscope (#{e}); falling back to speedscope.app|]+ return Nothing++ run cmd args = liftIO (readProcessWithExitCode cmd args "") >>= \case+ (ExitSuccess, _, _) -> return ()+ (code, _, stderr') -> throwIO $ userError [i|#{cmd} failed (#{code}): #{stderr'}|]++-- * Server++startServer :: T.Text -> TestTimer -> Maybe FilePath -> IO SpeedScopeServer+startServer runId testTimer bundleDir = do+ sock <- socket AF_INET Stream defaultProtocol+ setSocketOption sock ReuseAddr 1+ bind sock (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ listen sock 16+ port <- socketPort sock++ asy <- managedAsync runId "speedscope-server" $ void $ forever $ do+ (conn, _) <- accept sock+ void $ managedAsync runId "speedscope-request" $+ handleRequest conn `finally` close conn++ let url = case bundleDir of+ Just _ -> [i|http://127.0.0.1:#{port}/index.html\#profileURL=#{profilePath}&title=Sandwich|]+ -- This won't work on Safari, since it treats it as mixed content.+ Nothing -> [i|https://www.speedscope.app/\#profileURL=http%3A%2F%2F127.0.0.1%3A#{port}#{profilePath}&title=Sandwich|]++ return $ SpeedScopeServer {+ speedScopeServerSocket = sock+ , speedScopeServerAsync = asy+ , speedScopeServerUrl = url+ }++ where+ handleRequest conn = handle (\(_ :: SomeException) -> return ()) $ do+ path <- requestPath conn+ case path of+ Nothing -> respond conn "400 Bad Request" "text/plain" "Bad request"+ Just p | p == profilePath -> renderSpeedScopeFile testTimer >>= \case+ Nothing -> respond conn "404 Not Found" "text/plain" "No test timer is running"+ Just contents -> respond conn "200 OK" "application/json" contents+ Just p -> case bundleDir of+ Nothing -> respond conn "404 Not Found" "text/plain" "Not found"+ Just dir -> case bundleFile dir p of+ Nothing -> respond conn "404 Not Found" "text/plain" "Not found"+ Just file -> doesFileExist file >>= \case+ False -> respond conn "404 Not Found" "text/plain" "Not found"+ True -> do+ contents <- BL.readFile file+ respond conn "200 OK" (contentType file) contents++ bundleFile :: FilePath -> String -> Maybe FilePath+ bundleFile dir path = case segments of+ [] -> Just (dir </> "index.html")+ [file] | isValid file, not (isAbsolute file), file /= ".." -> Just (dir </> file)+ _ -> Nothing+ where+ segments = filter (`notElem` ["", ".", "/"]) $ splitDirectories $+ takeWhile (`notElem` ("?#" :: String)) path++ requestPath :: Socket -> IO (Maybe String)+ requestPath conn = go mempty+ where+ go acc+ | BS.length acc > 16384 = return Nothing+ | otherwise = case BS8.lines acc of+ (firstLine:_:_) -> return $ case BS8.words firstLine of+ (_method:path:_) -> Just (BS8.unpack path)+ _ -> Nothing+ _ -> recv conn 4096 >>= \chunk -> if BS.null chunk then return Nothing else go (acc <> chunk)++ respond :: Socket -> String -> String -> BL.ByteString -> IO ()+ respond conn status contentType' body = do+ sendAll conn $ BS8.pack $ L.intercalate "\r\n" [+ [i|HTTP/1.1 #{status}|]+ , [i|Content-Type: #{contentType'}|]+ , [i|Content-Length: #{BL.length body}|]+ -- So that speedscope.app can fetch the profile from us, when we're falling back to it.+ , "Access-Control-Allow-Origin: *"+ , "Cache-Control: no-store"+ , "Connection: close"+ , "", ""+ ]+ mapM_ (sendAll conn) (BL.toChunks body)++ contentType :: FilePath -> String+ contentType file = case takeExtension file of+ ".html" -> "text/html; charset=utf-8"+ ".js" -> "text/javascript"+ ".css" -> "text/css"+ ".json" -> "application/json"+ ".wasm" -> "application/wasm"+ ".woff2" -> "font/woff2"+ ".png" -> "image/png"+ ".ico" -> "image/x-icon"+ ".txt" -> "text/plain"+ ".md" -> "text/plain"+ _ -> "application/octet-stream"
src/Test/Sandwich/Formatters/TerminalUI/Types.hs view
@@ -14,8 +14,10 @@ import GHC.Stack import Lens.Micro.TH import Test.Sandwich.Formatters.TerminalUI.OpenInEditor+import Test.Sandwich.Formatters.TerminalUI.SpeedScope import Test.Sandwich.RunTree import Test.Sandwich.Types.RunTree+import UnliftIO.MVar data TerminalUIFormatter = TerminalUIFormatter {@@ -141,7 +143,8 @@ , _appShowLogSizes :: Bool , _appOpenInEditor :: SrcLoc -> IO ()- , _appDebug :: T.Text -> IO ()+ , _appSpeedScopeServer :: MVar (Maybe SpeedScopeServer)+ , _appDebug :: UTCTime -> T.Text -> IO () , _appCustomExceptionFormatters :: CustomExceptionFormatters }
src/Test/Sandwich/Internal/Inspection.hs view
@@ -10,6 +10,7 @@ import Test.Sandwich.Interpreters.FilterTree import Test.Sandwich.Interpreters.PruneTree import Test.Sandwich.Interpreters.RunTree+import Test.Sandwich.Interpreters.RunTree.FolderNameLength import Test.Sandwich.Types.RunTree @@ -24,6 +25,7 @@ spec & (\tree -> L.foldl' pruneTree tree pruneOpts) & (\tree -> L.foldl' filterTree tree filterOpts)+ & fitFolderPaths baseContext & specToRunTreeM baseContext printRunTree :: [RunNodeFixed ctx] -> IO ()
src/Test/Sandwich/Internal/Running.hs view
@@ -20,6 +20,7 @@ import Test.Sandwich.Interpreters.FilterTree import Test.Sandwich.Interpreters.PruneTree import Test.Sandwich.Interpreters.RunTree+import Test.Sandwich.Interpreters.RunTree.FolderNameLength import Test.Sandwich.Interpreters.RunTree.Util import Test.Sandwich.Interpreters.StartTree import Test.Sandwich.ManagedAsync@@ -43,6 +44,7 @@ runTree <- spec & (\tree -> L.foldl' pruneTree tree pruneOpts) & (\tree -> L.foldl' filterTree tree filterOpts)+ & fitFolderPaths baseContext & atomically . specToRunTreeVariable baseContext if | optionsDryRun -> markAllChildrenWithResult runTree baseContext DryRun@@ -114,13 +116,16 @@ let errorSymlinksDir = (</> "errors") <$> runRoot whenJust errorSymlinksDir $ createDirectoryIfMissing True++ timingProfile <- newTVarIO (TimingProfile defaultProfileName [])+ return $ BaseContext { baseContextPath = mempty , baseContextOptions = options , baseContextRunRoot = runRoot , baseContextErrorSymlinksDir = errorSymlinksDir , baseContextOnlyRunIds = Nothing- , baseContextTestTimerProfile = defaultProfileName+ , baseContextTimingProfile = timingProfile , baseContextTestTimer = testTimer , baseContextRunId = runId }
src/Test/Sandwich/Interpreters/RunTree.hs view
@@ -18,7 +18,8 @@ import Data.Functor.Identity import qualified Data.List as L import qualified Data.Map as M-import Data.Sequence as Seq+import Data.Sequence ((|>))+import qualified Data.Sequence as Seq import GHC.Stack import Lens.Micro import Lens.Micro.TH@@ -124,13 +125,13 @@ Just (rootFolder, numRootChildren) -> do nextRootChild <- _convertStateRootNextChildIndex <$> get modify (over convertStateRootNextChildIndex (+1))- pure $ Just (rootFolder </> nodeToFolderName l numRootChildren nextRootChild)+ pure $ Just (rootFolder </> nodeToFolderNameCapped nodeOptionsFolderNameCap l numRootChildren nextRootChild) Nothing -> pure Nothing Just (ancestor, (folder, totalChildren, nextChildIndex)) -> do let bumpAncestorNextChildIndex :: M.Map Int CreatedNode -> M.Map Int CreatedNode bumpAncestorNextChildIndex = M.adjust (over (createdNodeFolder . _Just . _3) (+1)) ancestor modify (over convertStateCreatedNodes bumpAncestorNextChildIndex)- pure $ Just (folder </> nodeToFolderName l totalChildren nextChildIndex)+ pure $ Just (folder </> nodeToFolderNameCapped nodeOptionsFolderNameCap l totalChildren nextChildIndex) -- Insert this node into the ConvertState modify $ over convertStateCreatedNodes $ M.insert ident $ CreatedNode $ case folder of
+ src/Test/Sandwich/Interpreters/RunTree/FolderNameLength.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE RankNTypes #-}++-- | Shortens node folder names so every node folder path fits within 'optionsMaxFolderPathLength'.++module Test.Sandwich.Interpreters.RunTree.FolderNameLength (fitFolderPaths) where++import Control.Monad.Free+import qualified Data.List as L+import System.FilePath+import Test.Sandwich.Interpreters.RunTree.Util+import Test.Sandwich.Types.RunTree+import Test.Sandwich.Types.Spec+++fitFolderPaths :: BaseContext -> Free (SpecCommand context m) () -> Free (SpecCommand context m) ()+fitFolderPaths (BaseContext {..}) spec = case (optionsMaxFolderPathLength baseContextOptions, baseContextRunRoot) of+ (Just maxLength, Just runRoot) -> fst $ go (maxLength - L.length (runRoot </> "results")) [] (countImmediateFolderChildren spec) spec+ _ -> spec++-- | A chain of folders is a list of (padding length, name length). Each chain gets the largest uniform name cap that+-- fits it, and each node takes the smallest cap of any chain through it, which is returned up the tree.+go :: Int -> [(Int, Int)] -> Int -> Free (SpecCommand context m) () -> (Free (SpecCommand context m) (), Maybe Int)+go available ancestors numSiblings = \case+ Free (It'' loc no l ex next) -> case visit no l 0 (\_ _ -> ((), Nothing)) of+ (no', (), cap) -> continue cap next (Free . It'' loc no' l ex)+ Free (Introduce'' loc no l cl alloc cleanup subspec next) -> case visit no l (countImmediateFolderChildren subspec) (goSub subspec) of+ (no', subspec', cap) -> continue cap next (Free . Introduce'' loc no' l cl alloc cleanup subspec')+ Free (IntroduceWith'' loc no l cl action subspec next) -> case visit no l (countImmediateFolderChildren subspec) (goSub subspec) of+ (no', subspec', cap) -> continue cap next (Free . IntroduceWith'' loc no' l cl action subspec')+ Free (Parallel'' loc no subspec next) -> case visit no "Parallel" (countImmediateFolderChildren subspec) (goSub subspec) of+ (no', subspec', cap) -> continue cap next (Free . Parallel'' loc no' subspec')+ -- Before'', After'', Around'', Describe''+ Free x -> case visit (nodeOptions x) (label x) (countImmediateFolderChildren (subspec x)) (goSub (subspec x)) of+ (no', subspec', cap) -> continue cap (next x) (\next' -> Free (x { nodeOptions = no', subspec = subspec', next = next' }))+ pureM@(Pure _) -> (pureM, Nothing)+ where+ goSub :: Free (SpecCommand ctx m) () -> [(Int, Int)] -> Int -> (Free (SpecCommand ctx m) (), Maybe Int)+ goSub subspec ancestors' numSiblings' = go available ancestors' numSiblings' subspec++ continue cap next mk = case go available ancestors numSiblings next of+ (next', nextCap) -> (mk next', minCap cap nextCap)++ -- Folder nodes start a new level of the chain; other nodes' children share this level.+ visit :: NodeOptions -> String -> Int -> ([(Int, Int)] -> Int -> (s, Maybe Int)) -> (NodeOptions, s, Maybe Int)+ visit no l numChildren goChildren+ | nodeOptionsCreateFolder no = case goChildren chain numChildren of+ (children, childrenCap) -> let cap = minCap (chainCap available chain) childrenCap in (no { nodeOptionsFolderNameCap = cap }, children, cap)+ | otherwise = case goChildren ancestors numSiblings of+ (children, childrenCap) -> (no, children, childrenCap)+ where+ paddingLength = L.length (folderNamePadding numSiblings 0)+ chain = ancestors <> [(paddingLength, L.length (nodeToFolderName l numSiblings 0) - paddingLength)]++minCap :: Maybe Int -> Maybe Int -> Maybe Int+minCap (Just x) (Just y) = Just (min x y)+minCap x Nothing = x+minCap Nothing y = y++minFolderNameCap :: Int+minFolderNameCap = 6++-- | The largest name cap that fits the chain within @available@ ('Nothing' if it fits uncapped), but at least 'minFolderNameCap'.+chainCap :: Int -> [(Int, Int)] -> Maybe Int+chainCap available chain+ | fits Nothing = Nothing+ | otherwise = Just (search minFolderNameCap (L.maximum (minFolderNameCap : fmap snd chain)))+ where+ fits cap = sum [1 + paddingLength + maybe id min cap nameLength | (paddingLength, nameLength) <- chain] <= available++ search lo hi+ | hi - lo <= 1 = lo+ | fits (Just mid) = search mid hi+ | otherwise = search lo mid+ where mid = (lo + hi) `div` 2
src/Test/Sandwich/Interpreters/RunTree/Util.hs view
@@ -48,9 +48,19 @@ maxFileNameLength = 150 nodeToFolderName :: String -> Int -> Int -> String-nodeToFolderName name 1 0 = truncateFileNameToLength maxFileNameLength $ fixupName name-nodeToFolderName name numSiblings indexInParent = padding <> truncateFileNameToLength (maxFileNameLength - (L.length padding)) (fixupName name)+nodeToFolderName = nodeToFolderNameCapped Nothing++-- | Like 'nodeToFolderName', but caps the name part (not the index padding).+nodeToFolderNameCapped :: Maybe Int -> String -> Int -> Int -> String+nodeToFolderNameCapped cap name numSiblings indexInParent = padding <> truncateFileNameToLength nameCap (fixupName name) where+ padding = folderNamePadding numSiblings indexInParent+ nameCap = maybe id min cap (maxFileNameLength - L.length padding)++folderNamePadding :: Int -> Int -> String+folderNamePadding 1 _ = ""+folderNamePadding numSiblings indexInParent = paddedNumber <> "_"+ where paddingNeeded | numSiblings < 10 = 1 | numSiblings < 100 = 2@@ -64,10 +74,7 @@ paddedNumber = printf [i|%0#{paddingNeeded :: Int}d|] indexInParent - padding = if | numSiblings == 1 -> ""- | otherwise -> paddedNumber <> "_" - charsToReplace :: [Char] #ifdef mingw32_HOST_OS charsToReplace = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']@@ -83,9 +90,4 @@ truncateFileNameToLength :: Int -> String -> String truncateFileNameToLength len x | L.length x <= len = x-truncateFileNameToLength len x = "..." <> (takeEnd (len - 3) x)--takeEnd :: Int -> [a] -> [a]-takeEnd j xs = f xs (L.drop j xs)- where f (_:zs) (_:ys) = f zs ys- f zs _ = zs+truncateFileNameToLength len x = L.take (len - 1) x <> "_"
src/Test/Sandwich/Interpreters/StartTree.hs view
@@ -135,9 +135,13 @@ Right intro -> do -- Special hack to modify the test timer profile via an introduce, without needing to track it everywhere. -- It would be better to track the profile at the type level- let ctxFinal = case cast intro of- Just (TestTimerProfile t) -> modifyBaseContext ctx (\bc -> bc { baseContextTestTimerProfile = t })- Nothing -> ctx+ ctxFinal <- case cast intro of+ Just (TestTimerProfile t) -> do+ -- A fresh cell, so we rename the profile for our children only.+ current <- readTVarIO (baseContextTimingProfile (getBaseContext ctx))+ timingProfile <- newTVarIO (current { timingProfileName = t })+ return $ modifyBaseContext ctx (\bc -> bc { baseContextTimingProfile = timingProfile })+ Nothing -> return ctx void $ runNodesSequentially runNodeChildrenAugmented ((LabelValue intro) :> ctxFinal) )@@ -278,13 +282,19 @@ runInAsync node ctx action = do let RunNodeCommonWithStatus {..} = runNodeCommon node let bc@(BaseContext {..}) = getBaseContext ctx- let timerFn = if runTreeRecordTime then timeAction' (getTestTimer bc) baseContextTestTimerProfile (T.pack runTreeLabel) else id let asyncName = T.pack [i|node #{runTreeId}, #{runTreeLabel}|] startTime <- liftIO getCurrentTime mvar <- liftIO newEmptyMVar- myAsync <- liftIO $ managedAsyncWithUnmask baseContextRunId asyncName $ \unmask -> do- flip withException (recordExceptionInStatus runTreeStatus) $ unmask $ do+ myAsync <- liftIO $ managedAsyncWithUnmaskAndHandler baseContextRunId asyncName (recordExceptionInStatus node) $ \unmask ->+ unmask $ do readMVar mvar+ -- Resolve the timing profile now rather than when this node was created, since a lane may+ -- have been claimed for us in the meantime.+ timerFn <- case runTreeRecordTime of+ False -> pure id+ True -> do+ profile <- currentTestTimerProfile bc+ pure $ timeAction' (getTestTimer bc) profile (T.pack runTreeLabel) (result, extraTimingInfo) <- timerFn action endTime <- liftIO getCurrentTime liftIO $ atomically $ writeTVar runTreeStatus $ Done startTime (setupFinishTime extraTimingInfo) (teardownStartTime extraTimingInfo) endTime result@@ -346,10 +356,16 @@ printLogs runTreeLogs return result- liftIO $ atomically $ writeTVar runTreeStatus $ Running startTime Nothing Nothing myAsync+ -- Only claim the node if nothing has given it a terminal status yet. If the tree is coming down+ -- around us, an ancestor may have finalized this subtree while we were starting it, and a+ -- 'Running' written on top of that would never be cleared.+ liftIO $ atomically $ modifyTVar' runTreeStatus $ \case+ NotStarted -> Running startTime Nothing Nothing myAsync+ status -> status+ liftIO $ emitEvent baseContextOptions startTime runTreeId runTreeLabel EventStarted liftIO $ putMVar mvar ()- return myAsync -- TODO: fix race condition with writing to runTreeStatus (here and above)+ return myAsync -- | Run a list of children sequentially, cancelling everything on async exception runNodesSequentially :: HasBaseContext context => [RunNode context] -> context -> IO [Result]@@ -361,22 +377,29 @@ -- | Run a list of children concurrently, cancelling everything on async exception runNodesConcurrently :: forall context. HasBaseContext context => RunNodeCommon -> [RunNode context] -> context -> IO [Result] runNodesConcurrently (RunNodeCommonWithStatus {runTreeLabel, runTreeId}) children ctx =- flip withException (\(e :: SomeAsyncException) -> cancelAllChildrenWith children e) $- mapM wait =<< sequence [startTree child (modifyTimingProfile ix ctx)- | (child, ix) <- L.zip runnableChildren [0..]]+ flip withException (\(e :: SomeAsyncException) -> cancelAllChildrenWith children e) $ do+ asyncs <- sequence [startTree child =<< childContext ix+ | (child, ix) <- L.zip runnableChildren [0..]]+ -- If we stop waiting early because one child threw, take the others down with us;+ -- the handler above only fires for async exceptions.+ mapM wait asyncs `onException` cancelAllChildrenWith runnableChildren (SomeAsyncException AsyncCancelled) where runnableChildren = L.filter (shouldRunChild ctx) children leftPadWithZeros :: Int -> String leftPadWithZeros num = L.replicate (L.length (show (L.length runnableChildren)) - L.length (show num)) '0' <> show num - modifyTimingProfile :: Int -> context -> context- modifyTimingProfile n = flip modifyBaseContext (modifyTimingProfile' n)+ -- Give each child its own test timer profile, since sharing one would mess up the nesting of the+ -- profile's frames. Children keep any lanes we're already holding, so they don't claim a second+ -- one and deadlock.+ childContext :: Int -> IO context+ childContext n = do+ current <- readTVarIO (baseContextTimingProfile (getBaseContext ctx))+ timingProfile <- newTVarIO (current { timingProfileName = timingProfileName current <> suffix n })+ return $ modifyBaseContext ctx $ \bc -> bc { baseContextTimingProfile = timingProfile } - modifyTimingProfile' :: Int -> BaseContext -> BaseContext- modifyTimingProfile' n bc@(BaseContext {..}) = bc {- baseContextTestTimerProfile = baseContextTestTimerProfile <> [i|-#{runTreeLabel}-#{runTreeId}-#{leftPadWithZeros n}|]- }+ suffix :: Int -> T.Text+ suffix n = [i|-#{runTreeLabel}-#{runTreeId}-#{leftPadWithZeros n}|] markAllChildrenWithResult :: (MonadIO m, HasBaseContext context') => [RunNode context] -> context' -> Result -> m () markAllChildrenWithResult children baseContext status = do@@ -388,16 +411,20 @@ _ -> Done now Nothing Nothing now status cancelAllChildrenWith :: [RunNode context] -> SomeAsyncException -> IO ()-cancelAllChildrenWith children e = do- forM_ children $ \node ->- readTVarIO (runTreeStatus $ runNodeCommon node) >>= \case- Running {..} -> cancelWith statusAsync e- NotStarted -> do- now <- getCurrentTime- let reason = GotAsyncException Nothing Nothing (SomeAsyncExceptionWithEq e)- atomically $ writeTVar (runTreeStatus $ runNodeCommon node) (Done now Nothing Nothing now (Failure reason))- _ -> return ()+cancelAllChildrenWith children e = cancelEach `finally` finalizeEach+ where+ cancelEach = forM_ children $ \node ->+ readTVarIO (runTreeStatus $ runNodeCommon node) >>= \case+ Running {..} -> cancelWith statusAsync e+ _ -> return () + -- Nodes record their own results, but ones that never started have nobody to do it for them,+ -- and 'cancelWith' doesn't return until the async has finished. We're already unwinding from+ -- an async exception here and can easily be interrupted partway through the cancelling+ -- above, so this has to happen either way.+ finalizeEach = uninterruptibleMask_ $ forM_ children $ \node ->+ markUnfinishedNodesDone node (Failure $ GotAsyncException Nothing Nothing (SomeAsyncExceptionWithEq e))+ shouldRunChild :: (HasBaseContext ctx) => ctx -> RunNodeWithStatus context s l t -> Bool shouldRunChild ctx node = shouldRunChild' ctx (runNodeCommon node) @@ -490,21 +517,30 @@ atomically $ writeTChan chan (NodeEvent ts nid label evtType) emitEvent _ _ _ _ _ = return () -recordExceptionInStatus :: (MonadIO m) => TVar Status -> SomeException -> m ()-recordExceptionInStatus status e = do+-- | Record an exception that escaped a node's runner. Besides the node itself, this finishes any+-- of its descendants that haven't finished yet: the exception may have cut the node off before it+-- got to them, and nothing else is going to give them a result.+recordExceptionInStatus :: (MonadIO m) => RunNode context -> SomeException -> m ()+recordExceptionInStatus node e = do endTime <- liftIO getCurrentTime let ret = case fromException e of Just (e' :: SomeAsyncException) -> Failure (GotAsyncException Nothing Nothing (SomeAsyncExceptionWithEq e')) _ -> case fromException e of Just (e' :: FailureReason) -> Failure e' _ -> Failure (GotException Nothing Nothing (SomeExceptionWithEq e))- liftIO $ atomically $ modifyTVar' status $ \case+ -- Do the descendants first, so anyone waiting on this node sees a finished subtree+ liftIO $ markUnfinishedNodesDone node ret+ liftIO $ atomically $ modifyTVar' (runTreeStatus (runNodeCommon node)) $ \case Running {..} -> Done statusStartTime statusSetupFinishTime statusTeardownStartTime endTime ret _ -> Done endTime Nothing Nothing endTime ret timed :: forall m a s l t. (MonadUnliftIO m) => RunNodeCommonWithStatus s l t -> Bool -> BaseContext -> String -> m a -> m (a, UTCTime, UTCTime)-timed _rnc recordTime bc@(BaseContext {..}) label action = do- let timerFn = if recordTime then timeAction' (getTestTimer bc) baseContextTestTimerProfile (T.pack label) else id+timed _rnc recordTime bc@(BaseContext {}) label action = do+ timerFn <- case recordTime of+ False -> pure id+ True -> do+ profile <- currentTestTimerProfile bc+ pure $ timeAction' (getTestTimer bc) profile (T.pack label) startTime <- liftIO getCurrentTime ret <- timerFn action
src/Test/Sandwich/Logging/Process.hs view
@@ -39,6 +39,17 @@ #endif +-- | Whether to spawn with 'close_fds', so other children don't inherit our logging pipe.+-- Before process-1.6.18, close_fds makes it fall back to fork/exec, where looking up a bare+-- command name with a custom 'env' and no 'cwd' dereferences NULL and segfaults on macOS+-- (haskell/process#295). There we keep the old behavior.+closeFdsIfSafe :: Bool+#if MIN_VERSION_process(1,6,18)+closeFdsIfSafe = True+#else+closeFdsIfSafe = False+#endif+ -- | Spawn a process with its stdout and stderr connected to the logging system. -- Every line output by the process will be fed to a 'debug' call. createProcessWithLogging :: (HasCallStack, MonadUnliftIO m, MonadLogger m, HasBaseContextMonad context m) => CreateProcess -> m (ProcessHandle, Async ())@@ -57,7 +68,9 @@ line <- liftIO $ hGetLine hRead logOtherCS callStack logLevel [i|#{name}: #{line}|] - (_, _, _, p) <- liftIO $ createProcess (cp { std_out = UseHandle hWrite, std_err = UseHandle hWrite })+ (_, _, _, p) <- liftIO $ createProcess (cp { std_out = UseHandle hWrite, std_err = UseHandle hWrite, close_fds = closeFdsIfSafe })+ -- The child has its own copy; ours would keep hRead from ever reaching EOF+ liftIO $ hClose hWrite return (p, streamsReaderAsy) -- | Like 'readCreateProcess', but capture the stderr output in the logs.@@ -80,11 +93,13 @@ (ex, output) <- managedWithAsyncContext_ "stderr-reader" stderrReader $- withCreateProcess (cp { std_in = CreatePipe, std_out = CreatePipe, std_err = UseHandle hWriteErr }) $ \sin' sout _ p ->+ withCreateProcess (cp { std_in = CreatePipe, std_out = CreatePipe, std_err = UseHandle hWriteErr, close_fds = closeFdsIfSafe }) $ \sin' sout _ p -> -- Do this just like 'readCreateProcess' -- https://hackage.haskell.org/package/process-1.6.17.0/docs/src/System.Process.html#readCreateProcess case (sin', sout) of (Just hIn, Just hOut) -> liftIO $ do+ -- The child has its own copy; ours would keep hReadErr from ever reaching EOF+ hClose hWriteErr output <- hGetContents hOut withForkWait (C.evaluate $ rnf output) $ \waitOut -> do -- now write any input
src/Test/Sandwich/ManagedAsync.hs view
@@ -4,6 +4,7 @@ -- * With explicit run ID managedAsync , managedAsyncWithUnmask+ , managedAsyncWithUnmaskAndHandler , managedWithAsync , managedWithAsync_ @@ -62,6 +63,15 @@ managedAsyncWithUnmask runId name action = do parentThreadId <- liftIO myThreadId asyncWithUnmask $ \unmask -> bracketedAction parentThreadId runId name (action unmask)++-- | Like 'managedAsyncWithUnmask', but the handler wraps the entire thread body, including this+-- module's own bookkeeping. That bookkeeping contains an interruptible 'atomically', so a handler+-- installed inside it can be skipped entirely by an exception delivered as the thread starts.+managedAsyncWithUnmaskAndHandler :: (MonadUnliftIO m, Exception e) => T.Text -> T.Text -> (e -> m b) -> ((forall c. m c -> m c) -> m a) -> m (Async a)+managedAsyncWithUnmaskAndHandler runId name handler action = do+ parentThreadId <- liftIO myThreadId+ asyncWithUnmask $ \unmask ->+ flip withException handler $ bracketedAction parentThreadId runId name (action unmask) managedWithAsync :: MonadUnliftIO m => T.Text -> T.Text -> m a -> (Async a -> m b) -> m b managedWithAsync runId name action cb = do
src/Test/Sandwich/Options.hs view
@@ -28,6 +28,14 @@ -- * Timing , optionsTestTimerType + -- * Long-running nodes+ , optionsWarnOnLongExecutionMs+ , optionsCancelOnLongExecutionMs++ -- * Folder path lengths+ , optionsMaxFolderPathLength+ , defaultMaxFolderPathLength+ -- * Dry run , optionsDryRun @@ -61,7 +69,16 @@ , optionsEventBroadcast = Nothing , optionsLateLogFile = Nothing , optionsRunId = "run0"+ , optionsMaxFolderPathLength = defaultMaxFolderPathLength }++-- | 200 on Windows, which leaves 59 characters for files under @MAX_PATH@ (260, including the terminating NUL). Unlimited elsewhere.+defaultMaxFolderPathLength :: Maybe Int+#ifdef mingw32_HOST_OS+defaultMaxFolderPathLength = Just 200+#else+defaultMaxFolderPathLength = Nothing+#endif -- | Generate a test artifacts directory based on a timestamp. --
src/Test/Sandwich/ParallelN.hs view
@@ -4,95 +4,223 @@ {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} --- | Wrapper around 'parallel' for limiting the threads using a semaphore.+-- | Limiting how much of a test tree runs at once. module Test.Sandwich.ParallelN (+ -- * Limiting a parallel node parallelN , parallelN' , parallelNFromArgs , parallelNFromArgs' + -- * Lower-level+ , withParallelLanes+ , withParallelLanesFromArgs++ , withParallelLane+ , takeParallelLane+ , defaultParallelNodeOptions -- * Types- , parallelSemaphore- , HasParallelSemaphore+ , ParallelLanes+ , parallelLanes+ , HasParallelLanes ) where import Control.Concurrent.QSem+import Control.Concurrent.STM (retry) import Control.Monad import Control.Monad.IO.Class import Control.Monad.IO.Unlift+import Control.Monad.Reader+import qualified Data.List as L+import Data.String.Interpolate+import qualified Data.Text as T import Test.Sandwich.Contexts+import Test.Sandwich.TestTimer import Test.Sandwich.Types.ArgParsing import Test.Sandwich.Types.RunTree import Test.Sandwich.Types.Spec import UnliftIO.Exception+import UnliftIO.STM -- * Types -parallelSemaphore :: Label "parallelSemaphore" QSem-parallelSemaphore = Label+-- | A pool of lanes. Each lane is held by one part of the tree at a time, and has a test timer+-- profile of its own.+data ParallelLanes = ParallelLanes {+ parallelLanesSource :: TimingLaneSource+ -- | The bound. Gating on this first hands lanes out in wait order.+ , parallelLanesSem :: QSem+ , parallelLanesFree :: TVar [Int]+ , parallelLanesProfileNames :: [T.Text]+ } -type HasParallelSemaphore context = HasLabel context "parallelSemaphore" QSem+parallelLanes :: Label "parallelLanes" ParallelLanes+parallelLanes = Label +type HasParallelLanes context = HasLabel context "parallelLanes" ParallelLanes+ defaultParallelNodeOptions :: NodeOptions defaultParallelNodeOptions = defaultNodeOptions { nodeOptionsVisibilityThreshold = 70 } +-- Options for nodes that only introduce or claim lanes. Timing them would put a frame outside+-- every lane, forcing a profile of its own.+laneNodeOptions :: NodeOptions+laneNodeOptions = defaultNodeOptions {+ nodeOptionsRecordTime = False+ , nodeOptionsCreateFolder = False+ , nodeOptionsVisibilityThreshold = 125+ }+ -- * Functions --- | Wrapper around 'parallel'. Introduces a semaphore to limit the parallelism to N threads.+-- | Like 'parallel', but limits the parallelism to N tests at a time.+--+-- Introduces a pool of N lanes, one of which each test claims while it runs. The pool is shared by+-- the whole subtree, so nested 'parallel' nodes are limited too, and each lane is a test timer+-- profile, so you get N profiles rather than one per test. parallelN :: (- MonadUnliftIO m- ) => Int -> SpecFree (LabelValue "parallelSemaphore" QSem :> context) m () -> SpecFree context m ()+ MonadUnliftIO m, HasBaseContext context+ )+ -- | Number of lanes+ => Int+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m ()+ -> SpecFree context m () parallelN = parallelN' defaultParallelNodeOptions parallelN' :: (- MonadUnliftIO m+ MonadUnliftIO m, HasBaseContext context ) -- | Node options => NodeOptions- -- | Number of threads+ -- | Number of lanes -> Int- -> SpecFree (LabelValue "parallelSemaphore" QSem :> context) m ()+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m () -> SpecFree context m ()-parallelN' nodeOptions n = parallelN'' nodeOptions (liftIO $ newQSem n)+parallelN' nodeOptions n = parallelN'' nodeOptions (pure n) --- | Same as 'parallelN', but extracts the semaphore size from the command line options.+-- | Same as 'parallelN', but extracts the number of lanes from the command line options. parallelNFromArgs :: forall context a m. (- MonadUnliftIO m, HasCommandLineOptions context a+ MonadUnliftIO m, HasBaseContext context, HasCommandLineOptions context a )- -- | Callback to extract the semaphore size+ -- | Callback to extract the number of lanes => (CommandLineOptions a -> Int)- -> SpecFree (LabelValue "parallelSemaphore" QSem :> context) m ()+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m () -> SpecFree context m () parallelNFromArgs = parallelNFromArgs' @context @a defaultParallelNodeOptions parallelNFromArgs' :: forall context a m. (- MonadUnliftIO m, HasCommandLineOptions context a+ MonadUnliftIO m, HasBaseContext context, HasCommandLineOptions context a ) -- | Node options => NodeOptions- -- | Callback to extract the semaphore size+ -- | Callback to extract the number of lanes -> (CommandLineOptions a -> Int)- -> SpecFree (LabelValue "parallelSemaphore" QSem :> context) m ()+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m () -> SpecFree context m ()-parallelNFromArgs' nodeOptions getParallelism = parallelN'' nodeOptions f- where- f = getContext commandLineOptions >>= (liftIO . newQSem) . getParallelism+parallelNFromArgs' nodeOptions getParallelism =+ parallelN'' nodeOptions (getParallelism <$> getContext commandLineOptions) parallelN'' :: (- MonadUnliftIO m+ MonadUnliftIO m, HasBaseContext context ) => NodeOptions- -> ExampleT context m QSem- -> SpecFree (LabelValue "parallelSemaphore" QSem :> context) m ()+ -> ExampleT context m Int+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m () -> SpecFree context m ()-parallelN'' nodeOptions makeQSem children = introduce "Introduce parallel semaphore" parallelSemaphore makeQSem (const $ return ()) $- parallel' nodeOptions $ aroundEach "Take parallel semaphore" claimRunSlot children+parallelN'' nodeOptions getLanes children =+ withParallelLanes'' getLanes $+ parallel' nodeOptions $+ aroundEach' Nothing laneNodeOptions "Take parallel lane" (withParallelLane . void) children++-- | Introduce a pool of N lanes, to be claimed with 'withParallelLane' or 'takeParallelLane'.+--+-- Use this when the tests to limit aren't in one place you can wrap with 'parallelN', such as ones+-- from 'Test.Sandwich.TH.getSpecFromFolder'.+withParallelLanes :: (+ MonadIO m, HasBaseContext context+ )+ -- | Number of lanes+ => Int+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m ()+ -> SpecFree context m ()+withParallelLanes n = withParallelLanes'' (pure n)++-- | Same as 'withParallelLanes', but extracts the number of lanes from the command line options.+withParallelLanesFromArgs :: forall context a m. (+ MonadIO m, HasBaseContext context, HasCommandLineOptions context a+ )+ -- | Callback to extract the number of lanes+ => (CommandLineOptions a -> Int)+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m ()+ -> SpecFree context m ()+withParallelLanesFromArgs getParallelism =+ withParallelLanes'' (getParallelism <$> getContext commandLineOptions)++withParallelLanes'' :: (+ MonadIO m, HasBaseContext context+ )+ => ExampleT context m Int+ -> SpecFree (LabelValue "parallelLanes" ParallelLanes :> context) m ()+ -> SpecFree context m ()+withParallelLanes'' getLanes =+ introduce' laneNodeOptions "Introduce parallel lanes" parallelLanes alloc (const $ return ()) where- claimRunSlot f = do- s <- getContext parallelSemaphore- bracket_ (liftIO $ waitQSem s) (liftIO $ signalQSem s) (void f)+ alloc = do+ numLanes <- max 1 <$> getLanes+ source <- newTimingLaneSource+ sem <- liftIO $ newQSem numLanes+ free <- newTVarIO [0 .. numLanes - 1]+ -- Name the lanes after the profile we're in, so lanes introduced inside another lane (or+ -- inside one branch of a parallel node) don't collide with ones introduced elsewhere.+ baseProfile <- asks getBaseContext >>= currentTestTimerProfile+ let names = [baseProfile <> [i|-lane-#{leftPadWithZeros numLanes lane}|]+ | lane <- [0 .. numLanes - 1]]+ return $ ParallelLanes source sem free names++ leftPadWithZeros :: Int -> Int -> String+ leftPadWithZeros total num =+ L.replicate (L.length (show (total - 1)) - L.length (show num)) '0' <> show num++-- | Claim a lane, run the action, and release it. Blocks until a lane is free. Everything the+-- action runs, at any depth, is timed under the lane's profile.+--+-- A no-op if this part of the tree already holds a lane from the same pool, since claiming a+-- second one could deadlock.+withParallelLane :: (+ MonadUnliftIO m, HasBaseContextMonad context m, HasParallelLanes context+ ) => m a -> m a+withParallelLane action = do+ pool <- getContext parallelLanes+ inTimingLane (parallelLanesSource pool) >>= \case+ True -> action+ False -> bracket (claimLane pool) (releaseLane pool) $ \lane ->+ withTimingLane (parallelLanesSource pool) (parallelLanesProfileNames pool !! lane) action++-- | 'withParallelLane' as a spec node, designed for use with+-- 'Test.Sandwich.TH.getSpecIndividualSpecHooks'.+takeParallelLane :: (+ MonadUnliftIO m, HasBaseContext context, HasParallelLanes context+ )+ -- | Ignored+ => FilePath+ -> SpecFree context m ()+ -> SpecFree context m ()+takeParallelLane _ = around' laneNodeOptions "Take parallel lane" (withParallelLane . void)++claimLane :: (MonadIO m) => ParallelLanes -> m Int+claimLane (ParallelLanes {parallelLanesSem, parallelLanesFree}) = liftIO $ do+ waitQSem parallelLanesSem+ flip onException (signalQSem parallelLanesSem) $ atomically $ readTVar parallelLanesFree >>= \case+ -- Can't happen: the semaphore already limits us to the number of lanes.+ [] -> retry+ (lane:rest) -> writeTVar parallelLanesFree rest >> return lane++releaseLane :: (MonadIO m) => ParallelLanes -> Int -> m ()+releaseLane (ParallelLanes {parallelLanesSem, parallelLanesFree}) lane = liftIO $ do+ atomically $ modifyTVar' parallelLanesFree (lane :)+ signalQSem parallelLanesSem
src/Test/Sandwich/RunTree.hs view
@@ -9,6 +9,8 @@ , extractValuesControlRecurse , getCommons + , markUnfinishedNodesDone+ , isDone , isFailure , isRunning@@ -18,11 +20,27 @@ ) where import Control.Concurrent.STM+import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.State+import Data.Time import Test.Sandwich.Types.RunTree import Test.Sandwich.Types.Spec ++-- | Give a terminal status to every node in the subtree that doesn't have one yet, leaving+-- nodes that are already 'Done' alone.+--+-- Call this once a subtree can't make any more progress: nodes record their own results, but+-- ones that never started have nobody to do it for them.+markUnfinishedNodesDone :: RunNode context -> Result -> IO ()+markUnfinishedNodesDone node result = do+ now <- getCurrentTime+ forM_ (getCommons node) $ \common ->+ atomically $ modifyTVar' (runTreeStatus common) $ \case+ done@(Done {}) -> done+ Running {..} -> Done statusStartTime statusSetupFinishTime statusTeardownStartTime now result+ NotStarted -> Done now Nothing Nothing now result extractValues :: (forall ctx. RunNodeWithStatus ctx s l t -> a) -> RunNodeWithStatus context s l t -> [a] extractValues f node@(RunNodeIt {}) = [f node]
src/Test/Sandwich/Shutdown.hs view
@@ -3,15 +3,17 @@ import Control.Concurrent.Async import Control.Concurrent.STM-import Data.Time+import Test.Sandwich.RunTree import Test.Sandwich.Types.RunTree import Test.Sandwich.Types.Spec cancelNode :: RunNode context -> IO ()-cancelNode node = readTVarIO (runTreeStatus $ runNodeCommon node) >>= \case- Running {..} -> cancel statusAsync- NotStarted -> do- now <- getCurrentTime- atomically $ writeTVar (runTreeStatus $ runNodeCommon node) (Done now Nothing Nothing now Cancelled)- Done {} -> return ()+cancelNode node = do+ readTVarIO (runTreeStatus $ runNodeCommon node) >>= \case+ Running {..} -> cancel statusAsync+ _ -> return ()++ -- 'cancel' doesn't return until the async has finished, and a node that hasn't started under+ -- a cancelled parent never will, so anything in here that isn't 'Done' by now never will be.+ markUnfinishedNodesDone node Cancelled
src/Test/Sandwich/TH.hs view
@@ -31,8 +31,10 @@ import Test.Sandwich.Types.Spec hiding (location) -constId :: b -> a -> a-constId = const id+-- | The default 'getSpecIndividualSpecHooks'. Takes a 'FilePath' rather than any @b@ so the+-- file name 'getSpecFromFolder' passes in doesn't need defaulting under @OverloadedStrings@.+ignoreFileName :: FilePath -> a -> a+ignoreFileName = const id data GetSpecFromFolderOptions = GetSpecFromFolderOptions { getSpecCombiner :: Name@@ -45,7 +47,7 @@ defaultGetSpecFromFolderOptions :: GetSpecFromFolderOptions defaultGetSpecFromFolderOptions = GetSpecFromFolderOptions { getSpecCombiner = 'describe- , getSpecIndividualSpecHooks = 'constId+ , getSpecIndividualSpecHooks = 'ignoreFileName , getSpecWarnOnParseError = WarnOnParseError } @@ -125,10 +127,13 @@ mangleFolderName :: String -> String mangleFolderName = T.unpack . wordify . T.pack . takeBaseName --- | Convert a string like "TeamTests" to "Team tests"+-- | Convert a string like "TeamTests" to "Team tests", leaving acronyms alone:+-- "LSP" stays "LSP" and "HTTPClient" becomes "HTTP client". wordify :: T.Text -> T.Text-wordify t = T.intercalate " " $ capitalizeFirst $ fmap (T.toLower . T.pack) parts- where parts = splitR (\c -> isUpper c || isDigit c) $ T.unpack t+wordify = T.intercalate " " . capitalizeFirst . fmap (unCamel . T.pack) . splitWords . T.unpack+ where+ unCamel w | T.length w > 1, T.all isUpper w = w+ | otherwise = T.toLower w capitalizeFirst :: [T.Text] -> [T.Text] capitalizeFirst [] = []@@ -138,15 +143,23 @@ capitalize t | T.length t == 1 = T.toUpper t capitalize t = toUpper (T.head t) `T.cons` (T.tail t) -splitR :: (Char -> Bool) -> String -> [String]-splitR _ [] = []-splitR p s =- let- go :: Char -> String -> [String]- go m s' = case L.break p s' of- (b', []) -> [ m:b' ]- (b', x:xs) -> ( m:b' ) : go x xs- in case L.break p s of- (b, []) -> [ b ]- ([], h:t) -> go h t- (b, h:t) -> b : go h t+-- | Split a camel-cased name into words, treating a run of capitals as one word and+-- starting a new word at a digit.+splitWords :: String -> [String]+splitWords = go . L.groupBy ((==) `on` charClass)+ where+ go (ups@(u:_) : word@(w:_) : rest)+ | charClass u == ClassUpper, charClass w == ClassLower = case ups of+ -- The last capital of a run starts the word after it.+ [_] -> (ups <> word) : go rest+ _ -> L.init ups : (L.last ups : word) : go rest+ go (g : rest) = g : go rest+ go [] = []++data CharClass = ClassUpper | ClassLower | ClassDigit+ deriving (Eq)++charClass :: Char -> CharClass+charClass c | isUpper c = ClassUpper+ | isDigit c = ClassDigit+ | otherwise = ClassLower
src/Test/Sandwich/TestTimer.hs view
@@ -14,8 +14,14 @@ , withTimingProfile , withTimingProfile' + , TimingLaneSource+ , newTimingLaneSource+ , withTimingLane+ , inTimingLane+ , newSpeedScopeTestTimer , finalizeSpeedScopeTestTimer+ , renderSpeedScopeFile ) where import Control.Monad.IO.Class@@ -24,6 +30,7 @@ import Control.Monad.Trans.State import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as BL+import Data.Foldable (toList) import qualified Data.List as L import qualified Data.Sequence as S import Data.String.Interpolate@@ -31,6 +38,7 @@ import qualified Data.Text.IO as T import Data.Time import Data.Time.Clock.POSIX+import Data.Unique import Lens.Micro import System.Directory import System.FilePath@@ -41,6 +49,7 @@ import Test.Sandwich.Util (whenJust) import UnliftIO.Concurrent import UnliftIO.Exception+import UnliftIO.STM type EventName = T.Text@@ -51,7 +60,9 @@ -- * User functions --- | Time a given action with a given event name. This name will be the "stack frame" of the given action in the profiling results. This function will use the current timing profile name.+-- | Time a given action with a given event name. This name will be the "stack+-- frame" of the given action in the profiling results. This function will use+-- the current timing profile name. timeAction :: (MonadUnliftIO m, HasBaseContextMonad context m, HasTestTimer context) -- | Event name => EventName@@ -59,10 +70,12 @@ -> m a timeAction eventName action = do tt <- asks getTestTimer- BaseContext {baseContextTestTimerProfile} <- asks getBaseContext- timeAction' tt baseContextTestTimerProfile eventName action+ bc <- asks getBaseContext+ profile <- currentTestTimerProfile bc+ timeAction' tt profile eventName action --- | Time a given action with a given profile name and event name. Use when you want to manually specify the profile name.+-- | Time a given action with a given profile name and event name. Use when you+-- want to manually specify the profile name. timeActionByProfile :: (MonadUnliftIO m, MonadReader context m, HasTestTimer context) -- | Profile name => ProfileName@@ -82,7 +95,8 @@ -> SpecFree context m () withTimingProfile pn = introduce' timingNodeOptions [i|Switch test timer profile to '#{pn}'|] testTimerProfile (pure $ TestTimerProfile pn) (\_ -> return ()) --- | Introduce a new timing profile name dynamically. The given 'ExampleT' should come up with the name and return it.+-- | Introduce a new timing profile name dynamically. The given 'ExampleT'+-- should come up with the name and return it. withTimingProfile' :: (Monad m) -- | Callback to generate the profile name => ExampleT context m ProfileName@@ -90,6 +104,38 @@ -> SpecFree context m () withTimingProfile' getName = introduce' timingNodeOptions [i|Switch test timer profile to dynamic value|] testTimerProfile (TestTimerProfile <$> getName) (\_ -> return ()) +-- * Timing lanes++-- | Make a new source of timing lanes. Pass the same one to 'withTimingLane' and 'inTimingLane'.+newTimingLaneSource :: MonadIO m => m TimingLaneSource+newTimingLaneSource = TimingLaneSource <$> liftIO newUnique++-- | Record this action, and everything below it in the tree, under the given profile. Unlike+-- 'withTimingProfile' this works from an 'around' handler, without changing the spec's type.+--+-- A 'Test.Sandwich.parallel' node below gives each of its children a suffixed profile of their+-- own, so concurrent branches never share one.+withTimingLane :: (MonadUnliftIO m, HasBaseContextMonad context m)+ -- | Who's handing out the lane+ => TimingLaneSource+ -- | Profile name for the lane+ -> ProfileName+ -> m a+ -> m a+withTimingLane source profileName action = do+ BaseContext {baseContextTimingProfile} <- asks getBaseContext+ previous <- readTVarIO baseContextTimingProfile+ let held = TimingProfile profileName (source : timingProfileLanes previous)+ bracket_ (atomically $ writeTVar baseContextTimingProfile held)+ (atomically $ writeTVar baseContextTimingProfile previous)+ action++-- | Whether this branch of the tree already holds a lane from the given source.+inTimingLane :: (MonadIO m, HasBaseContextMonad context m) => TimingLaneSource -> m Bool+inTimingLane source = do+ BaseContext {baseContextTimingProfile} <- asks getBaseContext+ (source `elem`) . timingProfileLanes <$> readTVarIO baseContextTimingProfile+ -- * Core timingNodeOptions :: NodeOptions@@ -117,13 +163,28 @@ finalizeSpeedScopeTestTimer :: TestTimer -> IO () finalizeSpeedScopeTestTimer NullTestTimer = return ()-finalizeSpeedScopeTestTimer (SpeedScopeTestTimer {..}) = do- endTime <- liftIO getPOSIXTime-- speedScopeFile <- readMVar testTimerSpeedScopeFile+finalizeSpeedScopeTestTimer tt@(SpeedScopeTestTimer {..}) = do+ contents <- renderSpeedScopeFile tt whenJust testTimerHandle hClose + whenJust contents $ BL.writeFile (testTimerBasePath </> "speedscope.json")++-- | Render the current state of the test timer as a speedscope profile. Frames+-- that are still open are closed off at the current time, so this can be called+-- while tests are running.+renderSpeedScopeFile :: MonadIO m => TestTimer -> m (Maybe BL.ByteString)+renderSpeedScopeFile NullTestTimer = return Nothing+renderSpeedScopeFile (SpeedScopeTestTimer {..}) = liftIO $ do+ now <- getPOSIXTime++ speedScopeFile <- closeOpenFrames now <$> readMVar testTimerSpeedScopeFile++ -- End at the last thing that happened, rather than at the current time, so that a profile+ -- rendered after the tests are done doesn't include all the time since.+ let endTime = L.foldl' max testTimerStartTime [time | p <- speedScopeFile ^. profiles+ , SpeedScopeEvent _ _ time <- toList (p ^. events)]+ -- Wrap every test profile in an overall frame called 'allTestsEventName'. If -- we don't do this, the speedscope viewer will show each profile as if it -- starts at time 0.@@ -136,8 +197,24 @@ speedScopeFile (fmap (^. name) (speedScopeFile ^. profiles)) - BL.writeFile (testTimerBasePath </> "speedscope.json") $ A.encode finalSpeedScopeFile+ return $ Just $ A.encode finalSpeedScopeFile + where+ closeOpenFrames :: POSIXTime -> SpeedScopeFile -> SpeedScopeFile+ closeOpenFrames time = over profiles (fmap closeProfile)+ where+ closeProfile :: SpeedScopeProfile -> SpeedScopeProfile+ closeProfile p = p+ & over events (<> S.fromList [SpeedScopeEvent SpeedScopeEventTypeClose frameID time+ | frameID <- openFrames (p ^. events)])++ openFrames :: S.Seq SpeedScopeEvent -> [Int]+ openFrames = L.foldl' step []+ where+ step open (SpeedScopeEvent SpeedScopeEventTypeOpen frameID _) = frameID : open+ step (_:rest) (SpeedScopeEvent SpeedScopeEventTypeClose _ _) = rest+ step [] (SpeedScopeEvent SpeedScopeEventTypeClose _ _) = []+ timeAction' :: (MonadUnliftIO m) => TestTimer -> T.Text -> T.Text -> m a -> m a timeAction' NullTestTimer _ _ = id timeAction' (SpeedScopeTestTimer {..}) profileName eventName = bracket_@@ -192,8 +269,9 @@ modify' $ over (profiles . ix profileIndex . events) ((SpeedScopeEvent eventType frameID time) S.<|) . over (profiles . ix profileIndex . startValue) (min time) --- | TODO: maybe use an intermediate format so the frames (and possibly profiles) aren't stored as lists,--- so we don't have to do O(N) L.length and S.findIndexL+-- | TODO: maybe use an intermediate format so the frames (and possibly+-- profiles) aren't stored as lists, so we don't have to do O(N) L.length and+-- S.findIndexL getFrameIDAndProfileIndex :: POSIXTime -> T.Text -> T.Text -> State SpeedScopeFile (Int, Int) getFrameIDAndProfileIndex time profileName eventName = do frameID <- get >>= \f -> case S.findIndexL (== SpeedScopeFrame eventName) (f ^. shared . frames) of
src/Test/Sandwich/Types/ArgParsing.hs view
@@ -58,6 +58,7 @@ , optDryRun :: Maybe Bool , optWarnOnLongExecutionMs :: Maybe Int , optCancelOnLongExecutionMs :: Maybe Int+ , optMaxFolderPathLength :: Maybe Int , optMarkdownSummaryPath :: Maybe FilePath , optTuiDebugSocket :: Bool , optSocketFormatter :: Bool
src/Test/Sandwich/Types/RunTree.hs view
@@ -153,11 +153,15 @@ , baseContextErrorSymlinksDir :: Maybe FilePath , baseContextOptions :: Options , baseContextOnlyRunIds :: Maybe (S.Set Int)- , baseContextTestTimerProfile :: T.Text+ , baseContextTimingProfile :: TVar TimingProfile , baseContextTestTimer :: TestTimer , baseContextRunId :: T.Text } +-- | The profile to record frames under right now.+currentTestTimerProfile :: MonadIO m => BaseContext -> m T.Text+currentTestTimerProfile (BaseContext {..}) = timingProfileName <$> liftIO (readTVarIO baseContextTimingProfile)+ -- | Has-* class for asserting a 'BaseContext' is available. class HasBaseContext a where getBaseContext :: a -> BaseContext@@ -324,6 +328,8 @@ -- ^ If set, log writes that occur after a node is already Done will be written to this file handle. , optionsRunId :: T.Text -- ^ An identifier for this test run, used to track managed async threads.+ , optionsMaxFolderPathLength :: Maybe Int+ -- ^ If set, shorten node folder names to keep every node folder path at most this long. } -- | A wrapper type for exceptions with attached callstacks. Haskell doesn't currently offer a way
src/Test/Sandwich/Types/Spec.hs view
@@ -220,11 +220,13 @@ -- ^ Whether to time this node. , nodeOptionsModuleInfo :: Maybe NodeModuleInfo -- ^ A main function run this entire node in isolation.+ , nodeOptionsFolderNameCap :: Maybe Int+ -- ^ Set by 'fitFolderPaths' to cap the length of this node's folder name. } deriving Show -- | Reasonable default node options. defaultNodeOptions :: NodeOptions-defaultNodeOptions = NodeOptions 100 True True Nothing+defaultNodeOptions = NodeOptions 100 True True Nothing Nothing data SpecCommand context m next where Before'' :: {
src/Test/Sandwich/Types/TestTimer.hs view
@@ -14,6 +14,7 @@ import Data.Sequence import qualified Data.Text as T import Data.Time.Clock.POSIX+import Data.Unique import Lens.Micro.TH import System.IO import Test.Sandwich.Types.Spec@@ -136,3 +137,17 @@ testTimerProfile = Label :: Label "testTimerProfile" TestTimerProfile newtype TestTimerProfile = TestTimerProfile T.Text++-- * Timing lanes++-- | Identifies whoever is handing out timing lanes. See+-- 'Test.Sandwich.TestTimer.newTimingLaneSource'.+newtype TimingLaneSource = TimingLaneSource Unique+ deriving (Eq)++-- | The test timer profile in effect on one branch of the test tree, and the timing lanes it's holding. Concurrent branches always get their own copy, so only one thread writes it at a time.+data TimingProfile = TimingProfile {+ timingProfileName :: T.Text+ -- | The sources we're holding a lane from. Claiming a second lane from one of these would deadlock, since only we can release it.+ , timingProfileLanes :: [TimingLaneSource]+ }
+ test/CancelOnLongExecution.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE DataKinds #-}++module CancelOnLongExecution (+ tests+ , main+ ) where++import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Trans.Writer+import Data.String.Interpolate+import GHC.Stack+import Test.Sandwich+import Test.Sandwich.Internal+import UnliftIO.Concurrent+import UnliftIO.Exception++import TestUtil++tests :: MonadIO m => WriterT [SomeException] m ()+tests = do+ run cancelOnLongExecutionLeavesNothingUnfinished++main :: IO ()+main = mainWith tests++-- * Tests++-- | With @--cancel-on-long-execution-ms@ the tree gets torn down from several places at once, and+-- a node's async can be killed before it has installed the handler that records its result,+-- leaving the node 'Running' for good.+cancelOnLongExecutionLeavesNothingUnfinished :: (HasCallStack) => IO ()+cancelOnLongExecutionLeavesNothingUnfinished =+ forM_ [1 .. 20 :: Int] $ \iteration -> do+ rts <- runSandwichTree options spec++ waitForAllNodesDone 2_000_000 rts >>= \case+ [] -> return ()+ notDone -> error [i|Iteration #{iteration} left #{length notDone} node(s) unfinished: #{notDone}|]+ where+ options = defaultOptions { optionsCancelOnLongExecutionMs = Just 200 }++-- | A lane pool holds back most of the tests, so nodes are constantly starting when the cancel+-- fires on the wrapper.+spec :: CoreSpec+spec = introduceWith "wrapper" fakeDatabaseLabel (\action -> void $ action FakeDatabase) $+ parallelN 8 $+ forM_ [1 .. 60 :: Int] $ \n ->+ describe [i|group #{n}|] $+ it [i|test #{n}|] $ liftIO $ threadDelay 100_000
+ test/EscapedExceptions.hs view
@@ -0,0 +1,69 @@+{-# LANGUAGE DataKinds #-}++module EscapedExceptions (+ tests+ , main+ ) where++import Control.Monad.IO.Class+import Control.Monad.Trans.Writer+import Data.String.Interpolate+import GHC.Stack+import System.Directory+import System.FilePath+import System.Timeout (timeout)+import Test.Sandwich+import Test.Sandwich.Internal+import TestUtil+import UnliftIO.Exception+++tests :: MonadIO m => FilePath -> WriterT [SomeException] m ()+tests testRunsDir = do+ run (siblingsFinishWhenExceptionEscapesNode testRunsDir)+ run formatterFinalizeFailureFailsRun++main :: IO ()+-- Not point-free (mainWith . tests), since GHC 9.0 rejects that for mainWith's constrained argument+main = getTestRunsDir >>= \testRunsDir -> mainWith (tests testRunsDir)++-- * Tests++-- | An exception escaping a node's runner (here, from writing its failure.txt) shouldn't leave the+-- nodes after it unfinished, since anything waiting on them would wait forever.+siblingsFinishWhenExceptionEscapesNode :: (HasCallStack) => FilePath -> IO ()+siblingsFinishWhenExceptionEscapesNode testRunsDir = withTempArtifactsDir testRunsDir $ \dir -> do+ rts <- startSandwichTree (defaultOptions { optionsTestArtifactsDirectory = TestArtifactsFixedDirectory dir }) $+ describe "outer" $ do+ it "blocks its own failure.txt" $ do+ getCurrentFolder >>= \case+ Nothing -> expectationFailure "Expected a test folder"+ Just folder -> liftIO $ createDirectoryIfMissing True (folder </> "failure.txt")+ expectationFailure "Failing so sandwich writes failure.txt"+ it "comes after" $ return ()+ mapM_ waitForTree rts++ waitForAllNodesDone 10_000_000 rts >>= \case+ [] -> return ()+ notDone -> expectationFailure [i|Nodes never finished: #{notDone}|]++-- | A formatter that throws while finalizing should fail the run with its exception, not hang it.+formatterFinalizeFailureFailsRun :: (HasCallStack) => IO ()+formatterFinalizeFailureFailsRun = do+ result <- timeout 30_000_000 $ tryAny $ runSandwich' Nothing (defaultOptions { optionsFormatters = [SomeFormatter ThrowingFormatter] }) $+ it "passes" $ return ()++ case result of+ Nothing -> expectationFailure "Run didn't finish"+ Just (Right x) -> expectationFailure [i|Expected the formatter's exception, but the run returned #{x}|]+ Just (Left e) -> show e `mustBe` show finalizeError++data ThrowingFormatter = ThrowingFormatter deriving Show++instance Formatter ThrowingFormatter where+ formatterName _ = "throwing-formatter"+ runFormatter _ _ _ _ = return ()+ finalizeFormatter _ _ _ = liftIO $ throwIO finalizeError++finalizeError :: IOError+finalizeError = userError "Formatter failed to finalize"
+ test/FolderPaths.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE ViewPatterns #-}++module FolderPaths where++import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Trans.Writer+import qualified Data.List as L+import Data.String.Interpolate+import System.FilePath+import Test.Sandwich+import Test.Sandwich.Internal+import TestUtil+import UnliftIO.Exception+++tests :: MonadIO m => WriterT [SomeException] m ()+tests = do+ -- Deep tree fits the max length+ run $ do+ folders <- getFolders (Just 150)+ forM_ folders $ \(_, folder) ->+ unless (L.length folder <= 150) $ expectationFailure [i|Folder too long (#{L.length folder}): #{folder}|]+ uncapped <- getFolders Nothing+ unless (L.any (\(_, f) -> L.length f > 150) uncapped) $ expectationFailure "Expected the uncapped tree to exceed the max length"++ -- Shallow names are kept+ run $ do+ folders <- getFolders (Just 150)+ case L.lookup "does a shallow thing with a fairly long but harmless label" folders of+ Nothing -> expectationFailure "Couldn't find shallow node"+ Just f -> takeFileName f `mustBe` "does a shallow thing with a fairly long but harmless label"++ -- Shortened names keep the start of the label+ run $ do+ folders <- getFolders (Just 150)+ let shortened = [(label, L.init name) | (label, takeFileName -> name) <- folders+ , "_" `L.isSuffixOf` name+ , not (label `L.isSuffixOf` name)]+ when (L.null shortened) $ expectationFailure "Expected some names to be shortened"+ forM_ shortened $ \(label, stem) ->+ unless (L.any (\k -> L.drop k stem `L.isPrefixOf` label) [0..4]) $+ expectationFailure [i|Expected '#{stem}' to start like '#{label}'|]++ -- Siblings stay unique+ run $ do+ paths <- fmap snd <$> getFolders (Just 150)+ L.length (L.nub paths) `mustBe` L.length paths++ -- No max length leaves names alone+ run $ do+ folders <- getFolders Nothing+ case L.lookup (longLabel 1) folders of+ Nothing -> expectationFailure "Couldn't find deep node"+ Just f -> takeFileName f `mustBe` ("1_" <> longLabel 1)++ -- A tiny max length uses the shortest names+ run $ do+ paths <- fmap snd <$> getFolders (Just 50)+ L.length (L.nub paths) `mustBe` L.length paths+ let deepest = L.maximumBy (\a b -> compare (L.length (splitDirectories a)) (L.length (splitDirectories b))) paths+ forM_ (splitDirectories (makeRelative "/root/results" deepest)) $ \component ->+ unless (L.length component <= 9) $ expectationFailure [i|Expected the shortest names, got: #{deepest}|]++-- | Nested describes with long labels, each with a couple of its, plus a shallow sibling at the top.+deepSpec :: CoreSpec+deepSpec = do+ describe "shallow sibling with a fairly long but harmless label" $+ it "does a shallow thing with a fairly long but harmless label" $ return ()+ go (12 :: Int)+ where+ go 0 = it (longLabel 0) $ return ()+ go n = describe (longLabel n) $ do+ it [i|first #{longLabel n}|] $ return ()+ go (n - 1)+ it [i|last #{longLabel n}|] $ return ()++longLabel :: Int -> String+longLabel n = [i|#{n}_manually goes back to the revision prior to the one that created the dummy settings file|]++-- | Folders by label, using 'getRunTree' (which puts the run root at "/root").+getFolders :: Maybe Int -> IO [(String, FilePath)]+getFolders maxLength = do+ tree <- getRunTree (defaultOptions { optionsMaxFolderPathLength = maxLength }) deepSpec+ return [(label, folder) | (label, Just folder) <- concatMap (extractValues (\n -> (runTreeLabel (runNodeCommon n), runTreeFolder (runNodeCommon n)))) tree]++main :: IO ()+main = mainWith tests
test/Main.hs view
@@ -4,16 +4,26 @@ import qualified Around import qualified Before+import qualified CancelOnLongExecution import qualified Describe+import qualified EscapedExceptions+import qualified FolderPaths import qualified Introduce import qualified IntroduceWith+import qualified UnicodeLabels import TestUtil main :: IO ()-main = mainWith $ do- Around.tests- Before.tests- Describe.tests- Introduce.tests- IntroduceWith.tests+main = do+ testRunsDir <- getTestRunsDir+ mainWith $ do+ Around.tests+ Before.tests+ CancelOnLongExecution.tests+ Describe.tests+ EscapedExceptions.tests testRunsDir+ FolderPaths.tests+ Introduce.tests+ IntroduceWith.tests+ UnicodeLabels.tests testRunsDir
test/TestUtil.hs view
@@ -10,8 +10,11 @@ import Control.Monad.Trans.Writer import Data.Foldable import Data.String.Interpolate+import Data.Time.Clock.POSIX (getPOSIXTime) import GHC.Stack+import System.Directory import System.Exit+import System.FilePath import Test.Sandwich import Test.Sandwich.Internal import UnliftIO.Exception@@ -92,11 +95,45 @@ | x == y = return () | otherwise = error [i|Expected #{show y} but got #{show x} (#{callStack})|] +getTestRunsDir :: IO FilePath+getTestRunsDir = (</> "test_runs") <$> getCurrentDirectory++withTempArtifactsDir :: FilePath -> (FilePath -> IO a) -> IO a+withTempArtifactsDir testRunsDir action = do+ micros :: Integer <- round . (* 1000000) <$> getPOSIXTime+ let dir = testRunsDir </> [i|sandwich-test-#{micros}|]+ createDirectoryIfMissing True dir+ action dir `finally` removePathForcibly dir+ waitUntilRunning :: TVar Status -> IO () waitUntilRunning status = atomically $ do readTVar status >>= \case Running {} -> return () _ -> retry++-- | Wait until every node has a terminal status, giving up after the given number of+-- microseconds. Returns whatever is still un-'Done'. Waits because nodes can still be unwinding+-- when the root finishes.+waitForAllNodesDone :: Int -> [RunNode context] -> IO [(String, Status)]+waitForAllNodesDone timeoutMicros rts = do+ timedOut <- registerDelay timeoutMicros++ -- The transaction reads every status, so it retries exactly when one of them is written+ atomically $ do+ (filter (not . isDoneStatus . snd) <$> mapM readCommon (concatMap getCommons rts)) >>= \case+ [] -> return []+ notDone -> readTVar timedOut >>= \case+ True -> return notDone+ False -> retry++ where+ readCommon common = do+ status <- readTVar (runTreeStatus common)+ return (runTreeLabel common, status)++ isDoneStatus :: Status -> Bool+ isDoneStatus (Done {}) = True+ isDoneStatus _ = False -- printFixedRunTree :: RunNodeFixed -> IO () -- printFixedRunTree = printFixedRunTree' 0
+ test/UnicodeLabels.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE DataKinds #-}++module UnicodeLabels (+ tests+ , main+ ) where++import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Trans.Writer+import qualified Data.List as L+import GHC.IO.Encoding+import GHC.Stack+import System.Directory+import System.FilePath+import System.IO+import System.Timeout (timeout)+import Test.Sandwich+import Test.Sandwich.Formatters.FailureReport+import TestUtil+import UnliftIO.Exception+++tests :: MonadIO m => FilePath -> WriterT [SomeException] m ()+tests testRunsDir = do+ run (unicodeLabelsWorkUnderAsciiLocale testRunsDir)++main :: IO ()+-- Not point-free (mainWith . tests), since GHC 9.0 rejects that for mainWith's constrained argument+main = getTestRunsDir >>= \testRunsDir -> mainWith (tests testRunsDir)++-- * Tests++-- | Non-ASCII labels should become folders and print, even under an ASCII locale like @LANG=C@.+unicodeLabelsWorkUnderAsciiLocale :: (HasCallStack) => FilePath -> IO ()+unicodeLabelsWorkUnderAsciiLocale testRunsDir = withTempArtifactsDir testRunsDir $ \dir -> withAsciiEncodings $ do+ let options = defaultOptions {+ optionsTestArtifactsDirectory = TestArtifactsFixedDirectory dir+ , optionsFormatters = [SomeFormatter defaultFailureReportFormatter]+ }+ result <- timeout 30_000_000 $ runSandwich' Nothing options $+ describe "outer…" $ do+ it "passes…" $ return ()+ it "is pending…" pending++ result `mustBe` Just (NormalExit, 0, 0)++ folders <- listDirectoriesRecursive dir+ unless (L.any (("passes…" `L.isSuffixOf`) . takeFileName) folders) $+ expectationFailure ("Expected a folder for 'passes…', got: " <> show folders)++-- | Run with ASCII file system and stdout encodings.+withAsciiEncodings :: IO a -> IO a+withAsciiEncodings action = bracket useAsciiEncodings restoreEncodings (const action)+ where+ useAsciiEncodings = do+ oldEncodings <- (,) <$> getFileSystemEncoding <*> hGetEncoding stdout+ asciiRoundtrip <- mkTextEncoding "ASCII//ROUNDTRIP"+ ascii <- mkTextEncoding "ASCII"+ setFileSystemEncoding asciiRoundtrip+ hSetEncoding stdout ascii+ return oldEncodings++ restoreEncodings (oldFileSystemEncoding, oldStdoutEncoding) = do+ setFileSystemEncoding oldFileSystemEncoding+ mapM_ (hSetEncoding stdout) oldStdoutEncoding++listDirectoriesRecursive :: FilePath -> IO [FilePath]+listDirectoriesRecursive dir = do+ children <- fmap (dir </>) <$> listDirectory dir+ childDirs <- filterM doesDirectoryExist children+ (childDirs <>) . mconcat <$> mapM listDirectoriesRecursive childDirs