jxy February 2016

How do I write unit test for code that should fail to compile in Nim?

I wrote most of my unit test with the help of the unittest module, but I’m 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 the compiler always errors during compilation (the type and template would be in a separate module), how do 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)

Answers


zah February 2016

You can do something similar with the compiles magic, provided 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

Notice how at the top of the file, we define accept and reject as simple static assertions using the compiles magic and we use them throughout the file to test valid and invalid overloaded calls.

Personally, I think failing at compile-time is better, but you can assign the result of compiles to a run-time value or use it in a check statement. The only advantage of this would be that failures will be reported in the standard way for the unittest library.

Post Status

Asked in February 2016
Viewed 3,102 times
Voted 11
Answered 1 times

Search




Leave an answer