tests for Sub::Quote/Sub::Defer in threads
[gitmo/Moo.git] / t / sub-quote-threads.t
1 use strictures 1;
2 use Test::More;
3 use Config;
4 BEGIN {
5   unless ($Config{useithreads} && eval { require threads } ) {
6     plan skip_all => "your perl does not support ithreads";
7   }
8 }
9
10 use Sub::Quote;
11
12 my $one = quote_sub my $one_code = q{
13     BEGIN { $::EVALED{'one'} = 1 }
14     42
15 };
16
17 my $two = quote_sub q{
18     BEGIN { $::EVALED{'two'} = 1 }
19     3 + $x++
20 } => { '$x' => \do { my $x = 0 } };
21
22 ok(threads->create(sub {
23   my $quoted = quoted_from_sub($one);
24   $quoted && $quoted->[1] eq $one_code;
25 })->join, 'able to retrieve quoted sub in thread');
26
27 my $u_one = unquote_sub $one;
28
29 is(threads->create(sub { $one->() })->join, 42, 'One (quoted version)');
30
31 is(threads->create(sub { $u_one->() })->join, 42, 'One (unquoted version)');
32
33 my $r = threads->create(sub {
34   my @r;
35   push @r, $two->();
36   push @r, unquote_sub($two)->();
37   push @r, $two->();
38   \@r;
39 })->join;
40
41 is($r->[0], 3, 'Two in thread (quoted version)');
42 is($r->[1], 4, 'Two in thread (unquoted version)');
43 is($r->[2], 5, 'Two in thread (quoted version again)');
44
45 done_testing;