当试图在Perl中实现C的assert()
宏时,存在一些基本问题。首先考虑以下代码:
sub assert($$) {
my ($assertion, $failure_msg) = @_;
die $failure_msg unless $assertion;
}
# ...
assert($boolean, $message);
虽然这有效,但它不像C:在C中我会写assert($foo <= $bar)
,但是在这个实现中我必须写assert($foo <= $bar, '$foo <= $bar')
,即重复条件为字符串。
现在我想知道如何有效地实现这一点。 easy变量似乎将字符串传递给assert()
并使用eval
来计算字符串,但在评估eval时无法访问变量。即使它可以工作,每次解析和评估条件也会非常低效。
传递表达式时,我不知道如何从中创建一个字符串,特别是在它已经被评估时。
另一个使用assert(sub { $condition })
的变体,它可能更容易从代码ref中创建一个字符串,被认为太难看了。
构造assert(sub { (eval $_[0], $_[0]) }->("condition"));
与
sub assert($)
{
die "Assertion failed: $_[1]\n" unless $_[0];
}
会怎么做,但打电话很难看。我正在寻找的解决方案是编写条件只检查一次,同时能够重现原始(未评估)条件并有效地评估条件。
那么更优雅的解决方案是什么?显然,如果Perl有一个宏或类似的语法机制允许在编译或评估之前转换输入,那么解决方案会更容易。
使用caller
并提取产生断言的源代码行?
sub assert {
my ($condition, $msg) = @_;
return if $condition;
if (!$msg) {
my ($pkg, $file, $line) = caller(0);
open my $fh, "<", $file;
my @lines = <$fh>;
close $fh;
$msg = "$file:$line: " . $lines[$line - 1];
}
die "Assertion failed: $msg";
}
assert(2 + 2 == 5);
输出:
Assertion failed: assert.pl:14: assert(2 + 2 == 5);
如果使用Carp::croak
而不是die
,Perl还将报告堆栈跟踪信息并确定调用失败断言的位置。
使用B::Deparse?
#!/usr/bin/perl
use strict;
use warnings;
use B::Deparse;
my $deparser = B::Deparse->new();
sub assert(&) {
my($condfunc) = @_;
my @caller = caller();
unless ($condfunc->()) {
my $src = $deparser->coderef2text($condfunc);
$src =~ s/^\s*use\s.*$//mg;
$src =~ s/^\s+(.+?)/$1/mg;
$src =~ s/(.+?)\s+$/$1/mg;
$src =~ s/[\r\n]+/ /mg;
$src =~ s/^\{\s*(.+?)\s*\}$/$1/g;
$src =~ s/;$//mg;
die "Assertion failed: $src at $caller[1] line $caller[2].\n";
}
}
my $var;
assert { 1 };
#assert { 0 };
assert { defined($var) };
exit 0;
测试输出:
$ perl dummy.pl
Assertion failed: defined $var at dummy.pl line 26.
CPAN上有一大堆断言模块。这些都是开源的,所以很容易看到它们,看看它们是如何完成的。
Carp::Assert是一个低魔法的实现。它在其文档中链接到一些更复杂的断言模块,其中一个是我的模块PerlX::Assert。
任何类型的“断言”的一种方法是使用测试框架。它不像C的assert
那样干净利落,但它更加灵活和易于管理,而测试仍然可以像assert
语句一样自由地嵌入到代码中。
一些非常简单的例子
use warnings;
use strict;
use feature 'say';
use Test::More 'no_plan';
Test::More->builder->output('/dev/null');
say "A few examples of tests, scattered around code\n";
like('may be', qr/(?:\w+\s+)?be/, 'regex');
cmp_ok('a', 'eq', 'a ', 'string equality');
my ($x, $y) = (1.7, 13);
cmp_ok($x, '==', $y, '$x == $y');
say "\n'eval' expression in a string so we can see the failing code\n";
my $expr = '$x**2 == $y';
ok(eval $expr, 'Quadratic') || diag explain $expr;
# ok(eval $expr, $expr);
与输出
A few examples of tests, scattered around code # Failed test 'string equality' # at assertion.pl line 19. # got: 'a' # expected: 'a ' # Failed test '$x == $y' # at assertion.pl line 20. # got: 1.7 # expected: 13 'eval' expression in a string so we can see the failing code # Failed test 'Quadratic' # at assertion.pl line 26. # $x**2 == $y # Looks like you failed 3 tests of 4.
这只是一个例子的散射,最后一个直接回答问题。
Test::More模块汇集了许多工具;如何使用它以及如何操作输出有很多选项。请参阅Test::Harness和Test::Builder(上面使用过),以及一些教程和SO帖子。
我不知道上面的eval
如何计入“优雅”,但它确实将你从单一和单独关注C风格的assert
陈述转向更容易管理的系统。
好的断言是作为系统测试和代码文档的意思和计划,但由于它们的性质缺乏正式的结构(因此可能最终分散和临时)。当这样做时,他们带有一个框架,可以使用许多工具进行管理和调整,也可以作为套件。