specs.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. msg.add '\n'
  197. inc result
  198. inc line
  199. col = 1
  200. elif isMsgDelimiter():
  201. trimTrailingMsgWhitespace()
  202. inc result
  203. skipWhitespace()
  204. addInlineError()
  205. inc result, len(inlineErrorKindMarker)
  206. inc col, 1 + len(inlineErrorKindMarker)
  207. kind.setLen 0
  208. msg.setLen 0
  209. parseKind()
  210. skipWhitespace()
  211. parseCaret()
  212. elif s[result] == ']' and s[result+1] == '#':
  213. trimTrailingMsgWhitespace()
  214. inc result, 2
  215. inc col, 2
  216. addInlineError()
  217. break
  218. else:
  219. msg.add s[result]
  220. inc result
  221. inc col
  222. if spec.inlineErrors.len > 0:
  223. spec.unjoinable = true
  224. proc extractSpec(filename: string; spec: var TSpec): string =
  225. const
  226. tripleQuote = "\"\"\""
  227. specStart = "discard " & tripleQuote
  228. var s = readFile(filename)
  229. var i = 0
  230. var a = -1
  231. var b = -1
  232. var line = 1
  233. var col = 1
  234. while i < s.len:
  235. if (i == 0 or s[i-1] != ' ') and s.continuesWith(specStart, i):
  236. # `s[i-1] == '\n'` would not work because of `tests/stdlib/tbase64.nim` which contains BOM (https://en.wikipedia.org/wiki/Byte_order_mark)
  237. const lineMax = 10
  238. if a != -1:
  239. raise newException(ValueError, "testament spec violation: duplicate `specStart` found: " & $(filename, a, b, line))
  240. elif line > lineMax:
  241. # not overly restrictive, but prevents mistaking some `specStart` as spec if deeep inside a test file
  242. raise newException(ValueError, "testament spec violation: `specStart` should be before line $1, or be indented; info: $2" % [$lineMax, $(filename, a, b, line)])
  243. i += specStart.len
  244. a = i
  245. elif a > -1 and b == -1 and s.continuesWith(tripleQuote, i):
  246. b = i
  247. i += tripleQuote.len
  248. elif s[i] == '\n':
  249. inc line
  250. inc i
  251. col = 1
  252. elif s.continuesWith(inlineErrorMarker, i):
  253. i = extractErrorMsg(s, i, line, col, spec)
  254. else:
  255. inc col
  256. inc i
  257. if a >= 0 and b > a:
  258. result = s.substr(a, b-1).multiReplace({"'''": tripleQuote, "\\31": "\31"})
  259. elif a >= 0:
  260. raise newException(ValueError, "testament spec violation: `specStart` found but not trailing `tripleQuote`: $1" % $(filename, a, b, line))
  261. else:
  262. result = ""
  263. proc parseTargets*(value: string): set[TTarget] =
  264. for v in value.normalize.splitWhitespace:
  265. case v
  266. of "c": result.incl(targetC)
  267. of "cpp", "c++": result.incl(targetCpp)
  268. of "objc": result.incl(targetObjC)
  269. of "js": result.incl(targetJS)
  270. else: raise newException(ValueError, "invalid target: '$#'" % v)
  271. proc initSpec*(filename: string): TSpec =
  272. result.file = filename
  273. proc isCurrentBatch*(testamentData: TestamentData; filename: string): bool =
  274. if testamentData.testamentNumBatch != 0:
  275. hash(filename) mod testamentData.testamentNumBatch == testamentData.testamentBatch
  276. else:
  277. true
  278. proc parseSpec*(filename: string): TSpec =
  279. result.file = filename
  280. result.filename = extractFilename(filename)
  281. let specStr = extractSpec(filename, result)
  282. var ss = newStringStream(specStr)
  283. var p: CfgParser
  284. open(p, ss, filename, 1)
  285. var flags: HashSet[string]
  286. var nimoutFound = false
  287. while true:
  288. var e = next(p)
  289. case e.kind
  290. of cfgKeyValuePair:
  291. let key = e.key.normalize
  292. const whiteListMulti = ["disabled", "ccodecheck"]
  293. ## list of flags that are correctly handled when passed multiple times
  294. ## (instead of being overwritten)
  295. if key notin whiteListMulti:
  296. doAssert key notin flags, $(key, filename)
  297. flags.incl key
  298. case key
  299. of "action":
  300. case e.value.normalize
  301. of "compile":
  302. result.action = actionCompile
  303. of "run":
  304. result.action = actionRun
  305. of "reject":
  306. result.action = actionReject
  307. else:
  308. result.parseErrors.addLine "cannot interpret as action: ", e.value
  309. of "file":
  310. if result.msg.len == 0 and result.nimout.len == 0:
  311. result.parseErrors.addLine "errormsg or msg needs to be specified before file"
  312. result.file = e.value
  313. of "line":
  314. if result.msg.len == 0 and result.nimout.len == 0:
  315. result.parseErrors.addLine "errormsg, msg or nimout needs to be specified before line"
  316. discard parseInt(e.value, result.line)
  317. of "column":
  318. if result.msg.len == 0 and result.nimout.len == 0:
  319. result.parseErrors.addLine "errormsg or msg needs to be specified before column"
  320. discard parseInt(e.value, result.column)
  321. of "output":
  322. if result.outputCheck != ocSubstr:
  323. result.outputCheck = ocEqual
  324. result.output = e.value
  325. of "input":
  326. result.input = e.value
  327. of "outputsub":
  328. result.outputCheck = ocSubstr
  329. result.output = strip(e.value)
  330. of "sortoutput":
  331. try:
  332. result.sortoutput = parseCfgBool(e.value)
  333. except:
  334. result.parseErrors.addLine getCurrentExceptionMsg()
  335. of "exitcode":
  336. discard parseInt(e.value, result.exitCode)
  337. result.action = actionRun
  338. of "errormsg":
  339. result.msg = e.value
  340. result.action = actionReject
  341. of "nimout":
  342. result.nimout = e.value
  343. nimoutFound = true
  344. of "nimoutfull":
  345. result.nimoutFull = parseCfgBool(e.value)
  346. of "batchable":
  347. result.unbatchable = not parseCfgBool(e.value)
  348. of "joinable":
  349. result.unjoinable = not parseCfgBool(e.value)
  350. of "valgrind":
  351. when defined(linux) and sizeof(int) == 8:
  352. result.useValgrind = if e.value.normalize == "leaks": leaking
  353. else: ValgrindSpec(parseCfgBool(e.value))
  354. result.unjoinable = true
  355. if result.useValgrind != disabled:
  356. result.outputCheck = ocSubstr
  357. else:
  358. # Windows lacks valgrind. Silly OS.
  359. # Valgrind only supports OSX <= 17.x
  360. result.useValgrind = disabled
  361. of "disabled":
  362. let value = e.value.normalize
  363. case value
  364. of "y", "yes", "true", "1", "on": result.err = reDisabled
  365. of "n", "no", "false", "0", "off": discard
  366. # These values are defined in `compiler/options.isDefined`
  367. of "win":
  368. when defined(windows): result.err = reDisabled
  369. of "linux":
  370. when defined(linux): result.err = reDisabled
  371. of "bsd":
  372. when defined(bsd): result.err = reDisabled
  373. of "osx":
  374. when defined(osx): result.err = reDisabled
  375. of "unix", "posix":
  376. when defined(posix): result.err = reDisabled
  377. of "freebsd":
  378. when defined(freebsd): result.err = reDisabled
  379. of "littleendian":
  380. when defined(littleendian): result.err = reDisabled
  381. of "bigendian":
  382. when defined(bigendian): result.err = reDisabled
  383. of "cpu8", "8bit":
  384. when defined(cpu8): result.err = reDisabled
  385. of "cpu16", "16bit":
  386. when defined(cpu16): result.err = reDisabled
  387. of "cpu32", "32bit":
  388. when defined(cpu32): result.err = reDisabled
  389. of "cpu64", "64bit":
  390. when defined(cpu64): result.err = reDisabled
  391. # These values are for CI environments
  392. of "travis": # deprecated
  393. if isTravis: result.err = reDisabled
  394. of "appveyor": # deprecated
  395. if isAppVeyor: result.err = reDisabled
  396. of "azure":
  397. if isAzure: result.err = reDisabled
  398. else:
  399. # Check whether the value exists as an OS or CPU that is
  400. # defined in `compiler/platform`.
  401. block checkHost:
  402. for os in platform.OS:
  403. # Check if the value exists as OS.
  404. if value == os.name.normalize:
  405. # The value exists; is it the same as the current host?
  406. if value == hostOS.normalize:
  407. # The value exists and is the same as the current host,
  408. # so disable the test.
  409. result.err = reDisabled
  410. # The value was defined, so there is no need to check further
  411. # values or raise an error.
  412. break checkHost
  413. for cpu in platform.CPU:
  414. # Check if the value exists as CPU.
  415. if value == cpu.name.normalize:
  416. # The value exists; is it the same as the current host?
  417. if value == hostCPU.normalize:
  418. # The value exists and is the same as the current host,
  419. # so disable the test.
  420. result.err = reDisabled
  421. # The value was defined, so there is no need to check further
  422. # values or raise an error.
  423. break checkHost
  424. # The value doesn't exist as an OS, CPU, or any previous value
  425. # defined in this case statement, so raise an error.
  426. result.parseErrors.addLine "cannot interpret as a bool: ", e.value
  427. of "cmd":
  428. if e.value.startsWith("nim "):
  429. result.cmd = compilerPrefix & e.value[3..^1]
  430. else:
  431. result.cmd = e.value
  432. of "ccodecheck":
  433. result.ccodeCheck.add e.value
  434. of "maxcodesize":
  435. discard parseInt(e.value, result.maxCodeSize)
  436. of "timeout":
  437. try:
  438. result.timeout = parseFloat(e.value)
  439. except ValueError:
  440. result.parseErrors.addLine "cannot interpret as a float: ", e.value
  441. of "targets", "target":
  442. try:
  443. result.targets.incl parseTargets(e.value)
  444. except ValueError as e:
  445. result.parseErrors.addLine e.msg
  446. of "matrix":
  447. for v in e.value.split(';'):
  448. result.matrix.add(v.strip)
  449. else:
  450. result.parseErrors.addLine "invalid key for test spec: ", e.key
  451. of cfgSectionStart:
  452. result.parseErrors.addLine "section ignored: ", e.section
  453. of cfgOption:
  454. result.parseErrors.addLine "command ignored: ", e.key & ": " & e.value
  455. of cfgError:
  456. result.parseErrors.addLine e.msg
  457. of cfgEof:
  458. break
  459. close(p)
  460. if skips.anyIt(it in result.file):
  461. result.err = reDisabled
  462. if nimoutFound and result.nimout.len == 0 and not result.nimoutFull:
  463. result.parseErrors.addLine "empty `nimout` is vacuously true, use `nimoutFull:true` if intentional"
  464. result.inCurrentBatch = isCurrentBatch(testamentData0, filename) or result.unbatchable
  465. if not result.inCurrentBatch:
  466. result.err = reDisabled
  467. # Interpolate variables in msgs:
  468. template varSub(msg: string): string =
  469. try:
  470. msg % ["/", $DirSep, "file", result.filename]
  471. except ValueError:
  472. result.parseErrors.addLine "invalid variable interpolation (see 'https://nim-lang.github.io/Nim/testament.html#writing-unitests-output-message-variable-interpolation')"
  473. msg
  474. result.nimout = result.nimout.varSub
  475. result.msg = result.msg.varSub
  476. for inlineError in result.inlineErrors.mitems:
  477. inlineError.msg = inlineError.msg.varSub