testament.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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, successOrig: TResultEnum,
  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 duration = epochTime() - test.startTime
  250. let success = if test.spec.timeout > 0.0 and duration > test.spec.timeout: reTimeout
  251. else: successOrig
  252. let durationStr = duration.formatFloat(ffDecimal, precision = 2).align(5)
  253. if backendLogging:
  254. backend.writeTestResult(name = name,
  255. category = test.cat.string,
  256. target = $target,
  257. action = $test.spec.action,
  258. result = $success,
  259. expected = expected,
  260. given = given)
  261. r.data.addf("$#\t$#\t$#\t$#", name, expected, given, $success)
  262. template dispNonSkipped(color, outcome) =
  263. maybeStyledEcho color, outcome, fgCyan, test.debugInfo, alignLeft(name, 60), fgBlue, " (", durationStr, " sec)"
  264. template disp(msg) =
  265. maybeStyledEcho styleDim, fgYellow, msg & ' ', styleBright, fgCyan, name
  266. if success == reSuccess:
  267. dispNonSkipped(fgGreen, "PASS: ")
  268. elif success == reDisabled:
  269. if test.spec.inCurrentBatch: disp("SKIP:")
  270. else: disp("NOTINBATCH:")
  271. elif success == reJoined: disp("JOINED:")
  272. else:
  273. dispNonSkipped(fgRed, failString)
  274. maybeStyledEcho styleBright, fgCyan, "Test \"", test.name, "\"", " in category \"", test.cat.string, "\""
  275. maybeStyledEcho styleBright, fgRed, "Failure: ", $success
  276. if givenSpec != nil and givenSpec.debugInfo.len > 0:
  277. echo "debugInfo: " & givenSpec.debugInfo
  278. if success in {reBuildFailed, reNimcCrash, reInstallFailed}:
  279. # expected is empty, no reason to print it.
  280. echo given
  281. else:
  282. maybeStyledEcho fgYellow, "Expected:"
  283. maybeStyledEcho styleBright, expected, "\n"
  284. maybeStyledEcho fgYellow, "Gotten:"
  285. maybeStyledEcho styleBright, given, "\n"
  286. echo diffStrings(expected, given).output
  287. if backendLogging and (isAppVeyor or isAzure):
  288. let (outcome, msg) =
  289. case success
  290. of reSuccess:
  291. ("Passed", "")
  292. of reDisabled, reJoined:
  293. ("Skipped", "")
  294. of reBuildFailed, reNimcCrash, reInstallFailed:
  295. ("Failed", "Failure: " & $success & '\n' & given)
  296. else:
  297. ("Failed", "Failure: " & $success & "\nExpected:\n" & expected & "\n\n" & "Gotten:\n" & given)
  298. if isAzure:
  299. azure.addTestResult(name, test.cat.string, int(duration * 1000), msg, success)
  300. else:
  301. var p = startProcess("appveyor", args = ["AddTest", test.name.replace("\\", "/") & test.options,
  302. "-Framework", "nim-testament", "-FileName",
  303. test.cat.string,
  304. "-Outcome", outcome, "-ErrorMessage", msg,
  305. "-Duration", $(duration * 1000).int],
  306. options = {poStdErrToStdOut, poUsePath, poParentStreams})
  307. discard waitForExit(p)
  308. close(p)
  309. proc toString(inlineError: InlineError, filename: string): string =
  310. result.add "$file($line, $col) $kind: $msg" % [
  311. "file", filename,
  312. "line", $inlineError.line,
  313. "col", $inlineError.col,
  314. "kind", $inlineError.kind,
  315. "msg", $inlineError.msg
  316. ]
  317. proc inlineErrorsMsgs(expected: TSpec): string =
  318. for inlineError in expected.inlineErrors.items:
  319. result.addLine inlineError.toString(expected.filename)
  320. proc checkForInlineErrors(expected, given: TSpec): bool =
  321. for inlineError in expected.inlineErrors:
  322. if inlineError.toString(expected.filename) notin given.nimout:
  323. return false
  324. true
  325. proc nimoutCheck(expected, given: TSpec): bool =
  326. result = true
  327. if expected.nimoutFull:
  328. if expected.nimout != given.nimout:
  329. result = false
  330. elif expected.nimout.len > 0 and not greedyOrderedSubsetLines(expected.nimout, given.nimout):
  331. result = false
  332. proc cmpMsgs(r: var TResults, expected, given: TSpec, test: TTest,
  333. target: TTarget, extraOptions: string) =
  334. if not checkForInlineErrors(expected, given) or
  335. (not expected.nimoutFull and not nimoutCheck(expected, given)):
  336. r.addResult(test, target, extraOptions, expected.nimout & inlineErrorsMsgs(expected), given.nimout, reMsgsDiffer)
  337. elif strip(expected.msg) notin strip(given.msg):
  338. r.addResult(test, target, extraOptions, expected.msg, given.msg, reMsgsDiffer)
  339. elif not nimoutCheck(expected, given):
  340. r.addResult(test, target, extraOptions, expected.nimout, given.nimout, reMsgsDiffer)
  341. elif extractFilename(expected.file) != extractFilename(given.file) and
  342. "internal error:" notin expected.msg:
  343. r.addResult(test, target, extraOptions, expected.file, given.file, reFilesDiffer)
  344. elif expected.line != given.line and expected.line != 0 or
  345. expected.column != given.column and expected.column != 0:
  346. r.addResult(test, target, extraOptions, $expected.line & ':' & $expected.column,
  347. $given.line & ':' & $given.column, reLinesDiffer)
  348. else:
  349. r.addResult(test, target, extraOptions, expected.msg, given.msg, reSuccess)
  350. inc(r.passed)
  351. proc generatedFile(test: TTest, target: TTarget): string =
  352. if target == targetJS:
  353. result = test.name.changeFileExt("js")
  354. else:
  355. let (_, name, _) = test.name.splitFile
  356. let ext = targetToExt[target]
  357. result = nimcacheDir(test.name, test.options, target) / "@m" & name.changeFileExt(ext)
  358. proc needsCodegenCheck(spec: TSpec): bool =
  359. result = spec.maxCodeSize > 0 or spec.ccodeCheck.len > 0
  360. proc codegenCheck(test: TTest, target: TTarget, spec: TSpec, expectedMsg: var string,
  361. given: var TSpec) =
  362. try:
  363. let genFile = generatedFile(test, target)
  364. let contents = readFile(genFile)
  365. for check in spec.ccodeCheck:
  366. if check.len > 0 and check[0] == '\\':
  367. # little hack to get 'match' support:
  368. if not contents.match(check.peg):
  369. given.err = reCodegenFailure
  370. elif contents.find(check.peg) < 0:
  371. given.err = reCodegenFailure
  372. expectedMsg = check
  373. if spec.maxCodeSize > 0 and contents.len > spec.maxCodeSize:
  374. given.err = reCodegenFailure
  375. given.msg = "generated code size: " & $contents.len
  376. expectedMsg = "max allowed size: " & $spec.maxCodeSize
  377. except ValueError:
  378. given.err = reInvalidPeg
  379. echo getCurrentExceptionMsg()
  380. except IOError:
  381. given.err = reCodeNotFound
  382. echo getCurrentExceptionMsg()
  383. proc compilerOutputTests(test: TTest, target: TTarget, extraOptions: string,
  384. given: var TSpec, expected: TSpec; r: var TResults) =
  385. var expectedmsg: string = ""
  386. var givenmsg: string = ""
  387. if given.err == reSuccess:
  388. if expected.needsCodegenCheck:
  389. codegenCheck(test, target, expected, expectedmsg, given)
  390. givenmsg = given.msg
  391. if not nimoutCheck(expected, given) or
  392. not checkForInlineErrors(expected, given):
  393. given.err = reMsgsDiffer
  394. expectedmsg = expected.nimout & inlineErrorsMsgs(expected)
  395. givenmsg = given.nimout.strip
  396. else:
  397. givenmsg = "$ " & given.cmd & '\n' & given.nimout
  398. if given.err == reSuccess: inc(r.passed)
  399. r.addResult(test, target, extraOptions, expectedmsg, givenmsg, given.err)
  400. proc getTestSpecTarget(): TTarget =
  401. if getEnv("NIM_COMPILE_TO_CPP", "false") == "true":
  402. result = targetCpp
  403. else:
  404. result = targetC
  405. var count = 0
  406. proc equalModuloLastNewline(a, b: string): bool =
  407. # allow lazy output spec that omits last newline, but really those should be fixed instead
  408. result = a == b or b.endsWith("\n") and a == b[0 ..< ^1]
  409. proc testSpecHelper(r: var TResults, test: var TTest, expected: TSpec,
  410. target: TTarget, extraOptions: string, nimcache: string) =
  411. test.startTime = epochTime()
  412. if testName(test, target, extraOptions, false) in skips:
  413. test.spec.err = reDisabled
  414. if test.spec.err in {reDisabled, reJoined}:
  415. r.addResult(test, target, extraOptions, "", "", test.spec.err)
  416. inc(r.skipped)
  417. return
  418. var given = callNimCompiler(expected.getCmd, test.name, test.options, nimcache, target, extraOptions)
  419. case expected.action
  420. of actionCompile:
  421. compilerOutputTests(test, target, extraOptions, given, expected, r)
  422. of actionRun:
  423. if given.err != reSuccess:
  424. r.addResult(test, target, extraOptions, "", "$ " & given.cmd & '\n' & given.nimout, given.err, givenSpec = given.addr)
  425. else:
  426. let isJsTarget = target == targetJS
  427. var exeFile = changeFileExt(test.name, if isJsTarget: "js" else: ExeExt)
  428. if not fileExists(exeFile):
  429. r.addResult(test, target, extraOptions, expected.output,
  430. "executable not found: " & exeFile, reExeNotFound)
  431. else:
  432. let nodejs = if isJsTarget: findNodeJs() else: ""
  433. if isJsTarget and nodejs == "":
  434. r.addResult(test, target, extraOptions, expected.output, "nodejs binary not in PATH",
  435. reExeNotFound)
  436. else:
  437. var exeCmd: string
  438. var args = test.testArgs
  439. if isJsTarget:
  440. exeCmd = nodejs
  441. # see D20210217T215950
  442. args = @["--unhandled-rejections=strict", exeFile] & args
  443. else:
  444. exeCmd = exeFile.dup(normalizeExe)
  445. if valgrindEnabled and expected.useValgrind != disabled:
  446. var valgrindOptions = @["--error-exitcode=1"]
  447. if expected.useValgrind != leaking:
  448. valgrindOptions.add "--leak-check=yes"
  449. args = valgrindOptions & exeCmd & args
  450. exeCmd = "valgrind"
  451. var (_, buf, exitCode) = execCmdEx2(exeCmd, args, input = expected.input)
  452. # Treat all failure codes from nodejs as 1. Older versions of nodejs used
  453. # to return other codes, but for us it is sufficient to know that it's not 0.
  454. if exitCode != 0: exitCode = 1
  455. let bufB =
  456. if expected.sortoutput:
  457. var buf2 = buf
  458. buf2.stripLineEnd
  459. var x = splitLines(buf2)
  460. sort(x, system.cmp)
  461. join(x, "\n") & '\n'
  462. else:
  463. buf
  464. if exitCode != expected.exitCode:
  465. given.err = reExitcodesDiffer
  466. r.addResult(test, target, extraOptions, "exitcode: " & $expected.exitCode,
  467. "exitcode: " & $exitCode & "\n\nOutput:\n" &
  468. bufB, reExitcodesDiffer)
  469. elif (expected.outputCheck == ocEqual and not expected.output.equalModuloLastNewline(bufB)) or
  470. (expected.outputCheck == ocSubstr and expected.output notin bufB):
  471. given.err = reOutputsDiffer
  472. r.addResult(test, target, extraOptions, expected.output, bufB, reOutputsDiffer)
  473. compilerOutputTests(test, target, extraOptions, given, expected, r)
  474. of actionReject:
  475. # Make sure its the compiler rejecting and not the system (e.g. segfault)
  476. cmpMsgs(r, expected, given, test, target, extraOptions)
  477. if given.exitCode != QuitFailure:
  478. r.addResult(test, target, extraOptions, "exitcode: " & $QuitFailure,
  479. "exitcode: " & $given.exitCode & "\n\nOutput:\n" &
  480. given.nimout, reExitcodesDiffer)
  481. proc targetHelper(r: var TResults, test: TTest, expected: TSpec, extraOptions: string) =
  482. for target in expected.targets:
  483. inc(r.total)
  484. if target notin gTargets:
  485. r.addResult(test, target, extraOptions, "", "", reDisabled)
  486. inc(r.skipped)
  487. elif simulate:
  488. inc count
  489. echo "testSpec count: ", count, " expected: ", expected
  490. else:
  491. let nimcache = nimcacheDir(test.name, test.options, target)
  492. var testClone = test
  493. testSpecHelper(r, testClone, expected, target, extraOptions, nimcache)
  494. proc testSpec(r: var TResults, test: TTest, targets: set[TTarget] = {}) =
  495. var expected = test.spec
  496. if expected.parseErrors.len > 0:
  497. # targetC is a lie, but a parameter is required
  498. r.addResult(test, targetC, "", "", expected.parseErrors, reInvalidSpec)
  499. inc(r.total)
  500. return
  501. expected.targets.incl targets
  502. # still no target specified at all
  503. if expected.targets == {}:
  504. expected.targets = {getTestSpecTarget()}
  505. if test.spec.matrix.len > 0:
  506. for m in test.spec.matrix:
  507. targetHelper(r, test, expected, m)
  508. else:
  509. targetHelper(r, test, expected, "")
  510. proc testSpecWithNimcache(r: var TResults, test: TTest; nimcache: string) {.used.} =
  511. for target in test.spec.targets:
  512. inc(r.total)
  513. var testClone = test
  514. testSpecHelper(r, testClone, test.spec, target, "", nimcache)
  515. proc makeTest(test, options: string, cat: Category): TTest =
  516. result.cat = cat
  517. result.name = test
  518. result.options = options
  519. result.spec = parseSpec(addFileExt(test, ".nim"))
  520. result.startTime = epochTime()
  521. proc makeRawTest(test, options: string, cat: Category): TTest {.used.} =
  522. result.cat = cat
  523. result.name = test
  524. result.options = options
  525. result.spec = initSpec(addFileExt(test, ".nim"))
  526. result.spec.action = actionCompile
  527. result.spec.targets = {getTestSpecTarget()}
  528. result.startTime = epochTime()
  529. # TODO: fix these files
  530. const disabledFilesDefault = @[
  531. "tableimpl.nim",
  532. "setimpl.nim",
  533. "hashcommon.nim",
  534. # Requires compiling with '--threads:on`
  535. "sharedlist.nim",
  536. "sharedtables.nim",
  537. # Error: undeclared identifier: 'hasThreadSupport'
  538. "ioselectors_epoll.nim",
  539. "ioselectors_kqueue.nim",
  540. "ioselectors_poll.nim",
  541. # Error: undeclared identifier: 'Timeval'
  542. "ioselectors_select.nim",
  543. ]
  544. when defined(windows):
  545. const
  546. # array of modules disabled from compilation test of stdlib.
  547. disabledFiles = disabledFilesDefault & @["coro.nim"]
  548. else:
  549. const
  550. # array of modules disabled from compilation test of stdlib.
  551. disabledFiles = disabledFilesDefault
  552. include categories
  553. proc loadSkipFrom(name: string): seq[string] =
  554. if name.len == 0: return
  555. # One skip per line, comments start with #
  556. # used by `nlvm` (at least)
  557. for line in lines(name):
  558. let sline = line.strip()
  559. if sline.len > 0 and not sline.startsWith('#'):
  560. result.add sline
  561. proc main() =
  562. azure.init()
  563. backend.open()
  564. var optPrintResults = false
  565. var optFailing = false
  566. var targetsStr = ""
  567. var isMainProcess = true
  568. var skipFrom = ""
  569. var p = initOptParser()
  570. p.next()
  571. while p.kind in {cmdLongOption, cmdShortOption}:
  572. case p.key.normalize
  573. of "print": optPrintResults = true
  574. of "verbose": optVerbose = true
  575. of "failing": optFailing = true
  576. of "pedantic": discard # deadcode refs https://github.com/nim-lang/Nim/issues/16731
  577. of "targets":
  578. targetsStr = p.val
  579. gTargets = parseTargets(targetsStr)
  580. targetsSet = true
  581. of "nim":
  582. compilerPrefix = addFileExt(p.val.absolutePath, ExeExt)
  583. of "directory":
  584. setCurrentDir(p.val)
  585. of "colors":
  586. case p.val:
  587. of "on":
  588. useColors = true
  589. of "off":
  590. useColors = false
  591. else:
  592. quit Usage
  593. of "batch":
  594. testamentData0.batchArg = p.val
  595. if p.val != "_" and p.val.len > 0 and p.val[0] in {'0'..'9'}:
  596. let s = p.val.split("_")
  597. doAssert s.len == 2, $(p.val, s)
  598. testamentData0.testamentBatch = s[0].parseInt
  599. testamentData0.testamentNumBatch = s[1].parseInt
  600. doAssert testamentData0.testamentNumBatch > 0
  601. doAssert testamentData0.testamentBatch >= 0 and testamentData0.testamentBatch < testamentData0.testamentNumBatch
  602. of "simulate":
  603. simulate = true
  604. of "megatest":
  605. case p.val:
  606. of "on":
  607. useMegatest = true
  608. of "off":
  609. useMegatest = false
  610. else:
  611. quit Usage
  612. of "valgrind":
  613. case p.val:
  614. of "on":
  615. valgrindEnabled = true
  616. of "off":
  617. valgrindEnabled = false
  618. else:
  619. quit Usage
  620. of "backendlogging":
  621. case p.val:
  622. of "on":
  623. backendLogging = true
  624. of "off":
  625. backendLogging = false
  626. else:
  627. quit Usage
  628. of "skipfrom":
  629. skipFrom = p.val
  630. else:
  631. quit Usage
  632. p.next()
  633. if p.kind != cmdArgument:
  634. quit Usage
  635. var action = p.key.normalize
  636. p.next()
  637. var r = initResults()
  638. case action
  639. of "all":
  640. #processCategory(r, Category"megatest", p.cmdLineRest, testsDir, runJoinableTests = false)
  641. var myself = quoteShell(getAppFilename())
  642. if targetsStr.len > 0:
  643. myself &= " " & quoteShell("--targets:" & targetsStr)
  644. myself &= " " & quoteShell("--nim:" & compilerPrefix)
  645. if testamentData0.batchArg.len > 0:
  646. myself &= " --batch:" & testamentData0.batchArg
  647. if skipFrom.len > 0:
  648. myself &= " " & quoteShell("--skipFrom:" & skipFrom)
  649. var cats: seq[string]
  650. let rest = if p.cmdLineRest.len > 0: " " & p.cmdLineRest else: ""
  651. for kind, dir in walkDir(testsDir):
  652. assert testsDir.startsWith(testsDir)
  653. let cat = dir[testsDir.len .. ^1]
  654. if kind == pcDir and cat notin ["testdata", "nimcache"]:
  655. cats.add cat
  656. if isNimRepoTests():
  657. cats.add AdditionalCategories
  658. if useMegatest: cats.add MegaTestCat
  659. var cmds: seq[string]
  660. for cat in cats:
  661. let runtype = if useMegatest: " pcat " else: " cat "
  662. cmds.add(myself & runtype & quoteShell(cat) & rest)
  663. proc progressStatus(idx: int) =
  664. echo "progress[all]: $1/$2 starting: cat: $3" % [$idx, $cats.len, cats[idx]]
  665. if simulate:
  666. skips = loadSkipFrom(skipFrom)
  667. for i, cati in cats:
  668. progressStatus(i)
  669. processCategory(r, Category(cati), p.cmdLineRest, testsDir, runJoinableTests = false)
  670. else:
  671. addExitProc azure.finalize
  672. quit osproc.execProcesses(cmds, {poEchoCmd, poStdErrToStdOut, poUsePath, poParentStreams}, beforeRunEvent = progressStatus)
  673. of "c", "cat", "category":
  674. skips = loadSkipFrom(skipFrom)
  675. var cat = Category(p.key)
  676. processCategory(r, cat, p.cmdLineRest, testsDir, runJoinableTests = true)
  677. of "pcat":
  678. skips = loadSkipFrom(skipFrom)
  679. # 'pcat' is used for running a category in parallel. Currently the only
  680. # difference is that we don't want to run joinable tests here as they
  681. # are covered by the 'megatest' category.
  682. isMainProcess = false
  683. var cat = Category(p.key)
  684. p.next
  685. processCategory(r, cat, p.cmdLineRest, testsDir, runJoinableTests = false)
  686. of "p", "pat", "pattern":
  687. skips = loadSkipFrom(skipFrom)
  688. let pattern = p.key
  689. p.next
  690. processPattern(r, pattern, p.cmdLineRest, simulate)
  691. of "r", "run":
  692. let (cat, path) = splitTestFile(p.key)
  693. processSingleTest(r, cat.Category, p.cmdLineRest, path, gTargets, targetsSet)
  694. of "html":
  695. generateHtml(resultsFile, optFailing)
  696. else:
  697. quit Usage
  698. if optPrintResults:
  699. if action == "html": openDefaultBrowser(resultsFile)
  700. else: echo r, r.data
  701. azure.finalize()
  702. backend.close()
  703. var failed = r.total - r.passed - r.skipped
  704. if failed != 0:
  705. echo "FAILURE! total: ", r.total, " passed: ", r.passed, " skipped: ",
  706. r.skipped, " failed: ", failed
  707. quit(QuitFailure)
  708. if isMainProcess:
  709. echo "Used ", compilerPrefix, " to run the tests. Use --nim to override."
  710. if paramCount() == 0:
  711. quit Usage
  712. main()