merge latest master into Wikidata branch
[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 Array of TestUser
10 */
11 public static $users;
12
13 /**
14 * @var DatabaseBase
15 */
16 protected $db;
17 protected $oldTablePrefix;
18 protected $useTemporaryTables = true;
19 protected $reuseDB = false;
20 protected $tablesUsed = array(); // tables with data
21
22 protected $restoreGlobals = array( // global variables to restore for each test
23 'wgLang',
24 'wgContLang',
25 'wgLanguageCode',
26 'wgUser',
27 'wgTitle',
28 );
29
30 private $savedGlobals = array();
31
32 private static $dbSetup = false;
33
34 /**
35 * Holds the paths of temporary files/directories created through getNewTempFile,
36 * and getNewTempDirectory
37 *
38 * @var array
39 */
40 private $tmpfiles = array();
41
42
43 /**
44 * Table name prefixes. Oracle likes it shorter.
45 */
46 const DB_PREFIX = 'unittest_';
47 const ORA_DB_PREFIX = 'ut_';
48
49 protected $supportedDBs = array(
50 'mysql',
51 'sqlite',
52 'postgres',
53 'oracle'
54 );
55
56 function __construct( $name = null, array $data = array(), $dataName = '' ) {
57 parent::__construct( $name, $data, $dataName );
58
59 $this->backupGlobals = false;
60 $this->backupStaticAttributes = false;
61 }
62
63 function run( PHPUnit_Framework_TestResult $result = NULL ) {
64 /* Some functions require some kind of caching, and will end up using the db,
65 * which we can't allow, as that would open a new connection for mysql.
66 * Replace with a HashBag. They would not be going to persist anyway.
67 */
68 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
69
70 if( $this->needsDB() ) {
71 global $wgDBprefix;
72
73 $this->useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
74 $this->reuseDB = $this->getCliArg('reuse-db');
75
76 $this->db = wfGetDB( DB_MASTER );
77
78 $this->checkDbIsSupported();
79
80 $this->oldTablePrefix = $wgDBprefix;
81
82 if( !self::$dbSetup ) {
83 $this->initDB();
84 self::$dbSetup = true;
85 }
86
87 $this->addCoreDBData();
88 $this->addDBData();
89
90 parent::run( $result );
91
92 $this->resetDB();
93 } else {
94 parent::run( $result );
95 }
96 }
97
98 /**
99 * obtains a new temporary file name
100 *
101 * The obtained filename is enlisted to be removed upon tearDown
102 *
103 * @returns string: absolute name of the temporary file
104 */
105 protected function getNewTempFile() {
106 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
107 $this->tmpfiles[] = $fname;
108 return $fname;
109 }
110
111 /**
112 * obtains a new temporary directory
113 *
114 * The obtained directory is enlisted to be removed (recursively with all its contained
115 * files) upon tearDown.
116 *
117 * @returns string: absolute name of the temporary directory
118 */
119 protected function getNewTempDirectory() {
120 // Starting of with a temporary /file/.
121 $fname = $this->getNewTempFile();
122
123 // Converting the temporary /file/ to a /directory/
124 //
125 // The following is not atomic, but at least we now have a single place,
126 // where temporary directory creation is bundled and can be improved
127 unlink( $fname );
128 $this->assertTrue( wfMkdirParents( $fname ) );
129 return $fname;
130 }
131
132 protected function setup() {
133 parent::setup();
134
135 foreach ( $this->restoreGlobals as $var ) {
136 $v = $GLOBALS[ $var ];
137
138 if ( is_object( $v ) || is_array( $v ) ) {
139 $v = clone $v;
140 }
141
142 $this->savedGlobals[ $var ] = $v;
143 }
144 }
145
146 protected function teardown() {
147 // Cleaning up temporary files
148 foreach ( $this->tmpfiles as $fname ) {
149 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
150 unlink( $fname );
151 } elseif ( is_dir( $fname ) ) {
152 wfRecursiveRemoveDir( $fname );
153 }
154 }
155
156 // clean up open transactions
157 if( $this->needsDB() && $this->db ) {
158 while( $this->db->trxLevel() > 0 ) {
159 $this->db->rollback();
160 }
161 }
162
163 // restore saved globals
164 foreach ( $this->savedGlobals as $k => $v ) {
165 $GLOBALS[ $k ] = $v;
166 }
167
168 parent::teardown();
169 }
170
171 function dbPrefix() {
172 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
173 }
174
175 function needsDB() {
176 # if the test says it uses database tables, it needs the database
177 if ( $this->tablesUsed ) {
178 return true;
179 }
180
181 # if the test says it belongs to the Database group, it needs the database
182 $rc = new ReflectionClass( $this );
183 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
184 return true;
185 }
186
187 return false;
188 }
189
190 /**
191 * Stub. If a test needs to add additional data to the database, it should
192 * implement this method and do so
193 */
194 function addDBData() {}
195
196 private function addCoreDBData() {
197 # disabled for performance
198 #$this->tablesUsed[] = 'page';
199 #$this->tablesUsed[] = 'revision';
200
201 if ( $this->db->getType() == 'oracle' ) {
202
203 # Insert 0 user to prevent FK violations
204 # Anonymous user
205 $this->db->insert( 'user', array(
206 'user_id' => 0,
207 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
208
209 # Insert 0 page to prevent FK violations
210 # Blank page
211 $this->db->insert( 'page', array(
212 'page_id' => 0,
213 'page_namespace' => 0,
214 'page_title' => ' ',
215 'page_restrictions' => NULL,
216 'page_counter' => 0,
217 'page_is_redirect' => 0,
218 'page_is_new' => 0,
219 'page_random' => 0,
220 'page_touched' => $this->db->timestamp(),
221 'page_latest' => 0,
222 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
223
224 }
225
226 User::resetIdByNameCache();
227
228 //Make sysop user
229 $user = User::newFromName( 'UTSysop' );
230
231 if ( $user->idForName() == 0 ) {
232 $user->addToDatabase();
233 $user->setPassword( 'UTSysopPassword' );
234
235 $user->addGroup( 'sysop' );
236 $user->addGroup( 'bureaucrat' );
237 $user->saveSettings();
238 }
239
240
241 //Make 1 page with 1 revision
242 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
243 if ( !$page->getId() == 0 ) {
244 $page->doEditContent(
245 new WikitextContent( 'UTContent' ),
246 'UTPageSummary',
247 EDIT_NEW,
248 false,
249 User::newFromName( 'UTSysop' ) );
250 }
251 }
252
253 private function initDB() {
254 global $wgDBprefix;
255 if ( $wgDBprefix === $this->dbPrefix() ) {
256 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
257 }
258
259 $tablesCloned = $this->listTables();
260 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
261 $dbClone->useTemporaryTables( $this->useTemporaryTables );
262
263 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
264 CloneDatabase::changePrefix( $this->dbPrefix() );
265 $this->resetDB();
266 return;
267 } else {
268 $dbClone->cloneTableStructure();
269 }
270
271 if ( $this->db->getType() == 'oracle' ) {
272 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
273 }
274 }
275
276 /**
277 * Empty all tables so they can be repopulated for tests
278 */
279 private function resetDB() {
280 if( $this->db ) {
281 if ( $this->db->getType() == 'oracle' ) {
282 if ( $this->useTemporaryTables ) {
283 wfGetLB()->closeAll();
284 $this->db = wfGetDB( DB_MASTER );
285 } else {
286 foreach( $this->tablesUsed as $tbl ) {
287 if( $tbl == 'interwiki') continue;
288 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
289 }
290 }
291 } else {
292 foreach( $this->tablesUsed as $tbl ) {
293 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
294 $this->db->delete( $tbl, '*', __METHOD__ );
295 }
296 }
297 }
298 }
299
300 function __call( $func, $args ) {
301 static $compatibility = array(
302 'assertInternalType' => 'assertType',
303 'assertNotInternalType' => 'assertNotType',
304 'assertInstanceOf' => 'assertType',
305 'assertEmpty' => 'assertEmpty2',
306 );
307
308 if ( method_exists( $this->suite, $func ) ) {
309 return call_user_func_array( array( $this->suite, $func ), $args);
310 } elseif ( isset( $compatibility[$func] ) ) {
311 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
312 } else {
313 throw new MWException( "Called non-existant $func method on "
314 . get_class( $this ) );
315 }
316 }
317
318 private function assertEmpty2( $value, $msg ) {
319 return $this->assertTrue( $value == '', $msg );
320 }
321
322 static private function unprefixTable( $tableName ) {
323 global $wgDBprefix;
324 return substr( $tableName, strlen( $wgDBprefix ) );
325 }
326
327 static private function isNotUnittest( $table ) {
328 return strpos( $table, 'unittest_' ) !== 0;
329 }
330
331 protected function listTables() {
332 global $wgDBprefix;
333
334 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
335 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
336
337 // Don't duplicate test tables from the previous fataled run
338 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
339
340 if ( $this->db->getType() == 'sqlite' ) {
341 $tables = array_flip( $tables );
342 // these are subtables of searchindex and don't need to be duped/dropped separately
343 unset( $tables['searchindex_content'] );
344 unset( $tables['searchindex_segdir'] );
345 unset( $tables['searchindex_segments'] );
346 $tables = array_flip( $tables );
347 }
348 return $tables;
349 }
350
351 protected function checkDbIsSupported() {
352 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
353 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
354 }
355 }
356
357 public function getCliArg( $offset ) {
358
359 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
360 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
361 }
362
363 }
364
365 public function setCliArg( $offset, $value ) {
366
367 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
368
369 }
370
371 /**
372 * Don't throw a warning if $function is deprecated and called later
373 *
374 * @param $function String
375 * @return null
376 */
377 function hideDeprecated( $function ) {
378 wfSuppressWarnings();
379 wfDeprecated( $function );
380 wfRestoreWarnings();
381 }
382
383 /**
384 * Asserts that the given database query yields the rows given by $expectedRows.
385 * The expected rows should be given as indexed (not associative) arrays, with
386 * the values given in the order of the columns in the $fields parameter.
387 * Note that the rows are sorted by the columns given in $fields.
388 *
389 * @since 1.20
390 *
391 * @param $table String|Array the table(s) to query
392 * @param $fields String|Array the columns to include in the result (and to sort by)
393 * @param $condition String|Array "where" condition(s)
394 * @param $expectedRows Array - an array of arrays giving the expected rows.
395 *
396 * @throws MWException if this test cases's needsDB() method doesn't return true.
397 * Test cases can use "@group Database" to enable database test support,
398 * or list the tables under testing in $this->tablesUsed, or override the
399 * needsDB() method.
400 */
401 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
402 if ( !$this->needsDB() ) {
403 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
404 ' method should return true. Use @group Database or $this->tablesUsed.');
405 }
406
407 $db = wfGetDB( DB_SLAVE );
408
409 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
410 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
411
412 $i = 0;
413
414 foreach ( $expectedRows as $expected ) {
415 $r = $res->fetchRow();
416 self::stripStringKeys( $r );
417
418 $i += 1;
419 $this->assertNotEmpty( $r, "row #$i missing" );
420
421 $this->assertEquals( $expected, $r, "row #$i mismatches" );
422 }
423
424 $r = $res->fetchRow();
425 self::stripStringKeys( $r );
426
427 $this->assertFalse( $r, "found extra row (after #$i)" );
428 }
429
430 /**
431 * Utility method taking an array of elements and wrapping
432 * each element in it's own array. Useful for data providers
433 * that only return a single argument.
434 *
435 * @since 1.20
436 *
437 * @param array $elements
438 *
439 * @return array
440 */
441 protected function arrayWrap( array $elements ) {
442 return array_map(
443 function( $element ) {
444 return array( $element );
445 },
446 $elements
447 );
448 }
449
450 /**
451 * Assert that two arrays are equal. By default this means that both arrays need to hold
452 * the same set of values. Using additional arguments, order and associated key can also
453 * be set as relevant.
454 *
455 * @since 1.20
456 *
457 * @param array $expected
458 * @param array $actual
459 * @param boolean $ordered If the order of the values should match
460 * @param boolean $named If the keys should match
461 */
462 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
463 if ( !$ordered ) {
464 $this->objectAssociativeSort( $expected );
465 $this->objectAssociativeSort( $actual );
466 }
467
468 if ( !$named ) {
469 $expected = array_values( $expected );
470 $actual = array_values( $actual );
471 }
472
473 call_user_func_array(
474 array( $this, 'assertEquals' ),
475 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
476 );
477 }
478
479 /**
480 * Put each HTML element on its own line and then equals() the results
481 *
482 * Use for nicely formatting of PHPUnit diff output when comparing very
483 * simple HTML
484 *
485 * @since 1.20
486 *
487 * @param String $expected HTML on oneline
488 * @param String $actual HTML on oneline
489 * @param String $msg Optional message
490 */
491 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
492 $expected = str_replace( '>', ">\n", $expected );
493 $actual = str_replace( '>', ">\n", $actual );
494
495 $this->assertEquals( $expected, $actual, $msg );
496 }
497
498 /**
499 * Does an associative sort that works for objects.
500 *
501 * @since 1.20
502 *
503 * @param array $array
504 */
505 protected function objectAssociativeSort( array &$array ) {
506 uasort(
507 $array,
508 function( $a, $b ) {
509 return serialize( $a ) > serialize( $b ) ? 1 : -1;
510 }
511 );
512 }
513
514 /**
515 * Utility function for eliminating all string keys from an array.
516 * Useful to turn a database result row as returned by fetchRow() into
517 * a pure indexed array.
518 *
519 * @since 1.20
520 *
521 * @param $r mixed the array to remove string keys from.
522 */
523 protected static function stripStringKeys( &$r ) {
524 if ( !is_array( $r ) ) {
525 return;
526 }
527
528 foreach ( $r as $k => $v ) {
529 if ( is_string( $k ) ) {
530 unset( $r[$k] );
531 }
532 }
533 }
534
535 /**
536 * Asserts that the provided variable is of the specified
537 * internal type or equals the $value argument. This is useful
538 * for testing return types of functions that return a certain
539 * type or *value* when not set or on error.
540 *
541 * @since 1.20
542 *
543 * @param string $type
544 * @param mixed $actual
545 * @param mixed $value
546 * @param string $message
547 */
548 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
549 if ( $actual === $value ) {
550 $this->assertTrue( true, $message );
551 }
552 else {
553 $this->assertType( $type, $actual, $message );
554 }
555 }
556
557 /**
558 * Asserts the type of the provided value. This can be either
559 * in internal type such as boolean or integer, or a class or
560 * interface the value extends or implements.
561 *
562 * @since 1.20
563 *
564 * @param string $type
565 * @param mixed $actual
566 * @param string $message
567 */
568 protected function assertType( $type, $actual, $message = '' ) {
569 if ( class_exists( $type ) || interface_exists( $type ) ) {
570 $this->assertInstanceOf( $type, $actual, $message );
571 }
572 else {
573 $this->assertInternalType( $type, $actual, $message );
574 }
575 }
576
577 }