### sample Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Generates and prints example values from a generator to standard output, using increasing size parameters for debugging. ```APIDOC ## sample ### Description Generates and prints example values from a generator. Generates values with increasing size parameters (0, 2, 4, ..., 20), helpful for debugging generators. ### Method `sample :: Show a => Gen a -> IO () ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```haskell sample (chooseInt (1, 100)) -- Output: -- 0 -- 75 -- 31 -- ... ``` ### Response #### Success Response (200) `IO ()` — Prints example values to stdout #### Response Example None provided ``` -------------------------------- ### Basic QuickCheck Test Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md A minimal example demonstrating how to write and run a basic QuickCheck property test. Ensure Test.QuickCheck is imported. ```haskell import Test.QuickCheck prop_reverse xs = reverse (reverse xs) == xs main = quickCheck prop_reverse ``` -------------------------------- ### QuickCheck Coverage Examples Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Illustrates how to use coverage checking with QuickCheck, including setting specific coverage requirements and adjusting confidence levels for strict, fast, or lenient testing. ```haskell import Test.QuickCheck -- Require 20% of tests to be in specific category prop = cover 20 (length xs > 5) "long lists" $ ... -- Strict coverage checking let conf = stdConfidence { tolerance = 1.0 } in quickCheckWith stdArgs (checkCoverageWith conf prop) -- Fast coverage checking (more false positives) let conf = stdConfidence { certainty = 10^6 } in quickCheckWith stdArgs (checkCoverageWith conf prop) -- Lenient coverage checking let conf = stdConfidence { tolerance = 0.7 } in quickCheckWith stdArgs (checkCoverageWith conf prop) ``` -------------------------------- ### Example Property Testing File IO Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md An example property demonstrating how to test file operations using `monadicIO`. It writes to a file, reads its contents, and asserts that the contents match. ```haskell prop_read_file :: FilePath -> Property prop_read_file f = monadicIO $ do run (writeFile f "hello") contents <- run (readFile f) assert (contents == "hello") ``` -------------------------------- ### Testing Functions with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md An example of testing functions using QuickCheck, specifically demonstrating the use of `Fn` to wrap a function for property testing. This is useful for advanced testing scenarios. ```haskell prop_apply (Fn f) x = f x == f x ``` -------------------------------- ### QuickCheck Property using applyFun Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Demonstrates using `applyFun` to extract a function and apply it within a QuickCheck property. This example tests properties of a function mapping `Int` to `Int`. ```haskell prop_double :: Fun Int Int -> Int -> Bool prop_double f x = let f' = applyFun f in f' (2 * x) == f' x + f' x || f' x * 2 == f' (2 * x) -- Or using pattern matching with Fn: prop_double (Fn f) x = f (2 * x) == f x + f x || f x * 2 == f (2 * x) ``` -------------------------------- ### Example Monadic IO Property Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md An example of a QuickCheck property that uses the `monadicIO` combinator to test an IO action. It demonstrates running an IO computation and asserting a condition on its result. ```haskell import Test.QuickCheck.Monadic prop_monadic_io :: Int -> Property prop_monadic_io n = monadicIO $ do result <- run (putStrLn "Testing" >> return (n + 1)) assert (result > n) ``` -------------------------------- ### Sample Generator Values to a List Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Similar to `sample`, but returns a list of example values instead of printing them. Generates values with sizes 0, 2, 4, ..., 20. ```haskell sample' :: Gen a -> IO [a] ``` ```haskell values <- sample' (chooseInt (1, 100)) mapM_ print values ``` -------------------------------- ### Displaying Failing Functions as Counterexamples Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Demonstrates how QuickCheck displays failing functions as counterexamples using a compact lookup table format. This example includes a property designed to fail to showcase this feature. ```haskell import Test.QuickCheck import Test.QuickCheck.Function -- This property will fail prop_always_positive :: Fun Int Int -> Bool prop_always_positive (Fn f) = f 0 > 0 && f 1 > 0 && f 2 > 0 -- When run: -- >>> quickCheck prop_always_positive -- *** Failed! Falsified (after 2 tests and 3 shrinks): -- {0->-1, 1->0, _->0} ``` -------------------------------- ### Sample Generator Values to Stdout Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Generates and prints example values from a generator to standard output. It uses increasing size parameters (0, 2, 4, ..., 20) for debugging. ```haskell sample :: Show a => Gen a -> IO () ``` ```haskell sample (chooseInt (1, 100)) -- Output: -- 0 -- 75 -- 31 -- ... ``` -------------------------------- ### QuickCheck Property using applyFun3 Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Tests properties of a three-argument function using `applyFun3`. This example checks if the result of a three-argument function is non-negative for specific inputs. ```haskell prop_add3 :: Fun Int (Fun Int (Fun Int Int)) -> Bool prop_add3 f = let f' = applyFun3 f in f' 1 2 3 >= 0 -- Using pattern: prop_add3 (Fn3 f) = f 1 2 3 >= 0 ``` -------------------------------- ### Example Property Testing ST Ref Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md An example property demonstrating the use of `monadicST` to test operations on an `STRef`. It shows creating, modifying, and reading from a mutable reference within the ST monad. ```haskell prop_vector :: Property prop_vector = monadicST $ do vec <- run $ newSTRef [] run $ modifySTRef vec (++ [1, 2, 3]) xs <- run $ readSTRef vec assert (xs == [1, 2, 3]) ``` -------------------------------- ### Combining Generators with Do-Notation Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Use do-notation to combine multiple generators sequentially. This example generates two integers, then randomly chooses between their sum or product. ```haskell gen = do x <- chooseInt (1, 10) y <- chooseInt (1, 10) z <- oneof [return (x + y), return (x * y)] return z ``` -------------------------------- ### Apply Fun Type Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/types.md Example of using the applyFun accessor to get the function from a Fun type. ```haskell prop_func (Fun _ f) = f 0 == f 0 ``` -------------------------------- ### QuickCheck Property using applyFun2 Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Tests properties of a curried function using `applyFun2`. The example checks if addition is commutative or non-negative for `Int` inputs. ```haskell prop_add :: Fun Int (Fun Int Int) -> Bool prop_add f = let f' = applyFun2 f in f' 1 2 == f' 2 1 || f' 1 2 >= 0 -- Using pattern: prop_add (Fn2 f) = f 1 2 == f 2 1 || f 1 2 >= 0 ``` -------------------------------- ### Getting Test Results with quickCheckResult Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Tests a property using `stdArgs` defaults and returns a structured `Result`. Prints output to stdout. ```haskell result <- quickCheckResult prop_reverse case result of Success {} -> putStrLn "All tests passed!" Failure {} -> putStrLn "Test failed!" _ -> putStrLn "Inconclusive" ``` -------------------------------- ### QuickCheck Property for Fun Type Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Example QuickCheck property demonstrating the usage of `Fun` type for generating functions. `f` is a generated function, and `x` is a generated integer. ```haskell {-# LANGUAGE GADTs #-} import Test.QuickCheck import Test.QuickCheck.Function prop_apply :: Fun Int Int -> Int -> Bool prop_apply f x = applyFun f x == applyFun f x -- f is a generated function, x is a generated integer ``` -------------------------------- ### quickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md The simplest way to test a property. Runs 100 tests by default. Prints pass/fail results and counterexamples if found. Uses stdArgs configuration. ```APIDOC ## quickCheck ### Description The simplest way to test a property. Runs 100 tests by default. Prints pass/fail results and counterexamples if found. Uses `stdArgs` configuration. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method ```haskell quickCheck :: Testable prop => prop -> IO () ``` ### Endpoint N/A (Haskell function) ### Request Example ```haskell import Test.QuickCheck prop_reverse :: [Int] -> Bool prop_reverse xs = reverse (reverse xs) == xs main :: IO () main = quickCheck prop_reverse -- Output: +++ OK, passed 100 tests. ``` ### Response #### Success Response (IO ()) Prints results to stdout. #### Response Example ``` +++ OK, passed 100 tests. ``` ``` -------------------------------- ### Basic Property Testing with quickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md The simplest way to test a property. Runs 100 tests by default and prints pass/fail results. Uses `stdArgs` configuration. ```haskell import Test.QuickCheck prop_reverse :: [Int] -> Bool prop_reverse xs = reverse (reverse xs) == xs main :: IO () main = quickCheck prop_reverse -- Output: +++ OK, passed 100 tests. ``` -------------------------------- ### sample' Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Similar to `sample`, but returns a list of generated values instead of printing them to stdout. ```APIDOC ## sample' ### Description Like `sample` but returns a list instead of printing. Generates values with sizes 0, 2, 4, ..., 20. ### Method `sample' :: Gen a -> IO [a] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```haskell values <- sample' (chooseInt (1, 100)) mapM_ print values ``` ### Response #### Success Response (200) `IO [a]` — List of example values #### Response Example None provided ``` -------------------------------- ### CI/Continuous Integration Configuration Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Configure QuickCheck for CI by setting `maxSuccess` to 10000, `maxSize` to 100, `chatty` to `False`, and `maxShrinks` to 1000. It also includes logic to exit with success or failure based on the test result. ```haskell let args = stdArgs { maxSuccess = 10000 , maxSize = 100 , chatty = False , maxShrinks = 1000 } in quickCheckWithResult args prop >>= \result -> case result of Success {} -> exitSuccess _ -> exitFailure ``` -------------------------------- ### forAllShow Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Like forAll but with custom output formatting. ```APIDOC ## forAllShow ### Description Like `forAll` but with custom output formatting. ### Method ```haskell forAllShow :: Testable prop => Gen a -> (a -> String) -> (a -> prop) -> Property ``` ### Parameters #### Path Parameters - **gen** (Gen a) - Yes - Generator - **shw** (a -> String) - Yes - Custom show function - **prop** (a -> prop) - Yes - Property ### Response #### Success Response (Property) - **Property** — Property with custom display ``` -------------------------------- ### Configure Fine-Grained Testing Parameters Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Sets multiple advanced configuration options for QuickCheck, including thorough testing (`maxSuccess`), larger structures (`maxSize`), limited shrinking (`maxShrinks`), strict discard ratio (`maxDiscardRatio`), and quiet mode (`chatty`). ```haskell let args = stdArgs { maxSuccess = 5000 -- Thorough testing , maxSize = 200 -- Allow very large structures , maxShrinks = 1000 -- Limit shrinking time , maxDiscardRatio = 5 -- Few discards allowed , chatty = False -- Quiet mode } in quickCheckWithResult args myProperty ``` -------------------------------- ### stdArgs Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Provides the standard default configuration for QuickCheck tests. ```APIDOC ## stdArgs ### Description Provides the standard default configuration for QuickCheck tests. ### Returns - `Args`: Default test arguments with 100 tests, ratio 10, size 100, chatty on, and unlimited shrinks. ``` -------------------------------- ### Args Type Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/types.md Configuration options for executing QuickCheck tests. ```APIDOC ## Args ### Description Configuration for test execution. ### Fields | Field | Type | Default | Description | |---|---|---|---| | `replay` | `Maybe (QCGen, Int)` | `Nothing` | Seed and size to replay a previous test | | `maxSuccess` | `Int` | `100` | Number of successful tests required for pass | | `maxDiscardRatio` | `Int` | `10` | Max discarded tests per successful test | | `maxSize` | `Int` | `100` | Maximum size parameter for generators | | `chatty` | `Bool` | `True` | Print progress to stdout | | `maxShrinks` | `Int` | `maxBound` | Maximum shrinking iterations | ``` -------------------------------- ### Get Current Size Parameter with `getSize` Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Retrieve the current size parameter within a monadic context using `getSize`. This allows for dynamic generation based on the active size. ```haskell gen = do n <- getSize vectorOf n (chooseInt (1, 100)) ``` -------------------------------- ### Showing Shrinking Steps with `verboseShrinking` Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Use `verboseShrinking` to make QuickCheck print each shrinking step for a property. This helps in understanding how counterexamples are reduced. ```haskell verboseShrinking :: Property -> Property ``` -------------------------------- ### Coverage Analysis with Classify Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/README.md Use `classify` to add coverage information to test results. This example classifies lists based on their length (empty or singleton). `verboseCheck` is used to display this information. ```haskell prop_list xs = classify (length xs == 0) "empty" $ classify (length xs == 1) "singleton" $ xs == xs main = verboseCheck prop_list ``` -------------------------------- ### Smart Wrapper for Improved Shrinking Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/modifiers-and-utils.md Utilize Smart to wrap values, enabling QuickCheck to generate them with an improved shrinking strategy. ```haskell newtype Smart a = Smart { getSmart :: a } ``` ```haskell prop_smart (Smart x) = x == x ``` -------------------------------- ### Run QuickCheck with Default Arguments Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Executes QuickCheck with the default `stdArgs`. This configuration runs 100 tests with a maximum size of 100 and no specific shrinking limit. ```haskell import Test.QuickCheck quickCheck myProperty ``` -------------------------------- ### Define Confidence for Coverage Checking Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/modifiers-and-utils.md The `Confidence` data type allows customization of statistical parameters for coverage checking, including `certainty` and `tolerance`. Example shows setting custom values and using them with `checkCoverageWith`. ```haskell data Confidence = Confidence { certainty :: Integer -- default: 10^9 , tolerance :: Double -- default: 0.9 } stdConfidence :: Confidence -- Conservative defaults suitable for CI let conf = Confidence { certainty = 10^6, tolerance = 0.95 } in checkCoverageWith conf myProperty ``` -------------------------------- ### QuickCheck Property with Positive Modifier Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/modifiers-and-utils.md An example property using the `Positive` modifier to test the `sqrt` function. The `Positive` wrapper guarantees that `x` is greater than 0, simplifying the property `sqrt (x * x) == x`. ```haskell prop_sqrt (Positive x) = sqrt (x * x) == x -- x > 0 guaranteed main = quickCheck prop_sqrt ``` -------------------------------- ### forAllShrinkShow: Full Control Over Shrinking and Display Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Provides full control over both shrinking and display of generated values during property testing. ```haskell forAllShrinkShow :: Testable prop => Gen a -> (a -> [a]) -> (a -> String) -> (a -> prop) -> Property ``` -------------------------------- ### Testing Function Properties with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Demonstrates testing for function purity, commutativity of addition, and function composition using QuickCheck's Fun type. Ensure QuickCheck and Function modules are imported. ```haskell {-# LANGUAGE GADTs #-} import Test.QuickCheck import Test.QuickCheck.Function -- Test that a function is pure (deterministic) prop_pure :: Fun Int Int -> Int -> Bool prop_pure (Fn f) x = f x == f x -- Test commutativity of addition prop_commute :: Fun Int (Fun Int Int) -> Bool prop_commute (Fn2 f) = f 1 2 == f 2 1 || f 1 2 >= 0 -- Test function composition prop_compose :: Fun Int Int -> Fun Int Int -> Int -> Bool prop_compose (Fn f) (Fn g) x = (f . g) x == f (g x) main = do quickCheck prop_pure quickCheck prop_commute quickCheck prop_compose ``` -------------------------------- ### printTestCase Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Alias for `counterexample`. Prints on failure. ```APIDOC ## printTestCase ### Description Alias for `counterexample`. Prints on failure. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Haskell Function ### Endpoint N/A ### Request Example N/A ### Response #### Success Response `Property` — Annotated property #### Response Example N/A ``` -------------------------------- ### Test a Property with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md Use this basic function to test a property with QuickCheck's default settings. ```haskell quickCheck prop ``` -------------------------------- ### quickCheckWithResult Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Runs tests with custom arguments and returns the full result. Prints output. ```APIDOC ## quickCheckWithResult ### Description Runs tests with custom arguments and returns the full result. Prints output. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method ```haskell quickCheckWithResult :: Testable prop => Args -> prop -> IO Result ``` ### Endpoint N/A (Haskell function) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **args** (`Args`) - Required - Test configuration - **property** (`prop`) - Required - Property to test ### Request Example ```haskell result <- quickCheckWithResult (stdArgs { maxSuccess = 1000, chatty = False }) prop case result of Success n _ _ _ _ _ -> putStrLn $ "Passed " ++ show n ++ " tests" Failure n _ shrinks _ _ _ _ _ reason _ _ _ _ -> do putStrLn $ "Failed after " ++ show n ++ " tests" putStrLn $ "Reason: " ++ reason putStrLn $ "Shrinks: " ++ show shrinks _ -> return () ``` ### Response #### Success Response (IO Result) Test result including all details. #### Response Example ```haskell Success {..} -- or Failure {..} -- or Inconclusive ``` ``` -------------------------------- ### forAllShow: Property with Custom Display Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Like `forAll` but with custom output formatting. This is useful for controlling how generated values are displayed during testing. ```haskell forAllShow :: Testable prop => Gen a -> (a -> String) -> (a -> prop) -> Property ``` -------------------------------- ### Custom Generator with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md Illustrates how to define a custom generator for QuickCheck properties using `forAll` and `listOf` with `chooseInt`. This allows for more specific test data generation. ```haskell prop = forAll (listOf (chooseInt (1, 100))) $ \xs -> sum xs >= 0 ``` -------------------------------- ### Testing Higher-Order Functions with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Illustrates testing standard higher-order functions like `map`, `filter`, and `fold` using generated functions and predicates from the Function module. This verifies the behavior of these functions with arbitrary inputs. ```haskell import Test.QuickCheck import Test.QuickCheck.Function -- Test map with a generated function prop_map :: Fun Int Int -> [Int] -> Bool prop_map (Fn f) xs = length (map f xs) == length xs -- Test filter with a generated predicate prop_filter :: Fun Int Bool -> [Int] -> Bool prop_filter (Fn p) xs = all p (filter p xs) && length (filter p xs) <= length xs -- Test fold with a generated binary function prop_fold :: Fun (Int, Int) Int -> [Int] -> Bool prop_fold (Fn f) xs = case xs of [] -> True (x:_) -> True -- Just test that it doesn't crash main = do quickCheck prop_map quickCheck prop_filter quickCheck prop_fold ``` -------------------------------- ### Function Display Formats Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Illustrates various ways functions can be displayed in QuickCheck, from simple mappings to complex ones. ```Haskell {0->1, _->0} -- Maps 0 to 1, everything else to 0 ``` ```Haskell {_->True} -- Constant function returning True ``` ```Haskell {_->[], [1]->[], ...} -- Maps different inputs to different lists ``` ```Haskell {_->...} -- Complex function (only shown as underscore) ``` -------------------------------- ### Basic Property Testing in Haskell Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/README.md Define a property and test it using QuickCheck's `quickCheck` function. Ensure `Test.QuickCheck` is imported. ```haskell import Test.QuickCheck -- Define a property prop_reverse :: [Int] -> Bool prop_reverse xs = reverse (reverse xs) == xs -- Test it main = quickCheck prop_reverse -- Output: +++ OK, passed 100 tests. ``` -------------------------------- ### run Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md Executes a monadic action within the PropertyM context. The result of the action is then available for further use in the property. ```APIDOC ## run ### Description Executes a monadic action. The result is available in the PropertyM context. Can be used in do-notation. ### Signature ```haskell run :: Monad m => m a -> PropertyM m a ``` ### Parameters #### Path Parameters - **action** (m a) - Required - Monadic action to execute ### Returns - **PropertyM m a** — Result wrapped in PropertyM ### Example ```haskell prop_io = monadicIO $ do result <- run (readFile "test.txt") assert (length result > 0) ``` ``` -------------------------------- ### Detailed Results with quickCheckWithResult Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Runs tests with custom arguments and returns the full `Result` object, including details like the number of tests, shrinks, and failure reasons. Prints output. ```haskell result <- quickCheckWithResult (stdArgs { maxSuccess = 1000, chatty = False }) prop case result of Success n _ _ _ _ _ -> putStrLn $ "Passed " ++ show n ++ " tests" Failure n _ shrinks _ _ _ _ _ reason _ _ _ _ -> do putStrLn $ "Failed after " ++ show n ++ " tests" putStrLn $ "Reason: " ++ reason putStrLn $ "Shrinks: " ++ show shrinks _ -> return () ``` -------------------------------- ### Custom Arbitrary Instance for Int with Shrinking Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/arbitrary-module.md Provides a custom Arbitrary instance for Int, defining how to generate random integers and shrink them towards zero. Shrinking is crucial for QuickCheck to find minimal failing test cases. ```haskell -- For integers, shrink towards 0 instance Arbitrary Int where arbitrary = ... shrink 0 = [] shrink n = [n-1, -(n-1)] ++ (if n > 0 then [0..(n-1)] else []) ``` -------------------------------- ### QuickCheck Test Execution Arguments Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Defines the `Args` data type, which encapsulates all configuration settings for QuickCheck's test execution. Use this to control parameters like test limits, replayability, and verbosity. ```haskell data Args = Args { replay :: Maybe (QCGen, Int) , maxSuccess :: Int , maxDiscardRatio :: Int , maxSize :: Int , chatty :: Bool , maxShrinks :: Int } ``` -------------------------------- ### Configure Thorough Testing Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Runs QuickCheck with an increased number of successful tests (10000) for more thorough bug detection. This requires using `quickCheckWith` and providing a modified `Args` record. ```haskell let args = stdArgs { maxSuccess = 10000 } in quickCheckWith args myProperty ``` -------------------------------- ### Define Default Arguments Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Defines the default configuration used by QuickCheck functions. This includes settings for replay, maximum successes, discard ratio, size, verbosity, and shrinking limits. ```haskell stdArgs :: Args stdArgs = Args { replay = Nothing , maxSuccess = 100 , maxDiscardRatio = 10 , maxSize = 100 , chatty = True , maxShrinks = maxBound } ``` -------------------------------- ### Custom Function Instance for User-Defined Types Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Shows how to create a custom Function instance for a user-defined data type (Expr) by providing `show` and `read` functions. This allows QuickCheck to generate and test functions operating on this custom type. ```haskell import Test.QuickCheck import Test.QuickCheck.Function data Expr = Const Int | Var String | Add Expr Expr deriving (Show, Eq) -- Provide bijection to String instance Function Expr where function = functionMap show read -- Now properties can test functions over Expr prop_eval :: Fun Expr Int -> Expr -> Bool prop_eval f expr = applyFun f expr >= 0 main = quickCheck prop_eval ``` -------------------------------- ### Enable Verbose Shrinking Output Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Use the `verboseShrinking` combinator or set `chatty` to `True` in `stdArgs` to see detailed shrinking steps. ```haskell -- See shrinking in action quickCheck (verboseShrinking prop) -- Or in args let args = stdArgs { chatty = True } in quickCheckWith args prop ``` -------------------------------- ### Fast Smoke Test Configuration Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Configure QuickCheck for a fast smoke test by setting `maxSuccess` to 100 and `maxSize` to 20. ```haskell let args = stdArgs { maxSuccess = 100 , maxSize = 20 } in quickCheckWith args prop ``` -------------------------------- ### quickCheckResult Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Tests a property and returns the structured result. Uses `stdArgs` defaults. Prints output. ```APIDOC ## quickCheckResult ### Description Tests a property and returns the structured result. Uses `stdArgs` defaults. Prints output. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method ```haskell quickCheckResult :: Testable prop => prop -> IO Result ``` ### Endpoint N/A (Haskell function) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **property** (`prop`) - Required - Property to test ### Request Example ```haskell result <- quickCheckResult prop_reverse case result of Success {} -> putStrLn "All tests passed!" Failure {} -> putStrLn "Test failed!" _ -> putStrLn "Inconclusive" ``` ### Response #### Success Response (IO Result) Test result including details. #### Response Example ```haskell Success {..} -- or Failure {..} -- or Inconclusive ``` ``` -------------------------------- ### Handle growingElements with empty list in QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/errors.md Similar to `elements`, `growingElements` must be provided with a non-empty list. An empty list will lead to an error. ```haskell growingElements [] -- Error! ``` -------------------------------- ### forAllShrinkShow Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Provides full control over shrinking and display of generated values. ```APIDOC ## forAllShrinkShow ### Description Provides full control over shrinking and display of generated values. ### Method ```haskell forAllShrinkShow :: Testable prop => Gen a -> (a -> [a]) -> (a -> String) -> (a -> prop) -> Property ``` ### Parameters #### Path Parameters - **gen** (Gen a) - Yes - Generator - **shr** (a -> [a]) - Yes - Shrink function - **shw** (a -> String) - Yes - Show function - **prop** (a -> prop) - Yes - Property ### Response #### Success Response (Property) - **Property** — Full control over shrinking and display ``` -------------------------------- ### Exhaustive Testing Configuration Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Configure QuickCheck for exhaustive testing by setting `maxSuccess` to 10000, `maxSize` to 200, and `maxShrinks` to 5000. ```haskell let args = stdArgs { maxSuccess = 10000 , maxSize = 200 , maxShrinks = 5000 } in quickCheckWith args prop ``` -------------------------------- ### verboseShrinking Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Prints each shrinking step for a property. ```APIDOC ## verboseShrinking ### Description Prints each shrinking step. ### Parameters #### Path Parameters - **prop** (Property) - Required - Property ### Returns `Property` — Property showing shrinking steps ``` -------------------------------- ### Integrate IO Actions in Properties with ioProperty Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md The `ioProperty` function allows you to include IO actions within your QuickCheck properties. Note that random values generated inside the IO action may not shrink effectively; it's recommended to generate them beforehand. ```haskell ioProperty :: Testable prop => IO prop -> Property ``` ```haskell prop_file :: FilePath -> Property prop_file f = ioProperty $ do writeFile f "test" contents <- readFile f return (contents == "test") ``` -------------------------------- ### Generate Random Integer with Arbitrary Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/arbitrary-module.md Demonstrates generating a random integer using the default Arbitrary instance. This generator can be used within QuickCheck properties. ```haskell import Test.QuickCheck -- Generate an integer using the Arbitrary instance intGen :: Gen Int intGen = arbitrary -- Use in a property prop_something (x :: Int) = x == x -- x generated by arbitrary ``` -------------------------------- ### wp Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md Runs a monadic action returning a boolean and asserts it's true. Shorthand for `run action >>= assert`. ```APIDOC ## wp ### Description Runs a monadic action returning a boolean and asserts it's true. Shorthand for `run action >>= assert`. ### Signature ```haskell wp :: Monad m => m Bool -> PropertyM m () ``` ### Parameters #### Path Parameters - **action** (m Bool) - Required - Monadic action returning boolean ### Returns `PropertyM m ()` — Result assertion ``` -------------------------------- ### Verbose Property Testing with verboseCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Similar to `quickCheck`, but prints every generated test case and its result. Useful for debugging. ```haskell verboseCheck prop_reverse -- Prints each generated list before testing ``` -------------------------------- ### Print Test Case Description on Failure with printTestCase Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md `printTestCase` is an alias for `counterexample` and prints a provided test case description when the property fails. ```haskell printTestCase :: String -> Property -> Property ``` -------------------------------- ### counterexample Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Adds a custom message that prints if the property fails. Multiple counterexamples accumulate. ```APIDOC ## counterexample ### Description Adds a custom message that prints if the property fails. Multiple counterexamples accumulate. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Haskell Function ### Endpoint N/A ### Request Example ```haskell prop_sort :: [Int] -> Property prop_sort xs = counterexample ("Input: " ++ show xs) $ counterexample ("Output: " ++ show (sort xs)) $ sort xs == sort xs ``` ### Response #### Success Response `Property` — Annotated property #### Response Example N/A ``` -------------------------------- ### Args Data Type Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Defines the configuration arguments for QuickCheck tests, including replay options, success counts, and size limits. ```APIDOC ## Args ### Description Test Configuration arguments. ### Fields - **replay** (`Maybe (QCGen, Int)`): Seed and size to replay a previous test. Defaults to `Nothing`. - **maxSuccess** (`Int`): Number of successful tests needed to pass. Defaults to `100`. - **maxDiscardRatio** (`Int`): Maximum discarded tests per successful test. Defaults to `10`. - **maxSize** (`Int`): Maximum size parameter for generators. Defaults to `100`. - **chatty** (`Bool`): Whether to print progress information during testing. Defaults to `True`. - **maxShrinks** (`Int`): Maximum shrinking attempts for failed tests. Defaults to `maxBound`. ### Example ```haskell let args = stdArgs { maxSuccess = 1000 , maxSize = 50 , chatty = False } in quickCheckWith args myProperty ``` ``` -------------------------------- ### (.&.) Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Combines two properties using logical AND. Both properties must hold, and it short-circuits on the first failure. ```APIDOC ## (.&.) ### Description Both properties must hold. Short-circuits on first failure. ### Signature ```haskell (.&.) :: Testable prop => prop -> prop -> Property ``` ### Parameters #### Path Parameters - **p1** (prop) - Required - The first property. - **p2** (prop) - Required - The second property. ### Returns `Property` — Conjunction of properties. ### Example ```haskell prop_and = prop1 .&. prop2 .&. prop3 ``` ``` -------------------------------- ### applyFun3 Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Like `applyFun2` but for three-argument functions. ```APIDOC ### applyFun3 ```haskell applyFun3 :: Fun a (b -> c -> d) -> (a -> b -> c -> d) ``` **Parameters:** | Parameter | |-----------|---| | f | `Fun a (b -> c -> d)` | Yes | Wrapped function of three arguments | **Returns:** `a -> b -> c -> d` — The function **Description:** Like `applyFun2` but for three-argument functions. **Example:** ```haskell prop_add3 :: Fun Int (Fun Int (Fun Int Int)) -> Bool prop_add3 f = let f' = applyFun3 f in f' 1 2 3 >= 0 -- Using pattern: prop_add3 (Fn3 f) = f 1 2 3 >= 0 ``` ``` -------------------------------- ### Test More Thoroughly with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md Configure QuickCheck to run more test cases by adjusting `maxSuccess` in `stdArgs` for more thorough testing. ```haskell quickCheckWith stdArgs { maxSuccess = 10000 } prop ``` -------------------------------- ### Medium Thoroughness Test Configuration Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Configure QuickCheck for medium thoroughness testing by increasing `maxSuccess` to 1000 and `maxSize` to 100. ```haskell let args = stdArgs { maxSuccess = 1000 , maxSize = 100 } in quickCheckWith args prop ``` -------------------------------- ### Interpreting QuickCheck Results Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Demonstrates how to use a `case` statement to pattern match on the `Result` of a QuickCheck test and handle each outcome appropriately. This is useful for reporting or taking action based on test success or failure. ```haskell result <- quickCheckResult myProperty case result of Success n _ _ _ _ _ -> putStrLn $ "All " ++ show n ++ " tests passed" Failure n _ shrinks _ _ _ _ reason _ testCase _ _ _ _ -> do putStrLn $ "Failed after " ++ show n ++ " tests, " ++ show shrinks ++ " shrinks" putStrLn $ "Reason: " ++ reason putStrLn $ "Counterexample: " ++ show testCase GaveUp n _ _ _ _ _ -> putStrLn $ "Gave up after " ++ show n ++ " tests" NoExpectedFailure n _ _ _ _ _ -> putStrLn $ "Expected failure did not occur after " ++ show n ++ " tests" ``` -------------------------------- ### forAllShrink Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Like forAll but with an explicit shrink function. ```APIDOC ## forAllShrink ### Description Like `forAll` but with an explicit shrink function. ### Method ```haskell forAllShrink :: (Show a, Testable prop) => Gen a -> (a -> [a]) -> (a -> prop) -> Property ``` ### Parameters #### Path Parameters - **gen** (Gen a) - Yes - Generator - **shr** (a -> [a]) - Yes - Custom shrink function - **prop** (a -> prop) - Yes - Property ### Response #### Success Response (Property) - **Property** — Property with custom shrinking ### Example ```haskell prop_custom = forAllShrink (chooseInt (1, 100)) (\x -> [x-1 | x > 0]) (\n -> n > 0 && n < 100) ``` ``` -------------------------------- ### Replay Exact Failure with Specific Arguments Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/errors.md Replay a specific failing test case by providing the `seed` and `size` from the failure output to `quickCheckWith`. This allows for precise reproduction of the error. ```haskell -- From output: *** Failed! Falsified (after 23 tests): let args = stdArgs { replay = Just (seed, size) } quickCheckWith args prop ``` -------------------------------- ### Configure Silent Testing Programmatically Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/configuration.md Runs QuickCheck in silent mode (`chatty = False`) and captures the result using `quickCheckWithResult`. The output is then manually printed based on the test outcome (Success, Failure, or Inconclusive). ```haskell let args = stdArgs { chatty = False } in do result <- quickCheckWithResult args myProperty case result of Success n _ _ _ _ _ -> putStrLn $ "Passed " ++ show n ++ " tests" Failure n _ shrinks _ _ _ _ _ _ reason _ _ _ _ -> putStrLn $ "Failed after " ++ show n ++ " tests, " ++ show shrinks ++ " shrinks" _ -> putStrLn "Inconclusive" ``` -------------------------------- ### generate Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Runs a generator in the IO monad with a random seed and a default size of 30. Use `resize` for custom sizes. ```APIDOC ## generate ### Description Runs a generator in the IO monad. The generator is run with a random seed and size parameter of 30. If you need a different size, use `resize` explicitly. ### Method `generate :: Gen a -> IO a` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```haskell import Test.QuickCheck main :: IO () main = do x <- generate (chooseInt (1, 100)) print x -- prints a random integer between 1 and 100 ``` ### Response #### Success Response (200) `IO a` — A random value of type `a` #### Response Example None provided ``` -------------------------------- ### Test InfiniteList Property and Execution Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/modifiers-and-utils.md Property to test the `InfiniteList` modifier by taking a prefix. Includes `main` to run the QuickCheck test. ```haskell prop_take_infinite (InfiniteList xs _) = take 5 xs == take 5 xs main = quickCheck prop_take_infinite -- On failure: "Failed! ... Falsified (after N tests): "prefix" ++ ..." ``` -------------------------------- ### Use Custom Generators in QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/00-START-HERE.md Integrate a custom generator (`myGen`) with `forAll` to provide specific values for testing a property. ```haskell forAll myGen $ \value -> prop value ``` -------------------------------- ### Label Property with String Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/modifiers-and-utils.md Use the `label` function to attach a descriptive string to a property. QuickCheck uses these labels to report the distribution of test cases across different categories. ```haskell label :: String -> Property -> Property ``` ```haskell prop_sort (Sorted xs) = label ("length = " ++ show (length xs)) $ xs == sort xs ``` -------------------------------- ### Configure test arguments with stdArgs Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Customize QuickCheck test configurations by modifying fields of the `stdArgs` record. This allows for adjustments to parameters like `maxSuccess`, `maxSize`, and `chatty`. ```haskell let args = stdArgs { maxSuccess = 1000 , maxSize = 50 , chatty = False } in quickCheckWith args myProperty ``` -------------------------------- ### applyFun Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/function-module.md Extracts the actual function from a `Fun` wrapper. Use this to apply the function to arguments. ```APIDOC ## Extracting Functions ### applyFun ```haskell applyFun :: Fun a b -> (a -> b) ``` **Parameters:** | Parameter | |-----------|---| | f | `Fun a b` | Yes | Wrapped function | **Returns:** `a -> b` — The actual function **Description:** Extracts the actual function from a `Fun` wrapper. Use this to apply the function to arguments. **Example:** ```haskell prop_double :: Fun Int Int -> Int -> Bool prop_double f x = let f' = applyFun f in f' (2 * x) == f' x + f' x || f' x * 2 == f' (2 * x) -- Or using pattern matching with Fn: prop_double (Fn f) x = f (2 * x) == f x + f x || f x * 2 == f (2 * x) ``` ``` -------------------------------- ### verboseCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Like `quickCheck` but prints every test case generated. Useful for debugging. ```APIDOC ## verboseCheck ### Description Like `quickCheck` but prints every test case generated. Useful for debugging. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method ```haskell verboseCheck :: Testable prop => prop -> IO () ``` ### Endpoint N/A (Haskell function) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **property** (`prop`) - Required - Property to test ### Request Example ```haskell verboseCheck prop_reverse -- Prints each generated list before testing ``` ### Response #### Success Response (IO ()) Prints all test cases and results. #### Response Example ``` (Output shows each test case and its result) ``` ``` -------------------------------- ### Run a Generator with IO Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/gen-module.md Runs a generator in the IO monad with a random seed and a default size of 30. Use resize explicitly for a different size. ```haskell generate :: Gen a -> IO a ``` ```haskell import Test.QuickCheck main :: IO () main = do x <- generate (chooseInt (1, 100)) print x -- prints a random integer between 1 and 100 ``` -------------------------------- ### monitor Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/monadic-module.md Applies a property modifier, such as `counterexample` or `label`, to the current property within the PropertyM context. ```APIDOC ## monitor ### Description Applies a property modifier (like `counterexample`, `label`, etc.) to the property. Useful for annotations. ### Signature ```haskell monitor :: Monad m => (Property -> Property) -> PropertyM m () ``` ### Parameters #### Path Parameters - **f** (Property -> Property) - Required - Function to modify the property ### Returns - **PropertyM m ()** — Modification applied ### Example ```haskell prop = monadicIO $ do x <- run someIO monitor $ counterexample ("Result was: " ++ show x) assert (x > 0) ``` ``` -------------------------------- ### verbose Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Makes a property print every test case it executes. ```APIDOC ## verbose ### Description Makes the property print every test case. ### Parameters #### Path Parameters - **prop** (Property) - Required - Property to make verbose ### Returns `Property` — Property that prints all test cases ``` -------------------------------- ### Use Counterexample for Debugging Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/errors.md Employ `counterexample` to add custom messages to test output, showing intermediate values or computed results. This aids in pinpointing the source of failures. ```haskell prop xs = counterexample ("Input: " ++ show xs) $ counterexample ("Output: " ++ show (sort xs)) $ sort xs == sort xs ``` -------------------------------- ### Run More Tests with QuickCheck Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/README.md Increase the number of successful test cases QuickCheck runs. Use `quickCheckWith` for more control over arguments or `quickCheck` with `withNumTests` for a direct approach. ```haskell quickCheckWith stdArgs { maxSuccess = 10000 } prop ``` ```haskell quickCheck (withNumTests 10000 prop) ``` -------------------------------- ### Limiting Shrinking Attempts with `withMaxShrinks` Source: https://github.com/nick8325/quickcheck/blob/master/_autodocs/api-reference/test-and-property.md Limit the number of shrinking attempts QuickCheck will perform for counterexamples using `withMaxShrinks`. This can prevent excessive shrinking. ```haskell withMaxShrinks :: Int -> Property -> Property ```