3debb35055bd8176bf0d9cde972349f8d9ecdba7
[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 temporary 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 // clean up open transactions
128 if( $this->needsDB() && $this->db ) {
129 while( $this->db->trxLevel() > 0 ) {
130 $this->db->rollback();
131 }
132 }
133
134 parent::tearDown();
135 }
136
137 function dbPrefix() {
138 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
139 }
140
141 function needsDB() {
142 # if the test says it uses database tables, it needs the database
143 if ( $this->tablesUsed ) {
144 return true;
145 }
146
147 # if the test says it belongs to the Database group, it needs the database
148 $rc = new ReflectionClass( $this );
149 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
150 return true;
151 }
152
153 return false;
154 }
155
156 /**
157 * Stub. If a test needs to add additional data to the database, it should
158 * implement this method and do so
159 */
160 function addDBData() {}
161
162 private function addCoreDBData() {
163 # disabled for performance
164 #$this->tablesUsed[] = 'page';
165 #$this->tablesUsed[] = 'revision';
166
167 if ( $this->db->getType() == 'oracle' ) {
168
169 # Insert 0 user to prevent FK violations
170 # Anonymous user
171 $this->db->insert( 'user', array(
172 'user_id' => 0,
173 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
174
175 # Insert 0 page to prevent FK violations
176 # Blank page
177 $this->db->insert( 'page', array(
178 'page_id' => 0,
179 'page_namespace' => 0,
180 'page_title' => ' ',
181 'page_restrictions' => NULL,
182 'page_counter' => 0,
183 'page_is_redirect' => 0,
184 'page_is_new' => 0,
185 'page_random' => 0,
186 'page_touched' => $this->db->timestamp(),
187 'page_latest' => 0,
188 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
189
190 }
191
192 User::resetIdByNameCache();
193
194 //Make sysop user
195 $user = User::newFromName( 'UTSysop' );
196
197 if ( $user->idForName() == 0 ) {
198 $user->addToDatabase();
199 $user->setPassword( 'UTSysopPassword' );
200
201 $user->addGroup( 'sysop' );
202 $user->addGroup( 'bureaucrat' );
203 $user->saveSettings();
204 }
205
206
207 //Make 1 page with 1 revision
208 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
209 if ( !$page->getId() == 0 ) {
210 $page->doEditContent(
211 new WikitextContent( 'UTContent' ),
212 'UTPageSummary',
213 EDIT_NEW,
214 false,
215 User::newFromName( 'UTSysop' ) );
216 }
217 }
218
219 private function initDB() {
220 global $wgDBprefix;
221 if ( $wgDBprefix === $this->dbPrefix() ) {
222 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
223 }
224
225 $tablesCloned = $this->listTables();
226 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
227 $dbClone->useTemporaryTables( $this->useTemporaryTables );
228
229 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
230 CloneDatabase::changePrefix( $this->dbPrefix() );
231 $this->resetDB();
232 return;
233 } else {
234 $dbClone->cloneTableStructure();
235 }
236
237 if ( $this->db->getType() == 'oracle' ) {
238 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
239 }
240 }
241
242 /**
243 * Empty all tables so they can be repopulated for tests
244 */
245 private function resetDB() {
246 if( $this->db ) {
247 if ( $this->db->getType() == 'oracle' ) {
248 if ( $this->useTemporaryTables ) {
249 wfGetLB()->closeAll();
250 $this->db = wfGetDB( DB_MASTER );
251 } else {
252 foreach( $this->tablesUsed as $tbl ) {
253 if( $tbl == 'interwiki') continue;
254 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
255 }
256 }
257 } else {
258 foreach( $this->tablesUsed as $tbl ) {
259 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
260 $this->db->delete( $tbl, '*', __METHOD__ );
261 }
262 }
263 }
264 }
265
266 function __call( $func, $args ) {
267 static $compatibility = array(
268 'assertInternalType' => 'assertType',
269 'assertNotInternalType' => 'assertNotType',
270 'assertInstanceOf' => 'assertType',
271 'assertEmpty' => 'assertEmpty2',
272 );
273
274 if ( method_exists( $this->suite, $func ) ) {
275 return call_user_func_array( array( $this->suite, $func ), $args);
276 } elseif ( isset( $compatibility[$func] ) ) {
277 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
278 } else {
279 throw new MWException( "Called non-existant $func method on "
280 . get_class( $this ) );
281 }
282 }
283
284 private function assertEmpty2( $value, $msg ) {
285 return $this->assertTrue( $value == '', $msg );
286 }
287
288 static private function unprefixTable( $tableName ) {
289 global $wgDBprefix;
290 return substr( $tableName, strlen( $wgDBprefix ) );
291 }
292
293 static private function isNotUnittest( $table ) {
294 return strpos( $table, 'unittest_' ) !== 0;
295 }
296
297 protected function listTables() {
298 global $wgDBprefix;
299
300 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
301 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
302
303 // Don't duplicate test tables from the previous fataled run
304 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
305
306 if ( $this->db->getType() == 'sqlite' ) {
307 $tables = array_flip( $tables );
308 // these are subtables of searchindex and don't need to be duped/dropped separately
309 unset( $tables['searchindex_content'] );
310 unset( $tables['searchindex_segdir'] );
311 unset( $tables['searchindex_segments'] );
312 $tables = array_flip( $tables );
313 }
314 return $tables;
315 }
316
317 protected function checkDbIsSupported() {
318 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
319 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
320 }
321 }
322
323 public function getCliArg( $offset ) {
324
325 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
326 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
327 }
328
329 }
330
331 public function setCliArg( $offset, $value ) {
332
333 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
334
335 }
336
337 /**
338 * Don't throw a warning if $function is deprecated and called later
339 *
340 * @param $function String
341 * @return null
342 */
343 function hideDeprecated( $function ) {
344 wfSuppressWarnings();
345 wfDeprecated( $function );
346 wfRestoreWarnings();
347 }
348
349 /**
350 * Asserts that the given database query yields the rows given by $expectedRows.
351 * The expected rows should be given as indexed (not associative) arrays, with
352 * the values given in the order of the columns in the $fields parameter.
353 * Note that the rows are sorted by the columns given in $fields.
354 *
355 * @since 1.20
356 *
357 * @param $table String|Array the table(s) to query
358 * @param $fields String|Array the columns to include in the result (and to sort by)
359 * @param $condition String|Array "where" condition(s)
360 * @param $expectedRows Array - an array of arrays giving the expected rows.
361 *
362 * @throws MWException if this test cases's needsDB() method doesn't return true.
363 * Test cases can use "@group Database" to enable database test support,
364 * or list the tables under testing in $this->tablesUsed, or override the
365 * needsDB() method.
366 */
367 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
368 if ( !$this->needsDB() ) {
369 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
370 ' method should return true. Use @group Database or $this->tablesUsed.');
371 }
372
373 $db = wfGetDB( DB_SLAVE );
374
375 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
376 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
377
378 $i = 0;
379
380 foreach ( $expectedRows as $expected ) {
381 $r = $res->fetchRow();
382 self::stripStringKeys( $r );
383
384 $i += 1;
385 $this->assertNotEmpty( $r, "row #$i missing" );
386
387 $this->assertEquals( $expected, $r, "row #$i mismatches" );
388 }
389
390 $r = $res->fetchRow();
391 self::stripStringKeys( $r );
392
393 $this->assertFalse( $r, "found extra row (after #$i)" );
394 }
395
396 /**
397 * Utility method taking an array of elements and wrapping
398 * each element in it's own array. Useful for data providers
399 * that only return a single argument.
400 *
401 * @since 1.20
402 *
403 * @param array $elements
404 *
405 * @return array
406 */
407 protected function arrayWrap( array $elements ) {
408 return array_map(
409 function( $element ) {
410 return array( $element );
411 },
412 $elements
413 );
414 }
415
416 /**
417 * Assert that two arrays are equal. By default this means that both arrays need to hold
418 * the same set of values. Using additional arguments, order and associated key can also
419 * be set as relevant.
420 *
421 * @since 1.20
422 *
423 * @param array $expected
424 * @param array $actual
425 * @param boolean $ordered If the order of the values should match
426 * @param boolean $named If the keys should match
427 */
428 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
429 if ( !$ordered ) {
430 $this->objectAssociativeSort( $expected );
431 $this->objectAssociativeSort( $actual );
432 }
433
434 if ( !$named ) {
435 $expected = array_values( $expected );
436 $actual = array_values( $actual );
437 }
438
439 call_user_func_array(
440 array( $this, 'assertEquals' ),
441 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
442 );
443 }
444
445 /**
446 * Does an associative sort that works for objects.
447 *
448 * @since 1.20
449 *
450 * @param array $array
451 */
452 protected function objectAssociativeSort( array &$array ) {
453 uasort(
454 $array,
455 function( $a, $b ) {
456 return serialize( $a ) > serialize( $b ) ? 1 : -1;
457 }
458 );
459 }
460
461 /**
462 * Utility function for eliminating all string keys from an array.
463 * Useful to turn a database result row as returned by fetchRow() into
464 * a pure indexed array.
465 *
466 * @since 1.20
467 *
468 * @param $r mixed the array to remove string keys from.
469 */
470 protected static function stripStringKeys( &$r ) {
471 if ( !is_array( $r ) ) {
472 return;
473 }
474
475 foreach ( $r as $k => $v ) {
476 if ( is_string( $k ) ) {
477 unset( $r[$k] );
478 }
479 }
480 }
481
482 }