tests for nesting inside catch block
[p5sagit/Try-Tiny.git] / t / basic.t
CommitLineData
3176feef 1#!/usr/bin/perl
2
3use strict;
06a9e570 4#use warnings;
3176feef 5
e605bd35 6use Test::More tests => 19;
3176feef 7
8BEGIN { use_ok 'Try::Tiny' };
9
10sub _eval {
11 local $@;
12 local $Test::Builder::Level = $Test::Builder::Level + 2;
13 return ( scalar(eval { $_[0]->(); 1 }), $@ );
14}
15
16
17sub lives_ok (&$) {
18 my ( $code, $desc ) = @_;
19 local $Test::Builder::Level = $Test::Builder::Level + 1;
20
21 my ( $ok, $error ) = _eval($code);
22
23 ok($ok, $desc );
24
25 diag "error: $@" unless $ok;
26}
27
28sub throws_ok (&$$) {
29 my ( $code, $regex, $desc ) = @_;
30 local $Test::Builder::Level = $Test::Builder::Level + 1;
31
32 my ( $ok, $error ) = _eval($code);
33
34 if ( $ok ) {
35 fail($desc);
36 } else {
37 like($error || '', $regex, $desc );
38 }
39}
40
41
3176feef 42lives_ok {
43 try {
44 die "foo";
45 };
46} "basic try";
47
48throws_ok {
49 try {
50 die "foo";
51 } catch { die $_ };
52} qr/foo/, "rethrow";
53
54
55{
56 local $@ = "magic";
57 is( try { 42 }, 42, "try block evaluated" );
58 is( $@, "magic", '$@ untouched' );
59}
60
61{
62 local $@ = "magic";
63 is( try { die "foo" }, undef, "try block died" );
64 is( $@, "magic", '$@ untouched' );
65}
66
67{
68 local $@ = "magic";
69 like( (try { die "foo" } catch { $_ }), qr/foo/, "catch block evaluated" );
70 is( $@, "magic", '$@ untouched' );
71}
72
2ab8fb1c 73is( scalar(try { "foo", "bar", "gorch" }), "gorch", "scalar context" );
3176feef 74is_deeply( [ try {qw(foo bar gorch)} ], [qw(foo bar gorch)], "list context" );
75
76
e605bd35 77lives_ok {
78 try {
79 die "foo";
80 } catch {
81 my $err = shift;
82
83 try {
84 like $err, qr/foo/;
85 } catch {
86 fail("shouldn't happen");
87 };
88
89 pass "got here";
90 }
91} "try in try catch block";
92
93throws_ok {
94 try {
95 die "foo";
96 } catch {
97 my $err = shift;
98
99 try { } catch { };
100
101 die "rethrowing $err";
102 }
103} qr/rethrowing foo/, "rethrow with try in catch block";
104
3176feef 105
1f7c5af6 106sub Evil::DESTROY {
107 eval { "oh noes" };
108}
109
110sub Evil::new { bless { }, $_[0] }
111
3176feef 112{
113 local $@ = "magic";
114 local $_ = "other magic";
115
116 try {
1f7c5af6 117 my $object = Evil->new;
3176feef 118 die "foo";
119 } catch {
120 pass("catch invoked");
121 local $TODO = "i don't think we can ever make this work sanely, maybe with SIG{__DIE__}";
122 like($_, qr/foo/);
123 };
124
125 is( $@, "magic", '$@ untouched' );
126 is( $_, "other magic", '$_ untouched' );
127}