categories.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. #
  2. #
  3. # Nim Tester
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Include for the tester that contains test suites that test special features
  10. ## of the compiler.
  11. # included from testament.nim
  12. import important_packages
  13. import std/[strformat, strutils]
  14. from std/sequtils import filterIt
  15. const
  16. specialCategories = [
  17. "assert",
  18. "async",
  19. "debugger",
  20. "dll",
  21. "examples",
  22. "gc",
  23. "io",
  24. "js",
  25. "ic",
  26. "lib",
  27. "manyloc",
  28. "nimble-packages",
  29. "niminaction",
  30. "threads",
  31. "untestable", # see trunner_special
  32. "testdata",
  33. "nimcache",
  34. "coroutines",
  35. "osproc",
  36. "shouldfail",
  37. "destructor"
  38. ]
  39. proc isTestFile*(file: string): bool =
  40. let (_, name, ext) = splitFile(file)
  41. result = ext == ".nim" and name.startsWith("t")
  42. # --------------------- DLL generation tests ----------------------------------
  43. proc runBasicDLLTest(c, r: var TResults, cat: Category, options: string) =
  44. const rpath = when defined(macosx):
  45. " --passL:-rpath --passL:@loader_path"
  46. else:
  47. ""
  48. var test1 = makeTest("lib/nimrtl.nim", options & " --outdir:tests/dll", cat)
  49. test1.spec.action = actionCompile
  50. testSpec c, test1
  51. var test2 = makeTest("tests/dll/server.nim", options & " --threads:on" & rpath, cat)
  52. test2.spec.action = actionCompile
  53. testSpec c, test2
  54. var test3 = makeTest("lib/nimhcr.nim", options & " --threads:off --outdir:tests/dll" & rpath, cat)
  55. test3.spec.action = actionCompile
  56. testSpec c, test3
  57. var test4 = makeTest("tests/dll/visibility.nim", options & " --threads:off --app:lib" & rpath, cat)
  58. test4.spec.action = actionCompile
  59. testSpec c, test4
  60. # windows looks in the dir of the exe (yay!):
  61. when not defined(windows):
  62. # posix relies on crappy LD_LIBRARY_PATH (ugh!):
  63. const libpathenv = when defined(haiku): "LIBRARY_PATH"
  64. else: "LD_LIBRARY_PATH"
  65. var libpath = getEnv(libpathenv)
  66. # Temporarily add the lib directory to LD_LIBRARY_PATH:
  67. putEnv(libpathenv, "tests/dll" & (if libpath.len > 0: ":" & libpath else: ""))
  68. defer: putEnv(libpathenv, libpath)
  69. testSpec r, makeTest("tests/dll/client.nim", options & " --threads:on" & rpath, cat)
  70. testSpec r, makeTest("tests/dll/nimhcr_unit.nim", options & " --threads:off" & rpath, cat)
  71. testSpec r, makeTest("tests/dll/visibility.nim", options & " --threads:off" & rpath, cat)
  72. if "boehm" notin options:
  73. # force build required - see the comments in the .nim file for more details
  74. var hcri = makeTest("tests/dll/nimhcr_integration.nim",
  75. options & " --threads:off --forceBuild --hotCodeReloading:on" & rpath, cat)
  76. let nimcache = nimcacheDir(hcri.name, hcri.options, getTestSpecTarget())
  77. let cmd = prepareTestCmd(hcri.spec.getCmd, hcri.name,
  78. hcri.options, nimcache, getTestSpecTarget())
  79. hcri.testArgs = cmd.parseCmdLine
  80. testSpec r, hcri
  81. proc dllTests(r: var TResults, cat: Category, options: string) =
  82. # dummy compile result:
  83. var c = initResults()
  84. runBasicDLLTest c, r, cat, options & " --mm:refc"
  85. runBasicDLLTest c, r, cat, options & " -d:release --mm:refc"
  86. when not defined(windows):
  87. # still cannot find a recent Windows version of boehm.dll:
  88. runBasicDLLTest c, r, cat, options & " --gc:boehm"
  89. runBasicDLLTest c, r, cat, options & " -d:release --gc:boehm"
  90. # ------------------------------ GC tests -------------------------------------
  91. proc gcTests(r: var TResults, cat: Category, options: string) =
  92. template testWithoutMs(filename: untyped) =
  93. testSpec r, makeTest("tests/gc" / filename, options & "--mm:refc", cat)
  94. testSpec r, makeTest("tests/gc" / filename, options &
  95. " -d:release -d:useRealtimeGC --mm:refc", cat)
  96. when filename != "gctest":
  97. testSpec r, makeTest("tests/gc" / filename, options &
  98. " --gc:orc", cat)
  99. testSpec r, makeTest("tests/gc" / filename, options &
  100. " --gc:orc -d:release", cat)
  101. template testWithoutBoehm(filename: untyped) =
  102. testWithoutMs filename
  103. testSpec r, makeTest("tests/gc" / filename, options &
  104. " --gc:markAndSweep", cat)
  105. testSpec r, makeTest("tests/gc" / filename, options &
  106. " -d:release --gc:markAndSweep", cat)
  107. template test(filename: untyped) =
  108. testWithoutBoehm filename
  109. when not defined(windows) and not defined(android):
  110. # AR: cannot find any boehm.dll on the net, right now, so disabled
  111. # for windows:
  112. testSpec r, makeTest("tests/gc" / filename, options &
  113. " --gc:boehm", cat)
  114. testSpec r, makeTest("tests/gc" / filename, options &
  115. " -d:release --gc:boehm", cat)
  116. testWithoutBoehm "foreign_thr"
  117. test "gcemscripten"
  118. test "growobjcrash"
  119. test "gcbench"
  120. test "gcleak"
  121. test "gcleak2"
  122. testWithoutBoehm "gctest"
  123. test "gcleak3"
  124. test "gcleak4"
  125. # Disabled because it works and takes too long to run:
  126. #test "gcleak5"
  127. testWithoutBoehm "weakrefs"
  128. test "cycleleak"
  129. testWithoutBoehm "closureleak"
  130. testWithoutMs "refarrayleak"
  131. testWithoutBoehm "tlists"
  132. testWithoutBoehm "thavlak"
  133. test "stackrefleak"
  134. test "cyclecollector"
  135. testWithoutBoehm "trace_globals"
  136. # ------------------------- threading tests -----------------------------------
  137. proc threadTests(r: var TResults, cat: Category, options: string) =
  138. template test(filename: untyped) =
  139. testSpec r, makeTest(filename, options, cat)
  140. testSpec r, makeTest(filename, options & " -d:release", cat)
  141. testSpec r, makeTest(filename, options & " --tlsEmulation:on", cat)
  142. for t in os.walkFiles("tests/threads/t*.nim"):
  143. test(t)
  144. # ------------------------- IO tests ------------------------------------------
  145. proc ioTests(r: var TResults, cat: Category, options: string) =
  146. # We need readall_echo to be compiled for this test to run.
  147. # dummy compile result:
  148. var c = initResults()
  149. testSpec c, makeTest("tests/system/helpers/readall_echo", options, cat)
  150. # ^- why is this not appended to r? Should this be discarded?
  151. # EDIT: this should be replaced by something like in D20210524T180826,
  152. # likewise in similar instances where `testSpec c` is used, or more generally
  153. # when a test depends on another test, as it makes tests non-independent,
  154. # creating complications for batching and megatest logic.
  155. testSpec r, makeTest("tests/system/tio", options, cat)
  156. # ------------------------- async tests ---------------------------------------
  157. proc asyncTests(r: var TResults, cat: Category, options: string) =
  158. template test(filename: untyped) =
  159. testSpec r, makeTest(filename, options, cat)
  160. for t in os.walkFiles("tests/async/t*.nim"):
  161. test(t)
  162. # ------------------------- debugger tests ------------------------------------
  163. proc debuggerTests(r: var TResults, cat: Category, options: string) =
  164. if fileExists("tools/nimgrep.nim"):
  165. var t = makeTest("tools/nimgrep", options & " --debugger:on", cat)
  166. t.spec.action = actionCompile
  167. # force target to C because of MacOS 10.15 SDK headers bug
  168. # https://github.com/nim-lang/Nim/pull/15612#issuecomment-712471879
  169. t.spec.targets = {targetC}
  170. testSpec r, t
  171. # ------------------------- JS tests ------------------------------------------
  172. proc jsTests(r: var TResults, cat: Category, options: string) =
  173. template test(filename: untyped) =
  174. testSpec r, makeTest(filename, options, cat), {targetJS}
  175. testSpec r, makeTest(filename, options & " -d:release", cat), {targetJS}
  176. for t in os.walkFiles("tests/js/t*.nim"):
  177. test(t)
  178. for testfile in ["exception/texceptions", "exception/texcpt1",
  179. "exception/texcsub", "exception/tfinally",
  180. "exception/tfinally2", "exception/tfinally3",
  181. "actiontable/tactiontable", "method/tmultimjs",
  182. "varres/tvarres0", "varres/tvarres3", "varres/tvarres4",
  183. "varres/tvartup", "misc/tints", "misc/tunsignedinc",
  184. "async/tjsandnativeasync"]:
  185. test "tests/" & testfile & ".nim"
  186. for testfile in ["strutils", "json", "random", "times", "logging"]:
  187. test "lib/pure/" & testfile & ".nim"
  188. # ------------------------- nim in action -----------
  189. proc testNimInAction(r: var TResults, cat: Category, options: string) =
  190. template test(filename: untyped) =
  191. testSpec r, makeTest(filename, options, cat)
  192. template testJS(filename: untyped) =
  193. testSpec r, makeTest(filename, options, cat), {targetJS}
  194. template testCPP(filename: untyped) =
  195. testSpec r, makeTest(filename, options, cat), {targetCpp}
  196. let tests = [
  197. "niminaction/Chapter1/various1",
  198. "niminaction/Chapter2/various2",
  199. "niminaction/Chapter2/resultaccept",
  200. "niminaction/Chapter2/resultreject",
  201. "niminaction/Chapter2/explicit_discard",
  202. "niminaction/Chapter2/no_def_eq",
  203. "niminaction/Chapter2/no_iterator",
  204. "niminaction/Chapter2/no_seq_type",
  205. "niminaction/Chapter3/ChatApp/src/server",
  206. "niminaction/Chapter3/ChatApp/src/client",
  207. "niminaction/Chapter3/various3",
  208. "niminaction/Chapter6/WikipediaStats/concurrency_regex",
  209. "niminaction/Chapter6/WikipediaStats/concurrency",
  210. "niminaction/Chapter6/WikipediaStats/naive",
  211. "niminaction/Chapter6/WikipediaStats/parallel_counts",
  212. "niminaction/Chapter6/WikipediaStats/race_condition",
  213. "niminaction/Chapter6/WikipediaStats/sequential_counts",
  214. "niminaction/Chapter6/WikipediaStats/unguarded_access",
  215. "niminaction/Chapter7/Tweeter/src/tweeter",
  216. "niminaction/Chapter7/Tweeter/src/createDatabase",
  217. "niminaction/Chapter7/Tweeter/tests/database_test",
  218. "niminaction/Chapter8/sdl/sdl_test"
  219. ]
  220. when false:
  221. # Verify that the files have not been modified. Death shall fall upon
  222. # whoever edits these hashes without dom96's permission, j/k. But please only
  223. # edit when making a conscious breaking change, also please try to make your
  224. # commit message clear and notify me so I can easily compile an errata later.
  225. # ---------------------------------------------------------
  226. # Hash-checks are disabled for Nim 1.1 and beyond
  227. # since we needed to fix the deprecated unary '<' operator.
  228. const refHashes = @[
  229. "51afdfa84b3ca3d810809d6c4e5037ba",
  230. "30f07e4cd5eaec981f67868d4e91cfcf",
  231. "d14e7c032de36d219c9548066a97e846",
  232. "b335635562ff26ec0301bdd86356ac0c",
  233. "6c4add749fbf50860e2f523f548e6b0e",
  234. "76de5833a7cc46f96b006ce51179aeb1",
  235. "705eff79844e219b47366bd431658961",
  236. "a1e87b881c5eb161553d119be8b52f64",
  237. "2d706a6ec68d2973ec7e733e6d5dce50",
  238. "c11a013db35e798f44077bc0763cc86d",
  239. "3e32e2c5e9a24bd13375e1cd0467079c",
  240. "a5452722b2841f0c1db030cf17708955",
  241. "dc6c45eb59f8814aaaf7aabdb8962294",
  242. "69d208d281a2e7bffd3eaf4bab2309b1",
  243. "ec05666cfb60211bedc5e81d4c1caf3d",
  244. "da520038c153f4054cb8cc5faa617714",
  245. "59906c8cd819cae67476baa90a36b8c1",
  246. "9a8fe78c588d08018843b64b57409a02",
  247. "8b5d28e985c0542163927d253a3e4fc9",
  248. "783299b98179cc725f9c46b5e3b5381f",
  249. "1a2b3fba1187c68d6a9bfa66854f3318",
  250. "391ff57b38d9ea6f3eeb3fe69ab539d3"
  251. ]
  252. for i, test in tests:
  253. let filename = testsDir / test.addFileExt("nim")
  254. let testHash = getMD5(readFile(filename).string)
  255. doAssert testHash == refHashes[i], "Nim in Action test " & filename &
  256. " was changed: " & $(i: i, testHash: testHash, refHash: refHashes[i])
  257. # Run the tests.
  258. for testfile in tests:
  259. test "tests/" & testfile & ".nim"
  260. let jsFile = "tests/niminaction/Chapter8/canvas/canvas_test.nim"
  261. testJS jsFile
  262. let cppFile = "tests/niminaction/Chapter8/sfml/sfml_test.nim"
  263. testCPP cppFile
  264. # ------------------------- manyloc -------------------------------------------
  265. proc findMainFile(dir: string): string =
  266. # finds the file belonging to ".nim.cfg"; if there is no such file
  267. # it returns the some ".nim" file if there is only one:
  268. const cfgExt = ".nim.cfg"
  269. result = ""
  270. var nimFiles = 0
  271. for kind, file in os.walkDir(dir):
  272. if kind == pcFile:
  273. if file.endsWith(cfgExt): return file[0..^(cfgExt.len+1)] & ".nim"
  274. elif file.endsWith(".nim"):
  275. if result.len == 0: result = file
  276. inc nimFiles
  277. if nimFiles != 1: result.setLen(0)
  278. proc manyLoc(r: var TResults, cat: Category, options: string) =
  279. for kind, dir in os.walkDir("tests/manyloc"):
  280. if kind == pcDir:
  281. when defined(windows):
  282. if dir.endsWith"nake": continue
  283. if dir.endsWith"named_argument_bug": continue
  284. let mainfile = findMainFile(dir)
  285. if mainfile != "":
  286. var test = makeTest(mainfile, options, cat)
  287. test.spec.action = actionCompile
  288. testSpec r, test
  289. proc compileExample(r: var TResults, pattern, options: string, cat: Category) =
  290. for test in os.walkFiles(pattern):
  291. var test = makeTest(test, options, cat)
  292. test.spec.action = actionCompile
  293. testSpec r, test
  294. proc testStdlib(r: var TResults, pattern, options: string, cat: Category) =
  295. var files: seq[string]
  296. proc isValid(file: string): bool =
  297. for dir in parentDirs(file, inclusive = false):
  298. if dir.lastPathPart in ["includes", "nimcache"]:
  299. # e.g.: lib/pure/includes/osenv.nim gives: Error: This is an include file for os.nim!
  300. return false
  301. let name = extractFilename(file)
  302. if name.splitFile.ext != ".nim": return false
  303. for namei in disabledFiles:
  304. # because of `LockFreeHash.nim` which has case
  305. if namei.cmpPaths(name) == 0: return false
  306. return true
  307. for testFile in os.walkDirRec(pattern):
  308. if isValid(testFile):
  309. files.add testFile
  310. files.sort # reproducible order
  311. for testFile in files:
  312. let contents = readFile(testFile)
  313. var testObj = makeTest(testFile, options, cat)
  314. #[
  315. todo:
  316. this logic is fragile:
  317. false positives (if appears in a comment), or false negatives, e.g.
  318. `when defined(osx) and isMainModule`.
  319. Instead of fixing this, see https://github.com/nim-lang/Nim/issues/10045
  320. for a much better way.
  321. ]#
  322. if "when isMainModule" notin contents:
  323. testObj.spec.action = actionCompile
  324. testSpec r, testObj
  325. # ----------------------------- nimble ----------------------------------------
  326. proc listPackagesAll(): seq[NimblePackage] =
  327. var nimbleDir = getEnv("NIMBLE_DIR")
  328. if nimbleDir.len == 0: nimbleDir = getHomeDir() / ".nimble"
  329. let packageIndex = nimbleDir / "packages_official.json"
  330. let packageList = parseFile(packageIndex)
  331. proc findPackage(name: string): JsonNode =
  332. for a in packageList:
  333. if a["name"].str == name: return a
  334. for pkg in important_packages.packages.items:
  335. var pkg = pkg
  336. if pkg.url.len == 0:
  337. let pkg2 = findPackage(pkg.name)
  338. if pkg2 == nil:
  339. raise newException(ValueError, "Cannot find package '$#'." % pkg.name)
  340. pkg.url = pkg2["url"].str
  341. result.add pkg
  342. proc listPackages(packageFilter: string): seq[NimblePackage] =
  343. let pkgs = listPackagesAll()
  344. if packageFilter.len != 0:
  345. # xxx document `packageFilter`, seems like a bad API,
  346. # at least should be a regex; a substring match makes no sense.
  347. result = pkgs.filterIt(packageFilter in it.name)
  348. else:
  349. if testamentData0.batchArg == "allowed_failures":
  350. result = pkgs.filterIt(it.allowFailure)
  351. elif testamentData0.testamentNumBatch == 0:
  352. result = pkgs
  353. else:
  354. let pkgs2 = pkgs.filterIt(not it.allowFailure)
  355. for i in 0..<pkgs2.len:
  356. if i mod testamentData0.testamentNumBatch == testamentData0.testamentBatch:
  357. result.add pkgs2[i]
  358. proc makeSupTest(test, options: string, cat: Category, debugInfo = ""): TTest =
  359. result.cat = cat
  360. result.name = test
  361. result.options = options
  362. result.debugInfo = debugInfo
  363. result.startTime = epochTime()
  364. import std/private/gitutils
  365. proc testNimblePackages(r: var TResults; cat: Category; packageFilter: string) =
  366. let nimbleExe = findExe("nimble")
  367. doAssert nimbleExe != "", "Cannot run nimble tests: Nimble binary not found."
  368. doAssert execCmd("$# update" % nimbleExe) == 0, "Cannot run nimble tests: Nimble update failed."
  369. let packageFileTest = makeSupTest("PackageFileParsed", "", cat)
  370. let packagesDir = "pkgstemp"
  371. createDir(packagesDir)
  372. var errors = 0
  373. try:
  374. let pkgs = listPackages(packageFilter)
  375. for i, pkg in pkgs:
  376. inc r.total
  377. var test = makeSupTest(pkg.name, "", cat, "[$#/$#] " % [$i, $pkgs.len])
  378. let buildPath = packagesDir / pkg.name
  379. template tryCommand(cmd: string, workingDir2 = buildPath, reFailed = reInstallFailed, maxRetries = 1): string =
  380. var outp: string
  381. let ok = retryCall(maxRetry = maxRetries, backoffDuration = 10.0):
  382. var status: int
  383. (outp, status) = execCmdEx(cmd, workingDir = workingDir2)
  384. status == QuitSuccess
  385. if not ok:
  386. if pkg.allowFailure:
  387. inc r.passed
  388. inc r.failedButAllowed
  389. addResult(r, test, targetC, "", "", cmd & "\n" & outp, reFailed, allowFailure = pkg.allowFailure)
  390. continue
  391. outp
  392. if not dirExists(buildPath):
  393. discard tryCommand("git clone $# $#" % [pkg.url.quoteShell, buildPath.quoteShell], workingDir2 = ".", maxRetries = 3)
  394. if not pkg.useHead:
  395. discard tryCommand("git fetch --tags", maxRetries = 3)
  396. let describeOutput = tryCommand("git describe --tags --abbrev=0")
  397. discard tryCommand("git checkout $#" % [describeOutput.strip.quoteShell])
  398. discard tryCommand("nimble install --depsOnly -y", maxRetries = 3)
  399. let cmds = pkg.cmd.split(';')
  400. for i in 0 ..< cmds.len - 1:
  401. discard tryCommand(cmds[i], maxRetries = 3)
  402. discard tryCommand(cmds[^1], reFailed = reBuildFailed)
  403. inc r.passed
  404. r.addResult(test, targetC, "", "", "", reSuccess, allowFailure = pkg.allowFailure)
  405. errors = r.total - r.passed
  406. if errors == 0:
  407. r.addResult(packageFileTest, targetC, "", "", "", reSuccess)
  408. else:
  409. r.addResult(packageFileTest, targetC, "", "", "", reBuildFailed)
  410. except JsonParsingError:
  411. errors = 1
  412. r.addResult(packageFileTest, targetC, "", "", "Invalid package file", reBuildFailed)
  413. raise
  414. except ValueError:
  415. errors = 1
  416. r.addResult(packageFileTest, targetC, "", "", "Unknown package", reBuildFailed)
  417. raise # bug #18805
  418. finally:
  419. if errors == 0: removeDir(packagesDir)
  420. # ---------------- IC tests ---------------------------------------------
  421. proc icTests(r: var TResults; testsDir: string, cat: Category, options: string;
  422. isNavigatorTest: bool) =
  423. const
  424. tooltests = ["compiler/nim.nim"]
  425. writeOnly = " --incremental:writeonly "
  426. readOnly = " --incremental:readonly "
  427. incrementalOn = " --incremental:on -d:nimIcIntegrityChecks "
  428. navTestConfig = " --ic:on -d:nimIcNavigatorTests --hint:Conf:off --warnings:off "
  429. template test(x: untyped) =
  430. testSpecWithNimcache(r, makeRawTest(file, x & options, cat), nimcache)
  431. template editedTest(x: untyped) =
  432. var test = makeTest(file, x & options, cat)
  433. if isNavigatorTest:
  434. test.spec.action = actionCompile
  435. test.spec.targets = {getTestSpecTarget()}
  436. testSpecWithNimcache(r, test, nimcache)
  437. template checkTest() =
  438. var test = makeRawTest(file, options, cat)
  439. test.spec.cmd = compilerPrefix & " check --hint:Conf:off --warnings:off --ic:on $options " & file
  440. testSpecWithNimcache(r, test, nimcache)
  441. if not isNavigatorTest:
  442. for file in tooltests:
  443. let nimcache = nimcacheDir(file, options, getTestSpecTarget())
  444. removeDir(nimcache)
  445. let oldPassed = r.passed
  446. checkTest()
  447. if r.passed == oldPassed+1:
  448. checkTest()
  449. if r.passed == oldPassed+2:
  450. checkTest()
  451. const tempExt = "_temp.nim"
  452. for it in walkDirRec(testsDir):
  453. # for it in ["tests/ic/timports.nim"]: # debugging: to try a specific test
  454. if isTestFile(it) and not it.endsWith(tempExt):
  455. let nimcache = nimcacheDir(it, options, getTestSpecTarget())
  456. removeDir(nimcache)
  457. let content = readFile(it)
  458. for fragment in content.split("#!EDIT!#"):
  459. let file = it.replace(".nim", tempExt)
  460. writeFile(file, fragment)
  461. let oldPassed = r.passed
  462. editedTest(if isNavigatorTest: navTestConfig else: incrementalOn)
  463. if r.passed != oldPassed+1: break
  464. # ----------------------------------------------------------------------------
  465. const AdditionalCategories = ["debugger", "examples", "lib", "ic", "navigator"]
  466. const MegaTestCat = "megatest"
  467. proc `&.?`(a, b: string): string =
  468. # candidate for the stdlib?
  469. result = if b.startsWith(a): b else: a & b
  470. proc processSingleTest(r: var TResults, cat: Category, options, test: string, targets: set[TTarget], targetsSet: bool) =
  471. var targets = targets
  472. if not targetsSet:
  473. let target = if cat.string.normalize == "js": targetJS else: targetC
  474. targets = {target}
  475. doAssert fileExists(test), test & " test does not exist"
  476. testSpec r, makeTest(test, options, cat), targets
  477. proc isJoinableSpec(spec: TSpec): bool =
  478. # xxx simplify implementation using a whitelist of fields that are allowed to be
  479. # set to non-default values (use `fieldPairs`), to avoid issues like bug #16576.
  480. result = useMegatest and not spec.sortoutput and
  481. spec.action == actionRun and
  482. not fileExists(spec.file.changeFileExt("cfg")) and
  483. not fileExists(spec.file.changeFileExt("nims")) and
  484. not fileExists(parentDir(spec.file) / "nim.cfg") and
  485. not fileExists(parentDir(spec.file) / "config.nims") and
  486. spec.cmd.len == 0 and
  487. spec.err != reDisabled and
  488. not spec.unjoinable and
  489. spec.exitCode == 0 and
  490. spec.input.len == 0 and
  491. spec.nimout.len == 0 and
  492. spec.nimoutFull == false and
  493. # so that tests can have `nimoutFull: true` with `nimout.len == 0` with
  494. # the meaning that they expect empty output.
  495. spec.matrix.len == 0 and
  496. spec.outputCheck != ocSubstr and
  497. spec.ccodeCheck.len == 0 and
  498. (spec.targets == {} or spec.targets == {targetC})
  499. if result:
  500. if spec.file.readFile.contains "when isMainModule":
  501. result = false
  502. proc quoted(a: string): string =
  503. # todo: consider moving to system.nim
  504. result.addQuoted(a)
  505. proc runJoinedTest(r: var TResults, cat: Category, testsDir: string, options: string) =
  506. ## returns a list of tests that have problems
  507. #[
  508. xxx create a reusable megatest API after abstracting out testament specific code,
  509. refs https://github.com/timotheecour/Nim/issues/655
  510. and https://github.com/nim-lang/gtk2/pull/28; it's useful in other contexts.
  511. ]#
  512. var specs: seq[TSpec] = @[]
  513. for kind, dir in walkDir(testsDir):
  514. assert dir.startsWith(testsDir)
  515. let cat = dir[testsDir.len .. ^1]
  516. if kind == pcDir and cat notin specialCategories:
  517. for file in walkDirRec(testsDir / cat):
  518. if isTestFile(file):
  519. var spec: TSpec
  520. try:
  521. spec = parseSpec(file)
  522. except ValueError:
  523. # e.g. for `tests/navigator/tincludefile.nim` which have multiple
  524. # specs; this will be handled elsewhere
  525. echo "parseSpec raised ValueError for: '$1', assuming this will be handled outside of megatest" % file
  526. continue
  527. if isJoinableSpec(spec):
  528. specs.add spec
  529. proc cmp(a: TSpec, b: TSpec): auto = cmp(a.file, b.file)
  530. sort(specs, cmp = cmp) # reproducible order
  531. echo "joinable specs: ", specs.len
  532. if simulate:
  533. var s = "runJoinedTest: "
  534. for a in specs: s.add a.file & " "
  535. echo s
  536. return
  537. var megatest: string
  538. # xxx (minor) put outputExceptedFile, outputGottenFile, megatestFile under here or `buildDir`
  539. var outDir = nimcacheDir(testsDir / "megatest", "", targetC)
  540. template toMarker(file, i): string =
  541. "megatest:processing: [$1] $2" % [$i, file]
  542. for i, runSpec in specs:
  543. let file = runSpec.file
  544. let file2 = outDir / ("megatest_a_$1.nim" % $i)
  545. # `include` didn't work with `trecmod2.nim`, so using `import`
  546. let code = "echo $1\nstatic: echo \"CT:\", $1\n" % [toMarker(file, i).quoted]
  547. createDir(file2.parentDir)
  548. writeFile(file2, code)
  549. megatest.add "import $1\nimport $2 as megatest_b_$3\n" % [file2.quoted, file.quoted, $i]
  550. let megatestFile = testsDir / "megatest.nim" # so it uses testsDir / "config.nims"
  551. writeFile(megatestFile, megatest)
  552. let root = getCurrentDir()
  553. var args = @["c", "--nimCache:" & outDir, "-d:testing", "-d:nimMegatest", "--listCmd",
  554. "--path:" & root]
  555. args.add options.parseCmdLine
  556. args.add megatestFile
  557. var (cmdLine, buf, exitCode) = execCmdEx2(command = compilerPrefix, args = args, input = "")
  558. if exitCode != 0:
  559. echo "$ " & cmdLine & "\n" & buf
  560. quit(failString & "megatest compilation failed")
  561. (buf, exitCode) = execCmdEx(megatestFile.changeFileExt(ExeExt).dup normalizeExe)
  562. if exitCode != 0:
  563. echo buf
  564. quit(failString & "megatest execution failed")
  565. const outputExceptedFile = "outputExpected.txt"
  566. const outputGottenFile = "outputGotten.txt"
  567. writeFile(outputGottenFile, buf)
  568. var outputExpected = ""
  569. for i, runSpec in specs:
  570. outputExpected.add toMarker(runSpec.file, i) & "\n"
  571. if runSpec.output.len > 0:
  572. outputExpected.add runSpec.output
  573. if not runSpec.output.endsWith "\n":
  574. outputExpected.add '\n'
  575. if buf != outputExpected:
  576. writeFile(outputExceptedFile, outputExpected)
  577. echo diffFiles(outputGottenFile, outputExceptedFile).output
  578. echo failString & "megatest output different, see $1 vs $2" % [outputGottenFile, outputExceptedFile]
  579. # outputGottenFile, outputExceptedFile not removed on purpose for debugging.
  580. quit 1
  581. else:
  582. echo "megatest output OK"
  583. # ---------------------------------------------------------------------------
  584. proc processCategory(r: var TResults, cat: Category,
  585. options, testsDir: string,
  586. runJoinableTests: bool) =
  587. let cat2 = cat.string.normalize
  588. var handled = false
  589. if isNimRepoTests():
  590. handled = true
  591. case cat2
  592. of "js":
  593. # only run the JS tests on Windows or Linux because Travis is bad
  594. # and other OSes like Haiku might lack nodejs:
  595. if not defined(linux) and isTravis:
  596. discard
  597. else:
  598. jsTests(r, cat, options)
  599. of "dll":
  600. dllTests(r, cat, options)
  601. of "gc":
  602. gcTests(r, cat, options)
  603. of "debugger":
  604. debuggerTests(r, cat, options)
  605. of "manyloc":
  606. manyLoc r, cat, options
  607. of "threads":
  608. threadTests r, cat, options & " --threads:on"
  609. of "io":
  610. ioTests r, cat, options
  611. of "async":
  612. asyncTests r, cat, options
  613. of "lib":
  614. testStdlib(r, "lib/pure/", options, cat)
  615. testStdlib(r, "lib/packages/docutils/", options, cat)
  616. of "examples":
  617. compileExample(r, "examples/*.nim", options, cat)
  618. compileExample(r, "examples/gtk/*.nim", options, cat)
  619. compileExample(r, "examples/talk/*.nim", options, cat)
  620. of "nimble-packages":
  621. testNimblePackages(r, cat, options)
  622. of "niminaction":
  623. testNimInAction(r, cat, options)
  624. of "ic":
  625. icTests(r, testsDir / cat2, cat, options, isNavigatorTest=false)
  626. of "navigator":
  627. icTests(r, testsDir / cat2, cat, options, isNavigatorTest=true)
  628. of "untestable":
  629. # These require special treatment e.g. because they depend on a third party
  630. # dependency; see `trunner_special` which runs some of those.
  631. discard
  632. else:
  633. handled = false
  634. if not handled:
  635. case cat2
  636. of "megatest":
  637. runJoinedTest(r, cat, testsDir, options)
  638. else:
  639. var testsRun = 0
  640. var files: seq[string]
  641. for file in walkDirRec(testsDir &.? cat.string):
  642. if isTestFile(file): files.add file
  643. files.sort # give reproducible order
  644. for i, name in files:
  645. var test = makeTest(name, options, cat)
  646. if runJoinableTests or not isJoinableSpec(test.spec) or cat.string in specialCategories:
  647. discard "run the test"
  648. else:
  649. test.spec.err = reJoined
  650. testSpec r, test
  651. inc testsRun
  652. if testsRun == 0:
  653. const whiteListedDirs = ["deps", "htmldocs", "pkgs"]
  654. # `pkgs` because bug #16556 creates `pkgs` dirs and this can affect some users
  655. # that try an old version of choosenim.
  656. doAssert cat.string in whiteListedDirs,
  657. "Invalid category specified: '$#' not in whilelist: $#" % [cat.string, $whiteListedDirs]
  658. proc processPattern(r: var TResults, pattern, options: string; simulate: bool) =
  659. var testsRun = 0
  660. if dirExists(pattern):
  661. for k, name in walkDir(pattern):
  662. if k in {pcFile, pcLinkToFile} and name.endsWith(".nim"):
  663. if simulate:
  664. echo "Detected test: ", name
  665. else:
  666. var test = makeTest(name, options, Category"pattern")
  667. testSpec r, test
  668. inc testsRun
  669. else:
  670. for name in walkPattern(pattern):
  671. if simulate:
  672. echo "Detected test: ", name
  673. else:
  674. var test = makeTest(name, options, Category"pattern")
  675. testSpec r, test
  676. inc testsRun
  677. if testsRun == 0:
  678. echo "no tests were found for pattern: ", pattern