specs.nim 18 KB

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