packages feed

sandwich-0.4.0.0: test/TestUtil.hs

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}

module TestUtil where

import Control.Concurrent.STM
import qualified Data.ByteString.Char8 as BS8
import Control.Monad.IO.Class
import Control.Monad.Logger
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

-- * Main function

mainWith :: (HasCallStack) => (HasCallStack => WriterT [SomeException] IO ()) -> IO ()
mainWith tests = do
  results <- execWriterT tests

  case results of
    [] -> do
      putStrLn "All tests succeeded!"
    xs -> do
      putStrLn [i|\n\n#{length xs} test(s) failed\n\n|]
      forM_ xs $ \x -> putStrLn [i|#{x}\n\n|]
      exitWith (ExitFailure 1)


-- * Values

data FakeDatabase = FakeDatabase deriving Show
fakeDatabaseLabel :: Label "fakeDatabase" FakeDatabase
fakeDatabaseLabel = Label

someUserError :: IOError
someUserError = userError "Oh no"

someUserErrorWrapped :: SomeExceptionWithEq
someUserErrorWrapped = SomeExceptionWithEq $ SomeException $ userError "Oh no"

-- * Helpers

run :: (MonadIO m) => IO () -> WriterT [SomeException] m ()
run test = liftIO (tryAny test) >>= \case
  Left err -> tell [err]
  Right () -> return ()

throwSomeUserError :: (MonadIO m) => m ()
throwSomeUserError = liftIO $ throwIO someUserError

runAndGetResults :: (HasCallStack) => CoreSpec -> IO [Result]
runAndGetResults spec = do
  finalTree <- runSandwichTree defaultOptions spec
  fixedTree <- atomically $ mapM fixRunTree finalTree
  return $ fmap statusToResult $ concatMap getStatuses fixedTree

runAndGetResultsAndLogs :: (HasCallStack) => CoreSpec -> IO ([Result], [[BS8.ByteString]])
runAndGetResultsAndLogs spec = do
  finalTree <- runSandwichTree defaultOptions spec
  getResultsAndMessages <$> fixTree finalTree

fixTree :: [RunNode context] -> IO [RunNodeFixed context]
fixTree rts = atomically $ mapM fixRunTree rts

getResultsAndMessages :: (HasCallStack) => [RunNodeFixed context] -> ([Result], [[BS8.ByteString]])
getResultsAndMessages fixedTree = (results, msgs)
  where
    results = fmap statusToResult $ concatMap getStatuses fixedTree
    msgs = getMessages fixedTree

getMessages :: [RunNodeFixed context] -> [[BS8.ByteString]]
getMessages fixedTree = fmap (toList . (fmap logEntryStr)) $ concatMap getLogs fixedTree

getStatuses :: RunNodeWithStatus context s l t -> [(String, s)]
getStatuses = extractValues $ \node -> (runTreeLabel $ runNodeCommon node, runTreeStatus $ runNodeCommon node)

getLogs :: RunNodeWithStatus context s l t -> [l]
getLogs = extractValues $ \node -> runTreeLogs $ runNodeCommon node

statusToResult :: (HasCallStack) => (String, Status) -> Result
statusToResult (label, NotStarted) = error [i|Expected status to be Done but was NotStarted for label '#{label}' (#{callStack})|]
statusToResult (label, Running {}) = error [i|Expected status to be Done but was Running for label '#{label}' (#{callStack})|]
statusToResult (_, Done _ _ _ _ result) = result

mustBe :: (HasCallStack, Eq a, Show a) => a -> a -> IO ()
mustBe x y
  | 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
--   where
--     printFixedRunTree' :: Int -> RunNodeFixed -> IO ()
--     printFixedRunTree' indent (RunTreeGroup {..}) = do
--       putStrLn [i|#{indentation}#{runTreeLabel} [#{statusResult runTreeStatus}]|]
--       forM_ runTreeChildren (printFixedRunTree' (indent + 1))
--       where indentation = L.replicate (indent * 4) ' '
--     printFixedRunTree' indent (RunTreeSingle {..}) = putStrLn [i|#{indentation}#{runTreeLabel} [#{statusResult runTreeStatus}]|]
--       where indentation = L.replicate (indent * 4) ' '