specs.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. import sequtils, parseutils, strutils, os, streams, parsecfg,
  10. tables, hashes, sets
  11. import compiler/platform
  12. type TestamentData* = ref object
  13. # better to group globals under 1 object; could group the other ones here too
  14. batchArg*: string
  15. testamentNumBatch*: int
  16. testamentBatch*: int
  17. let testamentData0* = TestamentData()
  18. var compilerPrefix* = findExe("nim")
  19. let isTravis* = existsEnv("TRAVIS")
  20. let isAppVeyor* = existsEnv("APPVEYOR")
  21. let isAzure* = existsEnv("TF_BUILD")
  22. var skips*: seq[string]
  23. type
  24. TTestAction* = enum
  25. actionRun = "run"
  26. actionCompile = "compile"
  27. actionReject = "reject"
  28. TOutputCheck* = enum
  29. ocIgnore = "ignore"
  30. ocEqual = "equal"
  31. ocSubstr = "substr"
  32. TResultEnum* = enum
  33. reNimcCrash, # nim compiler seems to have crashed
  34. reMsgsDiffer, # error messages differ
  35. reFilesDiffer, # expected and given filenames differ
  36. reLinesDiffer, # expected and given line numbers differ
  37. reOutputsDiffer,
  38. reExitcodesDiffer, # exit codes of program or of valgrind differ
  39. reTimeout,
  40. reInvalidPeg,
  41. reCodegenFailure,
  42. reCodeNotFound,
  43. reExeNotFound,
  44. reInstallFailed # package installation failed
  45. reBuildFailed # package building failed
  46. reDisabled, # test is disabled
  47. reJoined, # test is disabled because it was joined into the megatest
  48. reSuccess # test was successful
  49. reInvalidSpec # test had problems to parse the spec
  50. TTarget* = enum
  51. targetC = "c"
  52. targetCpp = "cpp"
  53. targetObjC = "objc"
  54. targetJS = "js"
  55. InlineError* = object
  56. kind*: string
  57. msg*: string
  58. line*, col*: int
  59. ValgrindSpec* = enum
  60. disabled, enabled, leaking
  61. TSpec* = object
  62. # xxx make sure `isJoinableSpec` takes into account each field here.
  63. action*: TTestAction
  64. file*, cmd*: string
  65. filename*: string ## Test filename (without path).
  66. input*: string
  67. outputCheck*: TOutputCheck
  68. sortoutput*: bool
  69. output*: string
  70. line*, column*: int
  71. exitCode*: int
  72. msg*: string
  73. ccodeCheck*: seq[string]
  74. maxCodeSize*: int
  75. err*: TResultEnum
  76. inCurrentBatch*: bool
  77. targets*: set[TTarget]
  78. matrix*: seq[string]
  79. nimout*: string
  80. nimoutFull*: bool # whether nimout is all compiler output or a subset
  81. parseErrors*: string # when the spec definition is invalid, this is not empty.
  82. unjoinable*: bool
  83. unbatchable*: bool
  84. # whether this test can be batchable via `NIM_TESTAMENT_BATCH`; only very
  85. # few tests are not batchable; the ones that are not could be turned batchable
  86. # by making the dependencies explicit
  87. useValgrind*: ValgrindSpec
  88. timeout*: float # in seconds, fractions possible,
  89. # but don't rely on much precision
  90. inlineErrors*: seq[InlineError] # line information to error message
  91. debugInfo*: string # debug info to give more context
  92. proc getCmd*(s: TSpec): string =
  93. if s.cmd.len == 0:
  94. result = compilerPrefix & " $target --hints:on -d:testing --nimblePath:build/deps/pkgs2 $options $file"
  95. else:
  96. result = s.cmd
  97. const
  98. targetToExt*: array[TTarget, string] = ["nim.c", "nim.cpp", "nim.m", "js"]
  99. targetToCmd*: array[TTarget, string] = ["c", "cpp", "objc", "js"]
  100. proc defaultOptions*(a: TTarget): string =
  101. case a
  102. of targetJS: "-d:nodejs"
  103. # once we start testing for `nim js -d:nimbrowser` (eg selenium or similar),
  104. # we can adapt this logic; or a given js test can override with `-u:nodejs`.
  105. else: ""
  106. when not declared(parseCfgBool):
  107. # candidate for the stdlib:
  108. proc parseCfgBool(s: string): bool =
  109. case normalize(s)
  110. of "y", "yes", "true", "1", "on": result = true
  111. of "n", "no", "false", "0", "off": result = false
  112. else: raise newException(ValueError, "cannot interpret as a bool: " & s)
  113. proc addLine*(self: var string; pieces: varargs[string]) =
  114. for piece in pieces:
  115. self.add piece
  116. self.add "\n"
  117. const
  118. inlineErrorKindMarker = "tt."
  119. inlineErrorMarker = "#[" & inlineErrorKindMarker
  120. proc extractErrorMsg(s: string; i: int; line: var int; col: var int; spec: var TSpec): int =
  121. ## Extract inline error messages.
  122. ##
  123. ## Can parse a single message for a line:
  124. ##
  125. ## .. code-block:: nim
  126. ##
  127. ## proc generic_proc*[T] {.no_destroy, userPragma.} = #[tt.Error
  128. ## ^ 'generic_proc' should be: 'genericProc' [Name] ]#
  129. ##
  130. ## Can parse multiple messages for a line when they are separated by ';':
  131. ##
  132. ## .. code-block:: nim
  133. ##
  134. ## proc generic_proc*[T] {.no_destroy, userPragma.} = #[tt.Error
  135. ## ^ 'generic_proc' should be: 'genericProc' [Name]; tt.Error
  136. ## ^ 'no_destroy' should be: 'nodestroy' [Name]; tt.Error
  137. ## ^ 'userPragma' should be: 'user_pragma' [template declared in mstyleCheck.nim(10, 9)] [Name] ]#
  138. ##
  139. ## .. code-block:: nim
  140. ##
  141. ## proc generic_proc*[T] {.no_destroy, userPragma.} = #[tt.Error
  142. ## ^ 'generic_proc' should be: 'genericProc' [Name];
  143. ## tt.Error ^ 'no_destroy' should be: 'nodestroy' [Name];
  144. ## tt.Error ^ 'userPragma' should be: 'user_pragma' [template declared in mstyleCheck.nim(10, 9)] [Name] ]#
  145. ##
  146. result = i + len(inlineErrorMarker)
  147. inc col, len(inlineErrorMarker)
  148. let msgLine = line
  149. var msgCol = -1
  150. var msg = ""
  151. var kind = ""
  152. template parseKind =
  153. while result < s.len and s[result] in IdentChars:
  154. kind.add s[result]
  155. inc result
  156. inc col
  157. if kind notin ["Hint", "Warning", "Error"]:
  158. spec.parseErrors.addLine "expected inline message kind: Hint, Warning, Error"
  159. template skipWhitespace =
  160. while result < s.len and s[result] in Whitespace:
  161. if s[result] == '\n':
  162. col = 1
  163. inc line
  164. else:
  165. inc col
  166. inc result
  167. template parseCaret =
  168. if result < s.len and s[result] == '^':
  169. msgCol = col
  170. inc result
  171. inc col
  172. skipWhitespace()
  173. else:
  174. spec.parseErrors.addLine "expected column marker ('^') for inline message"
  175. template isMsgDelimiter: bool =
  176. s[result] == ';' and
  177. (block:
  178. let nextTokenIdx = result + 1 + parseutils.skipWhitespace(s, result + 1)
  179. if s.len > nextTokenIdx + len(inlineErrorKindMarker) and
  180. s[nextTokenIdx..(nextTokenIdx + len(inlineErrorKindMarker) - 1)] == inlineErrorKindMarker:
  181. true
  182. else:
  183. false)
  184. template trimTrailingMsgWhitespace =
  185. while msg.len > 0 and msg[^1] in Whitespace:
  186. setLen msg, msg.len - 1
  187. template addInlineError =
  188. doAssert msg[^1] notin Whitespace
  189. if kind == "Error": spec.action = actionReject
  190. spec.inlineErrors.add InlineError(kind: kind, msg: msg, line: msgLine, col: msgCol)
  191. parseKind()
  192. skipWhitespace()
  193. parseCaret()
  194. while result < s.len-1:
  195. if s[result] == '\n':
  196. if result > 0 and s[result - 1] == '\r':
  197. msg[^1] = '\n'
  198. else:
  199. msg.add '\n'
  200. inc result
  201. inc line
  202. col = 1
  203. elif isMsgDelimiter():
  204. trimTrailingMsgWhitespace()
  205. inc result
  206. skipWhitespace()
  207. addInlineError()
  208. inc result, len(inlineErrorKindMarker)
  209. inc col, 1 + len(inlineErrorKindMarker)
  210. kind.setLen 0
  211. msg.setLen 0
  212. parseKind()
  213. skipWhitespace()
  214. parseCaret()
  215. elif s[result] == ']' and s[result+1] == '#':
  216. trimTrailingMsgWhitespace()
  217. inc result, 2
  218. inc col, 2
  219. addInlineError()
  220. break
  221. else:
  222. msg.add s[result]
  223. inc result
  224. inc col
  225. if spec.inlineErrors.len > 0:
  226. spec.unjoinable = true
  227. proc extractSpec(filename: string; spec: var TSpec): string =
  228. const
  229. tripleQuote = "\"\"\""
  230. specStart = "discard " & tripleQuote
  231. var s = readFile(filename)
  232. var i = 0
  233. var a = -1
  234. var b = -1
  235. var line = 1
  236. var col = 1
  237. while i < s.len:
  238. if (i == 0 or s[i-1] != ' ') and s.continuesWith(specStart, i):
  239. # `s[i-1] == '\n'` would not work because of `tests/stdlib/tbase64.nim` which contains BOM (https://en.wikipedia.org/wiki/Byte_order_mark)
  240. const lineMax = 10
  241. if a != -1:
  242. raise newException(ValueError, "testament spec violation: duplicate `specStart` found: " & $(filename, a, b, line))
  243. elif line > lineMax:
  244. # not overly restrictive, but prevents mistaking some `specStart` as spec if deeep inside a test file
  245. raise newException(ValueError, "testament spec violation: `specStart` should be before line $1, or be indented; info: $2" % [$lineMax, $(filename, a, b, line)])
  246. i += specStart.len
  247. a = i
  248. elif a > -1 and b == -1 and s.continuesWith(tripleQuote, i):
  249. b = i
  250. i += tripleQuote.len
  251. elif s[i] == '\n':
  252. inc line
  253. inc i
  254. col = 1
  255. elif s.continuesWith(inlineErrorMarker, i):
  256. i = extractErrorMsg(s, i, line, col, spec)
  257. else:
  258. inc col
  259. inc i
  260. if a >= 0 and b > a:
  261. result = s.substr(a, b-1).multiReplace({"'''": tripleQuote, "\\31": "\31"})
  262. elif a >= 0:
  263. raise newException(ValueError, "testament spec violation: `specStart` found but not trailing `tripleQuote`: $1" % $(filename, a, b, line))
  264. else:
  265. result = ""
  266. proc parseTargets*(value: string): set[TTarget] =
  267. for v in value.normalize.splitWhitespace:
  268. case v
  269. of "c": result.incl(targetC)
  270. of "cpp", "c++": result.incl(targetCpp)
  271. of "objc": result.incl(targetObjC)
  272. of "js": result.incl(targetJS)
  273. else: raise newException(ValueError, "invalid target: '$#'" % v)
  274. proc initSpec*(filename: string): TSpec =
  275. result.file = filename
  276. proc isCurrentBatch*(testamentData: TestamentData; filename: string): bool =
  277. if testamentData.testamentNumBatch != 0:
  278. hash(filename) mod testamentData.testamentNumBatch == testamentData.testamentBatch
  279. else:
  280. true
  281. proc parseSpec*(filename: string): TSpec =
  282. result.file = filename
  283. result.filename = extractFilename(filename)
  284. let specStr = extractSpec(filename, result)
  285. var ss = newStringStream(specStr)
  286. var p: CfgParser
  287. open(p, ss, filename, 1)
  288. var flags: HashSet[string]
  289. var nimoutFound = false
  290. while true:
  291. var e = next(p)
  292. case e.kind
  293. of cfgKeyValuePair:
  294. let key = e.key.normalize
  295. const whiteListMulti = ["disabled", "ccodecheck"]
  296. ## list of flags that are correctly handled when passed multiple times
  297. ## (instead of being overwritten)
  298. if key notin whiteListMulti:
  299. doAssert key notin flags, $(key, filename)
  300. flags.incl key
  301. case key
  302. of "action":
  303. case e.value.normalize
  304. of "compile":
  305. result.action = actionCompile
  306. of "run":
  307. result.action = actionRun
  308. of "reject":
  309. result.action = actionReject
  310. else:
  311. result.parseErrors.addLine "cannot interpret as action: ", e.value
  312. of "file":
  313. if result.msg.len == 0 and result.nimout.len == 0:
  314. result.parseErrors.addLine "errormsg or msg needs to be specified before file"
  315. result.file = e.value
  316. of "line":
  317. if result.msg.len == 0 and result.nimout.len == 0:
  318. result.parseErrors.addLine "errormsg, msg or nimout needs to be specified before line"
  319. discard parseInt(e.value, result.line)
  320. of "column":
  321. if result.msg.len == 0 and result.nimout.len == 0:
  322. result.parseErrors.addLine "errormsg or msg needs to be specified before column"
  323. discard parseInt(e.value, result.column)
  324. of "output":
  325. if result.outputCheck != ocSubstr:
  326. result.outputCheck = ocEqual
  327. result.output = e.value
  328. of "input":
  329. result.input = e.value
  330. of "outputsub":
  331. result.outputCheck = ocSubstr
  332. result.output = strip(e.value)
  333. of "sortoutput":
  334. try:
  335. result.sortoutput = parseCfgBool(e.value)
  336. except:
  337. result.parseErrors.addLine getCurrentExceptionMsg()
  338. of "exitcode":
  339. discard parseInt(e.value, result.exitCode)
  340. result.action = actionRun
  341. of "errormsg":
  342. result.msg = e.value
  343. result.action = actionReject
  344. of "nimout":
  345. result.nimout = e.value
  346. nimoutFound = true
  347. of "nimoutfull":
  348. result.nimoutFull = parseCfgBool(e.value)
  349. of "batchable":
  350. result.unbatchable = not parseCfgBool(e.value)
  351. of "joinable":
  352. result.unjoinable = not parseCfgBool(e.value)
  353. of "valgrind":
  354. when defined(linux) and sizeof(int) == 8:
  355. result.useValgrind = if e.value.normalize == "leaks": leaking
  356. else: ValgrindSpec(parseCfgBool(e.value))
  357. result.unjoinable = true
  358. if result.useValgrind != disabled:
  359. result.outputCheck = ocSubstr
  360. else:
  361. # Windows lacks valgrind. Silly OS.
  362. # Valgrind only supports OSX <= 17.x
  363. result.useValgrind = disabled
  364. of "disabled":
  365. let value = e.value.normalize
  366. case value
  367. of "y", "yes", "true", "1", "on": result.err = reDisabled
  368. of "n", "no", "false", "0", "off": discard
  369. # These values are defined in `compiler/options.isDefined`
  370. of "win":
  371. when defined(windows): result.err = reDisabled
  372. of "linux":
  373. when defined(linux): result.err = reDisabled
  374. of "bsd":
  375. when defined(bsd): result.err = reDisabled
  376. of "osx":
  377. when defined(osx): result.err = reDisabled
  378. of "unix", "posix":
  379. when defined(posix): result.err = reDisabled
  380. of "freebsd":
  381. when defined(freebsd): result.err = reDisabled
  382. of "littleendian":
  383. when defined(littleendian): result.err = reDisabled
  384. of "bigendian":
  385. when defined(bigendian): result.err = reDisabled
  386. of "cpu8", "8bit":
  387. when defined(cpu8): result.err = reDisabled
  388. of "cpu16", "16bit":
  389. when defined(cpu16): result.err = reDisabled
  390. of "cpu32", "32bit":
  391. when defined(cpu32): result.err = reDisabled
  392. of "cpu64", "64bit":
  393. when defined(cpu64): result.err = reDisabled
  394. # These values are for CI environments
  395. of "travis": # deprecated
  396. if isTravis: result.err = reDisabled
  397. of "appveyor": # deprecated
  398. if isAppVeyor: result.err = reDisabled
  399. of "azure":
  400. if isAzure: result.err = reDisabled
  401. else:
  402. # Check whether the value exists as an OS or CPU that is
  403. # defined in `compiler/platform`.
  404. block checkHost:
  405. for os in platform.OS:
  406. # Check if the value exists as OS.
  407. if value == os.name.normalize:
  408. # The value exists; is it the same as the current host?
  409. if value == hostOS.normalize:
  410. # The value exists and is the same as the current host,
  411. # so disable the test.
  412. result.err = reDisabled
  413. # The value was defined, so there is no need to check further
  414. # values or raise an error.
  415. break checkHost
  416. for cpu in platform.CPU:
  417. # Check if the value exists as CPU.
  418. if value == cpu.name.normalize:
  419. # The value exists; is it the same as the current host?
  420. if value == hostCPU.normalize:
  421. # The value exists and is the same as the current host,
  422. # so disable the test.
  423. result.err = reDisabled
  424. # The value was defined, so there is no need to check further
  425. # values or raise an error.
  426. break checkHost
  427. # The value doesn't exist as an OS, CPU, or any previous value
  428. # defined in this case statement, so raise an error.
  429. result.parseErrors.addLine "cannot interpret as a bool: ", e.value
  430. of "cmd":
  431. if e.value.startsWith("nim "):
  432. result.cmd = compilerPrefix & e.value[3..^1]
  433. else:
  434. result.cmd = e.value
  435. of "ccodecheck":
  436. result.ccodeCheck.add e.value
  437. of "maxcodesize":
  438. discard parseInt(e.value, result.maxCodeSize)
  439. of "timeout":
  440. try:
  441. result.timeout = parseFloat(e.value)
  442. except ValueError:
  443. result.parseErrors.addLine "cannot interpret as a float: ", e.value
  444. of "targets", "target":
  445. try:
  446. result.targets.incl parseTargets(e.value)
  447. except ValueError as e:
  448. result.parseErrors.addLine e.msg
  449. of "matrix":
  450. for v in e.value.split(';'):
  451. result.matrix.add(v.strip)
  452. else:
  453. result.parseErrors.addLine "invalid key for test spec: ", e.key
  454. of cfgSectionStart:
  455. result.parseErrors.addLine "section ignored: ", e.section
  456. of cfgOption:
  457. result.parseErrors.addLine "command ignored: ", e.key & ": " & e.value
  458. of cfgError:
  459. result.parseErrors.addLine e.msg
  460. of cfgEof:
  461. break
  462. close(p)
  463. if skips.anyIt(it in result.file):
  464. result.err = reDisabled
  465. if nimoutFound and result.nimout.len == 0 and not result.nimoutFull:
  466. result.parseErrors.addLine "empty `nimout` is vacuously true, use `nimoutFull:true` if intentional"
  467. result.inCurrentBatch = isCurrentBatch(testamentData0, filename) or result.unbatchable
  468. if not result.inCurrentBatch:
  469. result.err = reDisabled
  470. # Interpolate variables in msgs:
  471. template varSub(msg: string): string =
  472. try:
  473. msg % ["/", $DirSep, "file", result.filename]
  474. except ValueError:
  475. result.parseErrors.addLine "invalid variable interpolation (see 'https://nim-lang.github.io/Nim/testament.html#writing-unitests-output-message-variable-interpolation')"
  476. msg
  477. result.nimout = result.nimout.varSub
  478. result.msg = result.msg.varSub
  479. for inlineError in result.inlineErrors.mitems:
  480. inlineError.msg = inlineError.msg.varSub