How to write unit test for code that should not compile in Nim?

I wrote most of my unit test with a module unittest, but Im not sure how to use it for code that the compiler should reject at compile time. For example, if I want to write the following code and make sure that there were always compilation errors during compilation (the type and template will be in a separate module), how can I write a test case for this?

import macros
type
  T[n:static[int]] = object
template foo3(n: int): expr =
  static:
    if n > 3: error "n > 3"
  type T3 = T[n]
  T3
var
  bar: foo3(4)
+4
source share
3 answers

You can do something similar with the magic compilesprovided by the system module.

Here is an example from the compiler test suite:
https://github.com/nim-lang/Nim/blob/devel/tests/metatype/tbindtypedesc.nim#L19

, accept reject compiles, .

, , compiles check. , unittest.

+3

check compiles:

template notCompiles*(e: untyped): untyped =
  not compiles(e)

# usage in unit tests:
check:
  notCompiles: 
    does not compile
  notCompiles:
    let x = 1    # would fail

, not , .

+1

https://github.com/shaunc/cucumber_nim/blob/b1601a795dbf8ea0d0b5d96bf5b6a1cd90271327/tests/steps/dynmodule.nim

, nim. , , :

  sourceFN = "foo.nim"
  ... (write source) ...
  libFN = "foo.dll"
  let output = execProcess(
    "nim c --verbosity:0 --app:lib $1" % sourceFN,
    options = {poStdErrToStdOut, poUsePath, poEvalCommand})
  if not fileExists(libFN):
    echo "COULDN'T COMPILE"
0
source

Source: https://habr.com/ru/post/1627863/


All Articles