I am writing an introduction to Haskell for my local functional programming group.
As a base I am using the Tasty-testing framework and I want to test the indexing function (!!)
.
MinimalExample.hs
module MinimalExample where
myIndex :: Int -> [a] -> a
myIndex _ [] = error "index too large"
myIndex 0 (x:_) = x
myIndex n (_:xs) = myIndex (n-1) xs
MinimalTests.hs
module MinimalTests where
import Test.Tasty
import Test.Tasty.SmallCheck as SC
import Test.SmallCheck.Series
import MinimalExample
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [scProps]
scProps :: TestTree
scProps = testGroup "(checked by SmallCheck)"
[ SC.testProperty "(!!) == myIndex" $ \lst n ->
lst !! n == myIndex (n::Int) (lst::[Int])
]
The tests should not fail on "too large indices" as the Errors/Exceptions are the same.
The tests should fail with negative input - which could be resolved by adding NonNegative
as a constraint on the input, or adding the respective clause in the myIndex
-function.
- Can I test for exceptions in property based tests?
- Or do I have to use (H)Unit-tests like in How do I test for an error in Haskell? or Haskell exceptions and unit testing , in this case how do I choose the Index in the range of 0 to length of the generated testing list.