testament.nim 28 KB

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