From 9e80e3a702a1318a56b8a4bfb7dc52583a7687ed Mon Sep 17 00:00:00 2001 From: Christian Aistleitner Date: Tue, 10 Apr 2012 16:28:42 +0200 Subject: [PATCH] Adding temp file/dir management to MediaWikiTestCase Change-Id: I4ac8f44f1d681925af231377e9d1b984488d3198 --- tests/phpunit/MediaWikiTestCase.php | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/phpunit/MediaWikiTestCase.php b/tests/phpunit/MediaWikiTestCase.php index 6ec8bdc7fb..f6264593b8 100644 --- a/tests/phpunit/MediaWikiTestCase.php +++ b/tests/phpunit/MediaWikiTestCase.php @@ -16,6 +16,15 @@ abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase { private static $dbSetup = false; + /** + * Holds the paths of temporary files/directories created through getNewTempFile, + * and getNewTempDirectory + * + * @var array + */ + private $tmpfiles = array(); + + /** * Table name prefixes. Oracle likes it shorter. */ @@ -71,6 +80,53 @@ abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase { } } + /** + * obtains a new temporary file name + * + * The obtained filename is enlisted to be removed upon tearDown + * + * @returns string: absolute name of the temporary file + */ + protected function getNewTempFile() { + $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' ); + $this->tmpfiles[] = $fname; + return $fname; + } + + /** + * obtains a new temporary directory + * + * The obtained directory is enlisted to be removed (recursively with all its contained + * files) upon tearDown. + * + * @returns string: absolute name of the temporary directory + */ + protected function getNewTempDirectory() { + // Starting of with a temporary /file/. + $fname = $this->getNewTempFile(); + + // Converting the temporary /file/ to a /directory/ + // + // The following is not atomic, but at least we now have a single place, + // where temporary directory creation is bundled and can be improved + unlink( $fname ); + $this->assertTrue( wfMkdirParents( $fname ) ); + return $fname; + } + + protected function tearDown() { + // Cleaning up temoporary files + foreach ( $this->tmpfiles as $fname ) { + if ( is_file( $fname ) || ( is_link( $fname ) ) ) { + unlink( $fname ); + } elseif ( is_dir( $fname ) ) { + wfRecursiveRemoveDir( $fname ); + } + } + + parent::tearDown(); + } + function dbPrefix() { return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX; } -- 2.20.1