cleantest.icl 15.4 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

Camil Staps's avatar
Camil Staps committed
12
from Control.Monad import class Monad, mapM
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
Camil Staps's avatar
Camil Staps committed
27
from Text import <+, class Text(join,lpad,replaceSubString,split,trim,concat), instance Text String
28
import Text.GenJSON
29
import Text.GenParse
Camil Staps's avatar
Camil Staps committed
30
import Text.GenPrint
Camil Staps's avatar
Camil Staps committed
31
import Text.Language
Camil Staps's avatar
Camil Staps committed
32

Camil Staps's avatar
Camil Staps committed
33 34 35 36
import Testing.JUnitExport
import Testing.Util
import Util.ProcessOutput

Camil Staps's avatar
Camil Staps committed
37 38 39 40 41 42 43
derive gDiff GenConsAssoc, Maybe, JSONNode
derive gPrint Expression, JSONNode

gDiff{|Expression|} x y = case (x,y) of
	(JSON x,   JSON y)   -> gDiff{|*|} x y
	(GPrint x, GPrint y) -> gDiff{|*|} (preParseString x) (preParseString y)
	_                    -> simpleDiff (printToString x) (printToString y)
Camil Staps's avatar
Camil Staps committed
44 45 46 47 48 49 50

gDiff{|Expr|} x y = case (x,y) of
	(ExprInt a,    ExprInt b)    -> gDiff{|*|} a b
	(ExprChar a,   ExprChar b)   -> gDiff{|*|} a b
	(ExprBool a,   ExprBool b)   -> gDiff{|*|} a b
	(ExprReal a,   ExprReal b)   -> gDiff{|*|} a b
	(ExprString a, ExprString b) -> gDiff{|*|} a b
Steffen Michels's avatar
Steffen Michels committed
51 52 53 54 55 56 57
	(ExprApp a, ExprApp b) | a.[0] == b.[0] -> [
			{ status   = parentStatus argDiffs
			, value    = toString a.[0]
			, children = argDiffs
			}]
	where
		argDiffs = flatten [gDiff{|*|} x y \\ x <-: a & y <-: b & n <- [0..] | n > 0]
58 59 60
	(ExprTuple a,  ExprTuple b)  -> [ {diff & value="_Tuple"}
	                                \\ diff <- gDiff{|*->*|} gDiff{|*|} [x \\ x <-: a] [y \\ y <-: b]
	                                ]
Camil Staps's avatar
Camil Staps committed
61
	(ExprList a,   ExprList b)   -> gDiff{|*|} a b
62 63 64
	(ExprArray a,  ExprArray b)  -> [ {diff & value="_Array"}
	                                \\ diff <- gDiff{|*->*|} gDiff{|*|} [x \\ x <- a] [y \\ y <- b]
	                                ]
Camil Staps's avatar
Camil Staps committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	(ExprRecord r1 xs, ExprRecord r2 ys) | r1 == r2 -> [
			{ status   = parentStatus field_diffs
			, value    = fromMaybe "<unnamed record>" r1
			, children = field_diffs
			}]
		with
			field_diffs =
				[ let ds = gDiff{|*|} (find k xs) (find k ys) in
					{status=parentStatus ds, value=k +++ "=", children=ds} \\ k <- both] ++
				[{status=OnlyLeft,  value=k +++ "=", children=[{status=OnlyLeft,  value=toString (find k xs), children=[]}]} \\ k <- xonly] ++
				[{status=OnlyRight, value=k +++ "=", children=[{status=OnlyRight, value=toString (find k ys), children=[]}]} \\ k <- yonly]

			xkeys = [k \\ ExprField k _ <-: xs]
			ykeys = [k \\ ExprField k _ <-: ys]
			both = intersect xkeys ykeys
			xonly = difference xkeys ykeys
			yonly = difference ykeys xkeys
			find k vs = case [e \\ ExprField f e <-: vs | f == k] of
				[e:_] -> e
				_     -> abort "gDiff_Expr: internal error\n"
Camil Staps's avatar
Camil Staps committed
85 86
	_ -> simpleDiff (toString x) (toString y)

Steffen Michels's avatar
Steffen Michels committed
87 88 89
parentStatus :: [Diff] -> DiffStatus
parentStatus diffs = if (all (\d -> d.status == Common) diffs) Common Changed

Camil Staps's avatar
Camil Staps committed
90
simpleDiff :: !String !String -> [Diff]
Steffen Michels's avatar
Steffen Michels committed
91 92 93 94 95
simpleDiff left right
	| left == right =  [ {status=Common,    value=left,  children=[]} ]
	| otherwise     =  [ {status=OnlyLeft,  value=left,  children=[]}
	                   , {status=OnlyRight, value=right, children=[]}
	                   ]
96

97
:: MessageType = MT_Started | MT_Passed | MT_Failed | MT_Skipped | MT_Lost
98
:: OutputFormat = OF_HumanReadable | OF_JSON
99 100 101 102 103 104 105 106 107 108 109 110
:: 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

:: Options =
111 112 113
	{ test_options          :: !TestOptions
	, strategy              :: !Strategy
	, output_format         :: !OutputFormat
Camil Staps's avatar
Camil Staps committed
114
	, output_junit_file     :: !Maybe FilePath
115 116
	, hide                  :: ![MessageType]
	, stop_on_first_failure :: !Bool
117 118
	}

Camil Staps's avatar
Camil Staps committed
119
derive gDefault MessageType, Options, OutputFormat, Strategy, Maybe
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

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)"
Camil Staps's avatar
Camil Staps committed
142 143 144 145 146
	, Option
		"--junit"
		(\f opts -> Ok {opts & output_junit_file=Just f})
		"FILE"
		"Output test results in JUnit XML format to FILE"
147 148 149 150 151
	, 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)"
Camil Staps's avatar
Camil Staps committed
152
	, Shorthand "-F" "--stop-on-first-failure" $ Flag
153 154 155
		"--stop-on-first-failure"
		(\opts -> Ok {opts & stop_on_first_failure = True})
		"Stop after the first test failed"
156 157 158 159 160 161 162 163 164 165
	, 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 <+ "'"]
166

167 168 169 170
:: SubTestRun
	= JustRun           !TestRun
	| Only    ![String] !TestRun
	| Without ![String] !TestRun
171

Camil Staps's avatar
Camil Staps committed
172
Start w
173
// Parse command line arguments
Camil Staps's avatar
Camil Staps committed
174
# ([prog:args],w) = getCommandLine w
175 176
# opts = parseOptions optionDescription args gDefault{|*|}
| isError opts = exit (join "\n" $ fromError opts) w
Camil Staps's avatar
Camil Staps committed
177
# opts = fromOk opts
Camil Staps's avatar
Camil Staps committed
178 179 180 181 182
| 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
183 184 185 186 187
// 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
188
	Nothing  -> map JustRun opts.test_options.runs
189
	Just res -> makeRuns res opts.strategy opts.test_options.runs
Camil Staps's avatar
Camil Staps committed
190
# (_,rrs,w) = seqSt (runIteration opts) runs (True, [], w)
191
// Save results
Camil Staps's avatar
Camil Staps committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
# (ok,f,w) = fopen ".ctest-results.json" FWriteText w
# w = case ok of
	True
		# f = f <<< toJSON (mergeResults rrs)
		# (_,w) = fclose f w
		-> w
	False
		# (_,w) = fclose (stderr <<< "Failed to save .ctest-results.json\n") w
		-> w
// JUnit export
# w = case opts.output_junit_file of
	Nothing
		-> w
	Just junitf
		# (ok,f,w) = fopen junitf FWriteText w
		| not ok
			# (_,w) = fclose (stderr <<< "Failed to open '" <<< junitf <<< "', skipping JUnit export\n") w
			-> w
Camil Staps's avatar
Camil Staps committed
210
		# f = f <<< resultsToJUnitExport rrs
Camil Staps's avatar
Camil Staps committed
211 212
		# (_,w) = fclose f w
		-> w
Camil Staps's avatar
Camil Staps committed
213 214
= w
where
Camil Staps's avatar
Camil Staps committed
215 216 217 218 219
	runIteration :: !Options !SubTestRun !*(!Bool, ![RunResult], !*World) -> *(!Bool, ![RunResult], !*World)
	runIteration opts test (continue,rrs,w)
	| not continue = (False, reverse rrs, w)
	# (r,w) = run opts test w
	= (not $ opts.stop_on_first_failure && r.result=:Failed _, [r:rrs], w)
220

221
	exit :: String *World -> *World
Camil Staps's avatar
Camil Staps committed
222
	exit error w = snd $ fclose (stderr <<< error <<< "\n") $ setReturnCode 1 w
Camil Staps's avatar
Camil Staps committed
223

224 225
	makeRuns :: [RunResult] Strategy [TestRun] -> [SubTestRun]
	makeRuns _ S_Default runs = map JustRun runs
226
	makeRuns results S_FailedFirst runs =
227 228 229 230
		map (uncurry (flip Only)) failed_children ++
		map JustRun failed ++
		map (uncurry (flip Without)) failed_children ++
		map JustRun not_failed
231
	where
232 233
		failed_children = [(run, map fst cs) \\ {run,result=Failed (Just (FailedChildren cs))} <- results]
		failed = [run \\ {run,result=Failed fr} <- results | not (fr=:(Just (FailedChildren _)))]
234 235 236 237 238 239
		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
240 241 242 243 244 245 246 247 248 249 250 251
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)

252
run :: !Options !SubTestRun !*World -> *(!RunResult, !*World)
253
run opts r w
Camil Staps's avatar
Camil Staps committed
254
# (io,w) = stdio w
255 256 257 258 259
# 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
260
	Without names r -> (\(all,w) -> (case difference all names of
261
		[] -> Nothing
Camil Staps's avatar
Cleanup  
Camil Staps committed
262
		_  -> Just ["--skip":intersperse "--skip" names], r, w)) $ list r w
263 264 265 266 267 268
| isNothing extra_opts
	# io = emit (EndEvent
		{ name    = r.TestRun.name
		, event   = Passed
		, message = "No remaining tests"
		}) io
Camil Staps's avatar
Camil Staps committed
269
	= return Passed [] r io w
270 271
# extra_opts = fromJust extra_opts
# (h,w) = runProcessIO r.TestRun.name (r.options ++ extra_opts) Nothing w
Camil Staps's avatar
Camil Staps committed
272 273
| isError h
	# (err,msg) = fromError h
274
	# event = Failed Nothing
275
	# io = emit (EndEvent
276
		{ name    = r.TestRun.name
277
		, event   = event
278
		, message = "Failed to execute " <+ r.TestRun.name <+ " (" <+ err <+ "; " <+ msg <+ ")"
279
		}) io
Camil Staps's avatar
Camil Staps committed
280
	= return event [] r io w
Camil Staps's avatar
Camil Staps committed
281 282
# (h,pio) = fromOk h
# w = snd $ fclose io w
283
= redirect {lines=[], rest=""} h pio r w
Camil Staps's avatar
Camil Staps committed
284
where
Camil Staps's avatar
Camil Staps committed
285
	redirect :: !*ProcessOutput !ProcessHandle !ProcessIO !TestRun *World -> *(!RunResult, !*World)
286
	redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
287 288
	# (io,w) = stdio w
	// Check child output
289
	# (continue,output,io,w) = readPipes output pio io w
Camil Staps's avatar
Camil Staps committed
290
	| isError continue = return (Failed Nothing) [] r io w
291
	| continue=:(Ok False)
292
		# results = map (fromJSON o fromString) $ filter ((<>) "") output.lines
Camil Staps's avatar
Camil Staps committed
293 294
		# events = map fromJust results
		= return (collectEvents events).event [ee \\ EndEvent ee <- events] r io w
Camil Staps's avatar
Camil Staps committed
295 296 297 298
	// Check if child has terminated
	# (t,w) = checkProcess h w
	| isError t
		# (err,msg) = fromError t
299
		# event = Failed Nothing
300
		# io = emit (EndEvent
301
			{ name    = r.TestRun.name
302
			, event   = event
303
			, message = "Failed to check on child process (" <+ err <+ "; " <+ msg <+ ")"
304
			}) io
Camil Staps's avatar
Camil Staps committed
305
		= return event [] r io w
Camil Staps's avatar
Camil Staps committed
306 307
	# rcode = fromOk t
	// Check return code
308
	| isJust rcode
Camil Staps's avatar
Camil Staps committed
309
		# (_,output,io,w) = readPipes output pio io w
310
		# results = map (fromJSON o fromString) $ filter ((<>) "") output.lines
Camil Staps's avatar
Camil Staps committed
311
		| any isNothing results
312
			# event = Failed Nothing
313
			# io = emit (EndEvent
314
				{ name    = r.TestRun.name
315
				, event   = event
316
				, message = join "\n    "
Steffen Michels's avatar
Steffen Michels committed
317
					[ "Failed to read child messages:"
318
					: [printToString (ellipsis 40 outp) \\ outp <- output.lines & Nothing <- results]
Steffen Michels's avatar
Steffen Michels committed
319
					]
320
				}) io
321 322 323 324
				with
					ellipsis n s
					| size s <= n = s
					| otherwise   = s % (0,n-4) +++ "..."
Camil Staps's avatar
Camil Staps committed
325 326 327
			= return event [] r io w
		# events = map fromJust results
		# ee = collectEvents events
328
		# io = emit (EndEvent ee) io
329 330
		| fromJust rcode <> 0
			# event = Failed Nothing
331 332
			| ee.event=:(Failed (Just (FailedChildren _)))
				// We already have a FailedChildren message; no need for another about the exit code
Camil Staps's avatar
Camil Staps committed
333
				= return event [ee \\ EndEvent ee <- events] r io w
334 335 336 337 338 339
			# io = emit ( EndEvent  { name    = r.TestRun.name
			                        , event   = event
			                        , message = "Child process exited with " <+ fromJust rcode
			                        }
			            )
			            io
Camil Staps's avatar
Camil Staps committed
340 341
			= return event [ee \\ EndEvent ee <- events] r io w
		= return ee.event [ee \\ EndEvent ee <- events] r io w
Camil Staps's avatar
Camil Staps committed
342
	# w = snd $ fclose io w
343
	= redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
344
	where
345 346
		collectEvents :: [TestEvent] -> EndEvent
		collectEvents tes =
347
			{ name    = r.TestRun.name
348
			, event   = if (isEmpty failed && isEmpty lost) Passed
349
				(Failed $ Just $ FailedChildren $
350
					[(name, fr) \\ EndEvent {name,event=Failed fr} <- failed] ++
351
					[(l, Just Crashed) \\ l <- lost])
Camil Staps's avatar
Camil Staps committed
352
			, message =
353 354 355 356
				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
357 358
			}
		where
359 360 361 362 363 364 365
			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]
366

367
		readPipes :: !*ProcessOutput !ProcessIO !*File !*World -> *(!MaybeOSError Bool, !*ProcessOutput, !*File, !*World)
Camil Staps's avatar
Camil Staps committed
368
		readPipes output pio io w
369 370 371 372 373 374
		# (out,w) = readPipeBlocking pio.stdOut w
		# (err,w) = readPipeNonBlocking pio.stdErr w
		| isError out || isError err
			# oserr=:(err,msg) = case out of
				Error e -> e
				_       -> fromError err
Camil Staps's avatar
Camil Staps committed
375 376 377 378 379 380 381
			# 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)
382 383
		# out = fromOk out
		# err = fromOk err
Camil Staps's avatar
Camil Staps committed
384 385 386 387 388
		# (output,(continue,io)) = append out
			(\s (continue,io)
				| not continue && opts.stop_on_first_failure
					-> (continue, io)
					-> case fromJSON $ fromString s of
389
						Nothing -> (True, io)
Camil Staps's avatar
Camil Staps committed
390 391 392
						Just ev -> (not $ ev=:(EndEvent {event=Failed _}), emit ev io))
			output
			(True, io)
Camil Staps's avatar
Camil Staps committed
393
		# continue = continue || not opts.stop_on_first_failure
Camil Staps's avatar
Camil Staps committed
394
		# w = snd $ fclose (stderr <<< err) w
395
		= (Ok continue, output, io, w)
Camil Staps's avatar
Camil Staps committed
396

397 398 399
	emit :: TestEvent *File -> *File
	emit ev io
	| isMember (messageType ev) opts.hide = io
400
	| otherwise = case opts.output_format of
401 402 403 404 405
		OF_JSON          -> io <<< toJSON ev <<< "\n"
		OF_HumanReadable -> io <<< humanReadable ev <<< "\n"
	where
		humanReadable :: TestEvent -> String
		humanReadable (StartEvent se) = "Started:  " +++ se.StartEvent.name
406
		humanReadable (EndEvent ee) = event +++ ee.EndEvent.name +++ diff
407 408
		where
			event = case ee.event of
409 410 411
				Passed   -> "\033[0;32mPassed\033[0m:   "
				Failed _ -> "\033[0;31mFailed\033[0m:   "
				Skipped  -> "\033[0;33mSkipped\033[0m:  "
412
			diff = case ee.event of
413 414 415 416
				Failed (Just r) -> case r of
					FailedAssertions fas -> "\n  Failed assumptions:\n    " +++
						replaceSubString "\n" "\n    "
							(replaceSubString "\t" "  " $ join "\n" $ map printFA fas)
417 418
					CounterExamples ces  -> "\n  Counter-examples:\n  - " +++
						join "\n  - " (map (replaceSubString "\n" "\n    " o printCE) ces)
419 420
					FailedChildren fcs   -> "\n  Children tests failed: " +++ join ", " (map fst fcs)
					Crashed              -> "\n  Crashed"
421
				Failed Nothing -> "\n  " +++ ee.message
422 423 424 425
				_ -> ""
			where
				printFA :: FailedAssertion -> String
				printFA (ExpectedRelation x rel y) = "Expected " +++ toString rel +++ " on:\n" +++ case rel of
Camil Staps's avatar
Camil Staps committed
426
					Eq -> diffToConsole $ gDiff{|*|} x y
427 428
					_  -> toString x +++ "\n" +++ toString y

429 430 431 432 433
				printCE :: CounterExample -> String
				printCE ce = join " " (map toString ce.counterExample) +++ case ce.failedAssertions of
					[]  -> ""
					fas -> ":\n" +++ join "\n" (map printFA ce.failedAssertions)

Camil Staps's avatar
Camil Staps committed
434 435
	return :: !EndEventType ![EndEvent] !TestRun !*File !*World -> *(!RunResult, !*World)
	return eet children r io w
436
	# (_,w) = fclose io w
437 438 439
	# w = case eet of
		Failed _ -> setReturnCode 1 w
		_        -> w
Camil Staps's avatar
Camil Staps committed
440
	= ({run=r, result=eet, children=children}, w)