-
Notifications
You must be signed in to change notification settings - Fork 107
/
Property.hs
1309 lines (1137 loc) · 35.6 KB
/
Property.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# OPTIONS_HADDOCK not-home #-}
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-} -- Distributive
module Hedgehog.Internal.Property (
-- * Property
Property(..)
, PropertyT(..)
, PropertyName(..)
, PropertyConfig(..)
, TestLimit(..)
, TestCount(..)
, DiscardLimit(..)
, DiscardCount(..)
, ShrinkLimit(..)
, ShrinkCount(..)
, ShrinkRetries(..)
, withTests
, withDiscards
, withShrinks
, withRetries
, property
, test
, forAll
, forAllT
, forAllWith
, forAllWithT
, defaultMinTests
, discard
-- * Group
, Group(..)
, GroupName(..)
, PropertyCount(..)
-- * TestT
, MonadTest(..)
, Test
, TestT(..)
, Log(..)
, Journal(..)
, Failure(..)
, Diff(..)
, annotate
, annotateShow
, footnote
, footnoteShow
, failure
, success
, assert
, diff
, (===)
, (/==)
, eval
, evalNF
, evalM
, evalIO
, evalEither
, evalEitherM
, evalExceptT
, evalMaybe
, evalMaybeM
-- * Coverage
, Coverage(..)
, Label(..)
, LabelName(..)
, cover
, classify
, label
, collect
, coverPercentage
, labelCovered
, coverageSuccess
, coverageFailures
, journalCoverage
, Cover(..)
, CoverCount(..)
, CoverPercentage(..)
, toCoverCount
-- * Confidence
, Confidence(..)
, TerminationCriteria(..)
, confidenceSuccess
, confidenceFailure
, withConfidence
, verifiedTermination
, defaultConfidence
-- * Internal
-- $internal
, defaultConfig
, mapConfig
, failDiff
, failException
, failWith
, writeLog
, mkTest
, mkTestT
, runTest
, runTestT
, wilsonBounds
) where
import Control.Applicative (Alternative(..))
import Control.DeepSeq (NFData, rnf)
import Control.Monad (MonadPlus(..), (<=<))
import Control.Monad.Base (MonadBase(..))
import Control.Monad.Catch (MonadThrow(..), MonadCatch(..))
import Control.Monad.Catch (SomeException(..), displayException)
import Control.Monad.Error.Class (MonadError(..))
import qualified Control.Monad.Fail as Fail
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Morph (MFunctor(..))
import Control.Monad.Primitive (PrimMonad(..))
import Control.Monad.Reader.Class (MonadReader(..))
import Control.Monad.State.Class (MonadState(..))
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Control (ComposeSt, defaultLiftBaseWith, defaultRestoreM)
import Control.Monad.Trans.Control (MonadBaseControl(..), MonadTransControl(..))
import Control.Monad.Trans.Except (ExceptT(..), runExceptT)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Trans.Resource (MonadResource(..))
import Control.Monad.Trans.Resource (ResourceT)
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import qualified Data.Char as Char
import Data.Functor (($>))
import Data.Functor.Identity (Identity(..))
import Data.Int (Int64)
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Number.Erf (invnormcdf)
import qualified Data.List as List
import Data.String (IsString)
import Data.Ratio ((%))
import Data.Typeable (typeOf)
import Hedgehog.Internal.Distributive
import Hedgehog.Internal.Exception
import Hedgehog.Internal.Gen (Gen, GenT)
import qualified Hedgehog.Internal.Gen as Gen
import Hedgehog.Internal.Prelude
import Hedgehog.Internal.Show
import Hedgehog.Internal.Source
import Language.Haskell.TH.Syntax (Lift)
------------------------------------------------------------------------
-- | A property test, along with some configurable limits like how many times
-- to run the test.
--
data Property =
Property {
propertyConfig :: !PropertyConfig
, propertyTest :: PropertyT IO ()
}
-- | The property monad transformer allows both the generation of test inputs
-- and the assertion of expectations.
--
newtype PropertyT m a =
PropertyT {
unPropertyT :: TestT (GenT m) a
} deriving (
Functor
, Applicative
, Monad
, MonadIO
, MonadBase b
, MonadThrow
, MonadCatch
, MonadReader r
, MonadState s
, MonadError e
)
-- NOTE: Move this to the deriving list above when we drop 7.10
deriving instance MonadResource m => MonadResource (PropertyT m)
-- NOTE: Move this to the deriving list above when we drop 8.0
#if __GLASGOW_HASKELL__ >= 802
deriving instance MonadBaseControl b m => MonadBaseControl b (PropertyT m)
#else
instance MonadBaseControl b m => MonadBaseControl b (PropertyT m) where
type StM (PropertyT m) a = StM (TestT (GenT m)) a
liftBaseWith f = PropertyT $ liftBaseWith $ \rib -> f (rib . unPropertyT)
restoreM = PropertyT . restoreM
#endif
-- | A test monad allows the assertion of expectations.
--
type Test =
TestT Identity
-- | A test monad transformer allows the assertion of expectations.
--
newtype TestT m a =
TestT {
unTest :: ExceptT Failure (Lazy.WriterT Journal m) a
} deriving (
Functor
, Applicative
, MonadIO
, MonadBase b
, MonadThrow
, MonadCatch
, MonadReader r
, MonadState s
)
-- | The name of a property.
--
-- Should be constructed using `OverloadedStrings`:
--
-- @
-- "apples" :: PropertyName
-- @
--
newtype PropertyName =
PropertyName {
unPropertyName :: String
} deriving (Eq, Ord, Show, IsString, Semigroup, Lift)
-- | The acceptable occurrence of false positives
--
-- Example, @Confidence 10^9@ would mean that you'd accept a false positive
-- for 1 in 10^9 tests.
newtype Confidence =
Confidence {
unConfidence :: Int64
} deriving (Eq, Ord, Show, Num, Lift)
-- | Configuration for a property test.
--
data PropertyConfig =
PropertyConfig {
propertyDiscardLimit :: !DiscardLimit
, propertyShrinkLimit :: !ShrinkLimit
, propertyShrinkRetries :: !ShrinkRetries
, propertyTerminationCriteria :: !TerminationCriteria
} deriving (Eq, Ord, Show, Lift)
-- | The number of successful tests that need to be run before a property test
-- is considered successful.
--
-- Can be constructed using numeric literals:
--
-- @
-- 200 :: TestLimit
-- @
--
newtype TestLimit =
TestLimit Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral, Lift)
-- | The number of tests a property ran successfully.
--
newtype TestCount =
TestCount Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral)
-- | The number of tests a property had to discard.
--
newtype DiscardCount =
DiscardCount Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral)
-- | The number of discards to allow before giving up.
--
-- Can be constructed using numeric literals:
--
-- @
-- 10000 :: DiscardLimit
-- @
--
--
newtype DiscardLimit =
DiscardLimit Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral, Lift)
-- | The number of shrinks to try before giving up on shrinking.
--
-- Can be constructed using numeric literals:
--
-- @
-- 1000 :: ShrinkLimit
-- @
--
newtype ShrinkLimit =
ShrinkLimit Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral, Lift)
-- | The numbers of times a property was able to shrink after a failing test.
--
newtype ShrinkCount =
ShrinkCount Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral)
-- | The number of times to re-run a test during shrinking. This is useful if
-- you are testing something which fails non-deterministically and you want to
-- increase the change of getting a good shrink.
--
-- If you are doing parallel state machine testing, you should probably set
-- shrink retries to something like @10@. This will mean that during
-- shrinking, a parallel test case requires 10 successful runs before it is
-- passes and we try a different shrink.
--
-- Can be constructed using numeric literals:
--
-- @
-- 0 :: ShrinkRetries
-- @
--
newtype ShrinkRetries =
ShrinkRetries Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral, Lift)
-- | A named collection of property tests.
--
data Group =
Group {
groupName :: !GroupName
, groupProperties :: ![(PropertyName, Property)]
}
-- | The name of a group of properties.
--
-- Should be constructed using `OverloadedStrings`:
--
-- @
-- "fruit" :: GroupName
-- @
--
newtype GroupName =
GroupName {
unGroupName :: String
} deriving (Eq, Ord, Show, IsString, Semigroup, Lift)
-- | The number of properties in a group.
--
newtype PropertyCount =
PropertyCount Int
deriving (Eq, Ord, Show, Num, Enum, Real, Integral)
data TerminationCriteria =
EarlyTermination Confidence TestLimit
| NoEarlyTermination Confidence TestLimit
| NoConfidenceTermination TestLimit
deriving (Eq, Ord, Show, Lift)
--
-- FIXME This whole Log/Failure thing could be a lot more structured to allow
-- FIXME for richer user controlled error messages, think Doc. Ideally we'd
-- FIXME allow user's to crete their own diffs anywhere.
--
-- | Log messages which are recorded during a test run.
--
data Log =
Annotation (Maybe Span) String
| Footnote String
| Label (Label Cover)
deriving (Eq, Show)
-- | A record containing the details of a test run.
newtype Journal =
Journal {
journalLogs :: [Log]
} deriving (Eq, Show, Semigroup, Monoid)
-- | Details on where and why a test failed.
--
data Failure =
Failure (Maybe Span) String (Maybe Diff)
deriving (Eq, Show)
-- | The difference between some expected and actual value.
--
data Diff =
Diff {
diffPrefix :: String
, diffRemoved :: String
, diffInfix :: String
, diffAdded :: String
, diffSuffix :: String
, diffValue :: ValueDiff
} deriving (Eq, Show)
-- | Whether a test is covered by a classifier, and therefore belongs to a
-- 'Class'.
--
data Cover =
NoCover
| Cover
deriving (Eq, Ord, Show)
-- | The total number of tests which are covered by a classifier.
--
-- Can be constructed using numeric literals:
--
-- @
-- 30 :: CoverCount
-- @
--
newtype CoverCount =
CoverCount {
unCoverCount :: Int
} deriving (Eq, Ord, Show, Num)
-- | The relative number of tests which are covered by a classifier.
--
-- Can be constructed using numeric literals:
--
-- @
-- 30 :: CoverPercentage
-- @
--
newtype CoverPercentage =
CoverPercentage {
unCoverPercentage :: Double
} deriving (Eq, Ord, Show, Num, Fractional)
-- | The name of a classifier.
--
-- Should be constructed using `OverloadedStrings`:
--
-- @
-- "apples" :: LabelName
-- @
--
newtype LabelName =
LabelName {
unLabelName :: String
} deriving (Eq, Monoid, Ord, Semigroup, Show, IsString)
-- | The extent to which a test is covered by a classifier.
--
-- /When a classifier's coverage does not exceed the required minimum, the/
-- /test will be failed./
--
data Label a =
MkLabel {
labelName :: !LabelName
, labelLocation :: !(Maybe Span)
, labelMinimum :: !CoverPercentage
, labelAnnotation :: !a
} deriving (Eq, Show, Functor, Foldable, Traversable)
-- | The extent to which all classifiers cover a test.
--
-- /When a given classification's coverage does not exceed the required/
-- /minimum, the test will be failed./
--
newtype Coverage a =
Coverage {
coverageLabels :: Map LabelName (Label a)
} deriving (Eq, Show, Functor, Foldable, Traversable)
------------------------------------------------------------------------
-- TestT
instance Monad m => Monad (TestT m) where
return =
pure
(>>=) m k =
TestT $
unTest m >>=
unTest . k
instance Monad m => MonadFail (TestT m) where
fail err =
TestT . ExceptT . pure . Left $ Failure Nothing err Nothing
instance MonadTrans TestT where
lift =
TestT . lift . lift
instance MFunctor TestT where
hoist f =
TestT . hoist (hoist f) . unTest
instance MonadTransDistributive TestT where
type Transformer t TestT m = (
Transformer t (Lazy.WriterT Journal) m
, Transformer t (ExceptT Failure) (Lazy.WriterT Journal m)
)
distributeT =
hoist TestT .
distributeT .
hoist distributeT .
unTest
instance PrimMonad m => PrimMonad (TestT m) where
type PrimState (TestT m) =
PrimState m
primitive =
lift . primitive
-- FIXME instance MonadWriter w m => MonadWriter w (TestT m)
instance MonadError e m => MonadError e (TestT m) where
throwError =
lift . throwError
catchError m onErr =
TestT . ExceptT $
(runExceptT $ unTest m) `catchError`
(runExceptT . unTest . onErr)
instance MonadResource m => MonadResource (TestT m) where
liftResourceT =
lift . liftResourceT
instance MonadTransControl TestT where
type StT TestT a =
(Either Failure a, Journal)
liftWith f =
mkTestT . fmap (, mempty) . fmap Right $ f $ runTestT
restoreT =
mkTestT
instance MonadBaseControl b m => MonadBaseControl b (TestT m) where
type StM (TestT m) a =
ComposeSt TestT m a
liftBaseWith =
defaultLiftBaseWith
restoreM =
defaultRestoreM
class Monad m => MonadTest m where
liftTest :: Test a -> m a
instance Monad m => MonadTest (TestT m) where
liftTest =
hoist (pure . runIdentity)
instance MonadTest m => MonadTest (IdentityT m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (MaybeT m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (ExceptT x m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (ReaderT r m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (Lazy.StateT s m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (Strict.StateT s m) where
liftTest =
lift . liftTest
instance (MonadTest m, Monoid w) => MonadTest (Lazy.WriterT w m) where
liftTest =
lift . liftTest
instance (MonadTest m, Monoid w) => MonadTest (Strict.WriterT w m) where
liftTest =
lift . liftTest
instance (MonadTest m, Monoid w) => MonadTest (Lazy.RWST r w s m) where
liftTest =
lift . liftTest
instance (MonadTest m, Monoid w) => MonadTest (Strict.RWST r w s m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (ContT r m) where
liftTest =
lift . liftTest
instance MonadTest m => MonadTest (ResourceT m) where
liftTest =
lift . liftTest
mkTestT :: m (Either Failure a, Journal) -> TestT m a
mkTestT =
TestT . ExceptT . Lazy.WriterT
mkTest :: (Either Failure a, Journal) -> Test a
mkTest =
mkTestT . Identity
runTestT :: TestT m a -> m (Either Failure a, Journal)
runTestT =
Lazy.runWriterT . runExceptT . unTest
runTest :: Test a -> (Either Failure a, Journal)
runTest =
runIdentity . runTestT
-- | Log some information which might be relevant to a potential test failure.
--
writeLog :: MonadTest m => Log -> m ()
writeLog x =
liftTest $ mkTest (pure (), (Journal [x]))
-- | Fail the test with an error message, useful for building other failure
-- combinators.
--
failWith :: (MonadTest m, HasCallStack) => Maybe Diff -> String -> m a
failWith mdiff msg =
liftTest $ mkTest (Left $ Failure (getCaller callStack) msg mdiff, mempty)
-- | Annotates the source code with a message that might be useful for
-- debugging a test failure.
--
annotate :: (MonadTest m, HasCallStack) => String -> m ()
annotate x = do
writeLog $ Annotation (getCaller callStack) x
-- | Annotates the source code with a value that might be useful for
-- debugging a test failure.
--
annotateShow :: (MonadTest m, Show a, HasCallStack) => a -> m ()
annotateShow x = do
withFrozenCallStack $ annotate (showPretty x)
-- | Logs a message to be displayed as additional information in the footer of
-- the failure report.
--
footnote :: MonadTest m => String -> m ()
footnote =
writeLog . Footnote
-- | Logs a value to be displayed as additional information in the footer of
-- the failure report.
--
footnoteShow :: (MonadTest m, Show a) => a -> m ()
footnoteShow =
writeLog . Footnote . showPretty
-- | Fails with an error that shows the difference between two values.
failDiff :: (MonadTest m, Show a, Show b, HasCallStack) => a -> b -> m ()
failDiff x y =
case valueDiff <$> mkValue x <*> mkValue y of
Nothing ->
withFrozenCallStack $
failWith Nothing $
unlines $ [
"Failed"
, "━━ lhs ━━"
, showPretty x
, "━━ rhs ━━"
, showPretty y
]
Just vdiff@(ValueSame _) ->
withFrozenCallStack $
failWith (Just $
Diff "━━━ Failed (" "" "no differences" "" ") ━━━" vdiff) ""
Just vdiff ->
withFrozenCallStack $
failWith (Just $
Diff "━━━ Failed (" "- lhs" ") (" "+ rhs" ") ━━━" vdiff) ""
-- | Fails with an error which renders the type of an exception and its error
-- message.
--
failException :: (MonadTest m, HasCallStack) => SomeException -> m a
failException x =
withFrozenCallStack $
failExceptionWith [] x
-- | Fails with an error which renders the given messages, the type of an exception,
-- and its error message.
--
failExceptionWith :: (MonadTest m, HasCallStack) => [String] -> SomeException -> m a
failExceptionWith messages (SomeException x) =
withFrozenCallStack
failWith Nothing $ unlines $ messages <> [
"━━━ Exception (" ++ show (typeOf x) ++ ") ━━━"
, List.dropWhileEnd Char.isSpace (displayException x)
]
-- | Causes a test to fail.
--
failure :: (MonadTest m, HasCallStack) => m a
failure =
withFrozenCallStack $ failWith Nothing ""
-- | Another name for @pure ()@.
--
success :: MonadTest m => m ()
success =
pure ()
-- | Fails the test if the condition provided is 'False'.
--
assert :: (MonadTest m, HasCallStack) => Bool -> m ()
assert b = do
ok <- withFrozenCallStack $ eval b
if ok then
success
else
withFrozenCallStack failure
-- | Fails the test and shows a git-like diff if the comparison operation
-- evaluates to 'False' when applied to its arguments.
--
-- The comparison function is the second argument, which may be
-- counter-intuitive to Haskell programmers. However, it allows operators to
-- be written infix for easy reading:
--
-- @
-- diff y (<) 87
-- diff x (<=) 'r'
-- @
--
-- This function behaves like the unix @diff@ tool, which gives a 0 exit
-- code if the compared files are identical, or a 1 exit code code
-- otherwise. Like unix @diff@, if the arguments fail the comparison, a
-- /diff is shown.
--
diff :: (MonadTest m, Show a, Show b, HasCallStack) => a -> (a -> b -> Bool) -> b -> m ()
diff x op y = do
ok <- withFrozenCallStack $ eval (x `op` y)
if ok then
success
else
withFrozenCallStack $ failDiff x y
infix 4 ===
-- | Fails the test if the two arguments provided are not equal.
--
(===) :: (MonadTest m, Eq a, Show a, HasCallStack) => a -> a -> m ()
(===) x y =
withFrozenCallStack $
diff x (==) y
infix 4 /==
-- | Fails the test if the two arguments provided are equal.
--
(/==) :: (MonadTest m, Eq a, Show a, HasCallStack) => a -> a -> m ()
(/==) x y =
withFrozenCallStack $
diff x (/=) y
-- | Fails the test if the value throws an exception when evaluated to weak
-- head normal form (WHNF).
--
eval :: (MonadTest m, HasCallStack) => a -> m a
eval x =
either (withFrozenCallStack failException) pure (tryEvaluate x)
-- | Fails the test if the value throws an exception when evaluated to
-- normal form (NF).
--
evalNF :: (MonadTest m, NFData a, HasCallStack) => a -> m a
evalNF x =
let
messages =
["━━━ Value could not be evaluated to normal form ━━━"]
in
either (withFrozenCallStack (failExceptionWith messages)) pure (tryEvaluate (rnf x)) $> x
-- | Fails the test if the action throws an exception.
--
-- /The benefit of using this over simply letting the exception bubble up is/
-- /that the location of the closest 'evalM' will be shown in the output./
--
evalM :: (MonadTest m, MonadCatch m, HasCallStack) => m a -> m a
evalM m =
either (withFrozenCallStack failException) pure =<< tryAll m
-- | Fails the test if the 'IO' action throws an exception.
--
-- /The benefit of using this over 'liftIO' is that the location of the/
-- /exception will be shown in the output./
--
evalIO :: (MonadTest m, MonadIO m, HasCallStack) => IO a -> m a
evalIO m =
either (withFrozenCallStack failException) pure =<< liftIO (tryAll m)
-- | Fails the test if the 'Either' is 'Left', otherwise returns the value in
-- the 'Right'.
--
evalEither :: (MonadTest m, Show x, HasCallStack) => Either x a -> m a
evalEither = \case
Left x ->
withFrozenCallStack $ failWith Nothing $ showPretty x
Right x ->
pure x
-- | Fails the test if the action throws an exception, or if the
-- 'Either' is 'Left', otherwise returns the value in the 'Right'.
--
evalEitherM :: (MonadTest m, Show x, MonadCatch m, HasCallStack) => m (Either x a) -> m a
evalEitherM =
evalEither <=< evalM
-- | Fails the test if the 'ExceptT' is 'Left', otherwise returns the value in
-- the 'Right'.
--
evalExceptT :: (MonadTest m, Show x, HasCallStack) => ExceptT x m a -> m a
evalExceptT m =
withFrozenCallStack evalEither =<< runExceptT m
-- | Fails the test if the 'Maybe' is 'Nothing', otherwise returns the value in
-- the 'Just'.
--
evalMaybe :: (MonadTest m, Show a, HasCallStack) => Maybe a -> m a
evalMaybe = \case
Nothing ->
withFrozenCallStack $ failWith Nothing "the value was Nothing"
Just x ->
pure x
-- | Fails the test if the action throws an exception, or if the
-- 'Maybe' is 'Nothing', otherwise returns the value in the 'Just'.
--
evalMaybeM :: (MonadTest m, Show a, MonadCatch m, HasCallStack) => m (Maybe a) -> m a
evalMaybeM =
evalMaybe <=< evalM
------------------------------------------------------------------------
-- PropertyT
instance MonadTrans PropertyT where
lift =
PropertyT . lift . lift
instance Monad m => MonadFail (PropertyT m) where
fail err =
PropertyT (Fail.fail err)
instance MFunctor PropertyT where
hoist f =
PropertyT . hoist (hoist f) . unPropertyT
instance MonadTransDistributive PropertyT where
type Transformer t PropertyT m = (
Transformer t GenT m
, Transformer t TestT (GenT m)
)
distributeT =
hoist PropertyT .
distributeT .
hoist distributeT .
unPropertyT
instance PrimMonad m => PrimMonad (PropertyT m) where
type PrimState (PropertyT m) =
PrimState m
primitive =
lift . primitive
---- FIXME instance MonadWriter w m => MonadWriter w (PropertyT m)
instance Monad m => MonadTest (PropertyT m) where
liftTest =
PropertyT . hoist (pure . runIdentity)
instance MonadPlus m => MonadPlus (PropertyT m) where
mzero =
discard
mplus (PropertyT x) (PropertyT y) =
PropertyT . mkTestT $
mplus (runTestT x) (runTestT y)
instance MonadPlus m => Alternative (PropertyT m) where
empty =
mzero
(<|>) =
mplus
-- | Generates a random input for the test by running the provided generator.
--
-- /This is a the same as 'forAllT' but allows the user to provide a custom/
-- /rendering function. This is useful for values which don't have a/
-- /'Show' instance./
--
forAllWithT :: (Monad m, HasCallStack) => (a -> String) -> GenT m a -> PropertyT m a
forAllWithT render gen = do
x <- PropertyT $ lift gen
withFrozenCallStack $ annotate (render x)
return x
-- | Generates a random input for the test by running the provided generator.
--
-- /This is a the same as 'forAll' but allows the user to provide a custom/
-- /rendering function. This is useful for values which don't have a/
-- /'Show' instance./
--
forAllWith :: (Monad m, HasCallStack) => (a -> String) -> Gen a -> PropertyT m a
forAllWith render gen =
withFrozenCallStack $ forAllWithT render $ Gen.generalize gen
-- | Generates a random input for the test by running the provided generator.
--
--
forAllT :: (Monad m, Show a, HasCallStack) => GenT m a -> PropertyT m a
forAllT gen =
withFrozenCallStack $ forAllWithT showPretty gen
-- | Generates a random input for the test by running the provided generator.
--
forAll :: (Monad m, Show a, HasCallStack) => Gen a -> PropertyT m a
forAll gen =
withFrozenCallStack $ forAllWith showPretty gen
-- | Discards the current test entirely.
--
discard :: Monad m => PropertyT m a
discard =
PropertyT $ lift (Gen.generalize Gen.discard)
-- | Lift a test in to a property.
--
-- Because both 'TestT' and 'PropertyT' have 'MonadTest' instances, this
-- function is not often required. It can however be useful for writing
-- functions directly in 'TestT' and thus gaining a 'MonadTransControl'
-- instance at the expense of not being able to generate additional inputs
-- using 'forAll'.
--
-- An example where this is useful is parallel state machine testing, as
-- 'Hedgehog.Internal.State.executeParallel' requires 'MonadBaseControl' 'IO'
-- in order to be able to spawn threads in 'MonadTest'.
--
test :: Monad m => TestT m a -> PropertyT m a
test =
PropertyT . hoist lift
------------------------------------------------------------------------
-- Property
-- | The default configuration for a property test.
--
defaultConfig :: PropertyConfig
defaultConfig =
PropertyConfig {
propertyDiscardLimit =
100
, propertyShrinkLimit =
1000
, propertyShrinkRetries =
0
, propertyTerminationCriteria =
NoConfidenceTermination defaultMinTests
}
-- | The minimum amount of tests to run for a 'Property'
--
defaultMinTests :: TestLimit
defaultMinTests = 100