[Haskell-beginners] Re: hunit question

Joe Van Dyk joe at fixieconsulting.com
Tue Feb 2 16:36:44 EST 2010


On Tue, Feb 2, 2010 at 1:18 PM, Joe Van Dyk <joe at fixieconsulting.com> wrote:
> I have a little binary search function and am trying to write tests
> for it in hunit.
>
> The below approach doesn't compile, because I'm attempting to build a
> list of tuples of different types, which isn't working for me.
>
> What's the appropriate way to do this test?
>
> http://gist.github.com/293031
>
> import Test.HUnit
> import JoeBinarySearch
> -- Note:
> -- JoeBinarySearch.binary_search :: (Ord a) => [a] -> a -> Maybe Int
>
> assertions = [
>  ([1],       1, (Just 0)),
>  ([1, 3],    1, (Just 0)),
>  ([1, 3, 4], 4, (Just 2)),
>  ([1,2,4,6,8,9,12,15,17,20], 17, (Just 8)),
>  ([1,2,4,6,8,9,12,15,17,20], 20, (Just 9)),
>  ("hello",                 'l', (Just 2)), -- BOOM
>  ([0.0, 1.5, 3.0],         3.0, (Just 2)),
>  ([],                      1, Nothing),
>  ([1,3],                   2, Nothing),
>  ([1,4,6,8,9,12,15,17,20], 2, Nothing),
>  ([1,4,6,8,9,12,15,17,20], 100, Nothing),
>  ([1,4,6,8,9,12,15,17,20], (-100), Nothing)]
>
> test_list = TestList test_cases
>  where
>    test_cases = map test_func assertions
>    test_func (lst, input, expected) = TestCase $ assert_equal' (
> binary_search lst  input ) expected
>    assert_equal' = assertEqual "should equal"
>
> main :: IO ()
> main = do
>  runTestTT test_list
>  print "DONE"


I suppose I can live with this:

build_test_case list element expected = test_case
  where
    test_case = TestCase assertion
    assertion = assertEqual "should equal" (binary_search list element) expected

test_list = TestList [
  build_test_case [1] 1       (Just 0),
  build_test_case [1, 3]    1 (Just 0),
  build_test_case [1, 3, 4] 4 (Just 2),
  build_test_case [1,2,4,6,8,9,12,15,17,20] 17 (Just 8),
  build_test_case [1,2,4,6,8,9,12,15,17,20] 20 (Just 9),
  build_test_case "hello"                   'l' (Just 2),
  build_test_case [0.0, 1.5, 3.0]           3.0 (Just 2),
  build_test_case []                        1 Nothing,
  build_test_case [1,3]                     2 Nothing,
  build_test_case [1,4,6,8,9,12,15,17,20]   2 Nothing,
  build_test_case [1,4,6,8,9,12,15,17,20]   100 Nothing,
  build_test_case [1,4,6,8,9,12,15,17,20]   (-100) Nothing
  ]


main :: IO ()
main = do
  runTestTT test_list
  print "DONE"



But I assume there's a better way.


More information about the Beginners mailing list