Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Perl中写入文件时,测试错误处理的最简单方法是什么?_Perl_Testing_Integration Testing_Die - Fatal编程技术网

在Perl中写入文件时,测试错误处理的最简单方法是什么?

在Perl中写入文件时,测试错误处理的最简单方法是什么?,perl,testing,integration-testing,die,Perl,Testing,Integration Testing,Die,我有一个bog标准Perl文件编写代码,其中(希望)有足够的错误处理,类型如下: open(my $fh, ">", "$filename") or die "Could not open file $filname for writing: $!\n"; # Some code to get data to write print $fh $data or die "Could not write to file $filname: $!\n"; close $fh or die "

我有一个bog标准Perl文件编写代码,其中(希望)有足够的错误处理,类型如下:

open(my $fh, ">", "$filename") or die "Could not open file $filname for writing: $!\n";
# Some code to get data to write
print $fh $data  or die "Could not write to file $filname: $!\n";
close $fh  or die "Could not close file $filname afterwriting: $!\n";
# No I can't use File::Slurp, sorry.
(我刚从内存中编写了这段代码,请原谅任何打字错误或bug)

在第一个“die”行中测试错误处理有点容易(例如,创建一个与您计划编写的文件同名的不可写文件)

如何测试第二(打印)和第三(关闭)“模具”行中的错误处理? 据我所知,在关闭时导致错误的唯一方法是在编写时耗尽文件系统上的空间,这作为测试是不容易的


我更喜欢集成测试类型解决方案,而不是单元测试类型(这将涉及在Perl中模拟IO方法)。

使用错误的文件句柄将使它们都失败

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

my $file = shift || die "Usage: $0 out-filename\n";

open my $fh, '>', $file  or die "Can't open $file: $!";

$fh = \*10;

say $fh 'writes ok, ', scalar(localtime)  or warn "Can't write: $!";

close $fh or warn "Error closing: $!";
印刷品

say() on unopened filehandle 10 at ... Can't write: Bad file descriptor at ... close() on unopened filehandle 10 at ... Error closing: Bad file descriptor at ... 在未打开的文件句柄10上说()。。。 无法写入:错误的文件描述符位于。。。 关闭()未打开的文件句柄10位于。。。 关闭错误:错误的文件描述符位于。。。
如果您不想看到perl的警告,请使用
$SIG{{uuuu WARN\uuuu}
捕获它们,并将消息打印到文件(或
STDOUT
),例如。

翻阅zdim的答案

写入打开读取的文件句柄


关闭一个已经关闭的文件句柄。

相关:与此相同,但更简单:-它就像
/dev/null
用于读取,但在写入时总是失败。我从技术上喜欢这个答案;但是它并没有解决如何测试我在工作程序中拥有的好的、正确的代码的问题,这两件事都做不到:)我认为这个想法是把它添加到“好的、正确的”代码中,作为一个测试