2016-11-13 18 views
10

当Test :: More比较像arrayrefs和hashrefs彼此时,相应的诊断消息是非常有用的,并显示结构不同的第一个索引,无论嵌套深度如何。但是,在将arrayref或hashref与简单标量进行比较时,它会在诊断消息中生成字符串标量(带有内存地址和引用类型),这很难解释。Test :: More is_deeply在与字符串比较时不会很漂亮地打印数组/字符串

有没有一种方法来配置Test :: More以漂亮的打印阵列或hashrefs以自定义的方式(如使用Data :: Dumper)?

下面是两个测试用例的示例。第一个给你一些洞察你的程序中出现的内容,但意想不到的。第二个通知用户字符串和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)', 
); 

和抽头输出:

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在测试执行::更多,似乎没有要的方式来使用自定义美化打印机或配置冗长的模块。至少没有一点对我来说很明显。

这里是当我们比较的参考和非参考会发生什么:

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

回答

9

TL;博士根据具体情况使用is_deeply($this, $that) || diag explain $this

嗨。 I'm the one to blame for is_deeply。它故意设计成在出现故障时不会吐出一个潜在的巨大数据结构。相反,它停在第一个区别。出于这个原因,你可能不希望全局使is_deeply转储它的参数。如果类型错误,如果你期望苹果并且得到了斑马,那么知道多少斑马和它们的生活故事就没有多少意义。

有没有支持的方式来改变它的诊断,抱歉,这是不可能的。 Test :: More正在被Test2替代。 Test :: More已经在Test2之上实现了,但是由于向后兼容的原因没有利用它的特性。

您可以使用Test2::Bundle::More更直接地访问Test2的功能,但它不是100%兼容的,并且它显示与is_deeply相似。然而,它更加灵活,你可能想出一个方法来改变它的诊断行为。看看Test2::Compare


回到你的问题......通过个案的基础上的情况下,使用explainexplain使用正确配置的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更礼貌的方式)。

1

尝试eq_or_diff($got, $expected, $message)Test::Differences,它会打印出您的数据结构的一个美丽的表示,并清楚地突出确切的相似之处和差异。

+0

如果你想要一个数据结构的并排比较,这真的很不错。但是,如果您正在开发,并且数据结构发生了变化,您只需要替换测试模块中的定义,则'diag explain $ got'可以提供更容易的复制和粘贴输出。 – Randall