Debian Codegraph @

src/Test/Tasty/Ingredients/Rerun.hs

raw symbols SCIP
1 -- |
2 -- Module: Test.Tasty.Ingredients.Rerun
3 -- Copyright: Oliver Charles (c) 2014, Andrew Lelechenko (c) 2019
4 -- Licence: BSD3
5 --
6 -- This ingredient
7 -- for <https://hackage.haskell.org/package/tasty tasty> testing framework
8 -- allows to filter a test tree depending
9 -- on an outcome of the previous run.
10 -- This may be useful in many scenarios,
11 -- especially when a test suite grows large.
12 --
13 -- The behaviour is controlled by command-line options:
14 --
15 -- * @--rerun@ @ @
16 --
17 -- Rerun only tests, which failed during the last run.
18 -- If the last run was successful, execute a full test
19 -- suite afresh. A shortcut for @--rerun-update@
20 -- @--rerun-filter failures,exceptions@
21 -- @--rerun-all-on-success@.
22 --
23 -- * @--rerun-update@ @ @
24 --
25 -- Update the log file to reflect latest test outcomes.
26 --
27 -- * @--rerun-filter@ @CATEGORIES@
28 --
29 -- Read the log file and rerun only tests from a given
30 -- comma-separated list of categories: @failures@,
31 -- @exceptions@, @new@, @successful@. If this option is
32 -- omitted or the log file is missing, rerun everything.
33 --
34 -- * @--rerun-all-on-success@ @ @
35 --
36 -- If according to the log file and @--rerun-filter@ there
37 -- is nothing left to rerun, run all tests. This comes
38 -- especially handy in @stack test --file-watch@ or
39 -- @ghcid@ scenarios.
40 --
41 -- * @--rerun-log-file@ @FILE@
42 --
43 -- Location of the log file (default: @.tasty-rerun-log@).
44 --
45 -- To add it to your test suite just replace
46 -- 'Tasty.defaultMain' with
47 -- 'defaultMainWithRerun' or wrap arguments
48 -- of 'Tasty.defaultMainWithIngredients'
49 -- into 'rerunningTests'.
50
51 module Test.Tasty.Ingredients.Rerun
52 ( defaultMainWithRerun
53 , rerunningTests
54 ) where
55
56 import Prelude (Enum, Bounded, minBound, maxBound, error, (+))
57
58 import Control.Applicative (Const(..), (<$>), pure, (<$))
59 import Control.Arrow ((>>>))
60 import Control.Monad (when, return, fmap, mapM, (>>=))
61 import Control.Monad.Trans.Class (lift)
62 import Data.Bool (Bool (..), otherwise, not, (&&))
63 import Data.Char (isSpace, toLower)
64 import Data.Eq (Eq)
65 import Data.Foldable (asum)
66 import Data.Function ((.), ($), flip, const)
67 import Data.Int (Int)
68 import Data.List (intercalate, lookup, map, (++), reverse, dropWhile)
69 import Data.List.Split (endBy)
70 import Data.Maybe (fromMaybe, Maybe(..), maybe)
71 import Data.Monoid (Any(..), Monoid(..))
72 import Data.Ord (Ord)
73 import Data.Proxy (Proxy(..))
74 import Data.String (String)
75 import System.FilePath ((<.>), takeBaseName)
76 import System.IO (FilePath, IO, readFile', writeFile)
77 import System.IO.Error (catchIOError, isDoesNotExistError, ioError)
78 import System.IO.Unsafe (unsafePerformIO)
79 import Text.Read (Read, read)
80 import Text.Show (Show, show)
81
82 import qualified Control.Concurrent.STM as STM
83 import qualified Control.Monad.State as State
84 import qualified Data.Functor.Compose as Functor
85 import qualified Data.IntMap as IntMap
86 import qualified Data.Map.Strict as Map
87 import qualified Data.Set as Set
88 import qualified Options.Applicative as OptParse
89 import qualified System.Environment
90 import qualified Test.Tasty.Options as Tasty
91 import qualified Test.Tasty.Runners as Tasty
92
93 --------------------------------------------------------------------------------
94 data RerunLogFile
95 = DefaultRerunLogFile
96 | CustomRerunLogFile FilePath
97
98 instance Tasty.IsOption RerunLogFile where
99 optionName = return "rerun-log-file"
100 optionHelp = return
101 ( "Location of the log file (default: " ++
102 show (unsafePerformIO getDefaultLogfileName) ++ ")"
103 )
104 defaultValue = DefaultRerunLogFile
105 parseValue = Just . CustomRerunLogFile
106 optionCLParser = Tasty.mkOptionCLParser (OptParse.metavar "FILE")
107
108 --------------------------------------------------------------------------------
109 newtype UpdateLog = UpdateLog Bool
110
111 instance Tasty.IsOption UpdateLog where
112 optionName = return "rerun-update"
113 optionHelp = return "Update the log file to reflect latest test outcomes"
114 defaultValue = UpdateLog False
115 parseValue = fmap UpdateLog . Tasty.safeReadBool
116 optionCLParser = Tasty.mkFlagCLParser mempty (UpdateLog True)
117
118 --------------------------------------------------------------------------------
119 data Filter = Failures | Exceptions | New | Successful
120 deriving (Eq, Ord, Enum, Bounded, Show)
121
122 parseFilter :: String -> Maybe Filter
123 parseFilter s = lookup s (map (\x -> (map toLower (show x), x)) everything)
124
125 --------------------------------------------------------------------------------
126 everything :: [Filter]
127 everything = [minBound..maxBound]
128
129 --------------------------------------------------------------------------------
130 newtype FilterOption = FilterOption (Set.Set Filter)
131
132 instance Tasty.IsOption FilterOption where
133 optionName = return "rerun-filter"
134 optionHelp = return
135 $ "Read the log file and rerun only tests from a given comma-separated list of categories: "
136 ++ map toLower (intercalate ", " (map show everything))
137 ++ ". If this option is omitted or the log file is missing, rerun everything."
138 defaultValue = FilterOption (Set.fromList everything)
139 parseValue =
140 fmap (FilterOption . Set.fromList) . mapM (parseFilter . trim) . endBy ","
141 where trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
142 optionCLParser = Tasty.mkOptionCLParser (OptParse.metavar "CATEGORIES")
143
144 --------------------------------------------------------------------------------
145 newtype AllOnSuccess = AllOnSuccess Bool
146
147 instance Tasty.IsOption AllOnSuccess where
148 optionName = return "rerun-all-on-success"
149 optionHelp = return "If according to the log file and --rerun-filter there is nothing left to rerun, run all tests. This comes especially handy in `stack test --file-watch` or `ghcid` scenarios."
150 defaultValue = AllOnSuccess False
151 parseValue = fmap AllOnSuccess . Tasty.safeReadBool
152 optionCLParser = Tasty.mkFlagCLParser mempty (AllOnSuccess True)
153
154 --------------------------------------------------------------------------------
155 newtype Rerun = Rerun { unRerun :: Bool }
156
157 instance Tasty.IsOption Rerun where
158 optionName = return "rerun"
159 optionHelp = return "Rerun only tests, which failed during the last run. If the last run was successful, execute a full test suite afresh. A shortcut for --rerun-update --rerun-filter failures,exceptions --rerun-all-on-success"
160 defaultValue = Rerun False
161 parseValue = fmap Rerun . Tasty.safeReadBool
162 optionCLParser = Tasty.mkFlagCLParser mempty (Rerun True)
163
164 rerunMeaning :: (UpdateLog, AllOnSuccess, FilterOption)
165 rerunMeaning = (UpdateLog True, AllOnSuccess True, FilterOption (Set.fromList [Failures, Exceptions]))
166
167 --------------------------------------------------------------------------------
168 data TestResult = Completed Bool | ThrewException
169 deriving (Read, Show)
170
171
172 --------------------------------------------------------------------------------
173
174 -- | Drop-in replacement for 'Tasty.defaultMain'.
175 --
176 -- > import Test.Tasty
177 -- > import Test.Tasty.Ingredients.Rerun
178 -- >
179 -- > main :: IO ()
180 -- > main = defaultMainWithRerun tests
181 -- >
182 -- > tests :: TestTree
183 -- > tests = undefined
184 defaultMainWithRerun :: Tasty.TestTree -> IO ()
185 defaultMainWithRerun =
186 Tasty.defaultMainWithIngredients
187 [ rerunningTests [ Tasty.listingTests, Tasty.consoleTestReporter ] ]
188
189 -- | Ingredient transformer, to use with
190 -- 'Tasty.defaultMainWithIngredients'.
191 --
192 -- > import Test.Tasty
193 -- > import Test.Tasty.Runners
194 -- > import Test.Tasty.Ingredients.Rerun
195 -- >
196 -- > main :: IO ()
197 -- > main =
198 -- > defaultMainWithIngredients
199 -- > [ rerunningTests [ listingTests, consoleTestReporter ] ]
200 -- > tests
201 -- >
202 -- > tests :: TestTree
203 -- > tests = undefined
204 rerunningTests :: [Tasty.Ingredient] -> Tasty.Ingredient
205 rerunningTests ingredients =
206 Tasty.TestManager (rerunOptions ++ Tasty.ingredientsOptions ingredients) $
207 \options testTree -> Just $ do
208 stateFile <- case Tasty.lookupOption options of
209 DefaultRerunLogFile -> getDefaultLogfileName
210 CustomRerunLogFile stateFile -> return stateFile
211
212 let (UpdateLog updateLog, AllOnSuccess allOnSuccess, FilterOption filter)
213 | unRerun (Tasty.lookupOption options) = rerunMeaning
214 | otherwise = (Tasty.lookupOption options, Tasty.lookupOption options, Tasty.lookupOption options)
215
216 let nonEmptyFold = Tasty.trivialFold { Tasty.foldSingle = \_ _ _ -> Any True }
217 nullTestTree = not . getAny . Tasty.foldTestTree nonEmptyFold options
218 recoverFromEmpty t = if allOnSuccess && nullTestTree t then testTree else t
219
220 filteredTestTree <- maybe testTree (recoverFromEmpty . filterTestTree testTree filter)
221 <$> tryLoadStateFrom stateFile
222
223 let tryAndRun (Tasty.TestReporter _ f) = do
224 runner <- f options filteredTestTree
225 return $ do
226 (statusMap, outcome) <-
227 Tasty.launchTestTree options filteredTestTree $ \sMap ->
228 do f' <- runner sMap
229 return (fmap (\a -> (sMap, a)) . f')
230
231 let getTestResults =
232 fmap getConst $
233 flip State.evalStateT 0 $
234 Functor.getCompose $
235 Tasty.getTraversal $
236 Tasty.foldTestTree (observeResults statusMap)
237 options filteredTestTree
238
239 when updateLog (saveStateTo stateFile getTestResults)
240 return outcome
241
242 tryAndRun (Tasty.TestManager _ f) =
243 f options filteredTestTree
244
245 case asum (map tryAndRun ingredients) of
246 -- No Ingredients chose to run the tests, we should really return
247 -- Nothing, but we've already committed to run by the act of
248 -- filtering the TestTree.
249 Nothing -> return False
250 -- Otherwise, an Ingredient did choose to run the tests, so we
251 -- simply run the above constructed IO action.
252 Just e -> e
253 where
254 rerunOptions = [ Tasty.Option (Proxy :: Proxy Rerun)
255 , Tasty.Option (Proxy :: Proxy UpdateLog)
256 , Tasty.Option (Proxy :: Proxy FilterOption)
257 , Tasty.Option (Proxy :: Proxy AllOnSuccess)
258 , Tasty.Option (Proxy :: Proxy RerunLogFile)
259 ]
260
261 ------------------------------------------------------------------------------
262 filterTestTree :: Tasty.TestTree -> Set.Set Filter -> Map.Map [String] TestResult -> Tasty.TestTree
263 filterTestTree testTree filter lastRecord =
264 let go prefix (Tasty.SingleTest name t) =
265 let requiredFilter = case Map.lookup (prefix ++ [name]) lastRecord of
266 Just (Completed False) -> Failures
267 Just ThrewException -> Exceptions
268 Just (Completed True) -> Successful
269 Nothing -> New
270 in if (requiredFilter `Set.member` filter)
271 then Tasty.SingleTest name t
272 else Tasty.TestGroup "" []
273
274 go prefix (Tasty.TestGroup name tests) =
275 Tasty.TestGroup name (go (prefix ++ [name]) <$> tests)
276
277 go prefix (Tasty.PlusTestOptions f t) =
278 Tasty.PlusTestOptions f (go prefix t)
279
280 go prefix (Tasty.WithResource rSpec k) =
281 Tasty.WithResource rSpec (go prefix <$> k)
282
283 go prefix (Tasty.AskOptions k) =
284 Tasty.AskOptions (go prefix <$> k)
285
286 go prefix (Tasty.After a b c) =
287 Tasty.After a b (go prefix c)
288
289 in go [] testTree
290
291 tryLoadStateFrom :: FilePath -> IO (Maybe (Map.Map [String] TestResult))
292 tryLoadStateFrom filePath = do
293 fileContents <- (Just <$> readFile' filePath)
294 `catchIOError` (\e -> if isDoesNotExistError e
295 then return Nothing
296 else ioError e)
297 return (read <$> fileContents)
298
299 ------------------------------------------------------------------------------
300 saveStateTo :: FilePath -> IO (Map.Map [String] TestResult) -> IO ()
301 saveStateTo filePath getTestResults =
302 getTestResults >>= (show >>> writeFile filePath)
303
304 ------------------------------------------------------------------------------
305 observeResults
306 :: IntMap.IntMap (STM.TVar Tasty.Status)
307 -> Tasty.TreeFold (Tasty.Traversal (Functor.Compose (State.StateT Int IO) (Const (Map.Map [String] TestResult))))
308 observeResults statusMap =
309 let foldSingle _ name _ = Tasty.Traversal $ Functor.Compose $ do
310 i <- State.get
311
312 status <- lift $ STM.atomically $ do
313 status <- lookupStatus i
314 case status of
315 Tasty.Done result -> return $
316 case Tasty.resultOutcome result of
317 Tasty.Failure (Tasty.TestThrewException _) -> ThrewException
318 _ -> Completed (Tasty.resultSuccessful result)
319
320 _ -> STM.retry
321
322 Const (Map.singleton [name] status) <$ State.modify (+ 1)
323
324 foldGroup name children = Tasty.Traversal $ Functor.Compose $ do
325 Const soFar <- Functor.getCompose $ Tasty.getTraversal children
326 pure $ Const (Map.mapKeys (name :) soFar)
327
328 in Tasty.trivialFold
329 { Tasty.foldSingle = foldSingle
330 , Tasty.foldGroup = const (\name -> foldGroup name . mconcat)
331 }
332
333 where
334 lookupStatus i = STM.readTVar $
335 fromMaybe (error "Attempted to lookup test by index outside bounds")
336 (IntMap.lookup i statusMap)
337
338 -- | Get the default log file name.
339 -- Whether a package-wide or a per-component log file name is returned depends
340 -- on the possibility to determine the path to the test executable reliably; See
341 -- 'System.Environment.executablePath'.
342 getDefaultLogfileName :: IO FilePath
343 getDefaultLogfileName =
344 logfileName <$>
345 fromMaybe (return Nothing) System.Environment.executablePath
346
347 -- | Returns the default log file name.
348 -- The argument passed should be the file path of the test executable, if that
349 -- path is available. If @Nothing@ is passed, then a package-wide log file name
350 -- is returned, which may lead to problems; See
351 -- https://github.com/ocharles/tasty-rerun/issues/22 .
352 logfileName
353 :: Maybe FilePath -- ^ The file path of the test executable.
354 -> String -- ^ The Tasty Rerun log file name.
355 logfileName Nothing = ".tasty-rerun-log"
356 logfileName (Just executablePath) =
357 logfileName Nothing <.> takeBaseName executablePath