cleantest.icl 12.1 KB
Newer Older
Camil Staps's avatar
Camil Staps committed
1
module cleantest
Bas Lijnse's avatar
Bas Lijnse committed
2

3
import StdArray
4
import StdBool
Camil Staps's avatar
Camil Staps committed
5
import StdFile
6
from StdFunc import flip, o
Camil Staps's avatar
Camil Staps committed
7
import StdList
8
import StdMisc
Camil Staps's avatar
Camil Staps committed
9
import StdString
Camil Staps's avatar
Camil Staps committed
10
import StdTuple
Camil Staps's avatar
Camil Staps committed
11

12
import Control.Monad => qualified join
Camil Staps's avatar
Camil Staps committed
13
import Data.Error
14 15
from Data.Func import $, mapSt, seqSt
import Data.Functor
16 17
import Data.GenDiff
import Data.GenEq
18
import Data.List
Camil Staps's avatar
Camil Staps committed
19
import Data.Maybe
20
import Data.Tuple
Camil Staps's avatar
Camil Staps committed
21 22
import System.CommandLine
import System.FilePath
23
import System.Options
Camil Staps's avatar
Camil Staps committed
24
import System.Process
25
import Testing.Options
Camil Staps's avatar
Camil Staps committed
26
import Testing.TestEvents
27
from Text import <+, class Text(join,replaceSubString,split,trim), instance Text String
28
import Text.GenJSON
29
import Text.GenParse
Camil Staps's avatar
Camil Staps committed
30
import Text.Language
Camil Staps's avatar
Camil Staps committed
31

32
derive gDiff GenConsAssoc, Maybe, Expr
33

Camil Staps's avatar
Camil Staps committed
34
:: *ProcessOutput =
35 36 37 38
	{ lines :: ![String]
	, rest  :: !String
	}

Camil Staps's avatar
Camil Staps committed
39
append :: !String !(String .e -> .e) !*ProcessOutput .e -> *(*ProcessOutput, .e)
40 41 42 43 44 45 46 47
append s f out env
# out & rest = out.rest +++ s
# lines = split "\n" out.rest
| length lines == 1 = (out, env)
# env = seqSt f (init lines) env
# out & lines = out.lines ++ init lines
# out & rest  = last lines
= (out, env)
Camil Staps's avatar
Camil Staps committed
48

49 50 51 52 53 54 55 56 57 58 59 60 61
:: MessageType = MT_Started | MT_Passed | MT_Failed | MT_Skipped | MT_Lost
:: OutputFormat = OF_JSON | OF_HumanReadable
:: Strategy = S_Default | S_FailedFirst

messageType :: TestEvent -> MessageType
messageType (StartEvent _) = MT_Started
messageType (EndEvent ee) = case ee.event of
	Passed   -> MT_Passed
	Failed _ -> MT_Failed
	Skipped  -> MT_Skipped

derive gEq MessageType; instance == MessageType where == a b = a === b

62
:: RunResult =
63
	{ run    :: !TestRun
64 65 66
	, result :: !EndEventType
	}

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
mergeResults :: ![RunResult] -> [RunResult]
mergeResults [] = []
mergeResults [rr:rrs] = case partition (\rr` -> rr.run.TestRun.name == rr`.run.TestRun.name) rrs of
	([], rrs)    -> [rr:mergeResults rrs]
	([rr`], rrs) -> [{rr & result=merge rr.result rr`.result}:mergeResults rrs]
where
	merge :: !EndEventType !EndEventType -> EndEventType
	merge (Failed (Just r1)) (Failed (Just r2)) = case (r1,r2) of
		(FailedChildren cs1, FailedChildren cs2) -> Failed $ Just $ FailedChildren $ cs1 ++ cs2
	merge (Failed r) _ = Failed r
	merge _ (Failed r) = Failed r
	merge Skipped _       = Skipped
	merge _       Skipped = Skipped
	merge Passed  Passed  = Passed

82 83 84
derive JSONEncode RunResult, TestRun, EndEventType
derive JSONDecode RunResult, TestRun, EndEventType

85 86 87 88 89 90 91 92 93 94 95 96
instance <<< RunResult where <<< f rr = f <<< toJSON rr <<< "\n"

readResults :: !*File -> *(!Maybe [RunResult], !*File)
readResults f
# (e,f) = fend f
| e = (Just [], f)
# (l,f) = freadline f
# rr = fromJSON $ fromString l
| isNothing rr = (Nothing, f)
# (rrs,f) = readResults f
= ((\rrs -> [fromJust rr:rrs]) <$> rrs, f)

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
:: Options =
	{ test_options  :: !TestOptions
	, strategy      :: !Strategy
	, output_format :: !OutputFormat
	, hide          :: ![MessageType]
	}

derive gDefault MessageType, Options, OutputFormat, Strategy

optionDescription :: Option Options
optionDescription = WithHelp True $ Options
	[ Shorthand "-s" "--strategy" $ AddHelpLines
		[ "default       Order of the --run parameters"
		, "failed-first  First run tests that failed last time; if they passed continue with the rest"
		] $ Option
		"--strategy"
		(\s opts -> case s of
			"default"      -> Ok {opts & strategy=S_Default}
			"failed-first" -> Ok {opts & strategy=S_FailedFirst}
			s              -> Error ["Unknown strategy '" <+ s <+ "'"])
		"STRATEGY"
		"The test order strategy:"
	, Shorthand "-f" "--output-format" $ Option
		"--output-format"
		(\f opts -> case f of
			"json"  -> Ok {opts & output_format=OF_JSON}
			"human" -> Ok {opts & output_format=OF_HumanReadable}
			f       -> Error ["Unknown output format '" <+ f <+ "'"])
		"FMT"
		"The output format (json,human)"
	, Shorthand "-H" "--hide" $ Option
		"--hide"
		(\mts opts -> (\mts -> {opts & hide=mts}) <$> (mapM parseMT $ split "," mts))
		"TYPES"
		"Message types that should be hidden (start,pass,fail,skip,lost)"
	, Biject (\r->r.test_options) (\old r -> {old & test_options=r}) testOptionDescription
	]
where
	parseMT :: String -> MaybeError [String] MessageType
	parseMT "start" = Ok MT_Started
	parseMT "pass"  = Ok MT_Passed
	parseMT "fail"  = Ok MT_Failed
	parseMT "skip"  = Ok MT_Skipped
	parseMT "lost"  = Ok MT_Lost
	parseMT s       = Error ["Unknown message type '" <+ s <+ "'"]
142

143 144 145 146
:: SubTestRun
	= JustRun           !TestRun
	| Only    ![String] !TestRun
	| Without ![String] !TestRun
147

Camil Staps's avatar
Camil Staps committed
148
Start w
149
// Parse command line arguments
Camil Staps's avatar
Camil Staps committed
150
# ([prog:args],w) = getCommandLine w
151 152
# opts = parseOptions optionDescription args gDefault{|*|}
| isError opts = exit (join "\n" $ fromError opts) w
Camil Staps's avatar
Camil Staps committed
153
# opts = fromOk opts
Camil Staps's avatar
Camil Staps committed
154 155 156 157 158
| opts.test_options.list
	# (io,w) = stdio w
	# io = foldl (<<<) io [r.TestRun.name +++ "\n" \\ r <- opts.test_options.runs]
	# (_,w) = fclose io w
	= w
159 160 161 162 163
// Run tests
# (ok,f,w) = fopen ".ctest-results.json" FReadText w
# (l,f) = if ok freadline (tuple "") f
# (_,w) = fclose f w
# runs = case fromJSON (fromString l) of
164
	Nothing  -> map JustRun opts.test_options.runs
165
	Just res -> makeRuns res opts.strategy opts.test_options.runs
166 167 168
# (rrs,w) = mapSt (run opts) runs w
// Save results
# (_,f,w) = fopen ".ctest-results.json" FWriteText w
169
# f = f <<< toJSON (mergeResults rrs)
170
# (_,w) = fclose f w
Camil Staps's avatar
Camil Staps committed
171 172
= w
where
173
	exit :: String *World -> *World
Camil Staps's avatar
Camil Staps committed
174
	exit error w = snd $ fclose (stderr <<< error <<< "\n") $ setReturnCode 1 w
Camil Staps's avatar
Camil Staps committed
175

176 177
	makeRuns :: [RunResult] Strategy [TestRun] -> [SubTestRun]
	makeRuns _ S_Default runs = map JustRun runs
178
	makeRuns results S_FailedFirst runs =
179 180 181 182
		map (uncurry (flip Only)) failed_children ++
		map JustRun failed ++
		map (uncurry (flip Without)) failed_children ++
		map JustRun not_failed
183
	where
184 185
		failed_children = [(run, map fst cs) \\ {run,result=Failed (Just (FailedChildren cs))} <- results]
		failed = [run \\ {run,result=Failed fr} <- results | not (fr=:(Just (FailedChildren _)))]
186 187 188 189 190 191
		not_failed = [run \\ {run,result=res} <- results | not (res=:(Failed _))]

		prepend :: a [a] -> [a]
		prepend _ []     = []
		prepend p [x:xs] = [p,x:prepend p xs]

Camil Staps's avatar
Cleanup  
Camil Staps committed
192 193 194 195 196 197 198 199 200 201 202 203
list :: !TestRun !*World -> *(![String], !*World)
list r w
# (h,w) = runProcessIO r.TestRun.name ["--list"] Nothing w
| isError h = ([], w)
# (h,io) = fromOk h
# (c,w) = waitForProcess h w
| isError c = ([], w)
# (s,w) = readPipeBlocking io.stdOut w
| isError s = ([], w)
# (_,w) = closeProcessIO io w
= (filter (not o (==) 0 o size) $ map trim $ split "\n" (fromOk s), w)

204
run :: !Options !SubTestRun !*World -> *(!RunResult, !*World)
205
run opts r w
Camil Staps's avatar
Camil Staps committed
206
# (io,w) = stdio w
207 208 209 210 211
# io = emit (StartEvent {StartEvent | name=name}) io
	with name = (case r of JustRun r   -> r; Only _ r    -> r; Without _ r -> r).TestRun.name
# (extra_opts,r,w) = case r of
	JustRun r       -> (Just [], r, w)
	Only names    r -> (Just ["--run":intersperse "--run" names], r, w)
Camil Staps's avatar
Cleanup  
Camil Staps committed
212
	Without names r -> (\(all,w) -> (case difference all names of
213
		[] -> Nothing
Camil Staps's avatar
Cleanup  
Camil Staps committed
214
		_  -> Just ["--skip":intersperse "--skip" names], r, w)) $ list r w
215 216 217 218 219 220 221 222 223
| isNothing extra_opts
	# io = emit (EndEvent
		{ name    = r.TestRun.name
		, event   = Passed
		, message = "No remaining tests"
		}) io
	= return Passed r io w
# extra_opts = fromJust extra_opts
# (h,w) = runProcessIO r.TestRun.name (r.options ++ extra_opts) Nothing w
Camil Staps's avatar
Camil Staps committed
224 225
| isError h
	# (err,msg) = fromError h
226
	# event = Failed Nothing
227
	# io = emit (EndEvent
228
		{ name    = r.TestRun.name
229
		, event   = event
230
		, message = "Failed to execute " <+ r.TestRun.name <+ " (" <+ err <+ "; " <+ msg <+ ")"
231
		}) io
232
	= return event r io w
Camil Staps's avatar
Camil Staps committed
233 234
# (h,pio) = fromOk h
# w = snd $ fclose io w
235
= redirect {lines=[], rest=""} h pio r w
Camil Staps's avatar
Camil Staps committed
236
where
Camil Staps's avatar
Camil Staps committed
237
	redirect :: *ProcessOutput ProcessHandle ProcessIO TestRun *World -> *(!RunResult, !*World)
238
	redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
239 240
	# (io,w) = stdio w
	// Check child output
Camil Staps's avatar
Camil Staps committed
241 242
	# (ok,output,io,w) = readPipes output pio io w
	| isError ok = return (Failed Nothing) r io w
Camil Staps's avatar
Camil Staps committed
243 244 245 246
	// Check if child has terminated
	# (t,w) = checkProcess h w
	| isError t
		# (err,msg) = fromError t
247
		# event = Failed Nothing
248
		# io = emit (EndEvent
249
			{ name    = r.TestRun.name
250
			, event   = event
251
			, message = "Failed to check on child process (" <+ err <+ "; " <+ msg <+ ")"
252
			}) io
253
		= return event r io w
Camil Staps's avatar
Camil Staps committed
254 255
	# rcode = fromOk t
	// Check return code
256
	| isJust rcode
Camil Staps's avatar
Camil Staps committed
257
		# (_,output,io,w) = readPipes output pio io w
258
		# results = map (fromJSON o fromString) $ filter ((<>) "") output.lines
Camil Staps's avatar
Camil Staps committed
259
		| any isNothing results
260
			# event = Failed Nothing
261
			# io = emit (EndEvent
262
				{ name    = r.TestRun.name
263
				, event   = event
264
				, message = "Failed to read child messages"
265
				}) io
266
			= return event r io w
267 268
		# ee = mergeResults $ map fromJust results
		# io = emit (EndEvent ee) io
269 270 271 272 273 274 275 276 277
		| fromJust rcode <> 0
			# event = Failed Nothing
			# io = emit ( EndEvent  { name    = r.TestRun.name
			                        , event   = event
			                        , message = "Child process exited with " <+ fromJust rcode
			                        }
			            )
			            io
			= return event r io w
278
		= return ee.event r io w
Camil Staps's avatar
Camil Staps committed
279
	# w = snd $ fclose io w
280
	= redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
281 282 283
	where
		mergeResults :: [TestEvent] -> EndEvent
		mergeResults tes =
284
			{ name    = r.TestRun.name
285
			, event   = if (isEmpty failed && isEmpty lost) Passed
286
				(Failed $ Just $ FailedChildren $
287
					[(name, fr) \\ EndEvent {name,event=Failed fr} <- failed] ++
288
					[(l, Just Crashed) \\ l <- lost])
Camil Staps's avatar
Camil Staps committed
289
			, message =
290 291 292 293
				pluralisen English (length passed)  "test" <+ " passed, " <+
				pluralisen English (length failed)  "test" <+ " failed, " <+
				pluralisen English (length skipped) "test" <+ " skipped and " <+
				pluralisen English (length lost)    "test" <+ " lost."
Camil Staps's avatar
Camil Staps committed
294 295
			}
		where
296 297 298 299 300 301 302
			passed  = filter (\te -> te=:(EndEvent {event=Passed}))   tes
			failed  = filter (\te -> te=:(EndEvent {event=Failed _})) tes
			skipped = filter (\te -> te=:(EndEvent {event=Skipped}))  tes
			lost = [se.StartEvent.name \\ StartEvent se <- tes
				| not
					$ any (\(EndEvent ee) -> se.StartEvent.name == ee.EndEvent.name)
					$ passed ++ failed ++ skipped]
303

Camil Staps's avatar
Camil Staps committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
		readPipes :: !*ProcessOutput !ProcessIO !*File !*World -> *(!MaybeOSError (), !*ProcessOutput, !*File, !*World)
		readPipes output pio io w
		# (ss,w) = readPipeBlockingMulti [pio.stdOut, pio.stdErr] w
		| isError ss
			# oserr=:(err,msg) = fromError ss
			# event = Failed Nothing
			# io = emit (EndEvent
				{ name    = r.TestRun.name
				, event   = event
				, message = "Failed to read child process IO (" <+ err <+ "; " <+ msg <+ ")"
				}) io
			= (Error oserr, output, io, w)
		# [out,err:_] = fromOk ss
		# (output,io) = append out (\s io -> case fromJSON $ fromString s of
			Nothing -> io
			Just ev -> emit ev io) output io
		# w = snd $ fclose (stderr <<< err) w
		= (Ok (), output, io, w)

323 324 325
	emit :: TestEvent *File -> *File
	emit ev io
	| isMember (messageType ev) opts.hide = io
326
	| otherwise = case opts.output_format of
327 328 329 330 331
		OF_JSON          -> io <<< toJSON ev <<< "\n"
		OF_HumanReadable -> io <<< humanReadable ev <<< "\n"
	where
		humanReadable :: TestEvent -> String
		humanReadable (StartEvent se) = "Started:  " +++ se.StartEvent.name
332
		humanReadable (EndEvent ee) = event +++ ee.EndEvent.name +++ diff
333 334
		where
			event = case ee.event of
335 336 337
				Passed   -> "\033[0;32mPassed\033[0m:   "
				Failed _ -> "\033[0;31mFailed\033[0m:   "
				Skipped  -> "\033[0;33mSkipped\033[0m:  "
338
			diff = case ee.event of
339 340 341 342
				Failed (Just r) -> case r of
					FailedAssertions fas -> "\n  Failed assumptions:\n    " +++
						replaceSubString "\n" "\n    "
							(replaceSubString "\t" "  " $ join "\n" $ map printFA fas)
343 344
					CounterExamples ces  -> "\n  Counter-examples:\n  - " +++
						join "\n  - " (map (replaceSubString "\n" "\n    " o printCE) ces)
345 346
					FailedChildren fcs   -> "\n  Children tests failed: " +++ join ", " (map fst fcs)
					Crashed              -> "\n  Crashed"
347
				Failed Nothing -> "\n  " +++ ee.message
348 349 350 351
				_ -> ""
			where
				printFA :: FailedAssertion -> String
				printFA (ExpectedRelation x rel y) = "Expected " +++ toString rel +++ " on:\n" +++ case rel of
352
					Eq -> diffToConsole $ gDiff{|*|} (preParseString x) (preParseString y)
353 354
					_  -> toString x +++ "\n" +++ toString y

355 356 357 358 359
				printCE :: CounterExample -> String
				printCE ce = join " " (map toString ce.counterExample) +++ case ce.failedAssertions of
					[]  -> ""
					fas -> ":\n" +++ join "\n" (map printFA ce.failedAssertions)

360 361
	return :: !EndEventType !TestRun !*File !*World -> *(!RunResult, !*World)
	return eet r io w
362
	# (_,w) = fclose io w
363 364 365
	# w = case eet of
		Failed _ -> setReturnCode 1 w
		_        -> w
366
	= ({run=r, result=eet}, w)