Restore the value of $@ from before the local
[p5sagit/Try-Tiny.git] / t / basic.t
CommitLineData
3176feef 1#!/usr/bin/perl
2
3use strict;
06a9e570 4#use warnings;
3176feef 5
511c05ca 6use Test::More tests => 21;
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
511c05ca 42my $prev;
43
3176feef 44lives_ok {
45 try {
46 die "foo";
47 };
48} "basic try";
49
50throws_ok {
51 try {
52 die "foo";
53 } catch { die $_ };
54} qr/foo/, "rethrow";
55
56
57{
58 local $@ = "magic";
59 is( try { 42 }, 42, "try block evaluated" );
60 is( $@, "magic", '$@ untouched' );
61}
62
63{
64 local $@ = "magic";
65 is( try { die "foo" }, undef, "try block died" );
66 is( $@, "magic", '$@ untouched' );
67}
68
69{
70 local $@ = "magic";
71 like( (try { die "foo" } catch { $_ }), qr/foo/, "catch block evaluated" );
72 is( $@, "magic", '$@ untouched' );
73}
74
2ab8fb1c 75is( scalar(try { "foo", "bar", "gorch" }), "gorch", "scalar context" );
3176feef 76is_deeply( [ try {qw(foo bar gorch)} ], [qw(foo bar gorch)], "list context" );
77
78
e605bd35 79lives_ok {
80 try {
81 die "foo";
82 } catch {
83 my $err = shift;
84
85 try {
86 like $err, qr/foo/;
87 } catch {
88 fail("shouldn't happen");
89 };
90
91 pass "got here";
92 }
93} "try in try catch block";
94
95throws_ok {
96 try {
97 die "foo";
98 } catch {
99 my $err = shift;
100
101 try { } catch { };
102
103 die "rethrowing $err";
104 }
105} qr/rethrowing foo/, "rethrow with try in catch block";
106
3176feef 107
1f7c5af6 108sub Evil::DESTROY {
109 eval { "oh noes" };
110}
111
112sub Evil::new { bless { }, $_[0] }
113
3176feef 114{
115 local $@ = "magic";
116 local $_ = "other magic";
117
118 try {
1f7c5af6 119 my $object = Evil->new;
3176feef 120 die "foo";
121 } catch {
122 pass("catch invoked");
123 local $TODO = "i don't think we can ever make this work sanely, maybe with SIG{__DIE__}";
124 like($_, qr/foo/);
125 };
126
127 is( $@, "magic", '$@ untouched' );
128 is( $_, "other magic", '$_ untouched' );
129}
511c05ca 130
131{
132 my $caught;
133
134 {
135 local $@;
136
137 eval { die "bar\n" };
138
139 is( $@, "bar\n", 'previous value of $@' );
140
141 try {
142 die {
143 prev => $@,
144 }
145 } catch {
146 $caught = $_;
147 }
148 }
149
150 is_deeply( $caught, { prev => "bar\n" }, 'previous value of $@ available for capture' );
151}