2

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.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
epsilonhalbe
  • 15,637
  • 5
  • 46
  • 74
  • possible duplicate of [How to tell QuickCheck to generate only valid list indices for a parameter?](http://stackoverflow.com/questions/12827861/how-to-tell-quickcheck-to-generate-only-valid-list-indices-for-a-parameter) – hammar Mar 03 '14 at 21:52
  • thanks for the link, but the answers to it do not solve the problem of testing for the exceptions – epsilonhalbe Mar 03 '14 at 22:01

1 Answers1

1

You could use the spoon package, or write a similar function that would return the exception if you want to test that the exceptions are the same.

Roman Cheplyaka
  • 37,738
  • 7
  • 72
  • 121