Skip to content

Instantly share code, notes, and snippets.

@fiddlerwoaroof
Created February 27, 2018 00:44
Show Gist options
  • Select an option

  • Save fiddlerwoaroof/7594e0de5607b45a8dbf816865488c01 to your computer and use it in GitHub Desktop.

Select an option

Save fiddlerwoaroof/7594e0de5607b45a8dbf816865488c01 to your computer and use it in GitHub Desktop.
Unit-testing IO in Haskell
module Main where
import Data.IORef
import Data.Time.Clock.POSIX
realIoUnderTest :: IORef Int -> IORef [[Char]] -> IORef Int -> IORef String -> IO ()
realIoUnderTest a b c d = do
b' <- readIORef b
putStrLn $ Prelude.unlines b'
a' <- readIORef a
c' <- readIORef c
writeIORef d $ "This took " ++ show (c' - a') ++ " units of time"
ioUnderTest = do
a <- newIORef 0
writeIORef a 3
b <- newIORef []
writeIORef b ["a", "b", "c"]
c <- newIORef 0
writeIORef c 3
putStrLn "done stuff."
d <- newIORef ""
realIoUnderTest a b c d
d' <- readIORef d
if (d' == "This took 4 units of time")
then putStrLn "success!"
else putStrLn "fail!"
ioUnderTest' = do
t0 <- getPOSIXTime
a <- newIORef $ round t0
line1 <- readLn
line2 <- readLn
b <- newIORef [line1, line2]
t1 <- getPOSIXTime
c <- newIORef $ round t1
d <- newIORef ""
realIoUnderTest a b c d
d' <- readIORef d
putStrLn d'
test = ioUnderTest
main = ioUnderTest'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment