4

I'm writing a test in Perl, and I need to compare two big hashes. I use cmp_deep (Test::Deep) and is_deeply (Test::More). My problem is when something is different in those hashes, the program quits in the middle.

my $this = {    a=>1,   b=>2,   d=>2, };

my $that = {    a=>1,   b=>3,   c=>3, };

is_deeply($this , $that );

and the output is:

# not ok 1
# Failed test at Tester.pl line 32.
#     Structures begin differing at:
#          $got->{b} = '2'
#     $expected->{b} = '3'

but I have more values that are different! I need to see them all. How can I force is_deeply to print all the differences between the hashes rather than just the first difference between them?

Furthermore, there are some keys I need to ignore them. How can I do that?

4

2 回答 2

2

对于这类事情,阅读文档通常很方便。

您的问题几乎是Test::More文档中的确切用例。

use Test::More tests => 1;

my $hash1 = { a => 1, b => 2, c => 4 }; 
my $hash2 = { a => 1, b => 3, c => 4 };

is_deeply($hash1, $hash2, 'hash are equal') or diag explain($hash1,$hash2);

示例输出:

not ok 1 - hash are equal
#   Failed test 'hash are equal'
#   at test.pl line 7.
#     Structures begin differing at:
#          $got->{b} = '2'
#     $expected->{b} = '3'
# {
#   'a' => 1,
#   'b' => 2,
#   'c' => 4
# }
# {
#   'a' => 1,
#   'b' => 3,
#   'c' => 4
# }
1..1
# Looks like you failed 1 test of 1.

抱歉,我最初误读了您的问题。仔细阅读问题对于提供正确答案非常有帮助。无论如何,找到散列的差异会变得相当复杂。我相信有几个 CPAN 模块可以帮助您解决这个问题。我建议在那里找到可以处理您正在处理的数据结构以比较哈希差异。

除此之外,我不知道让 Test::More 或 Test::Deep 做你想做的事的好方法。其他人将不得不希望出现!祝你好运。

于 2013-10-07T21:42:21.970 回答
1

正如 Jonathan Leffler 指出的,显示所有差异的最佳方式是使用Test::Differences及其eq_or_diff方法。

但是您可能希望保留 Test::Deep ,因为它具有特殊功能,例如ignore()re()

所以,同时使用它们。您只需要在失败时查看差异。示例代码:

is_deeply($this, $that, "the data matches" )
    || eq_or_diff($this, $that, "the data matches (with details)");
于 2018-04-16T14:57:32.410 回答