計算機科学のブログ

コードの整理とプロジェクトのビルド QuickCheckを使ったプロパティテスト さまざまな種類のテスト ユニットテストの作成とstack testの使用

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT6(コードの整理とプロジェクトのビルド)、LESSON 36(QuickCheckを使ったプロパティテスト)、36.2(さまざまな種類のテスト)、ユニットテストの作成とstack testの使用、クイックチェック 36-3の解答を求めてみる。

palindrome-testing/test/Spec.hs

import Lib (isPalindrome)

assert :: Bool -> String -> String -> IO ()
assert test passStatement failStatement =
  putStrLn $
    if test
      then passStatement
      else failStatement

main :: IO ()
main = do
  putStrLn "Running tests..."
  mapM_
    ( \(func, word) ->
        assert
          (func word)
          (mconcat ["passed '", word, "'"])
          (mconcat ["FAIL: '", word, "'"])
    )
    [ (isPalindrome, "racecar"),
      (isPalindrome, "racecar!"),
      (not . isPalindrome, "cat"),
      (isPalindrome, "racecar."),
      (isPalindrome, ":racecar:")
    ]
  putStrLn "done!"

palindrome-testing/src/Lib.hs

module Lib
  ( isPalindrome,
  )
where

isPalindrome :: String -> Bool
isPalindrome text =
  let cleanText = filter (not . (`elem` ['!', '.'])) text
   in cleanText == reverse cleanText

入出力結果(Terminal, Zsh)

% stack test
palindrome-testing-0.1.0.0: unregistering (local file changes: test/Spec.hs)
palindrome-testing> build (lib + exe + test)
Preprocessing library for palindrome-testing-0.1.0.0..
Building library for palindrome-testing-0.1.0.0..
ld: warning: -undefined dynamic_lookup may not work with chained fixups
Preprocessing executable 'palindrome-testing-exe' for palindrome-testing-0.1.0.0..
Building executable 'palindrome-testing-exe' for palindrome-testing-0.1.0.0..
Preprocessing test suite 'palindrome-testing-test' for palindrome-testing-0.1.0.0..
Building test suite 'palindrome-testing-test' for palindrome-testing-0.1.0.0..
[2 of 2] Compiling Main         
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/palindrome-testing-test/palindrome-testing-test ...
palindrome-testing> copy/register
Installing library in /Users/…/palindrome-testing/.stack-work/install/x86_64-osx/dd0ba1c274e73dc536fbe6c0a59722f85fb3bc32a983d13f60410ac8cb68772f/9.0.2/lib/x86_64-osx-ghc-9.0.2/palindrome-testing-0.1.0.0-5TG33YXoyUc9xySoWsuis4
Installing executable palindrome-testing-exe in /Users/…/palindrome-testing/.stack-work/install/x86_64-osx/dd0ba1c274e73dc536fbe6c0a59722f85fb3bc32a983d13f60410ac8cb68772f/9.0.2/bin
Registering library for palindrome-testing-0.1.0.0..
palindrome-testing> test (suite: palindrome-testing-test)
                                
Running tests...
passed 'racecar'
passed 'racecar!'
passed 'cat'
passed 'racecar.'
passed ':racecar:'
done!

palindrome-testing> Test suite palindrome-testing-test passed
Completed 2 action(s).
%