計算機科学のブログ

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

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

コード

palindrome-testing/src/Lib.hs

module Lib (isPalindrome) where

isPalindrome :: String -> Bool
isPalindrome text = cleanText == reverse cleanText
    where cleanText = filter (not . (== '!')) text

コード

palindrome-testing/test/Spec.hs

import Lib(isPalindrome)

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

main :: IO ()
main = do
    putStrLn "Running tests..."
    assert (isPalindrome ":racecar:") "passed ':racecar:'" "FAIL: ':racecar:'"
    putStrLn "done!"

入出力結果(Terminal, Zsh)

% stack test
palindrome-testing> build (lib + exe + test) with ghc-9.8.4
Preprocessing library for palindrome-testing-0.1.0.0..
Building library for palindrome-testing-0.1.0.0..
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..
[1 of 2] Compiling Main
[3 of 3] Linking .stack-work/dist/aarch64-osx/ghc-9.8.4/build/palindrome-testing-test/palindrome-testing-test
ld: warning: -U option is redundant when using -undefined dynamic_lookup
palindrome-testing> copy/register
Installing library in /Users/.../palindrome-testing/.stack-work/install/aarch64-osx/e7436b3217cf53d6b9beeebd2bdc5dd8dcab6f8595b8bde259631442ce745f25/9.8.4/lib/aarch64-osx-ghc-9.8.4/palindrome-testing-0.1.0.0-79lc3QtIB5sEppb6jDwN1g
Installing executable palindrome-testing-exe in /Users/.../palindrome-testing/.stack-work/install/aarch64-osx/e7436b3217cf53d6b9beeebd2bdc5dd8dcab6f8595b8bde259631442ce745f25/9.8.4/bin
Registering library for palindrome-testing-0.1.0.0..
palindrome-testing> test (suite: palindrome-testing-test)
                                
Running tests...
passed ':racecar:'
done!



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