testament.nim 28 KB

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