Debian Codegraph @

src/Test/Hspec/Hedgehog.hs

raw
1 {-# LANGUAGE FlexibleContexts #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# LANGUAGE InstanceSigs #-}
4 {-# LANGUAGE OverloadedStrings #-}
5 {-# LANGUAGE PartialTypeSignatures #-}
6 {-# LANGUAGE RankNTypes #-}
7 {-# LANGUAGE RecordWildCards #-}
8 {-# LANGUAGE ScopedTypeVariables #-}
9 {-# LANGUAGE TypeFamilies #-}
10 {-# LANGUAGE TypeOperators #-}
11 {-# LANGUAGE TypeSynonymInstances #-}
12 {-# LANGUAGE ViewPatterns #-}
13
14 {-# OPTIONS_GHC -fno-warn-orphans #-}
15
16 -- | This module allows you to easily integrate the "Hedgehog" library with
17 -- "Test.Hspec" test-suites.
18 --
19 -- To get started, check out the 'hedgehog' function, which lets you embed
20 -- a 'PropertyT' directly.
21 --
22 -- @
23 -- spec :: 'Spec'
24 -- spec =
25 -- 'describe' \"my great test\" '$' do
26 -- 'it' \"generates stuff\" '$'
27 -- 'hedgehog' '$' do
28 -- a <- 'forAll' generator
29 -- a '===' expected
30 -- @
31 --
32 -- Truth be told, the functionality is in the two orphan instances of
33 -- 'Example' for 'PropertyT'. You can directly use code in the @'PropertyT'
34 -- 'IO'@ type. However, because most "Hedgehog" functions are abstract in
35 -- 'MonadTest', you might get errors about ambiguous types. The 'hedgehog'
36 -- function fixes the type to @'PropertyT' 'IO' '()'@, which works out just
37 -- fine.
38 --
39 -- You can use all of @hspec@'s hooks with this, of course.
40 --
41 -- @
42 -- spec :: Spec
43 -- spec = 'before' ('pure' \"Hello!\") '$' do
44 -- 'describe' \"with a string\" '$' do
45 -- 'it' \"gets a string\" '$' \\ str ->
46 -- 'hedgehog' '$' do
47 -- wrongLen <- 'forAll' $ 'Gen.integral' ('Range.linear' 0 3)
48 -- length str '/==' wrongLen
49 -- @
50 --
51 -- The function 'before' will make all the following spec items a function,
52 -- accepting that as a parameter. You should call 'hedgehog' after the
53 -- lambda.
54 --
55 -- If you are morally opposed to the pattern:
56 --
57 -- @
58 -- 'it' \"message\" $ 'hedgehog' $ do
59 -- True '===' False
60 -- @
61 --
62 -- Then you can alternatively force the type some other way. One option is
63 -- to use a no-op function, like this:
64 --
65 -- @
66 -- 'it' \"message\" $ do
67 -- 'pure' () :: 'PropertyT' 'IO' ()
68 -- True '===' False
69 -- @
70 --
71 -- This style has the advantage that parameters via hooks are less
72 -- difficult to get right.
73 --
74 -- @
75 -- 'before' ('pure' \"Hello!\") $ do
76 -- 'it' \"message\" $ \\str -> do
77 -- 'pure' () :: 'PropertyT' 'IO' ()
78 -- wrongLen <- 'forAll' $ 'Gen.integral' ('Range.linear' 0 3)
79 -- 'length' str '/==' wrongLen
80 -- @
81 --
82 -- You don't have to remember to put the 'hedgehog' call after the lambda.
83 module Test.Hspec.Hedgehog
84 ( -- * The Main Function
85 hedgehog
86 -- * Hspec re-exports
87 --
88 -- | 'Test.Hspec.QuickCheck.modifyMaxSize' isn't re-exported, since
89 -- hedgehog has nothing that corresponds to it.
90 , modifyArgs
91 , modifyMaxSuccess
92 , modifyMaxDiscardRatio
93 , modifyMaxShrinks
94 -- * Hedgehog Re-exports
95 , module Hedgehog
96 ) where
97
98 import Control.Monad.IO.Class (liftIO)
99 import Data.Char (isSpace)
100 import Data.Coerce (coerce)
101 import Data.IORef (newIORef, readIORef, writeIORef)
102 import GHC.Stack (withFrozenCallStack)
103 import Hedgehog
104 import Hedgehog.Internal.Config (UseColor(..))
105 import Hedgehog.Internal.Property (DiscardLimit (..), Property (..),
106 PropertyConfig (..),
107 ShrinkLimit (..),
108 TerminationCriteria (..),
109 TestCount (..), TestLimit (..))
110 import Hedgehog.Internal.Report hiding (renderResult)
111 import Hedgehog.Internal.Runner (checkReport)
112 import qualified Hedgehog.Internal.Seed as Seed
113 import Hedgehog.Internal.Source (ColumnNo (..), LineNo (..),
114 Span (..))
115 import System.Random.SplitMix (unseedSMGen)
116 import Test.Hspec
117 import Test.Hspec.Core.Spec as Hspec
118 import Test.Hspec.QuickCheck (modifyArgs, modifyMaxDiscardRatio,
119 modifyMaxShrinks, modifyMaxSuccess)
120 import Test.QuickCheck.Random (QCGen (..))
121 import Test.QuickCheck.Test (Args (..))
122
123 -- | Embed a "Hedgehog" @'PropertyT' 'IO' ()@ in an @hspec@ test.
124 --
125 -- @
126 -- spec :: 'Spec'
127 -- spec =
128 -- 'describe' \"my great test\" '$' do
129 -- 'it' \"generates stuff\" '$'
130 -- 'hedgehog' '$' do
131 -- a <- 'forAll' generator
132 -- a '===' expected
133 -- @
134 --
135 -- This function is only used to fix the type of the @'PropertyT'@ monad
136 -- transformer. The functions in "Hedgehog" are typically abstract in
137 -- a 'MonadTest', and it's easy to get ambiguous type errors if you leave
138 -- this out.
139 --
140 -- @since 0.0.0.0
141 hedgehog :: HasCallStack => PropertyT IO () -> PropertyT IO ()
142 hedgehog = id
143
144 -- | Warning: Orphan instance! This instance is used to embed a "Hedgehog"
145 -- property seamlessly into the @hspec@ framework. See the other instance
146 -- of 'Example' for a function for more details.
147 --
148 -- @since 0.0.0.0
149 instance m ~ IO => Example (PropertyT m ()) where
150 type Arg (PropertyT m ()) = ()
151 evaluateExample e = evaluateExample (\() -> e)
152
153 propertyWithoutCallStack :: PropertyT IO () -> Property
154 propertyWithoutCallStack = withFrozenCallStack property
155
156 -- | Warning: orphan instance! This instance is used to embed a "Hedgehog"
157 -- property seamlessly into the @hspec@ framework.
158 --
159 -- The instance will pick things up from the "Test.Hspec.QuickCheck"
160 -- configuration. For example, if the program is supposed to use
161 -- a predetermined seed, then the same seed will be used for QuickCheck and
162 -- Hedgehog tests.
163 --
164 -- @since 0.0.0.0
165 instance (m ~ IO) => Example (a -> PropertyT m ()) where
166 type Arg (a -> PropertyT m ()) = a
167
168 evaluateExample (fmap propertyWithoutCallStack -> aprop) params aroundAction progressCallback = do
169 ref <- newIORef (Result "" (Pending Nothing Nothing))
170 aroundAction $ \a -> do
171 let size = 0
172 prop = aprop a
173 propConfig = useQuickCheckArgs (propertyConfig prop)
174 qcArgs = paramsQuickCheckArgs params
175
176 maxTests = maxSuccess qcArgs
177 useQuickCheckArgs pc =
178 pc
179 { propertyTerminationCriteria =
180 case propertyTerminationCriteria pc of
181 EarlyTermination x (TestLimit _) ->
182 EarlyTermination x (TestLimit maxTests)
183 NoEarlyTermination x (TestLimit _) ->
184 NoEarlyTermination x (TestLimit maxTests)
185 NoConfidenceTermination (TestLimit _) ->
186 NoConfidenceTermination (TestLimit maxTests)
187 , propertyDiscardLimit =
188 DiscardLimit $ maxDiscardRatio qcArgs * maxTests
189 , propertyShrinkLimit =
190 ShrinkLimit $ maxShrinks qcArgs
191 }
192 testCount report =
193 case reportTests report of
194 TestCount n -> n
195 cb progress = do
196 case reportStatus progress of
197 Running ->
198 progressCallback (testCount progress, maxTests)
199 Shrinking _ ->
200 progressCallback (testCount progress, maxTests)
201
202 seed <- liftIO $ case replay (paramsQuickCheckArgs params) of
203 Nothing -> Seed.random
204 Just (rng, _) -> pure (uncurry Seed (unseedSMGen (coerce rng)))
205 hedgeResult <- checkReport propConfig size seed (propertyTest prop) cb
206
207 let
208 config = defaultConfig {
209 configContext = Context 3
210 , configPrintFailedAtLocation = False
211 , configPrintReproduceMessage = False
212 , configPrintPrefixIcons = DisablePrefixIcons
213 }
214 renderResult color = unlines . unindent . lines . dropWhileEnd isSpace <$> renderResultWith config color (Just "") hedgeResult
215
216 case reportStatus hedgeResult of
217 Failed FailureReport{..} -> do
218 ppresult <- renderResult EnableColor
219 let
220 fromSpan Span{..} =
221 Location
222 { locationFile = spanFile
223 , locationLine = coerce spanStartLine
224 , locationColumn = coerce spanStartColumn
225 }
226 writeIORef ref $ Result "" $ Hspec.Failure (fromSpan <$> failureLocation) $ ColorizedReason ppresult
227 GaveUp -> do
228 ppresult <- renderResult DisableColor
229 writeIORef ref $ Result "" $ Failure Nothing (Reason ppresult)
230 OK -> do
231 ppresult <- renderResult DisableColor
232 writeIORef ref $ Result ppresult Success
233 readIORef ref
234
235 dropWhileEnd :: (a -> Bool) -> [a] -> [a]
236 dropWhileEnd p = reverse . dropWhile p . reverse
237
238 unindent :: [String] -> [String]
239 unindent xs = map (drop indentation) xs
240 where
241 indentation = minimum $ map (length . takeWhile (== ' ')) xs