Compile error with my macro in unit test


#1

This is should be simple enough for me to fix on my own, but I am having a mental block figuring out why my unit tests code cannot compile because my custom macro cannot be found.

here’s my project structure:

.
├── Cargo.toml
├── src
│   ├── main.rs
│   ├── processors
│   │   ├── mod.rs
│   │   ├── process_for_individual_test_results.rs
│   │   └── types.rs
│   └── utils
│       ├── environment.rs
│       ├── logger.rs
│       ├── macros.rs
│       ├── mod.rs
│       ├── random.rs
│       └── string_utils.rs

in file utils\macros.rs I have a macro like this:

#[macro_export]
macro_rules! string {
    ($s: expr) => {
        $s.to_string()
    };
}

I also modified, utils\mod.rs to include module macros.rs.

#[macro_use] pub mod macros;

I have a test mod in file processors\process_for_individual_tests_results.rs, like this:

#[cfg(test)]
mod process_for_individual_test_results_tests {

    use super::ProcessIndividualTestResults;
    #[macro_use] use utils::macros;
    #[test]
    fn small_failures_section_success(){
        let mut lines: Vec<String> = Vec::new();
        lines.push(string!("        failures:"));
    }

}

and when I run my tests I get this compile error:

error: cannot find macro `string!` in this scope
   --> src/processors/process_for_individual_test_results.rs:162:20
    |
162 |         lines.push(string!("        failures:"));
    |                    ^^^^^^
    |
    = help: have you added the `#[macro_use]` on the module/import?

Any ideas what I am missing?

Thnx
Matt


#2

#[macro_use] doesn’t work on use. (huh, that should probably produce better diagnostics: I opened an issue)

#[macro_use] can only be used on extern crate name; and mod name;. Furthermore, these items must be declared in the right order, so that anything that defines macros comes before the stuff that uses them.

// main.rs

// wrong
mod processors;

#[macro_use]
mod utils;

// correct
#[macro_use]
mod utils;

mod processors;

#3

Wow. That is it. I did not realize the order mattered one bit. Thank you.