繁体   English   中英

在 Perl 中测试两个哈希键是否具有相同的结构

[英]Testing that two hash keys have equal structures in Perl

我正在编写一个单元测试,我必须检查两个散列变量(散列的散列)的关键结构是否相同。 键值可以不同。 散列的深度是任意的。

Test::Deep似乎很理想,但我不知道如何让cmp_deeply忽略这些值。

use Test::Deep;

my %hash1 = ( key1 => "foo", key2 => {key21 => "bar", key22 => "yeah"});
my %hash2 = ( key1 => "foo", key2 => {key21 => "bar", key22 => "wow"});

cmp_deeply(\%hash1, \%hash2, "This test should not fail");

输出:

not ok 1 - This test should not fail
#   Failed test 'This test should not fail'
#   at demo.pl line 13.
# Compared $data->{"key2"}{"key22"}
#    got : 'yeah'
# expect : 'wow'

如果散列具有已知结构,我可以使用值为ignore()的测试变量。 但是,就我而言,最好的解决方案是我不必更新测试代码中的结构。

我尝试使用Data::Walk遍历%hash1并检查每个键是否存在于%hash2但发现很难从$Data::Walk::container值中获取当前键。

关于合适的比较工具的任何想法?

看来你需要忽略这些结构中的叶子,否则会比较。

然后可以比较两个结构之间的所有路径到叶子,而忽略叶子。

模块Data::Leaf::Walker可以帮助解决这个问题,生成所有叶子的路径数组。 然后这些需要进行比较,而Test::Deep和它的 bag-comparison 只是一个工具。

use warnings;
use strict;
use feature 'say';

use Data::Leaf::Walker;
use Test::More qw(no_plan);
use Test::Deep;

my %h1 = (key1 => "foo", key2 => {key21 => "bar", key22 => "yeah"});
my %h2 = (key1 => "foo", key2 => {key21 => "bar", key22 => "wow"});

my @key_paths_h1 = Data::Leaf::Walker->new(\%h1)->keys;

my @key_paths_h2 = Data::Leaf::Walker->new(\%h2)->keys;

# Now compare @key_paths_h1 and @key_paths_h2
# Order of arrayrefs in the top-level arrays doesn't matter
# but order of elements in each arrayref does 
cmp_bag(\@key_paths_h1, \@key_paths_h2, 'key-paths');

这按预期打印, ok 1 - key-paths 更改任何键的结果not ok 1 ...


一旦我们开始,我想提一下该模块提供了一个迭代器

my $walker = Data::Leaf::Walker->new($data_structure_ref);

while ( my ($keys_path, $value) = $walker->each ) {
    say "[ @$keys_path ] => $value"
}   

这样我们就可以得到路径和它们的值,一次一个。 只有几个,但精心挑选的方法。 请参阅文档。

以下是如何手动执行此操作的示例:

use strict;
use warnings;
use experimental qw(signatures);
use Test::More;

{
    my %hash1 = ( key1 => "foo", key2 => {key21 => "bar", key22 => "yeah"});
    my %hash2 = ( key1 => "foo", key2 => {key21 => "bar", key22 => "wow"});
    ok(cmp_keys(\%hash1, \%hash2), "Hash keys identical");
}
done_testing();

sub cmp_keys( $hash1, $hash2 ) {
    my @keys1 = flatten_keys( $hash1 );
    my @keys2 = flatten_keys( $hash2 );
    return 0 if @keys1 != @keys2;
    for my $i (0..$#keys1) {
        return 0 if $keys1[$i] ne $keys2[$i];
    }
    return 1;
}

sub flatten_keys( $hash ) {
    my @keys;
    my $prefix = '';
    _flatten_keys( $hash, $prefix, \@keys);
    return sort @keys;
}

sub _flatten_keys ( $hash, $prefix, $keys) {
    # $; The subscript separator for multidimensional array emulation,
    #    default value is "\034" = 0x1C
    my $sep = $;;
    for my $key (keys %$hash) {
        if (ref $hash->{$key} eq "HASH") {
            _flatten_keys( $hash->{$key}, $prefix . $key . $sep, $keys );
        }
        push @$keys, $prefix . $key;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM