testament.nim 31 KB

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