refactor code needing version
[dbsrgits/DBIx-Class.git] / t / 34exception_action.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use Test::Warn;
7 use lib qw(t/lib);
8 use DBICTest;
9
10 # Set up the "usual" sqlite for DBICTest
11 my $schema = DBICTest->init_schema;
12
13 # This is how we're generating exceptions in the rest of these tests,
14 #  which might need updating at some future time to be some other
15 #  exception-generating statement:
16
17 my $throw  = sub { $schema->resultset("Artist")->search(1,1,1) };
18 my $ex_regex = qr/Odd number of arguments to search/;
19
20 # Basic check, normal exception
21 throws_ok \&$throw, $ex_regex;
22
23 my $e = $@;
24
25 # Re-throw the exception with rethrow()
26 throws_ok { $e->rethrow }
27   $ex_regex;
28 isa_ok( $@, 'DBIx::Class::Exception' );
29
30 # Now lets rethrow via exception_action
31 $schema->exception_action(sub { die @_ });
32 throws_ok \&$throw, $ex_regex;
33
34 #
35 # This should have never worked!!!
36 #
37 # Now lets suppress the error
38 $schema->exception_action(sub { 1 });
39 throws_ok \&$throw,
40   qr/exception_action handler .+ did \*not\* result in an exception.+original error: $ex_regex/;
41
42 # Now lets fall through and let croak take back over
43 $schema->exception_action(sub { return });
44 throws_ok {
45   warnings_are \&$throw,
46     qr/exception_action handler installed .+ returned false instead throwing an exception/;
47 } $ex_regex;
48
49 # again to see if no warning
50 throws_ok {
51   warnings_are \&$throw,
52     [];
53 } $ex_regex;
54
55
56 # Whacky useless exception class
57 {
58     package DBICTest::Exception;
59     use overload '""' => \&stringify, fallback => 1;
60     sub new {
61         my $class = shift;
62         bless { msg => shift }, $class;
63     }
64     sub throw {
65         my $self = shift;
66         die $self if ref $self eq __PACKAGE__;
67         die $self->new(shift);
68     }
69     sub stringify {
70         "DBICTest::Exception is handling this: " . shift->{msg};
71     }
72 }
73
74 # Try the exception class
75 $schema->exception_action(sub { DBICTest::Exception->throw(@_) });
76 throws_ok \&$throw,
77   qr/DBICTest::Exception is handling this: $ex_regex/;
78
79 # While we're at it, lets throw a custom exception through Storage::DBI
80 throws_ok { $schema->storage->throw_exception('floob') }
81   qr/DBICTest::Exception is handling this: floob/;
82
83 done_testing;