63e510c9a514580b74f235d087c21b02914ab145
[p5sagit/Try-Tiny.git] / t / erroneous_usage.t
1 use strict;
2 use warnings;
3
4 use Test::More tests => 8;
5
6 use Try::Tiny;
7
8 sub _eval {
9   local $@;
10   local $Test::Builder::Level = $Test::Builder::Level + 2;
11   return ( scalar(eval { $_[0]->(); 1 }), $@ );
12 }
13
14 sub throws_ok (&$$) {
15   my ( $code, $regex, $desc ) = @_;
16   local $Test::Builder::Level = $Test::Builder::Level + 1;
17
18   my ( $ok, $error ) = _eval($code);
19
20   if ( $ok ) {
21     fail($desc);
22   } else {
23     like($error || '', $regex, $desc );
24   }
25 }
26
27 throws_ok {
28   try { 1 }; catch { 2 };
29 } qr/\QUseless bare catch()/, 'Bare catch() detected';
30
31 throws_ok {
32   try { 1 }; finally { 2 };
33 } qr/\QUseless bare finally()/, 'Bare finally() detected';
34
35 throws_ok {
36   try { 1 }; catch { 2 } finally { 2 };
37 } qr/\QUseless bare catch()/, 'Bare catch()/finally() detected';
38
39 throws_ok {
40   try { 1 }; finally { 2 } catch { 2 };
41 } qr/\QUseless bare finally()/, 'Bare finally()/catch() detected';
42
43
44 throws_ok {
45   try { 1 } catch { 2 } catch { 3 } finally { 4 } finally { 5 }
46 } qr/\QA try() may not be followed by multiple catch() blocks/, 'Multi-catch detected';
47
48
49 throws_ok {
50   try { 1 } catch { 2 }
51   do { 2 }
52 } qr/\Qtry() encountered an unexpected argument (2) - perhaps a missing semi-colon before or at/,
53   'Unterminated try detected';
54
55 sub foo {
56   try { 0 }; catch { 2 }
57 }
58
59 throws_ok {
60   if (foo()) {
61     # ...
62   }
63 } qr/\QUseless bare catch/,
64   'Bare catch at the end of a function call';
65
66 sub bar {
67   try { 0 }; finally { 2 }
68 }
69
70 throws_ok {
71   if (bar()) {
72     # ...
73   }
74 } qr/\QUseless bare finally/,
75   'Bare finally at the end of a function call';