gpt4 book ai didi

perl - 如何测试与间接对象语法一起使用的 exec?

转载 作者:行者123 更新时间:2023-12-01 11:20:22 25 4
gpt4 key购买 nike

测试使用间接对象语法调用 exec 的 Perl 脚本的最佳方法是什么?有没有一种方法可以模拟 exec 而不会导致语法错误?我是否必须将 exec 移动到只调用 exec 并模拟该函数的包装函数?还是有其他方法来测试脚本?

Perl Testing - A Developer's Notebook

Chapter 5 有一个关于Overriding Built-ins 的例子,他们覆盖system 来测试一个模块。我想做同样的事情来测试 exec,但在间接对象语法中。

exec.pl(使用间接对象语法)

package Local::Exec;

use strict;
use warnings;

main() if !caller;

sub main {
my $shell = '/usr/bin/ksh93';
my $shell0 = 'ksh93';

# launch a login shell
exec {$shell} "-$shell0";
return;
}

1;

exec.t

#!perl

use strict;
use warnings;

use Test::More;

require_ok('./exec.pl');

package Local::Exec;
use subs 'exec';
package main;

my @exec_args;

*Local::Exec::exec = sub {
@exec_args = @_;
return 0;
};

is(Local::Exec::main(), undef, 'main() returns undef');
is_deeply(\@exec_args, [ '/usr/bin/ksh93' ], 'exec() was called with correct arguments');

done_testing;

证明-vt exec.t

这不起作用,my exec 不适用于间接对象语法,而 built-in 可以。

$ prove -vt exec.t
exec.t .. String found where operator expected at ./exec.pl line 15, near "} "-$shell0""
(Missing operator before "-$shell0"?)

not ok 1 - require './exec.pl';
# Failed test 'require './exec.pl';'
# at exec.t line 8.
# Tried to require ''./exec.pl''.
# Error: syntax error at ./exec.pl line 15, near "} "-$shell0""
# Compilation failed in require at (eval 6) line 2.
Undefined subroutine &Local::Exec::main called at exec.t line 21.
# Tests were run but no plan was declared and done_testing() was not seen.
# Looks like your test exited with 255 just after 1.
Dubious, test returned 255 (wstat 65280, 0xff00)
Failed 1/1 subtests

Test Summary Report
-------------------
exec.t (Wstat: 65280 Tests: 1 Failed: 1)
Failed test: 1
Non-zero exit status: 255
Parse errors: No plan found in TAP output
Files=1, Tests=1, 1 wallclock secs ( 0.02 usr 0.01 sys + 0.04 cusr 0.01 csys = 0.08 CPU)
Result: FAIL

exec.pl(没有间接对象语法)

package Local::Exec;

use strict;
use warnings;

main() if !caller;

sub main {
my $shell = '/usr/bin/ksh93';

exec $shell;
return;
}

1;

证明-vt exec.t

仅供引用,这个有效:

$ prove -vt exec.t
exec.t ..
ok 1 - require './exec.pl';
ok 2 - main() returns undef
ok 3 - exec() was called with correct arguments
1..3
ok
All tests successful.
Files=1, Tests=3, 0 wallclock secs ( 0.02 usr 0.01 sys + 0.04 cusr 0.01 csys = 0.08 CPU)
Result: PASS

最佳答案

替换

exec { $shell } "-$shell0";

sub _exec(&@) {
my $prog_cb = shift;
exec { $prog_cb->() } @_
}

_exec { $shell } "-$shell0"

然后你的测试可以替换_exec

关于perl - 如何测试与间接对象语法一起使用的 exec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44597021/

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