packages feed

arduino-copilot-1.5.5: test.hs

-- The examples also constitute the test suite: Make sure they all compile.

import Control.Monad
import Control.Exception
import System.Directory
import System.IO
import System.IO.Temp
import System.Process
import System.Exit

import qualified Examples.Blink.Demo
import qualified Examples.Button.Demo
import qualified Examples.EEPROM.Demo
import qualified Examples.EEPROMrange.Demo
import qualified Examples.Random.Demo
import qualified Examples.Robot.Demo
import qualified Examples.SerialPort.Demo
import qualified Examples.WaterHeater.Demo
import qualified Examples.ButtonHold.Demo

data TestCase = TestCase
	{ desc :: String
	, builder :: IO ()
	, compileC :: Bool
	}

tests :: [TestCase]
tests =
	[ TestCase "Blink" Examples.Blink.Demo.main True
	, TestCase "Button" Examples.Button.Demo.main True
	-- EEPROM needs an additional arduino libraries installed to
	-- compile the generated C code, so that is skipped.
	, TestCase "EEPROM" Examples.EEPROM.Demo.main False
	, TestCase "EEPROMrange" Examples.EEPROMrange.Demo.main False
	, TestCase "Random" Examples.Random.Demo.main True
	, TestCase "Robot" Examples.Robot.Demo.main True
	, TestCase "SerialPort" Examples.SerialPort.Demo.main True
	, TestCase "WaterHeater" Examples.WaterHeater.Demo.main True
	, TestCase "ButtonHold" Examples.ButtonHold.Demo.main True
	]

main :: IO ()
main = do
	canccompile <- doesFileExist arduinoMakefile
	unless canccompile $
		putStrLn $ "Skipping C compilation tests, did not find Arduino-Makefile installed in " ++ arduinoMakefile
	forM_ tests (runtest canccompile)

runtest :: Bool -> TestCase -> IO ()
runtest canccompile t = withSystemTempDirectory "arduino-copilot-test" $ \tmpdir ->
	bracket (setup tmpdir) cleanup (const copilottest)
  where
	setup tmpdir = do
		setCurrentDirectory tmpdir
	cleanup _ = return ()
	
	copilottest = do
		putStr (desc t ++ " copilot ")
		hFlush stdout
		r <- try' (builder t)
		case r of
			Right () -> do
				putStrLn "OK"
				hFlush stdout
				ccompiletest
			Left ex ->
				 putStrLn ("FAILED: " ++ show ex)

	ccompiletest = when (canccompile && compileC t) $ do
		putStr (desc t ++ " C compilation ")
		writeFile "Makefile" $ unlines
			-- All examples currently use uno.
			[ "BOARD_TAG = uno"
			, "include " ++ arduinoMakefile
			]
		r <- readCreateProcessWithExitCode (proc "make" []) ""
		case r of
			(ExitSuccess, _, _) ->
				putStrLn "OK"
			(_, _out, err) -> do
				putStrLn "FAILED"
				putStrLn err

	try' :: IO () -> IO (Either SomeException ())
	try' = try

-- This is the location it's installed to on a Debian system
-- by apt-get install arduino-mk
arduinoMakefile :: FilePath
arduinoMakefile = "/usr/share/arduino/Arduino.mk"