Skip to content

Can't unit test procedural macros #110247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
TadaHrd opened this issue Apr 12, 2023 · 3 comments
Closed

Can't unit test procedural macros #110247

TadaHrd opened this issue Apr 12, 2023 · 3 comments
Labels
A-libtest Area: `#[test]` / the `test` library A-proc-macros Area: Procedural macros

Comments

@TadaHrd
Copy link

TadaHrd commented Apr 12, 2023

I have this test:

mod tests {
    use crate::str2code;
    #[test]
    fn test() {
        str2code!(r#"println!("Hello, world!");"#);
    }
}

The str2code macro is a procedural macro that I made.

#[proc_macro]
pub fn str2code(input: TokenStream) -> TokenStream

It gives this error:

error: can't use a procedural macro from the same crate that defines it
  --> src\lib.rs:31:9
   |
31 |         str2code!(r#"println!("Hello, world!");"#);
   |         ^^^^^^^^

Why does the compiler not let me test my macros and why does this exist?

@clubby789
Copy link
Contributor

Procedural macros are essentially compiler plugins, and need to be compiled before they're used. As the error says, it can't us used within the crate it's defined in. You can instead define your tests in <project-dir>/tests/<file>.rs

@jyn514 jyn514 changed the title Can't test procedural macros Can't unit test procedural macros Apr 13, 2023
@jyn514 jyn514 added A-libtest Area: `#[test]` / the `test` library A-proc-macros Area: Procedural macros labels Apr 13, 2023
@TadaHrd
Copy link
Author

TadaHrd commented Apr 13, 2023

I get it now. I would have thought that the devs would put effort into making code easier for this.

@TadaHrd TadaHrd closed this as completed Apr 13, 2023
@clubby789
Copy link
Contributor

I've opend a PR to note a suggestion for tests

matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Apr 23, 2023
…jackh726

Suggest using integration tests for test crate using own proc-macro

cc rust-lang#110247
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Apr 24, 2023
…jackh726

Suggest using integration tests for test crate using own proc-macro

cc rust-lang#110247
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Apr 24, 2023
…jackh726

Suggest using integration tests for test crate using own proc-macro

cc rust-lang#110247
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-libtest Area: `#[test]` / the `test` library A-proc-macros Area: Procedural macros
Projects
None yet
Development

No branches or pull requests

3 participants