I'm an inexperienced Perl programmer (my background is mainly in Python), charged with keeping a legacy app running, and I'm having trouble figuring out how to validate a date. (At least, that's what I think the problem is.)
We have a function that takes a date value and does some transformations on it. This is thoroughly tested and works fine for its use case, but we don't actually have a test for what happens if someone sends garbage into it—it assumes the input really is a valid date. Normally, this is fine; the input comes from internal sources and should always be OK. We now need to extend it for a case when we don't have control over the incoming data. So, I tried to wrap it in an eval to catch any errors. Currently, it looks like this:
The test script now has this:# in MyApp::Util sub convert_datetime { my ( $self, $incoming_datetime ) = @_; my $new_dt; eval { $new_dt = DateTime::Format::ISO8601->parse_datetime( $incom +ing_datetime ); }; return undef if $@; # No error, now we can convert the date (not shown) }
When I run this, however, I get (I've changed the file paths):my $bogus_datetime = MyApp::Util->convert_datetime("FOO"); is ($bogus_datetime, undef, "convert_datetime doesn't blow up if sent +bogus date");
ok 141 - convert_datetime doesn't blow up if sent bogus date Invalid date format: at /path/to/MyApp/Util.pm line 818. eval {...} called at /path/to/MyApp/Util.pm line 818 MyApp::Util::convert_datetime("MyApp::Util", "FOO") called at t/Ut +il.t line 297 ...propagated at t/Util.t line 298.
So the test "works" in that it returns an "ok" value, but it also prints the whole "Invalid date format" thing. How do I get it to _not_ do this, or otherwise test to see if the input is valid before I pass it to DateTime::Format::ISO8601->parse_datetime? The docs for this function say "The parse_datetime method will attempt to match these ambiguous strings" etc., but doesn't say what happens if it can't, or what you're supposed to do to test for valid input.
I tried to write a test script, but even though it looks identical (to me), this does _not_ print the "Invalid date format":
#!/usr/bin/env perl use strict; use warnings; use DateTime::Format::ISO8601; eval {my $foo = DateTime::Format::ISO8601->parse_datetime("FOO");}; print "ERROR\n" if $@;
Running this simply prints "ERROR" and that's it, no other output. What's going on in the real code, or what's the right way to handle this?
In reply to Catching error in DateTime::Format by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |