Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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: !?

Note: this is RT#77823 in HTML-Tree.

like image 947
cjm Avatar asked Jun 16 '12 19:06

cjm


People also ask

What is error message explain with example?

An error message is information displayed when an unforeseen problem occurs, usually on a computer or other device. On modern operating systems with graphical user interfaces, error messages are often displayed using dialog boxes.

What is a good error message?

Good error message should include: Explicit indication that something has gone wrong. The very worst error messages are those that don't exist. When users make mistakes and get no feedback, they're completely lost.


2 Answers

You could use %! to test for errors symbolically as in

unless (open my $fh, "<", "/does/not/exist") {
  die "$0: unexpected errno " . ($! + 0)
    unless $!{ENOENT};
}
like image 190
Greg Bacon Avatar answered Oct 19 '22 09:10

Greg Bacon


Is there a better solution than changing the test to only check for qr!^unable to parse file: !?

$! is a dual variable, i.e. it has string and numeric values. You could use the numeric value in the error message.

like image 30
Eugene Yarmash Avatar answered Oct 19 '22 09:10

Eugene Yarmash