bliako has asked for the wisdom of the Perl Monks concerning the following question:
Often in test files I create temporary dirs with File::Temp's tempdir(). I want these tempdirs to be erased upon successful completion or be retained in case of test failures with a BAIL_OUT or 3rdparty die, for inspection. I am using Test::More's BAIL_OUT() because I see no point in keep testing when the input file is missing!
The solution (Re^4: File::Temp does not cleanup() on demand) is to set the global $File::Temp::KEEP_ALL = 1; and do manual cleanup only on successful completion with this at the end:
$File::Temp::KEEP_ALL = 0; File::Temp::cleanup;
All works OK except that it messes up the temp dirs handling of other modules I import. For example:
use strict; use warnings; use Capture::Tiny qw(capture); use File::Temp 'tempdir'; $File::Temp::KEEP_ALL = 1; my $tmpdir = File::Temp::tempdir(); print "at1: ";system("ls /tmp | wc -l"); my ($stdout, $stderr) = capture { # do some system command }; # now there are two more temp files in /tmp # they should have not been there! print "at2: ";system("ls /tmp | wc -l"); $File::Temp::KEEP_ALL = 0; File::Temp::cleanup; # they are still there print "at3: ";system("ls /tmp | wc -l");
Above, I monitor the /tmp dir for temp files and sure enough there are 2 more (for capture's saving the stderr, stdout) on completion.
The problem is fixed if I set $File::Temp::KEEP_ALL = 0; or don't use it at all.
And I have experimented with the order of importing the packages, but it has no effect. The global variable affects them anyway.
Ideally, my cleanup() would have cleaned capture's cleanup. But it doesn't. Although my $KEEP_ALL affects capture's behaviour.
I have thought about the OO interface of File::Temp but it still relies on the global $KEEP_ALL, from the doc:
... If the global variable $KEEP_ALL is true, the file or directory will n +ot be removed.
I wonder if there is a way around it. Perhaps a saner File::Temp which is not relying on global variables? One which encapsulates options to an object rather than relying on globals for such a sensitive issue? It looks to me there could be security implications in this too.
bw, bliako
|
|---|