testament.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. #
  2. #
  3. # Nim Testament
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This program verifies Nim against the testcases.
  10. import
  11. strutils, pegs, os, osproc, streams, json, std/exitprocs,
  12. backend, parseopt, specs, htmlgen, browsers, terminal,
  13. algorithm, times, azure, intsets, macros
  14. from std/sugar import dup
  15. import compiler/nodejs
  16. import lib/stdtest/testutils
  17. from lib/stdtest/specialpaths import splitTestFile
  18. from std/private/gitutils import diffStrings
  19. import ../dist/checksums/src/checksums/md5
  20. proc trimUnitSep(x: var string) =
  21. let L = x.len
  22. if L > 0 and x[^1] == '\31':
  23. setLen x, L-1
  24. var useColors = true
  25. var backendLogging = true
  26. var simulate = false
  27. var optVerbose = false
  28. var useMegatest = true
  29. var valgrindEnabled = true
  30. proc verboseCmd(cmd: string) =
  31. if optVerbose:
  32. echo "executing: ", cmd
  33. const
  34. failString* = "FAIL: " # ensures all failures can be searched with 1 keyword in CI logs
  35. testsDir = "tests" & DirSep
  36. resultsFile = "testresults.html"
  37. Usage = """Usage:
  38. testament [options] command [arguments]
  39. Command:
  40. p|pat|pattern <glob> run all the tests matching the given pattern
  41. all run all tests in category folders
  42. c|cat|category <category> run all the tests of a certain category
  43. r|run <test> run single test file
  44. html generate $1 from the database
  45. Arguments:
  46. arguments are passed to the compiler
  47. Options:
  48. --print print results to the console
  49. --verbose print commands (compiling and running tests)
  50. --simulate see what tests would be run but don't run them (for debugging)
  51. --failing only show failing/ignored tests
  52. --targets:"c cpp js objc" run tests for specified targets (default: c)
  53. --nim:path use a particular nim executable (default: $$PATH/nim)
  54. --directory:dir Change to directory dir before reading the tests or doing anything else.
  55. --colors:on|off Turn messages coloring on|off.
  56. --backendLogging:on|off Disable or enable backend logging. By default turned on.
  57. --megatest:on|off Enable or disable megatest. Default is on.
  58. --valgrind:on|off Enable or disable valgrind support. Default is on.
  59. --skipFrom:file Read tests to skip from `file` - one test per line, # comments ignored
  60. On Azure Pipelines, testament will also publish test results via Azure Pipelines' Test Management API
  61. provided that System.AccessToken is made available via the environment variable SYSTEM_ACCESSTOKEN.
  62. Experimental: using environment variable `NIM_TESTAMENT_REMOTE_NETWORKING=1` enables
  63. tests with remote networking (as in CI).
  64. """ % resultsFile
  65. proc isNimRepoTests(): bool =
  66. # this logic could either be specific to cwd, or to some file derived from
  67. # the input file, eg testament r /pathto/tests/foo/tmain.nim; we choose
  68. # the former since it's simpler and also works with `testament all`.
  69. let file = "testament"/"testament.nim.cfg"
  70. result = file.fileExists
  71. type
  72. Category = distinct string
  73. TResults = object
  74. total, passed, failedButAllowed, skipped: int
  75. ## xxx rename passed to passedOrAllowedFailure
  76. data: string
  77. TTest = object
  78. name: string
  79. cat: Category
  80. options: string
  81. testArgs: seq[string]
  82. spec: TSpec
  83. startTime: float
  84. debugInfo: string
  85. # ----------------------------------------------------------------------------
  86. let
  87. pegLineError =
  88. peg"{[^(]*} '(' {\d+} ', ' {\d+} ') ' ('Error') ':' \s* {.*}"
  89. pegOtherError = peg"'Error:' \s* {.*}"
  90. pegOfInterest = pegLineError / pegOtherError
  91. var gTargets = {low(TTarget)..high(TTarget)}
  92. var targetsSet = false
  93. proc isSuccess(input: string): bool =
  94. # not clear how to do the equivalent of pkg/regex's: re"FOO(.*?)BAR" in pegs
  95. # note: this doesn't handle colors, eg: `\e[1m\e[0m\e[32mHint:`; while we
  96. # could handle colors, there would be other issues such as handling other flags
  97. # that may appear in user config (eg: `--filenames`).
  98. # Passing `XDG_CONFIG_HOME= testament args...` can be used to ignore user config
  99. # stored in XDG_CONFIG_HOME, refs https://wiki.archlinux.org/index.php/XDG_Base_Directory
  100. input.startsWith("Hint: ") and input.endsWith("[SuccessX]")
  101. proc getFileDir(filename: string): string =
  102. result = filename.splitFile().dir
  103. if not result.isAbsolute():
  104. result = getCurrentDir() / result
  105. proc execCmdEx2(command: string, args: openArray[string]; workingDir, input: string = ""): tuple[
  106. cmdLine: string,
  107. output: string,
  108. exitCode: int] {.tags:
  109. [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
  110. result.cmdLine.add quoteShell(command)
  111. for arg in args:
  112. result.cmdLine.add ' '
  113. result.cmdLine.add quoteShell(arg)
  114. verboseCmd(result.cmdLine)
  115. var p = startProcess(command, workingDir = workingDir, args = args,
  116. options = {poStdErrToStdOut, poUsePath})
  117. var outp = outputStream(p)
  118. # There is no way to provide input for the child process
  119. # anymore. Closing it will create EOF on stdin instead of eternal
  120. # blocking.
  121. let instream = inputStream(p)
  122. instream.write(input)
  123. close instream
  124. result.exitCode = -1
  125. var line = newStringOfCap(120)
  126. while true:
  127. if outp.readLine(line):
  128. result.output.add line
  129. result.output.add '\n'
  130. else:
  131. result.exitCode = peekExitCode(p)
  132. if result.exitCode != -1: break
  133. close(p)
  134. proc nimcacheDir(filename, options: string, target: TTarget): string =
  135. ## Give each test a private nimcache dir so they don't clobber each other's.
  136. let hashInput = options & $target
  137. result = "nimcache" / (filename & '_' & hashInput.getMD5)
  138. proc prepareTestCmd(cmdTemplate, filename, options, nimcache: string,
  139. target: TTarget, extraOptions = ""): string =
  140. var options = target.defaultOptions & ' ' & options
  141. if nimcache.len > 0: options.add(" --nimCache:$#" % nimcache.quoteShell)
  142. options.add ' ' & extraOptions
  143. # we avoid using `parseCmdLine` which is buggy, refs bug #14343
  144. result = cmdTemplate % ["target", targetToCmd[target],
  145. "options", options, "file", filename.quoteShell,
  146. "filedir", filename.getFileDir(), "nim", compilerPrefix]
  147. proc callNimCompiler(cmdTemplate, filename, options, nimcache: string,
  148. target: TTarget, extraOptions = ""): TSpec =
  149. result.cmd = prepareTestCmd(cmdTemplate, filename, options, nimcache, target,
  150. extraOptions)
  151. verboseCmd(result.cmd)
  152. var p = startProcess(command = result.cmd,
  153. options = {poStdErrToStdOut, poUsePath, poEvalCommand})
  154. let outp = p.outputStream
  155. var foundSuccessMsg = false
  156. var foundErrorMsg = false
  157. var err = ""
  158. var x = newStringOfCap(120)
  159. result.nimout = ""
  160. while true:
  161. if outp.readLine(x):
  162. trimUnitSep x
  163. result.nimout.add(x & '\n')
  164. if x =~ pegOfInterest:
  165. # `err` should contain the last error message
  166. err = x
  167. foundErrorMsg = true
  168. elif x.isSuccess:
  169. foundSuccessMsg = true
  170. elif not running(p):
  171. break
  172. result.msg = ""
  173. result.file = ""
  174. result.output = ""
  175. result.line = 0
  176. result.column = 0
  177. result.err = reNimcCrash
  178. result.exitCode = p.peekExitCode
  179. close p
  180. case result.exitCode
  181. of 0:
  182. if foundErrorMsg:
  183. result.debugInfo.add " compiler exit code was 0 but some Error's were found."
  184. else:
  185. result.err = reSuccess
  186. of 1:
  187. if not foundErrorMsg:
  188. result.debugInfo.add " compiler exit code was 1 but no Error's were found."
  189. if foundSuccessMsg:
  190. result.debugInfo.add " compiler exit code was 1 but no `isSuccess` was true."
  191. else:
  192. result.debugInfo.add " expected compiler exit code 0 or 1, got $1." % $result.exitCode
  193. if err =~ pegLineError:
  194. result.file = extractFilename(matches[0])
  195. result.line = parseInt(matches[1])
  196. result.column = parseInt(matches[2])
  197. result.msg = matches[3]
  198. elif err =~ pegOtherError:
  199. result.msg = matches[0]
  200. trimUnitSep result.msg
  201. proc initResults: TResults =
  202. result.total = 0
  203. result.passed = 0
  204. result.failedButAllowed = 0
  205. result.skipped = 0
  206. result.data = ""
  207. macro ignoreStyleEcho(args: varargs[typed]): untyped =
  208. let typForegroundColor = bindSym"ForegroundColor".getType
  209. let typBackgroundColor = bindSym"BackgroundColor".getType
  210. let typStyle = bindSym"Style".getType
  211. let typTerminalCmd = bindSym"TerminalCmd".getType
  212. result = newCall(bindSym"echo")
  213. for arg in children(args):
  214. if arg.kind == nnkNilLit: continue
  215. let typ = arg.getType
  216. if typ.kind != nnkEnumTy or
  217. typ != typForegroundColor and
  218. typ != typBackgroundColor and
  219. typ != typStyle and
  220. typ != typTerminalCmd:
  221. result.add(arg)
  222. template maybeStyledEcho(args: varargs[untyped]): untyped =
  223. if useColors:
  224. styledEcho(args)
  225. else:
  226. ignoreStyleEcho(args)
  227. proc `$`(x: TResults): string =
  228. result = """
  229. Tests passed or allowed to fail: $2 / $1 <br />
  230. Tests failed and allowed to fail: $3 / $1 <br />
  231. Tests skipped: $4 / $1 <br />
  232. """ % [$x.total, $x.passed, $x.failedButAllowed, $x.skipped]
  233. proc testName(test: TTest, target: TTarget, extraOptions: string, allowFailure: bool): string =
  234. var name = test.name.replace(DirSep, '/')
  235. name.add ' ' & $target
  236. if allowFailure:
  237. name.add " (allowed to fail) "
  238. if test.options.len > 0: name.add ' ' & test.options
  239. if extraOptions.len > 0: name.add ' ' & extraOptions
  240. name.strip()
  241. proc addResult(r: var TResults, test: TTest, target: TTarget,
  242. extraOptions, expected, given: string, success: TResultEnum, duration: float,
  243. allowFailure = false, givenSpec: ptr TSpec = nil) =
  244. # instead of `ptr TSpec` we could also use `Option[TSpec]`; passing `givenSpec` makes it easier to get what we need
  245. # instead of having to pass individual fields, or abusing existing ones like expected vs given.
  246. # test.name is easier to find than test.name.extractFilename
  247. # A bit hacky but simple and works with tests/testament/tshould_not_work.nim
  248. let name = testName(test, target, extraOptions, allowFailure)
  249. let durationStr = duration.formatFloat(ffDecimal, precision = 2).align(5)
  250. if backendLogging:
  251. backend.writeTestResult(name = name,
  252. category = test.cat.string,
  253. target = $target,
  254. action = $test.spec.action,
  255. result = $success,
  256. expected = expected,
  257. given = given)
  258. r.data.addf("$#\t$#\t$#\t$#", name, expected, given, $success)
  259. template dispNonSkipped(color, outcome) =
  260. maybeStyledEcho color, outcome, fgCyan, test.debugInfo, alignLeft(name, 60), fgBlue, " (", durationStr, " sec)"
  261. template disp(msg) =
  262. maybeStyledEcho styleDim, fgYellow, msg & ' ', styleBright, fgCyan, name
  263. if success == reSuccess:
  264. dispNonSkipped(fgGreen, "PASS: ")
  265. elif success == reDisabled:
  266. if test.spec.inCurrentBatch: disp("SKIP:")
  267. else: disp("NOTINBATCH:")
  268. elif success == reJoined: disp("JOINED:")
  269. else:
  270. dispNonSkipped(fgRed, failString)
  271. maybeStyledEcho styleBright, fgCyan, "Test \"", test.name, "\"", " in category \"", test.cat.string, "\""
  272. maybeStyledEcho styleBright, fgRed, "Failure: ", $success
  273. if givenSpec != nil and givenSpec.debugInfo.len > 0:
  274. echo "debugInfo: " & givenSpec.debugInfo
  275. if success in {reBuildFailed, reNimcCrash, reInstallFailed}:
  276. # expected is empty, no reason to print it.
  277. echo given
  278. else:
  279. maybeStyledEcho fgYellow, "Expected:"
  280. maybeStyledEcho styleBright, expected, "\n"
  281. maybeStyledEcho fgYellow, "Gotten:"
  282. maybeStyledEcho styleBright, given, "\n"
  283. echo diffStrings(expected, given).output
  284. if backendLogging and (isAppVeyor or isAzure):
  285. let (outcome, msg) =
  286. case success
  287. of reSuccess:
  288. ("Passed", "")
  289. of reDisabled, reJoined:
  290. ("Skipped", "")
  291. of reBuildFailed, reNimcCrash, reInstallFailed:
  292. ("Failed", "Failure: " & $success & '\n' & given)
  293. else:
  294. ("Failed", "Failure: " & $success & "\nExpected:\n" & expected & "\n\n" & "Gotten:\n" & given)
  295. if isAzure:
  296. azure.addTestResult(name, test.cat.string, int(duration * 1000), msg, success)
  297. else:
  298. var p = startProcess("appveyor", args = ["AddTest", test.name.replace("\\", "/") & test.options,
  299. "-Framework", "nim-testament", "-FileName",
  300. test.cat.string,
  301. "-Outcome", outcome, "-ErrorMessage", msg,
  302. "-Duration", $(duration * 1000).int],
  303. options = {poStdErrToStdOut, poUsePath, poParentStreams})
  304. discard waitForExit(p)
  305. close(p)
  306. proc finishTest(r: var TResults, test: TTest, target: TTarget,
  307. extraOptions, expected, given: string, successOrig: TResultEnum,
  308. allowFailure = false, givenSpec: ptr TSpec = nil): bool =
  309. result = false
  310. let duration = epochTime() - test.startTime
  311. let success = if test.spec.timeout > 0.0 and duration > test.spec.timeout: reTimeout
  312. else: successOrig
  313. if test.spec.retries > 0 and success notin {reSuccess, reDisabled, reJoined, reInvalidSpec}:
  314. return true
  315. else:
  316. addResult(r, test, target, extraOptions, expected, given, success, duration, allowFailure, givenSpec)
  317. proc toString(inlineError: InlineError, filename: string): string =
  318. result.add "$file($line, $col) $kind: $msg" % [
  319. "file", filename,
  320. "line", $inlineError.line,
  321. "col", $inlineError.col,
  322. "kind", $inlineError.kind,
  323. "msg", $inlineError.msg
  324. ]
  325. proc inlineErrorsMsgs(expected: TSpec): string =
  326. for inlineError in expected.inlineErrors.items:
  327. result.addLine inlineError.toString(expected.filename)
  328. proc checkForInlineErrors(expected, given: TSpec): bool =
  329. for inlineError in expected.inlineErrors:
  330. if inlineError.toString(expected.filename) notin given.nimout:
  331. return false
  332. true
  333. proc nimoutCheck(expected, given: TSpec): bool =
  334. result = true
  335. if expected.nimoutFull:
  336. if expected.nimout != given.nimout:
  337. result = false
  338. elif expected.nimout.len > 0 and not greedyOrderedSubsetLines(expected.nimout, given.nimout):
  339. result = false
  340. proc cmpMsgs(r: var TResults, expected, given: TSpec, test: TTest,
  341. target: TTarget, extraOptions: string): bool =
  342. if not checkForInlineErrors(expected, given) or
  343. (not expected.nimoutFull and not nimoutCheck(expected, given)):
  344. result = r.finishTest(test, target, extraOptions, expected.nimout & inlineErrorsMsgs(expected), given.nimout, reMsgsDiffer)
  345. elif strip(expected.msg) notin strip(given.msg):
  346. result = r.finishTest(test, target, extraOptions, expected.msg, given.msg, reMsgsDiffer)
  347. elif not nimoutCheck(expected, given):
  348. result = r.finishTest(test, target, extraOptions, expected.nimout, given.nimout, reMsgsDiffer)
  349. elif extractFilename(expected.file) != extractFilename(given.file) and
  350. "internal error:" notin expected.msg:
  351. result = r.finishTest(test, target, extraOptions, expected.file, given.file, reFilesDiffer)
  352. elif expected.line != given.line and expected.line != 0 or
  353. expected.column != given.column and expected.column != 0:
  354. result = r.finishTest(test, target, extraOptions, $expected.line & ':' & $expected.column,
  355. $given.line & ':' & $given.column, reLinesDiffer)
  356. else:
  357. result = r.finishTest(test, target, extraOptions, expected.msg, given.msg, reSuccess)
  358. inc(r.passed)
  359. proc generatedFile(test: TTest, target: TTarget): string =
  360. if target == targetJS:
  361. result = test.name.changeFileExt("js")
  362. else:
  363. let (_, name, _) = test.name.splitFile
  364. let ext = targetToExt[target]
  365. result = nimcacheDir(test.name, test.options, target) / "@m" & name.changeFileExt(ext)
  366. proc needsCodegenCheck(spec: TSpec): bool =
  367. result = spec.maxCodeSize > 0 or spec.ccodeCheck.len > 0
  368. proc codegenCheck(test: TTest, target: TTarget, spec: TSpec, expectedMsg: var string,
  369. given: var TSpec) =
  370. try:
  371. let genFile = generatedFile(test, target)
  372. let contents = readFile(genFile)
  373. for check in spec.ccodeCheck:
  374. if check.len > 0 and check[0] == '\\':
  375. # little hack to get 'match' support:
  376. if not contents.match(check.peg):
  377. given.err = reCodegenFailure
  378. elif contents.find(check.peg) < 0:
  379. given.err = reCodegenFailure
  380. expectedMsg = check
  381. if spec.maxCodeSize > 0 and contents.len > spec.maxCodeSize:
  382. given.err = reCodegenFailure
  383. given.msg = "generated code size: " & $contents.len
  384. expectedMsg = "max allowed size: " & $spec.maxCodeSize
  385. except ValueError:
  386. given.err = reInvalidPeg
  387. echo getCurrentExceptionMsg()
  388. except IOError:
  389. given.err = reCodeNotFound
  390. echo getCurrentExceptionMsg()
  391. proc compilerOutputTests(test: TTest, target: TTarget, extraOptions: string,
  392. given: var TSpec, expected: TSpec; r: var TResults): bool =
  393. var expectedmsg: string = ""
  394. var givenmsg: string = ""
  395. if given.err == reSuccess:
  396. if expected.needsCodegenCheck:
  397. codegenCheck(test, target, expected, expectedmsg, given)
  398. givenmsg = given.msg
  399. if not nimoutCheck(expected, given) or
  400. not checkForInlineErrors(expected, given):
  401. given.err = reMsgsDiffer
  402. expectedmsg = expected.nimout & inlineErrorsMsgs(expected)
  403. givenmsg = given.nimout.strip
  404. else:
  405. givenmsg = "$ " & given.cmd & '\n' & given.nimout
  406. if given.err == reSuccess: inc(r.passed)
  407. result = r.finishTest(test, target, extraOptions, expectedmsg, givenmsg, given.err)
  408. proc getTestSpecTarget(): TTarget =
  409. if getEnv("NIM_COMPILE_TO_CPP", "false") == "true":
  410. result = targetCpp
  411. else:
  412. result = targetC
  413. var count = 0
  414. proc equalModuloLastNewline(a, b: string): bool =
  415. # allow lazy output spec that omits last newline, but really those should be fixed instead
  416. result = a == b or b.endsWith("\n") and a == b[0 ..< ^1]
  417. proc testSpecHelper(r: var TResults, test: var TTest, expected: TSpec,
  418. target: TTarget, extraOptions: string, nimcache: string) =
  419. template maybeRetry(x: bool) =
  420. if x:
  421. test.spec.err = reRetry
  422. dec test.spec.retries
  423. testSpecHelper(r, test, expected, target, extraOptions, nimcache)
  424. return
  425. if test.spec.err != reRetry:
  426. test.startTime = epochTime()
  427. if testName(test, target, extraOptions, false) in skips:
  428. test.spec.err = reDisabled
  429. if test.spec.err in {reDisabled, reJoined}:
  430. discard r.finishTest(test, target, extraOptions, "", "", test.spec.err)
  431. inc(r.skipped)
  432. return
  433. var given = callNimCompiler(expected.getCmd, test.name, test.options, nimcache, target, extraOptions)
  434. case expected.action
  435. of actionCompile:
  436. maybeRetry compilerOutputTests(test, target, extraOptions, given, expected, r)
  437. of actionRun:
  438. if given.err != reSuccess:
  439. maybeRetry r.finishTest(test, target, extraOptions, "", "$ " & given.cmd & '\n' & given.nimout, given.err, givenSpec = given.addr)
  440. else:
  441. let isJsTarget = target == targetJS
  442. var exeFile = changeFileExt(test.name, if isJsTarget: "js" else: ExeExt)
  443. if not fileExists(exeFile):
  444. maybeRetry r.finishTest(test, target, extraOptions, expected.output,
  445. "executable not found: " & exeFile, reExeNotFound)
  446. else:
  447. let nodejs = if isJsTarget: findNodeJs() else: ""
  448. if isJsTarget and nodejs == "":
  449. maybeRetry r.finishTest(test, target, extraOptions, expected.output, "nodejs binary not in PATH",
  450. reExeNotFound)
  451. else:
  452. var exeCmd: string
  453. var args = test.testArgs
  454. if isJsTarget:
  455. exeCmd = nodejs
  456. # see D20210217T215950
  457. args = @["--unhandled-rejections=strict", exeFile] & args
  458. else:
  459. exeCmd = exeFile.dup(normalizeExe)
  460. if valgrindEnabled and expected.useValgrind != disabled:
  461. var valgrindOptions = @["--error-exitcode=1"]
  462. if expected.useValgrind != leaking:
  463. valgrindOptions.add "--leak-check=yes"
  464. args = valgrindOptions & exeCmd & args
  465. exeCmd = "valgrind"
  466. var (_, buf, exitCode) = execCmdEx2(exeCmd, args, input = expected.input)
  467. # Treat all failure codes from nodejs as 1. Older versions of nodejs used
  468. # to return other codes, but for us it is sufficient to know that it's not 0.
  469. if exitCode != 0: exitCode = 1
  470. let bufB =
  471. if expected.sortoutput:
  472. var buf2 = buf
  473. buf2.stripLineEnd
  474. var x = splitLines(buf2)
  475. sort(x, system.cmp)
  476. join(x, "\n") & '\n'
  477. else:
  478. buf
  479. if exitCode != expected.exitCode:
  480. given.err = reExitcodesDiffer
  481. maybeRetry r.finishTest(test, target, extraOptions, "exitcode: " & $expected.exitCode,
  482. "exitcode: " & $exitCode & "\n\nOutput:\n" &
  483. bufB, reExitcodesDiffer)
  484. elif (expected.outputCheck == ocEqual and not expected.output.equalModuloLastNewline(bufB)) or
  485. (expected.outputCheck == ocSubstr and expected.output notin bufB):
  486. given.err = reOutputsDiffer
  487. maybeRetry r.finishTest(test, target, extraOptions, expected.output, bufB, reOutputsDiffer)
  488. maybeRetry compilerOutputTests(test, target, extraOptions, given, expected, r)
  489. of actionReject:
  490. # Make sure its the compiler rejecting and not the system (e.g. segfault)
  491. maybeRetry cmpMsgs(r, expected, given, test, target, extraOptions)
  492. if given.exitCode != QuitFailure:
  493. maybeRetry r.finishTest(test, target, extraOptions, "exitcode: " & $QuitFailure,
  494. "exitcode: " & $given.exitCode & "\n\nOutput:\n" &
  495. given.nimout, reExitcodesDiffer)
  496. proc targetHelper(r: var TResults, test: TTest, expected: TSpec, extraOptions: string) =
  497. for target in expected.targets:
  498. inc(r.total)
  499. if target notin gTargets:
  500. discard r.finishTest(test, target, extraOptions, "", "", reDisabled)
  501. inc(r.skipped)
  502. elif simulate:
  503. inc count
  504. echo "testSpec count: ", count, " expected: ", expected
  505. else:
  506. let nimcache = nimcacheDir(test.name, test.options, target)
  507. var testClone = test
  508. testSpecHelper(r, testClone, expected, target, extraOptions, nimcache)
  509. proc testSpec(r: var TResults, test: TTest, targets: set[TTarget] = {}) =
  510. var expected = test.spec
  511. if expected.parseErrors.len > 0:
  512. # targetC is a lie, but a parameter is required
  513. discard r.finishTest(test, targetC, "", "", expected.parseErrors, reInvalidSpec)
  514. inc(r.total)
  515. return
  516. expected.targets.incl targets
  517. # still no target specified at all
  518. if expected.targets == {}:
  519. expected.targets = {getTestSpecTarget()}
  520. if test.spec.matrix.len > 0:
  521. for m in test.spec.matrix:
  522. targetHelper(r, test, expected, m)
  523. else:
  524. targetHelper(r, test, expected, "")
  525. proc testSpecWithNimcache(r: var TResults, test: TTest; nimcache: string) {.used.} =
  526. for target in test.spec.targets:
  527. inc(r.total)
  528. var testClone = test
  529. testSpecHelper(r, testClone, test.spec, target, "", nimcache)
  530. proc makeTest(test, options: string, cat: Category): TTest =
  531. result.cat = cat
  532. result.name = test
  533. result.options = options
  534. result.spec = parseSpec(addFileExt(test, ".nim"))
  535. result.startTime = epochTime()
  536. proc makeRawTest(test, options: string, cat: Category): TTest {.used.} =
  537. result.cat = cat
  538. result.name = test
  539. result.options = options
  540. result.spec = initSpec(addFileExt(test, ".nim"))
  541. result.spec.action = actionCompile
  542. result.spec.targets = {getTestSpecTarget()}
  543. result.startTime = epochTime()
  544. # TODO: fix these files
  545. const disabledFilesDefault = @[
  546. "tableimpl.nim",
  547. "setimpl.nim",
  548. "hashcommon.nim",
  549. # Requires compiling with '--threads:on`
  550. "sharedlist.nim",
  551. "sharedtables.nim",
  552. # Error: undeclared identifier: 'hasThreadSupport'
  553. "ioselectors_epoll.nim",
  554. "ioselectors_kqueue.nim",
  555. "ioselectors_poll.nim",
  556. # Error: undeclared identifier: 'Timeval'
  557. "ioselectors_select.nim",
  558. ]
  559. when defined(windows):
  560. const
  561. # array of modules disabled from compilation test of stdlib.
  562. disabledFiles = disabledFilesDefault & @["coro.nim"]
  563. else:
  564. const
  565. # array of modules disabled from compilation test of stdlib.
  566. disabledFiles = disabledFilesDefault
  567. include categories
  568. proc loadSkipFrom(name: string): seq[string] =
  569. if name.len == 0: return
  570. # One skip per line, comments start with #
  571. # used by `nlvm` (at least)
  572. for line in lines(name):
  573. let sline = line.strip()
  574. if sline.len > 0 and not sline.startsWith('#'):
  575. result.add sline
  576. proc main() =
  577. azure.init()
  578. backend.open()
  579. var optPrintResults = false
  580. var optFailing = false
  581. var targetsStr = ""
  582. var isMainProcess = true
  583. var skipFrom = ""
  584. var p = initOptParser()
  585. p.next()
  586. while p.kind in {cmdLongOption, cmdShortOption}:
  587. case p.key.normalize
  588. of "print": optPrintResults = true
  589. of "verbose": optVerbose = true
  590. of "failing": optFailing = true
  591. of "pedantic": discard # deadcode refs https://github.com/nim-lang/Nim/issues/16731
  592. of "targets":
  593. targetsStr = p.val
  594. gTargets = parseTargets(targetsStr)
  595. targetsSet = true
  596. of "nim":
  597. compilerPrefix = addFileExt(p.val.absolutePath, ExeExt)
  598. of "directory":
  599. setCurrentDir(p.val)
  600. of "colors":
  601. case p.val:
  602. of "on":
  603. useColors = true
  604. of "off":
  605. useColors = false
  606. else:
  607. quit Usage
  608. of "batch":
  609. testamentData0.batchArg = p.val
  610. if p.val != "_" and p.val.len > 0 and p.val[0] in {'0'..'9'}:
  611. let s = p.val.split("_")
  612. doAssert s.len == 2, $(p.val, s)
  613. testamentData0.testamentBatch = s[0].parseInt
  614. testamentData0.testamentNumBatch = s[1].parseInt
  615. doAssert testamentData0.testamentNumBatch > 0
  616. doAssert testamentData0.testamentBatch >= 0 and testamentData0.testamentBatch < testamentData0.testamentNumBatch
  617. of "simulate":
  618. simulate = true
  619. of "megatest":
  620. case p.val:
  621. of "on":
  622. useMegatest = true
  623. of "off":
  624. useMegatest = false
  625. else:
  626. quit Usage
  627. of "valgrind":
  628. case p.val:
  629. of "on":
  630. valgrindEnabled = true
  631. of "off":
  632. valgrindEnabled = false
  633. else:
  634. quit Usage
  635. of "backendlogging":
  636. case p.val:
  637. of "on":
  638. backendLogging = true
  639. of "off":
  640. backendLogging = false
  641. else:
  642. quit Usage
  643. of "skipfrom":
  644. skipFrom = p.val
  645. else:
  646. quit Usage
  647. p.next()
  648. if p.kind != cmdArgument:
  649. quit Usage
  650. var action = p.key.normalize
  651. p.next()
  652. var r = initResults()
  653. case action
  654. of "all":
  655. #processCategory(r, Category"megatest", p.cmdLineRest, testsDir, runJoinableTests = false)
  656. var myself = quoteShell(getAppFilename())
  657. if targetsStr.len > 0:
  658. myself &= " " & quoteShell("--targets:" & targetsStr)
  659. myself &= " " & quoteShell("--nim:" & compilerPrefix)
  660. if testamentData0.batchArg.len > 0:
  661. myself &= " --batch:" & testamentData0.batchArg
  662. if skipFrom.len > 0:
  663. myself &= " " & quoteShell("--skipFrom:" & skipFrom)
  664. var cats: seq[string]
  665. let rest = if p.cmdLineRest.len > 0: " " & p.cmdLineRest else: ""
  666. for kind, dir in walkDir(testsDir):
  667. assert testsDir.startsWith(testsDir)
  668. let cat = dir[testsDir.len .. ^1]
  669. if kind == pcDir and cat notin ["testdata", "nimcache"]:
  670. cats.add cat
  671. if isNimRepoTests():
  672. cats.add AdditionalCategories
  673. if useMegatest: cats.add MegaTestCat
  674. var cmds: seq[string]
  675. for cat in cats:
  676. let runtype = if useMegatest: " pcat " else: " cat "
  677. cmds.add(myself & runtype & quoteShell(cat) & rest)
  678. proc progressStatus(idx: int) =
  679. echo "progress[all]: $1/$2 starting: cat: $3" % [$idx, $cats.len, cats[idx]]
  680. if simulate:
  681. skips = loadSkipFrom(skipFrom)
  682. for i, cati in cats:
  683. progressStatus(i)
  684. processCategory(r, Category(cati), p.cmdLineRest, testsDir, runJoinableTests = false)
  685. else:
  686. addExitProc azure.finalize
  687. quit osproc.execProcesses(cmds, {poEchoCmd, poStdErrToStdOut, poUsePath, poParentStreams}, beforeRunEvent = progressStatus)
  688. of "c", "cat", "category":
  689. skips = loadSkipFrom(skipFrom)
  690. var cat = Category(p.key)
  691. processCategory(r, cat, p.cmdLineRest, testsDir, runJoinableTests = true)
  692. of "pcat":
  693. skips = loadSkipFrom(skipFrom)
  694. # 'pcat' is used for running a category in parallel. Currently the only
  695. # difference is that we don't want to run joinable tests here as they
  696. # are covered by the 'megatest' category.
  697. isMainProcess = false
  698. var cat = Category(p.key)
  699. p.next
  700. processCategory(r, cat, p.cmdLineRest, testsDir, runJoinableTests = false)
  701. of "p", "pat", "pattern":
  702. skips = loadSkipFrom(skipFrom)
  703. let pattern = p.key
  704. p.next
  705. processPattern(r, pattern, p.cmdLineRest, simulate)
  706. of "r", "run":
  707. let (cat, path) = splitTestFile(p.key)
  708. processSingleTest(r, cat.Category, p.cmdLineRest, path, gTargets, targetsSet)
  709. of "html":
  710. generateHtml(resultsFile, optFailing)
  711. else:
  712. quit Usage
  713. if optPrintResults:
  714. if action == "html": openDefaultBrowser(resultsFile)
  715. else: echo r, r.data
  716. azure.finalize()
  717. backend.close()
  718. var failed = r.total - r.passed - r.skipped
  719. if failed != 0:
  720. echo "FAILURE! total: ", r.total, " passed: ", r.passed, " skipped: ",
  721. r.skipped, " failed: ", failed
  722. quit(QuitFailure)
  723. if isMainProcess:
  724. echo "Used ", compilerPrefix, " to run the tests. Use --nim to override."
  725. if paramCount() == 0:
  726. quit Usage
  727. main()