Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Scala macros?

What is the proposed way of performing tests on scala macros?

I realize that one needs two projects due to the necessity of separate compilation. This step, if necessary, is acceptable and mostly clear.

But how do you assert a macro expansion fails when it should? Without some special facility, the test case won't compile and therefore the whole test project won't compile.

I think this assert would require another macro of the form

errors(code: => _): List[CompileError]

which returns the compile errors of the inner macro. The same would be required for testing that warnings occur if they should and so on...

Are there some existing testing facilities for Scala macros?

like image 804
Martin Ring Avatar asked Apr 02 '14 12:04

Martin Ring


People also ask

Does Scala have macros?

One of its flagship features is principled metaprogramming. This includes macros — compile-time code generation. Macros have been pioneered through an experimental API since Scala 2.10. Even though the API was experimental, macros have become a useful tool, leveraged by a number of libraries.


1 Answers

You can use assertDoesNotCompile from ScalaTest. Here is an example of using this to test the Scala typechecker:

import org.scalatest.FunSuite

class TypeTest extends FunSuite {
  test("String vals can't hold ints") {
    assertDoesNotCompile("val x: String = 1")
  }
}

You can pass a string containing an example of when your macro expansion should fail to assertDoesNotCompile. Note that that there is also assertCompiles, if you feel the need for that.

like image 114
Brian McCutchon Avatar answered Sep 20 '22 13:09

Brian McCutchon