]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - t/lib/Scope/Upper/TestThreads.pm
Port module loading in tests to VPIT::TestHelpers
[perl/modules/Scope-Upper.git] / t / lib / Scope / Upper / TestThreads.pm
1 package Scope::Upper::TestThreads;
2
3 use strict;
4 use warnings;
5
6 use Config qw<%Config>;
7
8 use Scope::Upper qw<SU_THREADSAFE>;
9
10 use VPIT::TestHelpers;
11
12 sub diag {
13  require Test::Leaner;
14  Test::Leaner::diag(@_);
15 }
16
17 sub import {
18  shift;
19
20  skip_all 'This Scope::Upper isn\'t thread safe' unless SU_THREADSAFE;
21
22  my $force = $ENV{PERL_SCOPE_UPPER_TEST_THREADS} ? 1 : !1;
23  skip_all 'This perl wasn\'t built to support threads'
24                                                     unless $Config{useithreads};
25  skip_all 'perl 5.13.4 required to test thread safety'
26                                              unless $force or "$]" >= 5.013_004;
27
28  load_or_skip('threads', $force ? '0' : '1.67', [ ],
29               'required to test thread safety');
30
31  my %exports = (
32   spawn => \&spawn,
33  );
34
35  my $usleep;
36  if (do { local $@; eval { require Time::HiRes; 1 } }) {
37   defined and diag "Using Time::HiRes $_" for $Time::HiRes::VERSION;
38   $exports{usleep} = \&Time::HiRes::usleep;
39  } else {
40   diag 'Using fallback usleep';
41   $exports{usleep} = sub {
42    my $s = int($_[0] / 2.5e5);
43    sleep $s if $s;
44   };
45  }
46
47  my $pkg = caller;
48  while (my ($name, $code) = each %exports) {
49   no strict 'refs';
50   *{$pkg.'::'.$name} = $code;
51  }
52 }
53
54 sub spawn {
55  local $@;
56  my @diag;
57  my $thread = eval {
58   local $SIG{__WARN__} = sub { push @diag, "Thread creation warning: @_" };
59   threads->create(@_);
60  };
61  push @diag, "Thread creation error: $@" if $@;
62  if (@diag) {
63   require Test::Leaner;
64   Test::Leaner::diag($_) for @diag;
65  }
66  return $thread ? $thread : ();
67 }
68
69 1;