0

I'm following this workaround to get info!, log! etc working on tests:

https://stackoverflow.com/a/67105052/5884503

This is what I did. I created proxy functions to be imported just in the case we're testing, like this:

#[cfg(not(test))] 
use log::{info, error}; // Use log crate when building application
#[cfg(test)]
use crate::{info, error}; // Workaround to use prinltn! for logs.

Here it is:

#[macro_export]
macro_rules! info {
    (target: $target:expr, $($arg:tt)*) => { println!("target: {}, info: {}", $target, $($arg),*) };
    ($($arg:tt)*) => { println!("info: {}", $($arg),*) };
}

#[macro_export]
macro_rules! error {
    (target: $target:expr, $($arg:tt)*) => { printn!("target: {}, info: {}", $target, $($arg),*) };
    ($($arg:tt)*) => { println!("error: {}", $($arg),*) };
}

Then I call like this:

       error!("Unauthorized message has authentication header but WwwAuthenticate fails to parse. RTSP Message: {:?}", message);

but I get:

error: expected expression, found `,`
   --> src/rtsp_machine.rs:440:96
    |
440 |                     "Unauthorized message has no AuthenticationInfo header. RTSP Message: {:?}",
    |                                                                                                ^ expected expression

Something is wrong with the repetition in the macro argument but I don't know what exactly

Gatonito
  • 1,662
  • 5
  • 26
  • 55

1 Answers1

2

You didn't specify the possibility for your arguments to be separated by commas, hence the "expected expression, found ," error.

You must also include format! as the first argument of the generated println! isn't the format chain.

Then, also making the last comma optional with the $(,)? part, I can change your macros to this:

#[macro_export]
macro_rules! error {
    (target: $target:expr $(,$arg:tt)*) => { println!("target: {}, info: {}", $target, format!($($arg,)*)) };
    ($($arg:tt),*$(,)?) => { println!("error: {}", format!($($arg,)*)) };
}

Exemple:

fn main() {
    error!(target: "my target" , " thing={:?}", "test");
    error!("bla={} and bit={}", 54, 7);
}

would print

target: my target, info:  thing="test"
error: bla=54 and bit=7
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758