Mostly to learn how to write procedural macro, I tried to tackle a very simple use case which is: provide a temporary folder to a test function that will be wiped out once the test is done.
For example, I would write something like
#[test_with_tempdir]
fn my_test(path: &Path) {
// write tests using path as an existing temporary folder
}
So far, I've been able to write this macro which basically take the input TokenStream
, and wrap it inside another function with no argument that creates a temporary folder, then call the inside function with the provided &Path
(see here). And this works fine... for a happy scenario that will pass. As soon as I try to test scenarios that I expect to fail.
#[test_with_tempdir]
#[should_panic]
fn my_test(path: &Path) {
// write tests
}
the compiler complains that my #[should_panic]
is a
warning: unused attribute
--> tests/tempdir.rs:47:1
|
47 | #[should_panic] | ^^^^^^^^^^^^^^^
|
= note: #[warn(unused_attributes)] on by default
I realized that maybe the #[should_panic]
was behaving weirdly because it didn't find a corresponding #[test]
so I experimented a change in my design with something like.
#[test]
#[with_tempdir]
fn my_test(path: &Path) {
// write tests
}
but then the compiler would tell me this
error: functions used as tests can not have any arguments
--> tests/tempdir.rs:12:1
|
12 | / fn path_exists(path: &Path) {
13 | | assert_eq!(path.exists(), true);
14 | | }
| |_^
A few questions comes to mind:
- Is it possible to make my macro be executed before
#[test]
so I can replace the function with a no-argument function before#[test]
start to execute? - When there is multiple macros on a function, is the order important?
- Can one macro know there is another one, parse it and interpret it (for example, does
#[test]
know there is#[should_panic]
and behave accordingly)? - How can I make the
#[should_panic]
be considered? I could obviously change the design to accept something like#[test_with_tempdir(should_panic)]
for example, but it'd be nice to be able to reuse existing macros#[test]
and#[should_panic]
instead of rewriting everything
There is a git repository temp_testdir_proc_macro
which is quite experimental for now but I believe the code is readable. Don't hesitate to ask questions if things are not clear.
And in advance, thank you for those who will take the time to read, maybe understand and even more answer to my ask for help
UPDATE: I've moved the repository to the following link GitHub - woshilapin/with_tempdir_procmacro so some of the above link will likely be outdated.