cleantest.icl 15.7 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
Steffen Michels's avatar
Steffen Michels committed
27
from Text import <+, class Text(join,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 37 38 39
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
40 41 42 43 44 45 46

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
47 48 49 50 51 52 53
	(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]
54 55 56
	(ExprTuple a,  ExprTuple b)  -> [ {diff & value="_Tuple"}
	                                \\ diff <- gDiff{|*->*|} gDiff{|*|} [x \\ x <-: a] [y \\ y <-: b]
	                                ]
Camil Staps's avatar
Camil Staps committed
57
	(ExprList a,   ExprList b)   -> gDiff{|*|} a b
58 59 60
	(ExprArray a,  ExprArray b)  -> [ {diff & value="_Array"}
	                                \\ diff <- gDiff{|*->*|} gDiff{|*|} [x \\ x <- a] [y \\ y <- b]
	                                ]
Camil Staps's avatar
Camil Staps committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	(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
81 82
	_ -> simpleDiff (toString x) (toString y)

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

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

Camil Staps's avatar
Camil Staps committed
93
:: *ProcessOutput =
94 95 96 97
	{ lines :: ![String]
	, rest  :: !String
	}

Camil Staps's avatar
Camil Staps committed
98
append :: !String !(String .e -> .e) !*ProcessOutput .e -> *(*ProcessOutput, .e)
99 100 101 102 103 104 105 106
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
107

108
:: MessageType = MT_Started | MT_Passed | MT_Failed | MT_Skipped | MT_Lost
109
:: OutputFormat = OF_HumanReadable | OF_JSON
110 111 112 113 114 115 116 117 118 119 120
:: 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

121
:: RunResult =
122
	{ run    :: !TestRun
123 124 125
	, result :: !EndEventType
	}

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
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

141 142 143
derive JSONEncode RunResult, TestRun, EndEventType
derive JSONDecode RunResult, TestRun, EndEventType

144 145 146 147 148 149 150 151 152 153 154 155
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)

156
:: Options =
157 158 159 160 161
	{ test_options          :: !TestOptions
	, strategy              :: !Strategy
	, output_format         :: !OutputFormat
	, hide                  :: ![MessageType]
	, stop_on_first_failure :: !Bool
162 163 164
	}

derive gDefault MessageType, Options, OutputFormat, Strategy
165
gDefault{|Bool|} = False
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

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)"
Camil Staps's avatar
Camil Staps committed
193
	, Shorthand "-F" "--stop-on-first-failure" $ Flag
194 195 196
		"--stop-on-first-failure"
		(\opts -> Ok {opts & stop_on_first_failure = True})
		"Stop after the first test failed"
197 198 199 200 201 202 203 204 205 206
	, 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 <+ "'"]
207

208 209 210 211
:: SubTestRun
	= JustRun           !TestRun
	| Only    ![String] !TestRun
	| Without ![String] !TestRun
212

Camil Staps's avatar
Camil Staps committed
213
Start w
214
// Parse command line arguments
Camil Staps's avatar
Camil Staps committed
215
# ([prog:args],w) = getCommandLine w
216 217
# opts = parseOptions optionDescription args gDefault{|*|}
| isError opts = exit (join "\n" $ fromError opts) w
Camil Staps's avatar
Camil Staps committed
218
# opts = fromOk opts
Camil Staps's avatar
Camil Staps committed
219 220 221 222 223
| 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
224 225 226 227 228
// 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
229
	Nothing  -> map JustRun opts.test_options.runs
230
	Just res -> makeRuns res opts.strategy opts.test_options.runs
Camil Staps's avatar
Camil Staps committed
231
# (_,rrs,w) = seqSt (runIteration opts) runs (True, [], w)
232 233
// Save results
# (_,f,w) = fopen ".ctest-results.json" FWriteText w
234
# f = f <<< toJSON (mergeResults rrs)
235
# (_,w) = fclose f w
Camil Staps's avatar
Camil Staps committed
236 237
= w
where
Camil Staps's avatar
Camil Staps committed
238 239 240 241 242
	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)
243

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

247 248
	makeRuns :: [RunResult] Strategy [TestRun] -> [SubTestRun]
	makeRuns _ S_Default runs = map JustRun runs
249
	makeRuns results S_FailedFirst runs =
250 251 252 253
		map (uncurry (flip Only)) failed_children ++
		map JustRun failed ++
		map (uncurry (flip Without)) failed_children ++
		map JustRun not_failed
254
	where
255 256
		failed_children = [(run, map fst cs) \\ {run,result=Failed (Just (FailedChildren cs))} <- results]
		failed = [run \\ {run,result=Failed fr} <- results | not (fr=:(Just (FailedChildren _)))]
257 258 259 260 261 262
		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
263 264 265 266 267 268 269 270 271 272 273 274
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)

275
run :: !Options !SubTestRun !*World -> *(!RunResult, !*World)
276
run opts r w
Camil Staps's avatar
Camil Staps committed
277
# (io,w) = stdio w
278 279 280 281 282
# 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
283
	Without names r -> (\(all,w) -> (case difference all names of
284
		[] -> Nothing
Camil Staps's avatar
Cleanup  
Camil Staps committed
285
		_  -> Just ["--skip":intersperse "--skip" names], r, w)) $ list r w
286 287 288 289 290 291 292 293 294
| 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
295 296
| isError h
	# (err,msg) = fromError h
297
	# event = Failed Nothing
298
	# io = emit (EndEvent
299
		{ name    = r.TestRun.name
300
		, event   = event
301
		, message = "Failed to execute " <+ r.TestRun.name <+ " (" <+ err <+ "; " <+ msg <+ ")"
302
		}) io
303
	= return event r io w
Camil Staps's avatar
Camil Staps committed
304 305
# (h,pio) = fromOk h
# w = snd $ fclose io w
306
= redirect {lines=[], rest=""} h pio r w
Camil Staps's avatar
Camil Staps committed
307
where
Camil Staps's avatar
Camil Staps committed
308
	redirect :: *ProcessOutput ProcessHandle ProcessIO TestRun *World -> *(!RunResult, !*World)
309
	redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
310 311
	# (io,w) = stdio w
	// Check child output
312 313 314 315 316 317
	# (continue,output,io,w) = readPipes output pio io w
	| isError continue = return (Failed Nothing) r io w
	| continue =: (Ok False)
		# results = map (fromJSON o fromString) $ filter ((<>) "") output.lines
		# ee = mergeResults $ map fromJust results
		= return ee.event r io w
Camil Staps's avatar
Camil Staps committed
318 319 320 321
	// Check if child has terminated
	# (t,w) = checkProcess h w
	| isError t
		# (err,msg) = fromError t
322
		# event = Failed Nothing
323
		# io = emit (EndEvent
324
			{ name    = r.TestRun.name
325
			, event   = event
326
			, message = "Failed to check on child process (" <+ err <+ "; " <+ msg <+ ")"
327
			}) io
328
		= return event r io w
Camil Staps's avatar
Camil Staps committed
329 330
	# rcode = fromOk t
	// Check return code
331
	| isJust rcode
Camil Staps's avatar
Camil Staps committed
332
		# (_,output,io,w) = readPipes output pio io w
333
		# results = map (fromJSON o fromString) $ filter ((<>) "") output.lines
Camil Staps's avatar
Camil Staps committed
334
		| any isNothing results
335
			# event = Failed Nothing
336
			# io = emit (EndEvent
337
				{ name    = r.TestRun.name
338
				, event   = event
339
				, message = join "\n    "
Steffen Michels's avatar
Steffen Michels committed
340
					[ "Failed to read child messages:"
341
					: [printToString (ellipsis 40 outp) \\ outp <- output.lines & Nothing <- results]
Steffen Michels's avatar
Steffen Michels committed
342
					]
343
				}) io
344 345 346 347
				with
					ellipsis n s
					| size s <= n = s
					| otherwise   = s % (0,n-4) +++ "..."
348
			= return event r io w
349 350
		# ee = mergeResults $ map fromJust results
		# io = emit (EndEvent ee) io
351 352 353 354 355 356 357 358 359
		| 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
360
		= return ee.event r io w
Camil Staps's avatar
Camil Staps committed
361
	# w = snd $ fclose io w
362
	= redirect output h pio r w
Camil Staps's avatar
Camil Staps committed
363 364 365
	where
		mergeResults :: [TestEvent] -> EndEvent
		mergeResults tes =
366
			{ name    = r.TestRun.name
367
			, event   = if (isEmpty failed && isEmpty lost) Passed
368
				(Failed $ Just $ FailedChildren $
369
					[(name, fr) \\ EndEvent {name,event=Failed fr} <- failed] ++
370
					[(l, Just Crashed) \\ l <- lost])
Camil Staps's avatar
Camil Staps committed
371
			, message =
372 373 374 375
				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
376 377
			}
		where
378 379 380 381 382 383 384
			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]
385

386
		readPipes :: !*ProcessOutput !ProcessIO !*File !*World -> *(!MaybeOSError Bool, !*ProcessOutput, !*File, !*World)
Camil Staps's avatar
Camil Staps committed
387 388 389 390 391 392 393 394 395 396 397 398
		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
Camil Staps's avatar
Camil Staps committed
399 400 401 402 403 404 405 406 407
		# (output,(continue,io)) = append out
			(\s (continue,io)
				| not continue && opts.stop_on_first_failure
					-> (continue, io)
					-> case fromJSON $ fromString s of
						Nothing -> (False, io)
						Just ev -> (not $ ev=:(EndEvent {event=Failed _}), emit ev io))
			output
			(True, io)
Camil Staps's avatar
Camil Staps committed
408
		# w = snd $ fclose (stderr <<< err) w
409
		= (Ok continue, output, io, w)
Camil Staps's avatar
Camil Staps committed
410

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

443 444 445 446 447
				printCE :: CounterExample -> String
				printCE ce = join " " (map toString ce.counterExample) +++ case ce.failedAssertions of
					[]  -> ""
					fas -> ":\n" +++ join "\n" (map printFA ce.failedAssertions)

448 449
	return :: !EndEventType !TestRun !*File !*World -> *(!RunResult, !*World)
	return eet r io w
450
	# (_,w) = fclose io w
451 452 453
	# w = case eet of
		Failed _ -> setReturnCode 1 w
		_        -> w
454
	= ({run=r, result=eet}, w)