testament.nim 28 KB

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