Is it possible to write a `#[test]` to catch panics in proc_macros?


#1

Is it possible to write a #[test] to catch panics in proc_macros?

#[proc_macro_derive(X)]
pub fn mymacro(input: TokenStream) -> TokenStream {
    panic!("catch me if you can!");
}

… asking for a friend :slight_smile:


#2

Option one is to implement it as a doc-test, then you can use the compile_fail attribute to check that it fails, you can’t really introspect the errors if you do this.

Option two is to split your proc-macro into two crates, the first is the one that is an actual proc-macro crate with the proc_macro_derive in it, that just then calls into the second crate which is a normal crate with a normal fn foo(TokenStream) -> Result<TokenStream, MyError> and unwraps the result. You can then implement normal tests in the second crate checking for error conditions, using something like quote! to generate the TokenStreams to pass in to it.


#3

Oh yes of course! Awesome thanks.

10 mins later … and it works! v happy.


#4

compiletest is another way to test for failures that are supposed to happen at compile time.