Testing macros?


#1

I looked through a few projects, including rust-lang, and could not find a single example of a macro being automatically tested.

Is this something that’s just not done?

Does anyone know of an example of a macro being tested?

If not, how would one go about testing macros? For instance, how would someone test the println macro in libstd?


#2

What sort of testing are you visualising? One can stick a macro invocation in a #[test] to check the (runtime) result is correct, and to test for compile-time error cases there’s compiletest, which can run the compiler and check any errors/warnings match annotations that describe what is expected. It was pioneered by Rust’s test suite (the src/test/{compile-fail,run-pass} tests are run via compiletest), but is used by some external crates.


#3

What sort of testing are you visualising?

Having never tested macros in other languages I didn’t really know what I was looking for. I thought there may be some magical way to confirm a macro worked as expected (beyond putting it in production and hoping).

Having read your answer it’s pretty clear I was overthinking the subject. With a little refactoring, #[test] should take care of everything I need.

Thanks for the response.


#4

Actually, one huge help would just be knowing what command expands the macro, so I can see what an expected case looks like.

This is possible through some special commands introduced in the book: https://doc.rust-lang.org/book/macros.html#debugging-macro-code