testament.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. std/[strutils, pegs, os, osproc, streams, json,
  12. parseopt, browsers, terminal, exitprocs,
  13. algorithm, times, intsets, macros]
  14. import backend, specs, azure, htmlgen
  15. from std/sugar import dup
  16. import compiler/nodejs
  17. import lib/stdtest/testutils
  18. from lib/stdtest/specialpaths import splitTestFile
  19. from std/private/gitutils import diffStrings
  20. import ../dist/checksums/src/checksums/md5
  21. proc trimUnitSep(x: var string) =
  22. let L = x.len
  23. if L > 0 and x[^1] == '\31':
  24. setLen x, L-1
  25. var useColors = true
  26. var backendLogging = true
  27. var simulate = false
  28. var optVerbose = false
  29. var useMegatest = true
  30. var valgrindEnabled = true
  31. proc verboseCmd(cmd: string) =
  32. if optVerbose:
  33. echo "executing: ", cmd
  34. const
  35. failString* = "FAIL: " # ensures all failures can be searched with 1 keyword in CI logs
  36. testsDir = "tests" & DirSep
  37. resultsFile = "testresults.html"
  38. Usage = """Usage:
  39. testament [options] command [arguments]
  40. Command:
  41. p|pat|pattern <glob> run all the tests matching the given pattern
  42. all run all tests in category folders
  43. c|cat|category <category> run all the tests of a certain category
  44. r|run <test> run single test file
  45. html generate $1 from the database
  46. Arguments:
  47. arguments are passed to the compiler
  48. Options:
  49. --print print results to the console
  50. --verbose print commands (compiling and running tests)
  51. --simulate see what tests would be run but don't run them (for debugging)
  52. --failing only show failing/ignored tests
  53. --targets:"c cpp js objc" run tests for specified targets (default: c)
  54. --nim:path use a particular nim executable (default: $$PATH/nim)
  55. --directory:dir Change to directory dir before reading the tests or doing anything else.
  56. --colors:on|off Turn messages coloring on|off.
  57. --backendLogging:on|off Disable or enable backend logging. By default turned on.
  58. --megatest:on|off Enable or disable megatest. Default is on.
  59. --valgrind:on|off Enable or disable valgrind support. Default is on.
  60. --skipFrom:file Read tests to skip from `file` - one test per line, # comments ignored
  61. On Azure Pipelines, testament will also publish test results via Azure Pipelines' Test Management API
  62. provided that System.AccessToken is made available via the environment variable SYSTEM_ACCESSTOKEN.
  63. Experimental: using environment variable `NIM_TESTAMENT_REMOTE_NETWORKING=1` enables
  64. tests with remote networking (as in CI).
  65. """ % resultsFile
  66. proc isNimRepoTests(): bool =
  67. # this logic could either be specific to cwd, or to some file derived from
  68. # the input file, eg testament r /pathto/tests/foo/tmain.nim; we choose
  69. # the former since it's simpler and also works with `testament all`.
  70. let file = "testament"/"testament.nim.cfg"
  71. result = file.fileExists
  72. type
  73. Category = distinct string
  74. TResults = object
  75. total, passed, failedButAllowed, skipped: int
  76. ## xxx rename passed to passedOrAllowedFailure
  77. data: string
  78. TTest = object
  79. name: string
  80. cat: Category
  81. options: string
  82. testArgs: seq[string]
  83. spec: TSpec
  84. startTime: float
  85. debugInfo: string
  86. # ----------------------------------------------------------------------------
  87. let
  88. pegLineError =
  89. peg"{[^(]*} '(' {\d+} ', ' {\d+} ') ' ('Error') ':' \s* {.*}"
  90. pegOtherError = peg"'Error:' \s* {.*}"
  91. pegOfInterest = pegLineError / pegOtherError
  92. var gTargets = {low(TTarget)..high(TTarget)}
  93. var targetsSet = false
  94. proc isSuccess(input: string): bool =
  95. # not clear how to do the equivalent of pkg/regex's: re"FOO(.*?)BAR" in pegs
  96. # note: this doesn't handle colors, eg: `\e[1m\e[0m\e[32mHint:`; while we
  97. # could handle colors, there would be other issues such as handling other flags
  98. # that may appear in user config (eg: `--filenames`).
  99. # Passing `XDG_CONFIG_HOME= testament args...` can be used to ignore user config
  100. # stored in XDG_CONFIG_HOME, refs https://wiki.archlinux.org/index.php/XDG_Base_Directory
  101. input.startsWith("Hint: ") and input.endsWith("[SuccessX]")
  102. proc getFileDir(filename: string): string =
  103. result = filename.splitFile().dir
  104. if not result.isAbsolute():
  105. result = getCurrentDir() / result
  106. proc execCmdEx2(command: string, args: openArray[string]; workingDir, input: string = ""): tuple[
  107. cmdLine: string,
  108. output: string,
  109. exitCode: int] {.tags:
  110. [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
  111. result.cmdLine.add quoteShell(command)
  112. for arg in args:
  113. result.cmdLine.add ' '
  114. result.cmdLine.add quoteShell(arg)
  115. verboseCmd(result.cmdLine)
  116. var p = startProcess(command, workingDir = workingDir, args = args,
  117. options = {poStdErrToStdOut, poUsePath})
  118. var outp = outputStream(p)
  119. # There is no way to provide input for the child process
  120. # anymore. Closing it will create EOF on stdin instead of eternal
  121. # blocking.
  122. let instream = inputStream(p)
  123. instream.write(input)
  124. close instream
  125. result.exitCode = -1
  126. var line = newStringOfCap(120)
  127. while true:
  128. if outp.readLine(line):
  129. result.output.add line
  130. result.output.add '\n'
  131. else:
  132. result.exitCode = peekExitCode(p)
  133. if result.exitCode != -1: break
  134. close(p)
  135. proc nimcacheDir(filename, options: string, target: TTarget): string =
  136. ## Give each test a private nimcache dir so they don't clobber each other's.
  137. let hashInput = options & $target
  138. result = "nimcache" / (filename & '_' & hashInput.getMD5)
  139. proc prepareTestCmd(cmdTemplate, filename, options, nimcache: string,
  140. target: TTarget, extraOptions = ""): string =
  141. var options = target.defaultOptions & ' ' & options
  142. if nimcache.len > 0: options.add(" --nimCache:$#" % nimcache.quoteShell)
  143. options.add ' ' & extraOptions
  144. # we avoid using `parseCmdLine` which is buggy, refs bug #14343
  145. result = cmdTemplate % ["target", targetToCmd[target],
  146. "options", options, "file", filename.quoteShell,
  147. "filedir", filename.getFileDir(), "nim", compilerPrefix]
  148. proc callNimCompiler(cmdTemplate, filename, options, nimcache: string,
  149. target: TTarget, extraOptions = ""): TSpec =
  150. result.cmd = prepareTestCmd(cmdTemplate, filename, options, nimcache, target,
  151. extraOptions)
  152. verboseCmd(result.cmd)
  153. var p = startProcess(command = result.cmd,
  154. options = {poStdErrToStdOut, poUsePath, poEvalCommand})
  155. let outp = p.outputStream
  156. var foundSuccessMsg = false
  157. var foundErrorMsg = false
  158. var err = ""
  159. var x = newStringOfCap(120)
  160. result.nimout = ""
  161. while true:
  162. if outp.readLine(x):
  163. trimUnitSep x
  164. result.nimout.add(x & '\n')
  165. if x =~ pegOfInterest:
  166. # `err` should contain the last error message
  167. err = x
  168. foundErrorMsg = true
  169. elif x.isSuccess:
  170. foundSuccessMsg = true
  171. elif not running(p):
  172. break
  173. result.msg = ""
  174. result.file = ""
  175. result.output = ""
  176. result.line = 0
  177. result.column = 0
  178. result.err = reNimcCrash
  179. result.exitCode = p.peekExitCode
  180. close p
  181. case result.exitCode
  182. of 0:
  183. if foundErrorMsg:
  184. result.debugInfo.add " compiler exit code was 0 but some Error's were found."
  185. else:
  186. result.err = reSuccess
  187. of 1:
  188. if not foundErrorMsg:
  189. result.debugInfo.add " compiler exit code was 1 but no Error's were found."
  190. if foundSuccessMsg:
  191. result.debugInfo.add " compiler exit code was 1 but no `isSuccess` was true."
  192. else:
  193. result.debugInfo.add " expected compiler exit code 0 or 1, got $1." % $result.exitCode
  194. if err =~ pegLineError:
  195. result.file = extractFilename(matches[0])
  196. result.line = parseInt(matches[1])
  197. result.column = parseInt(matches[2])
  198. result.msg = matches[3]
  199. elif err =~ pegOtherError:
  200. result.msg = matches[0]
  201. trimUnitSep result.msg
  202. proc initResults: TResults =
  203. result.total = 0
  204. result.passed = 0
  205. result.failedButAllowed = 0
  206. result.skipped = 0
  207. result.data = ""
  208. macro ignoreStyleEcho(args: varargs[typed]): untyped =
  209. let typForegroundColor = bindSym"ForegroundColor".getType
  210. let typBackgroundColor = bindSym"BackgroundColor".getType
  211. let typStyle = bindSym"Style".getType
  212. let typTerminalCmd = bindSym"TerminalCmd".getType
  213. result = newCall(bindSym"echo")
  214. for arg in children(args):
  215. if arg.kind == nnkNilLit: continue
  216. let typ = arg.getType
  217. if typ.kind != nnkEnumTy or
  218. typ != typForegroundColor and
  219. typ != typBackgroundColor and
  220. typ != typStyle and
  221. typ != typTerminalCmd:
  222. result.add(arg)
  223. template maybeStyledEcho(args: varargs[untyped]): untyped =
  224. if useColors:
  225. styledEcho(args)
  226. else:
  227. ignoreStyleEcho(args)
  228. proc `$`(x: TResults): string =
  229. result = """
  230. Tests passed or allowed to fail: $2 / $1 <br />
  231. Tests failed and allowed to fail: $3 / $1 <br />
  232. Tests skipped: $4 / $1 <br />
  233. """ % [$x.total, $x.passed, $x.failedButAllowed, $x.skipped]
  234. proc testName(test: TTest, target: TTarget, extraOptions: string, allowFailure: bool): string =
  235. var name = test.name.replace(DirSep, '/')
  236. name.add ' ' & $target
  237. if allowFailure:
  238. name.add " (allowed to fail) "
  239. if test.options.len > 0: name.add ' ' & test.options
  240. if extraOptions.len > 0: name.add ' ' & extraOptions
  241. name.strip()
  242. proc addResult(r: var TResults, test: TTest, target: TTarget,
  243. extraOptions, expected, given: string, successOrig: TResultEnum,
  244. allowFailure = false, givenSpec: ptr TSpec = nil) =
  245. # instead of `ptr TSpec` we could also use `Option[TSpec]`; passing `givenSpec` makes it easier to get what we need
  246. # instead of having to pass individual fields, or abusing existing ones like expected vs given.
  247. # test.name is easier to find than test.name.extractFilename
  248. # A bit hacky but simple and works with tests/testament/tshould_not_work.nim
  249. let name = testName(test, target, extraOptions, allowFailure)
  250. let duration = epochTime() - test.startTime
  251. let success = if test.spec.timeout > 0.0 and duration > test.spec.timeout: reTimeout
  252. else: successOrig
  253. let durationStr = duration.formatFloat(ffDecimal, precision = 2).align(5)
  254. if backendLogging:
  255. backend.writeTestResult(name = name,
  256. category = test.cat.string,
  257. target = $target,
  258. action = $test.spec.action,
  259. result = $success,
  260. expected = expected,
  261. given = given)
  262. r.data.addf("$#\t$#\t$#\t$#", name, expected, given, $success)
  263. template dispNonSkipped(color, outcome) =
  264. maybeStyledEcho color, outcome, fgCyan, test.debugInfo, alignLeft(name, 60), fgBlue, " (", durationStr, " sec)"
  265. template disp(msg) =
  266. maybeStyledEcho styleDim, fgYellow, msg & ' ', styleBright, fgCyan, name
  267. if success == reSuccess:
  268. dispNonSkipped(fgGreen, "PASS: ")
  269. elif success == reDisabled:
  270. if test.spec.inCurrentBatch: disp("SKIP:")
  271. else: disp("NOTINBATCH:")
  272. elif success == reJoined: disp("JOINED:")
  273. else:
  274. dispNonSkipped(fgRed, failString)
  275. maybeStyledEcho styleBright, fgCyan, "Test \"", test.name, "\"", " in category \"", test.cat.string, "\""
  276. maybeStyledEcho styleBright, fgRed, "Failure: ", $success
  277. if givenSpec != nil and givenSpec.debugInfo.len > 0:
  278. echo "debugInfo: " & givenSpec.debugInfo
  279. if success in {reBuildFailed, reNimcCrash, reInstallFailed}:
  280. # expected is empty, no reason to print it.
  281. echo given
  282. else:
  283. maybeStyledEcho fgYellow, "Expected:"
  284. maybeStyledEcho styleBright, expected, "\n"
  285. maybeStyledEcho fgYellow, "Gotten:"
  286. maybeStyledEcho styleBright, given, "\n"
  287. echo diffStrings(expected, given).output
  288. if backendLogging and (isAppVeyor or isAzure):
  289. let (outcome, msg) =
  290. case success
  291. of reSuccess:
  292. ("Passed", "")
  293. of reDisabled, reJoined:
  294. ("Skipped", "")
  295. of reBuildFailed, reNimcCrash, reInstallFailed:
  296. ("Failed", "Failure: " & $success & '\n' & given)
  297. else:
  298. ("Failed", "Failure: " & $success & "\nExpected:\n" & expected & "\n\n" & "Gotten:\n" & given)
  299. if isAzure:
  300. azure.addTestResult(name, test.cat.string, int(duration * 1000), msg, success)
  301. else:
  302. var p = startProcess("appveyor", args = ["AddTest", test.name.replace("\\", "/") & test.options,
  303. "-Framework", "nim-testament", "-FileName",
  304. test.cat.string,
  305. "-Outcome", outcome, "-ErrorMessage", msg,
  306. "-Duration", $(duration * 1000).int],
  307. options = {poStdErrToStdOut, poUsePath, poParentStreams})
  308. discard waitForExit(p)
  309. close(p)
  310. proc toString(inlineError: InlineError, filename: string): string =
  311. result.add "$file($line, $col) $kind: $msg" % [
  312. "file", filename,
  313. "line", $inlineError.line,
  314. "col", $inlineError.col,
  315. "kind", $inlineError.kind,
  316. "msg", $inlineError.msg
  317. ]
  318. proc inlineErrorsMsgs(expected: TSpec): string =
  319. for inlineError in expected.inlineErrors.items:
  320. result.addLine inlineError.toString(expected.filename)
  321. proc checkForInlineErrors(expected, given: TSpec): bool =
  322. for inlineError in expected.inlineErrors:
  323. if inlineError.toString(expected.filename) notin given.nimout:
  324. return false
  325. true
  326. proc nimoutCheck(expected, given: TSpec): bool =
  327. result = true
  328. if expected.nimoutFull:
  329. if expected.nimout != given.nimout:
  330. result = false
  331. elif expected.nimout.len > 0 and not greedyOrderedSubsetLines(expected.nimout, given.nimout):
  332. result = false
  333. proc cmpMsgs(r: var TResults, expected, given: TSpec, test: TTest,
  334. target: TTarget, extraOptions: string) =
  335. if not checkForInlineErrors(expected, given) or
  336. (not expected.nimoutFull and not nimoutCheck(expected, given)):
  337. r.addResult(test, target, extraOptions, expected.nimout & inlineErrorsMsgs(expected), given.nimout, reMsgsDiffer)
  338. elif strip(expected.msg) notin strip(given.msg):
  339. r.addResult(test, target, extraOptions, expected.msg, given.msg, reMsgsDiffer)
  340. elif not nimoutCheck(expected, given):
  341. r.addResult(test, target, extraOptions, expected.nimout, given.nimout, reMsgsDiffer)
  342. elif extractFilename(expected.file) != extractFilename(given.file) and
  343. "internal error:" notin expected.msg:
  344. r.addResult(test, target, extraOptions, expected.file, given.file, reFilesDiffer)
  345. elif expected.line != given.line and expected.line != 0 or
  346. expected.column != given.column and expected.column != 0:
  347. r.addResult(test, target, extraOptions, $expected.line & ':' & $expected.column,
  348. $given.line & ':' & $given.column, reLinesDiffer)
  349. else:
  350. r.addResult(test, target, extraOptions, expected.msg, given.msg, reSuccess)
  351. inc(r.passed)
  352. proc generatedFile(test: TTest, target: TTarget): string =
  353. if target == targetJS:
  354. result = test.name.changeFileExt("js")
  355. else:
  356. let (_, name, _) = test.name.splitFile
  357. let ext = targetToExt[target]
  358. result = nimcacheDir(test.name, test.options, target) / "@m" & name.changeFileExt(ext)
  359. proc needsCodegenCheck(spec: TSpec): bool =
  360. result = spec.maxCodeSize > 0 or spec.ccodeCheck.len > 0
  361. proc codegenCheck(test: TTest, target: TTarget, spec: TSpec, expectedMsg: var string,
  362. given: var TSpec) =
  363. try:
  364. let genFile = generatedFile(test, target)
  365. let contents = readFile(genFile)
  366. for check in spec.ccodeCheck:
  367. if check.len > 0 and check[0] == '\\':
  368. # little hack to get 'match' support:
  369. if not contents.match(check.peg):
  370. given.err = reCodegenFailure
  371. elif contents.find(check.peg) < 0:
  372. given.err = reCodegenFailure
  373. expectedMsg = check
  374. if spec.maxCodeSize > 0 and contents.len > spec.maxCodeSize:
  375. given.err = reCodegenFailure
  376. given.msg = "generated code size: " & $contents.len
  377. expectedMsg = "max allowed size: " & $spec.maxCodeSize
  378. except ValueError:
  379. given.err = reInvalidPeg
  380. echo getCurrentExceptionMsg()
  381. except IOError:
  382. given.err = reCodeNotFound
  383. echo getCurrentExceptionMsg()
  384. proc compilerOutputTests(test: TTest, target: TTarget, extraOptions: string,
  385. given: var TSpec, expected: TSpec; r: var TResults) =
  386. var expectedmsg: string = ""
  387. var givenmsg: string = ""
  388. if given.err == reSuccess:
  389. if expected.needsCodegenCheck:
  390. codegenCheck(test, target, expected, expectedmsg, given)
  391. givenmsg = given.msg
  392. if not nimoutCheck(expected, given) or
  393. not checkForInlineErrors(expected, given):
  394. given.err = reMsgsDiffer
  395. expectedmsg = expected.nimout & inlineErrorsMsgs(expected)
  396. givenmsg = given.nimout.strip
  397. else:
  398. givenmsg = "$ " & given.cmd & '\n' & given.nimout
  399. if given.err == reSuccess: inc(r.passed)
  400. r.addResult(test, target, extraOptions, expectedmsg, givenmsg, given.err)
  401. proc getTestSpecTarget(): TTarget =
  402. if getEnv("NIM_COMPILE_TO_CPP", "false") == "true":
  403. result = targetCpp
  404. else:
  405. result = targetC
  406. var count = 0
  407. proc equalModuloLastNewline(a, b: string): bool =
  408. # allow lazy output spec that omits last newline, but really those should be fixed instead
  409. result = a == b or b.endsWith("\n") and a == b[0 ..< ^1]
  410. proc testSpecHelper(r: var TResults, test: var TTest, expected: TSpec,
  411. target: TTarget, extraOptions: string, nimcache: string) =
  412. test.startTime = epochTime()
  413. if testName(test, target, extraOptions, false) in skips:
  414. test.spec.err = reDisabled
  415. if test.spec.err in {reDisabled, reJoined}:
  416. r.addResult(test, target, extraOptions, "", "", test.spec.err)
  417. inc(r.skipped)
  418. return
  419. var given = callNimCompiler(expected.getCmd, test.name, test.options, nimcache, target, extraOptions)
  420. case expected.action
  421. of actionCompile:
  422. compilerOutputTests(test, target, extraOptions, given, expected, r)
  423. of actionRun:
  424. if given.err != reSuccess:
  425. r.addResult(test, target, extraOptions, "", "$ " & given.cmd & '\n' & given.nimout, given.err, givenSpec = given.addr)
  426. else:
  427. let isJsTarget = target == targetJS
  428. var exeFile = changeFileExt(test.name, if isJsTarget: "js" else: ExeExt)
  429. if not fileExists(exeFile):
  430. r.addResult(test, target, extraOptions, expected.output,
  431. "executable not found: " & exeFile, reExeNotFound)
  432. else:
  433. let nodejs = if isJsTarget: findNodeJs() else: ""
  434. if isJsTarget and nodejs == "":
  435. r.addResult(test, target, extraOptions, expected.output, "nodejs binary not in PATH",
  436. reExeNotFound)
  437. else:
  438. var exeCmd: string
  439. var args = test.testArgs
  440. if isJsTarget:
  441. exeCmd = nodejs
  442. # see D20210217T215950
  443. args = @["--unhandled-rejections=strict", exeFile] & args
  444. else:
  445. exeCmd = exeFile.dup(normalizeExe)
  446. if valgrindEnabled and expected.useValgrind != disabled:
  447. var valgrindOptions = @["--error-exitcode=1"]
  448. if expected.useValgrind != leaking:
  449. valgrindOptions.add "--leak-check=yes"
  450. args = valgrindOptions & exeCmd & args
  451. exeCmd = "valgrind"
  452. var (_, buf, exitCode) = execCmdEx2(exeCmd, args, input = expected.input)
  453. # Treat all failure codes from nodejs as 1. Older versions of nodejs used
  454. # to return other codes, but for us it is sufficient to know that it's not 0.
  455. if exitCode != 0: exitCode = 1
  456. let bufB =
  457. if expected.sortoutput:
  458. var buf2 = buf
  459. buf2.stripLineEnd
  460. var x = splitLines(buf2)
  461. sort(x, system.cmp)
  462. join(x, "\n") & '\n'
  463. else:
  464. buf
  465. if exitCode != expected.exitCode:
  466. given.err = reExitcodesDiffer
  467. r.addResult(test, target, extraOptions, "exitcode: " & $expected.exitCode,
  468. "exitcode: " & $exitCode & "\n\nOutput:\n" &
  469. bufB, reExitcodesDiffer)
  470. elif (expected.outputCheck == ocEqual and not expected.output.equalModuloLastNewline(bufB)) or
  471. (expected.outputCheck == ocSubstr and expected.output notin bufB):
  472. given.err = reOutputsDiffer
  473. r.addResult(test, target, extraOptions, expected.output, bufB, reOutputsDiffer)
  474. compilerOutputTests(test, target, extraOptions, given, expected, r)
  475. of actionReject:
  476. # Make sure its the compiler rejecting and not the system (e.g. segfault)
  477. cmpMsgs(r, expected, given, test, target, extraOptions)
  478. if given.exitCode != QuitFailure:
  479. r.addResult(test, target, extraOptions, "exitcode: " & $QuitFailure,
  480. "exitcode: " & $given.exitCode & "\n\nOutput:\n" &
  481. given.nimout, reExitcodesDiffer)
  482. proc changeTarget(extraOptions: string; defaultTarget: TTarget): TTarget =
  483. result = defaultTarget
  484. var p = parseopt.initOptParser(extraOptions)
  485. while true:
  486. parseopt.next(p)
  487. case p.kind
  488. of cmdEnd: break
  489. of cmdLongOption, cmdShortOption:
  490. if p.key == "b" or p.key == "backend":
  491. result = parseEnum[TTarget](p.val.normalize)
  492. # chooses the last one
  493. else:
  494. discard
  495. proc targetHelper(r: var TResults, test: TTest, expected: TSpec, extraOptions: string) =
  496. for target in expected.targets:
  497. inc(r.total)
  498. if target notin gTargets:
  499. r.addResult(test, target, extraOptions, "", "", reDisabled)
  500. inc(r.skipped)
  501. elif simulate:
  502. inc count
  503. echo "testSpec count: ", count, " expected: ", expected
  504. else:
  505. let nimcache = nimcacheDir(test.name, test.options, target)
  506. var testClone = test
  507. let target = changeTarget(extraOptions, target)
  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. r.addResult(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()