gpt4 book ai didi

perl - 我们如何使用 Test2::V0 测试可选的哈希字段

转载 作者:行者123 更新时间:2023-11-28 19:56:54 25 4
gpt4 key购买 nike

我正在尝试找出如何使用 Test2::V0 测试可选哈希字段的方法.我目前有以下内容:

use 5.016;
use Test2::V0;

subtest 'optional fields in a hash' => sub {
my $check = hash {
field foo => qr/^[0-9]+$/;
field bar => qr/^[a-zA-Z]+$/; # this field is optional
};

like(
{ foo => 1 },
$check,
'should pass when optional field is omitted',
);

like(
{ foo => 2, bar => 'a' },
$check,
'should pass when optional field is provided',
);
};

done_testing;

现在,如果我取消对可选字段的检查:

my $check = hash {
field foo => qr/^[0-9]+$/;
# field bar => qr/^[a-zA-Z]+$/; # this field is optional
};

测试将通过。但我想在它存在时测试它的值。

有什么想法吗?

最佳答案

参见 Test2::Tools::Comparein_set - 以下对我有用。不要忘记测试失败 :-)

use warnings;
use 5.016;
use Test2::V0;

subtest 'optional fields in a hash' => sub {
my $check = hash {
field foo => qr/^[0-9]+$/;
field bar => in_set( DNE(), qr/^[a-zA-Z]+$/ );
};
like( { foo => 1 }, $check,
'should pass when optional field is omitted' );
like( { foo => 2, bar => 'a' }, $check,
'should pass when optional field is provided' );
unlike( { foo => 2, bar => undef }, $check,
'should fail when optional field is provided with no value' );
unlike( { foo => 2, bar => '+' }, $check,
'should fail when optional field is provided with bad value' );
};

done_testing;

关于perl - 我们如何使用 Test2::V0 测试可选的哈希字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54408357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com