module Test.Torch.Run (run) where

import Control.Monad (forM_)
import Control.Monad.Writer (execWriterT)

import Test.Torch.Types hiding (run)
import Test.Torch.Report (makeReportWithHook, zeroHook)
import Test.Torch.Build (Builder, runBuilder, getTests)
import Test.Torch.Hook

{-|

  'run' takes a builder (do block contains some tests such as 'is' or
  'notOk'), and build test from builder, run it, and report to stdout.

  You can define your own 'run', see 'makeReportWithHook'.

 -}

run :: Builder a -> IO ()
run builder = do
  tests <- getTests builder
  report <- get_report tests
  print_report report

get_report :: Tests -> IO Report
get_report = flip makeReportWithHook $ asHook $ do
               onPass $ putChar '.'
               onFail $ const $ putChar 'f'
               beforeTest $ \ts ->
                 putStrLn $ "Running " ++ show (length ts) ++ " tests."

print_report :: Report -> IO ()
print_report r = do
  if failed r == 0
    then putStrLn "\nOk, All tests passed."
    else do
      putStrLn $ '\n' : show (failed r) ++ " test(s) failed."
      forM_ (failures r) $ putStrLn . describe