e703b5abc22e702ac189e455ab8ed55d51c8fc18
[p5sagit/Module-Metadata.git] / t / lib / MBTest.pm
1 package MBTest;
2
3 use strict;
4 use warnings;
5
6 use File::Spec;
7 use File::Temp ();
8
9 # Setup the code to clean out %ENV
10 BEGIN {
11     # Environment variables which might effect our testing
12     my @delete_env_keys = qw(
13         HOME
14         DEVEL_COVER_OPTIONS
15         MODULEBUILDRC
16         PERL_MB_OPT
17         HARNESS_TIMER
18         HARNESS_OPTIONS
19         HARNESS_VERBOSE
20         PREFIX
21         INSTALL_BASE
22         INSTALLDIRS
23     );
24
25     # Remember the ENV values because on VMS %ENV is global
26     # to the user, not the process.
27     my %restore_env_keys;
28
29     sub clean_env {
30         for my $key (@delete_env_keys) {
31             if( exists $ENV{$key} ) {
32                 $restore_env_keys{$key} = delete $ENV{$key};
33             }
34             else {
35                 delete $ENV{$key};
36             }
37         }
38     }
39
40     END {
41         while( my($key, $val) = each %restore_env_keys ) {
42             $ENV{$key} = $val;
43         }
44     }
45 }
46
47
48 BEGIN {
49   clean_env();
50
51   # In case the test wants to use our other bundled
52   # modules, make sure they can be loaded.
53   my $t_lib = File::Spec->catdir('t', 'bundled');
54   push @INC, $t_lib; # Let user's installed version override
55
56   if ($ENV{PERL_CORE}) {
57     # We change directories, so expand @INC and $^X to absolute paths
58     # Also add .
59     @INC = (map(File::Spec->rel2abs($_), @INC), ".");
60     $^X = File::Spec->rel2abs($^X);
61   }
62 }
63
64 use Cwd ();
65
66 ########################################################################
67
68 # always return to the current directory
69 {
70   my $cwd = File::Spec->rel2abs(Cwd::cwd);
71
72   sub original_cwd { return $cwd }
73
74   END {
75     # Go back to where you came from!
76     chdir $cwd or die "Couldn't chdir to $cwd";
77   }
78 }
79 ########################################################################
80
81 # Setup a temp directory
82 sub tmpdir {
83   my ($self, @args) = @_;
84   my $dir = $ENV{PERL_CORE} ? MBTest->original_cwd : File::Spec->tmpdir;
85   return File::Temp::tempdir('MB-XXXXXXXX', CLEANUP => 1, DIR => $dir, @args);
86 }
87
88 BEGIN {
89   $ENV{HOME} = tmpdir; # don't want .modulebuildrc or other things interfering
90 }
91
92 1;
93 # vim:ts=2:sw=2:et:sta