categories.nim 29 KB

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