categories.nim 29 KB

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