Merge "Fix PostgreSQL updater to produce 1.19 schema"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
4 public $suite;
5 public $regex = '';
6 public $runDisabled = false;
7
8 /**
9 * @var DatabaseBase
10 */
11 protected $db;
12 protected $oldTablePrefix;
13 protected $useTemporaryTables = true;
14 protected $reuseDB = false;
15 protected $tablesUsed = array(); // tables with data
16
17 private static $dbSetup = false;
18
19 /**
20 * Holds the paths of temporary files/directories created through getNewTempFile,
21 * and getNewTempDirectory
22 *
23 * @var array
24 */
25 private $tmpfiles = array();
26
27
28 /**
29 * Table name prefixes. Oracle likes it shorter.
30 */
31 const DB_PREFIX = 'unittest_';
32 const ORA_DB_PREFIX = 'ut_';
33
34 protected $supportedDBs = array(
35 'mysql',
36 'sqlite',
37 'postgres',
38 'oracle'
39 );
40
41 function __construct( $name = null, array $data = array(), $dataName = '' ) {
42 parent::__construct( $name, $data, $dataName );
43
44 $this->backupGlobals = false;
45 $this->backupStaticAttributes = false;
46 }
47
48 function run( PHPUnit_Framework_TestResult $result = NULL ) {
49 /* Some functions require some kind of caching, and will end up using the db,
50 * which we can't allow, as that would open a new connection for mysql.
51 * Replace with a HashBag. They would not be going to persist anyway.
52 */
53 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
54
55 if( $this->needsDB() ) {
56 global $wgDBprefix;
57
58 $this->useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
59 $this->reuseDB = $this->getCliArg('reuse-db');
60
61 $this->db = wfGetDB( DB_MASTER );
62
63 $this->checkDbIsSupported();
64
65 $this->oldTablePrefix = $wgDBprefix;
66
67 if( !self::$dbSetup ) {
68 $this->initDB();
69 self::$dbSetup = true;
70 }
71
72 $this->addCoreDBData();
73 $this->addDBData();
74
75 parent::run( $result );
76
77 $this->resetDB();
78 } else {
79 parent::run( $result );
80 }
81 }
82
83 /**
84 * obtains a new temporary file name
85 *
86 * The obtained filename is enlisted to be removed upon tearDown
87 *
88 * @returns string: absolute name of the temporary file
89 */
90 protected function getNewTempFile() {
91 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
92 $this->tmpfiles[] = $fname;
93 return $fname;
94 }
95
96 /**
97 * obtains a new temporary directory
98 *
99 * The obtained directory is enlisted to be removed (recursively with all its contained
100 * files) upon tearDown.
101 *
102 * @returns string: absolute name of the temporary directory
103 */
104 protected function getNewTempDirectory() {
105 // Starting of with a temporary /file/.
106 $fname = $this->getNewTempFile();
107
108 // Converting the temporary /file/ to a /directory/
109 //
110 // The following is not atomic, but at least we now have a single place,
111 // where temporary directory creation is bundled and can be improved
112 unlink( $fname );
113 $this->assertTrue( wfMkdirParents( $fname ) );
114 return $fname;
115 }
116
117 protected function tearDown() {
118 // Cleaning up temoporary files
119 foreach ( $this->tmpfiles as $fname ) {
120 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
121 unlink( $fname );
122 } elseif ( is_dir( $fname ) ) {
123 wfRecursiveRemoveDir( $fname );
124 }
125 }
126
127 parent::tearDown();
128 }
129
130 function dbPrefix() {
131 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
132 }
133
134 function needsDB() {
135 $rc = new ReflectionClass( $this );
136 return strpos( $rc->getDocComment(), '@group Database' ) !== false;
137 }
138
139 /**
140 * Stub. If a test needs to add additional data to the database, it should
141 * implement this method and do so
142 */
143 function addDBData() {}
144
145 private function addCoreDBData() {
146 # disabled for performance
147 #$this->tablesUsed[] = 'page';
148 #$this->tablesUsed[] = 'revision';
149
150 if ( $this->db->getType() == 'oracle' ) {
151
152 # Insert 0 user to prevent FK violations
153 # Anonymous user
154 $this->db->insert( 'user', array(
155 'user_id' => 0,
156 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
157
158 # Insert 0 page to prevent FK violations
159 # Blank page
160 $this->db->insert( 'page', array(
161 'page_id' => 0,
162 'page_namespace' => 0,
163 'page_title' => ' ',
164 'page_restrictions' => NULL,
165 'page_counter' => 0,
166 'page_is_redirect' => 0,
167 'page_is_new' => 0,
168 'page_random' => 0,
169 'page_touched' => $this->db->timestamp(),
170 'page_latest' => 0,
171 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
172
173 }
174
175 User::resetIdByNameCache();
176
177 //Make sysop user
178 $user = User::newFromName( 'UTSysop' );
179
180 if ( $user->idForName() == 0 ) {
181 $user->addToDatabase();
182 $user->setPassword( 'UTSysopPassword' );
183
184 $user->addGroup( 'sysop' );
185 $user->addGroup( 'bureaucrat' );
186 $user->saveSettings();
187 }
188
189
190 //Make 1 page with 1 revision
191 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
192 if ( !$page->getId() == 0 ) {
193 $page->doEdit( 'UTContent',
194 'UTPageSummary',
195 EDIT_NEW,
196 false,
197 User::newFromName( 'UTSysop' ) );
198 }
199 }
200
201 private function initDB() {
202 global $wgDBprefix;
203 if ( $wgDBprefix === $this->dbPrefix() ) {
204 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
205 }
206
207 $tablesCloned = $this->listTables();
208 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
209 $dbClone->useTemporaryTables( $this->useTemporaryTables );
210
211 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
212 CloneDatabase::changePrefix( $this->dbPrefix() );
213 $this->resetDB();
214 return;
215 } else {
216 $dbClone->cloneTableStructure();
217 }
218
219 if ( $this->db->getType() == 'oracle' ) {
220 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
221 }
222 }
223
224 /**
225 * Empty all tables so they can be repopulated for tests
226 */
227 private function resetDB() {
228 if( $this->db ) {
229 if ( $this->db->getType() == 'oracle' ) {
230 if ( $this->useTemporaryTables ) {
231 wfGetLB()->closeAll();
232 $this->db = wfGetDB( DB_MASTER );
233 } else {
234 foreach( $this->tablesUsed as $tbl ) {
235 if( $tbl == 'interwiki') continue;
236 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
237 }
238 }
239 } else {
240 foreach( $this->tablesUsed as $tbl ) {
241 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
242 $this->db->delete( $tbl, '*', __METHOD__ );
243 }
244 }
245 }
246 }
247
248 function __call( $func, $args ) {
249 static $compatibility = array(
250 'assertInternalType' => 'assertType',
251 'assertNotInternalType' => 'assertNotType',
252 'assertInstanceOf' => 'assertType',
253 'assertEmpty' => 'assertEmpty2',
254 );
255
256 if ( method_exists( $this->suite, $func ) ) {
257 return call_user_func_array( array( $this->suite, $func ), $args);
258 } elseif ( isset( $compatibility[$func] ) ) {
259 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
260 } else {
261 throw new MWException( "Called non-existant $func method on "
262 . get_class( $this ) );
263 }
264 }
265
266 private function assertEmpty2( $value, $msg ) {
267 return $this->assertTrue( $value == '', $msg );
268 }
269
270 static private function unprefixTable( $tableName ) {
271 global $wgDBprefix;
272 return substr( $tableName, strlen( $wgDBprefix ) );
273 }
274
275 static private function isNotUnittest( $table ) {
276 return strpos( $table, 'unittest_' ) !== 0;
277 }
278
279 protected function listTables() {
280 global $wgDBprefix;
281
282 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
283 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
284
285 // Don't duplicate test tables from the previous fataled run
286 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
287
288 if ( $this->db->getType() == 'sqlite' ) {
289 $tables = array_flip( $tables );
290 // these are subtables of searchindex and don't need to be duped/dropped separately
291 unset( $tables['searchindex_content'] );
292 unset( $tables['searchindex_segdir'] );
293 unset( $tables['searchindex_segments'] );
294 $tables = array_flip( $tables );
295 }
296 return $tables;
297 }
298
299 protected function checkDbIsSupported() {
300 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
301 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
302 }
303 }
304
305 public function getCliArg( $offset ) {
306
307 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
308 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
309 }
310
311 }
312
313 public function setCliArg( $offset, $value ) {
314
315 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
316
317 }
318
319 public static function disableInterwikis( $prefix, &$data ) {
320 return false;
321 }
322
323 /**
324 * Don't throw a warning if $function is deprecated and called later
325 *
326 * @param $function String
327 * @return null
328 */
329 function hideDeprecated( $function ) {
330 wfSuppressWarnings();
331 wfDeprecated( $function );
332 wfRestoreWarnings();
333 }
334 }