Created
October 27, 2015 14:27
-
-
Save fujimura/58ff6782e881f0d49455 to your computer and use it in GitHub Desktop.
Run program with mocked stdin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Exception | |
import GHC.IO.Handle | |
import System.IO | |
import System.IO.Temp | |
main :: IO () | |
main = do | |
runWithStdin "Ornette Coleman Trio\nAt the Golden Circle Stockholm" $ do | |
getLine >>= putStrLn | |
getLine >>= putStrLn | |
runWithStdin "Albert Ayler\nSpiritual Unity" $ do | |
getLine >>= putStrLn | |
getLine >>= putStrLn | |
runWithStdin :: String -> IO () -> IO () | |
runWithStdin input action = do | |
withSystemTempFile "runWithInput" $ \path handle -> do | |
hPutStrLn handle input | |
hClose handle | |
handle' <- openFile path ReadMode | |
stdin' <- hDuplicate stdin | |
hDuplicateTo handle' stdin | |
finally action $ do | |
hDuplicateTo stdin' stdin | |
hClose handle' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment