rust 如何让Cargo Test漂亮打印失败输出

dfty9e19  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(234)

我有一个Rust测试,它比较实现PartialEqDebug的两个结构体。
根据cargo test输出的帮助页面,应该可以“漂亮地打印”每个失败Assert的左参数和右参数:

$ cargo test_foo --lib -- --help

warning: `google2005` (lib test) generated 4 warnings
    Finished test [unoptimized + debuginfo] target(s) in 0.07s
     Running unittests (target/debug/deps/foo)
Usage: test_foo [OPTIONS] [FILTERS...]

Options:
        --include-ignored 
                        Run ignored and not ignored tests
        --ignored       Run only ignored tests
...
***** snipped *****
...
        --format pretty|terse|json|junit
                        Configure formatting of output:
                        pretty = Print verbose output;
                        terse = Display one character per test;
                        json = Output a json document;
                        junit = Output a JUnit document

...
***** snipped *****

我希望这样可以打印出结构体,并带有适当的缩进,就像在Debug输出中使用{:#?}漂亮打印标记一样。但是它似乎没有任何效果:

$ cargo test test_foo --lib -- --format pretty
   Finished test [unoptimized + debuginfo] target(s) in 0.07s
     Running unittests (target/debug/deps/foo)

running 1 test
test parser::test::test_walk_scrapes_description ... FAILED

failures:

---- parser::test::test_walk_scrapes_description stdout ----
thread 'parser::test::test_walk_scrapes_description' panicked at 'assertion failed: `(left == right)`
  left: `Cat { name: "Fluffy", age: 8, breed: "Siamese", color: "Brown", weight: 12, chip_number: 10001001 }`,
 right: `Cat { name: "Fluffy", age: 8, breed: "Siamese", color: "Brown", weight: 13, chip_number: 10010001 }`', src/parser.rs:170:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

failures:
    parser::test::test_walk_scrapes_description

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 13 filtered out; finished in 0.00s

我认为这是可能做到这样的事情:

left: `Cat {
             name: "Fluffy",
             age: 8,
             breed: "Siamese",
             color: "Brown",
             weight: 12,
             chip_number: 10001001
 }`,
 right: `Cat {
             name: "Fluffy",
             age: 8,
             breed: "Siamese",
             color: "Brown",
             weight: 13,
             chip_number: 10010001
 }`',

我已经尝试了rustc 1.59.0 (9d1b2106e 2022-02-23)rustc 1.63.0-nightly (a6b8c6954 2022-06-03)

5rgfhyps

5rgfhyps1#

由于assert_eq!()本身打印内容,而cargo test获取的是已经格式化的字符串,因此这是相当有问题的。
也不可能对宏进行特征门控,并在test下精确打印变量,因为std的代码(目前)不能进行特征门控。
不过,您可以编写宏来执行此操作,或者使用pretty-assertions之类的库。
但是请注意,RFC改进了assert!()宏的显示(通常不认为这是一个重大更改),因此将来也有可能修复此问题:

相关问题