简体   繁体   English

如何测试包括$的错误消息!没有区域设置问题?

[英]How can I test error messages including $! without locale issues?

In my module, I've got this code: 在我的模块中,我有这个代码:

croak("unable to parse file: $!");

Then, in my tests, I want to check that I get the right error message when I attempt to parse a file that doesn't exist: 然后,在我的测试中,我想检查当我尝试解析不存在的文件时,我得到了正确的错误消息:

like(
    exception { HTML::Tree->new_from_file( "t/non_existent.html" ) },
    qr!^unable to parse file: No such file !,
    "opening missing file failed"
);

This works fine, as long as the tests are running in an English locale. 只要测试在英语语言环境中运行,这样就可以正常工作。 But if you run the tests in a German locale, the error message will come back unable to parse file: Datei oder Verzeichnis nicht gefunden and the test fails. 但是如果你在德语语言环境中运行测试,错误消息将返回unable to parse file: Datei oder Verzeichnis nicht gefunden并且测试失败。 Other locales have similar issues. 其他语言环境也存在类似问题。

I can't believe this is the first time this has come up, but I can't find any modules on CPAN that address this issue. 我不敢相信这是第一次出现,但我找不到CPAN上解决这个问题的任何模块。 Do people simply never test the $! 人们根本就不会测试$! part of the error message? 部分错误消息? Is there a better solution than changing the test to only check for qr!^unable to parse file: ! 有没有比更改测试更好的解决方案只检查qr!^unable to parse file: ! ?

Note: this is RT#77823 in HTML-Tree . 注意:这是HTML-Tree中的RT#77823

Is there a better solution than changing the test to only check for qr!^unable to parse file: !? 有没有比更改测试更好的解决方案只检查qr!^无法解析文件:!?

$! is a dual variable, ie it has string and numeric values. 是一个双变量,即它有字符串和数字值。 You could use the numeric value in the error message. 您可以使用错误消息中的数值。

You could use %! 你可以使用%! to test for errors symbolically as in 以象征性方式测试错误

unless (open my $fh, "<", "/does/not/exist") {
  die "$0: unexpected errno " . ($! + 0)
    unless $!{ENOENT};
}
  1. Tests for a module M should not check for features that M isn't responsible for. 对于模M的测试不应检测功能,M是不负责的。
  2. Code that fails because of a non existing file should not croak "can't parse (file spec)", but "can't find (file spec)". 失败,因为一个不存在的文件应该发牢骚代码“无法解析(文件规范)”,但“无法找到(文件规范)”。

The way I solve this is to put 我解决这个问题的方法是放

BEGIN { $ENV{LANG} = $ENV{LC_MESSAGES} = $ENV{LC_ALL} = "C" }

in any unit test script that involves such testing. 在任何涉及此类测试的单元测试脚本中。 That way, the locale is set to C for the duration of that test, and messages will reliably come in the plain C locale, rather than being localised. 这样,在该测试期间,语言环境设置为C,并且消息将可靠地进入普通C语言环境,而不是本地化。

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

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