]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/41-clone.t
t/41-clone.t needs to call wizard into an eval block
[perl/modules/Variable-Magic.git] / t / 41-clone.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Config qw/%Config/;
7
8 BEGIN {
9  if (!$Config{useithreads}) {
10   require Test::More;
11   Test::More->import;
12   plan(skip_all => 'This perl wasn\'t built to support threads');
13  }
14 }
15
16 use threads; # Before Test::More
17 use threads::shared;
18
19 use Test::More;
20
21 use Variable::Magic qw/wizard cast dispell getdata getsig VMG_THREADSAFE/;
22
23 if (VMG_THREADSAFE) {
24  plan tests => 3 + 2 * (2 * 8 + 2) + 2 * (2 * 5 + 2);
25  diag 'This will leak a few scalars';
26 } else {
27  plan skip_all => 'This Variable::Magic isn\'t thread safe';
28 }
29
30 my $destroyed : shared = 0;
31 my $c         : shared = 0;
32 my $wiz = eval {
33  wizard get  => sub { ++$c },
34         data => sub { $_[1] + threads->tid() },
35         free => sub { ++$destroyed }
36 };
37 is($@,     '',    "wizard in main thread doesn't croak");
38 isnt($wiz, undef, "wizard in main thread is defined");
39 is($c,     0,     "wizard in main thread doesn't trigger magic");
40
41 my $sig;
42
43 sub try {
44  my ($dispell) = @_;
45  my $tid = threads->tid();
46  my $a   = 3;
47  my $res = eval { cast $a, $sig, sub { 5 }->() };
48  is($@, '', "cast in thread $tid doesn't croak");
49  my $b;
50  eval { $b = $a };
51  is($@, '', "get in thread $tid doesn't croak");
52  is($b, 3,  "get in thread $tid returns the right thing");
53  my $d = eval { getdata $a, $sig };
54  is($@, '',       "getdata in thread $tid doesn't croak");
55  is($d, 5 + $tid, "getdata in thread $tid returns the right thing");
56  if ($dispell) {
57   $res = eval { dispell $a, $sig };
58   is($@, '', "dispell in thread $tid doesn't croak");
59   undef $b;
60   eval { $b = $a };
61   is($@, '', "get in thread $tid after dispell doesn't croak");
62   is($b, 3,  "get in thread $tid after dispell returns the right thing");
63  }
64  return; # Ugly if not here
65 }
66
67 for my $dispell (1, 0) {
68  $c = 0;
69  $destroyed = 0;
70  $sig = $wiz;
71
72  my @t = map { threads->create(\&try, $dispell) } 1 .. 2;
73  $t[0]->join;
74  $t[1]->join;
75
76  is($c, 2, "get triggered twice");
77  is($destroyed, (1 - $dispell) * 2, 'destructors');
78
79  $c = 0;
80  $destroyed = 0;
81  $sig = getsig $wiz;
82
83  @t = map { threads->create(\&try, $dispell) } 1 .. 2;
84  $t[0]->join;
85  $t[1]->join;
86
87  is($c, 2, "get triggered twice");
88  is($destroyed, (1 - $dispell) * 2, 'destructors');
89 }