categories.nim 29 KB

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