当 Test::More 像 arrayrefs 和 hashrefs 一样相互比较时,相应的诊断消息确实提供了丰富的信息,并显示了结构不同的第一个索引,而不管嵌套深度如何。但是,当它将 arrayref 或 hashref 与简单的标量进行比较时,它会在诊断消息中生成一个字符串化的标量(带有内存地址和引用类型),这很难解释。
有没有办法以自定义方式(例如使用 Data::Dumper)将 Test::More 配置为 pretty-print 数组或 hashrefs?
这是一个带有两个测试用例的示例。第一个让您深入了解程序中存在但出乎意料的内容。第二个通知用户字符串和 arrayref 之间的类型不匹配,但不打印 arrayref 中的任何项目。
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 2;
is_deeply(
{
a => [5],
},
{
a => [5, 6, 8],
},
'compare two hashrefs structurally (very informative output)',
);
is_deeply(
[5, 6, 8],
"",
'compare two "incompatible" values structurally (uninformative output)',
);
TAP 输出:
1..2
not ok 1 - compare two hashrefs structurally (very informative output)
# Failed test 'compare two hashrefs structurally (very informative output)'
# at test-more-failure.pl line 6.
# Structures begin differing at:
# $got->{a}[1] = Does not exist
# $expected->{a}[1] = '6'
not ok 2 - compare two "incompatible" values structurally (uninformative output)
# Failed test 'compare two "incompatible" values structurally (uninformative output)'
# at test-more-failure.pl line 16.
# Structures begin differing at:
# $got = ARRAY(0x7fe66b82cde8)
# $expected = ''
# Looks like you failed 2 tests of 2.
查看
is_deeply
的执行情况在 Test::More 中,似乎没有办法使用自定义的 pretty-print 或配置模块的详细程度。至少没有一个对我来说是显而易见的。当我们比较引用和非引用时会发生以下情况:
https://metacpan.org/source/EXODIST/Test-Simple-1.302062/lib/Test/More.pm#L1121
它似乎在调用
_format_stack({vals => [...]})
而不是 _format_stack(...)
https://metacpan.org/source/EXODIST/Test-Simple-1.302062/lib/Test/More.pm#L1139
最佳答案
tl;博士使用is_deeply($this, $that) || diag explain $this
根据具体情况。
你好。 I'm the one to blame for is_deeply
.它被刻意设计为在出现故障时不会吐出潜在的巨大数据结构。相反,它停在第一个差异处。出于这个原因,您可能不想全局制作 is_deeply
抛弃它的论点。如果类型是错误的,如果你期待苹果并得到斑马,那么知道有多少斑马和它们的生活故事就没有多大意义了。
没有支持的方法来更改其诊断,抱歉,而且不太可能会有。测试::More 被 Test2 取代. Test::More 已经在 Test2 之上实现,但出于向后兼容性的原因并没有利用其功能。
您可以使用Test2::Bundle::More更直接地访问 Test2 的功能,但它不是 100% 兼容的,它的显示类似于 is_deeply
做。但是,它更加灵活,您可能会想办法改变它的诊断行为。查看 Test2::Compare .
回到你的问题...使用 explain
根据具体情况。 explain
使用正确配置的 Data::Dumper 来转储数据结构。由于 Test::More 函数返回是否通过或失败,你可以写 is_deeply($this, $that) || diag explain $this
.例如...
my $stuff = [5, 6, 8];
is_deeply $stuff, "" || diag explain $stuff;
not ok 2
# Failed test at /Users/schwern/tmp/test.plx line 17.
# Structures begin differing at:
# $got = ARRAY(0x7f80b3803078)
# $expected = ''
# [
# 5,
# 6,
# 8
# ]
diag
是您打印故障诊断的方式(这是打印到 STDERR 的一种更礼貌的方式)。
关于perl - 与字符串进行比较时,Test::More is_deeply 不会漂亮地打印数组/哈希引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569822/