-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathTrace.hs
71 lines (61 loc) · 2.36 KB
/
Trace.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Provides functions for setting up and capturing logging so that expectations
-- about logging can be asserted in test scenarios.
module Test.Utils.Trace
( withLogging
, withLogging'
, captureLogging
, captureLogging'
, traceSpec
) where
import Prelude
import Cardano.BM.Trace
( traceInTVarIO )
import Control.Monad.IO.Unlift
( MonadIO (..), MonadUnliftIO (..) )
import Control.Tracer
( Tracer, natTracer )
import Data.Text.Class
( ToText (..) )
import Say
( say )
import Test.Hspec
( HasCallStack, Spec, SpecWith, around )
import UnliftIO.Exception
( onException )
import UnliftIO.STM
( newTVarIO, readTVarIO )
-- | Run an action with a logging 'Trace' object, and a function to get all
-- messages that have been traced.
withLogging :: MonadUnliftIO m => ((Tracer m msg, m [msg]) -> m a) -> m a
withLogging = withLogging'
-- | Same as 'withLogging', but with a different Tracer monad.
withLogging' :: forall m mtr msg a. (MonadUnliftIO m, MonadIO mtr) => ((Tracer mtr msg, m [msg]) -> m a) -> m a
withLogging' action = do
tvar <- newTVarIO []
let getMsgs = reverse <$> readTVarIO tvar
action (natTracer liftIO (traceInTVarIO tvar), getMsgs)
-- | Run an action with a 'Trace', returning captured log messages along with
-- the result of the action.
captureLogging :: MonadUnliftIO m => (Tracer m msg -> m a) -> m ([msg], a)
captureLogging = captureLogging'
-- | Same as 'captureLogging', but with a different Tracer monad.
captureLogging' :: forall m mtr msg a. (MonadUnliftIO m, MonadIO mtr) => (Tracer mtr msg -> m a) -> m ([msg], a)
captureLogging' action = withLogging' @m @mtr $ \(tr, getMsgs) -> do
res <- action tr
msgs <- getMsgs
pure (msgs, res)
-- | Provides a Tracer to the spec, which is silent, unless something goes
-- wrong. In that case, it dumps all the traces it has collected to stdout.
traceSpec :: (HasCallStack, ToText msg) => SpecWith (Tracer IO msg) -> Spec
traceSpec = around $ \spec -> withLogging $ \(tr, getMsgs) -> do
let dumpLogs = getMsgs >>= mapM_ (say . toText)
rule s = say ("--- Failed spec logs " <> s <> " ---")
explain a = rule "BEGIN" *> a <* rule "END"
spec tr `onException` explain dumpLogs