mitsuhiko / insta

A snapshot testing library for rust
https://insta.rs
Apache License 2.0
2.07k stars 93 forks source link

Change std macro calls to be fully qualified #469

Closed BurntSushi closed 3 months ago

BurntSushi commented 3 months ago

This changes calls like format! and vec! within insta's macros to be std::format! and std::vec!. I ran into this issue in a crate where std's prelude isn't enabled, even in tests. While perhaps a bit of a niche case, I don't think this fix has any downsides.

The specific kind of error that happens is if you use insta::assert_snapshot! (or similar) and the (for example) format! macro isn't in scope. Here's a small example. First a Cargo.toml:

[package]
publish = false
name = "insta-no-std"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
insta = "1.37.0"

[lib]
name = "insta_no_std"
path = "lib.rs"

And now lib.rs:

(EDIT: I forgot to include the #![no_std] attribute when I originally wrote this. I've included it now.)

#![no_std]

#[cfg(test)]
extern crate std;

fn itworks() {
    insta::assert_snapshot!((-128i8).saturating_abs());
}

And now here's what happens when you try to build it:

$ cargo t --no-run
   Compiling insta-no-std v0.1.0 (/home/andrew/tmp/scratch/rust/insta-no-std)
error: cannot find macro `format` in this scope
 --> lib.rs:8:5
  |
8 |     insta::assert_snapshot!((-128i8).saturating_abs());
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in the macro `insta::assert_snapshot` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider importing this macro
  |
3 + use std::format;
  |

error: could not compile `insta-no-std` (lib test) due to 1 previous error

This can be pretty easily worked around by adding use std::format; so that the macro can call it. But I figure it's better to just have the macros do the right thing by default. Moreover, I suspect this is also important in other (perhaps strange) contexts where there is a custom format! macro defined and in scope. insta would use the custom macro instead of the one from std. But with this change, it will always use the one from std.

mitsuhiko commented 3 months ago

Thank you :)