Merge "(bug 35839) Check permisions for revdel blocks"
[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->doEdit( 'UTContent',
211 'UTPageSummary',
212 EDIT_NEW,
213 false,
214 User::newFromName( 'UTSysop' ) );
215 }
216 }
217
218 private function initDB() {
219 global $wgDBprefix;
220 if ( $wgDBprefix === $this->dbPrefix() ) {
221 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
222 }
223
224 $tablesCloned = $this->listTables();
225 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
226 $dbClone->useTemporaryTables( $this->useTemporaryTables );
227
228 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
229 CloneDatabase::changePrefix( $this->dbPrefix() );
230 $this->resetDB();
231 return;
232 } else {
233 $dbClone->cloneTableStructure();
234 }
235
236 if ( $this->db->getType() == 'oracle' ) {
237 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
238 }
239 }
240
241 /**
242 * Empty all tables so they can be repopulated for tests
243 */
244 private function resetDB() {
245 if( $this->db ) {
246 if ( $this->db->getType() == 'oracle' ) {
247 if ( $this->useTemporaryTables ) {
248 wfGetLB()->closeAll();
249 $this->db = wfGetDB( DB_MASTER );
250 } else {
251 foreach( $this->tablesUsed as $tbl ) {
252 if( $tbl == 'interwiki') continue;
253 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
254 }
255 }
256 } else {
257 foreach( $this->tablesUsed as $tbl ) {
258 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
259 $this->db->delete( $tbl, '*', __METHOD__ );
260 }
261 }
262 }
263 }
264
265 function __call( $func, $args ) {
266 static $compatibility = array(
267 'assertInternalType' => 'assertType',
268 'assertNotInternalType' => 'assertNotType',
269 'assertInstanceOf' => 'assertType',
270 'assertEmpty' => 'assertEmpty2',
271 );
272
273 if ( method_exists( $this->suite, $func ) ) {
274 return call_user_func_array( array( $this->suite, $func ), $args);
275 } elseif ( isset( $compatibility[$func] ) ) {
276 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
277 } else {
278 throw new MWException( "Called non-existant $func method on "
279 . get_class( $this ) );
280 }
281 }
282
283 private function assertEmpty2( $value, $msg ) {
284 return $this->assertTrue( $value == '', $msg );
285 }
286
287 static private function unprefixTable( $tableName ) {
288 global $wgDBprefix;
289 return substr( $tableName, strlen( $wgDBprefix ) );
290 }
291
292 static private function isNotUnittest( $table ) {
293 return strpos( $table, 'unittest_' ) !== 0;
294 }
295
296 protected function listTables() {
297 global $wgDBprefix;
298
299 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
300 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
301
302 // Don't duplicate test tables from the previous fataled run
303 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
304
305 if ( $this->db->getType() == 'sqlite' ) {
306 $tables = array_flip( $tables );
307 // these are subtables of searchindex and don't need to be duped/dropped separately
308 unset( $tables['searchindex_content'] );
309 unset( $tables['searchindex_segdir'] );
310 unset( $tables['searchindex_segments'] );
311 $tables = array_flip( $tables );
312 }
313 return $tables;
314 }
315
316 protected function checkDbIsSupported() {
317 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
318 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
319 }
320 }
321
322 public function getCliArg( $offset ) {
323
324 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
325 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
326 }
327
328 }
329
330 public function setCliArg( $offset, $value ) {
331
332 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
333
334 }
335
336 /**
337 * Don't throw a warning if $function is deprecated and called later
338 *
339 * @param $function String
340 * @return null
341 */
342 function hideDeprecated( $function ) {
343 wfSuppressWarnings();
344 wfDeprecated( $function );
345 wfRestoreWarnings();
346 }
347
348 /**
349 * Asserts that the given database query yields the rows given by $expectedRows.
350 * The expected rows should be given as indexed (not associative) arrays, with
351 * the values given in the order of the columns in the $fields parameter.
352 * Note that the rows are sorted by the columns given in $fields.
353 *
354 * @since 1.20
355 *
356 * @param $table String|Array the table(s) to query
357 * @param $fields String|Array the columns to include in the result (and to sort by)
358 * @param $condition String|Array "where" condition(s)
359 * @param $expectedRows Array - an array of arrays giving the expected rows.
360 *
361 * @throws MWException if this test cases's needsDB() method doesn't return true.
362 * Test cases can use "@group Database" to enable database test support,
363 * or list the tables under testing in $this->tablesUsed, or override the
364 * needsDB() method.
365 */
366 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
367 if ( !$this->needsDB() ) {
368 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
369 ' method should return true. Use @group Database or $this->tablesUsed.');
370 }
371
372 $db = wfGetDB( DB_SLAVE );
373
374 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
375 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
376
377 $i = 0;
378
379 foreach ( $expectedRows as $expected ) {
380 $r = $res->fetchRow();
381 self::stripStringKeys( $r );
382
383 $i += 1;
384 $this->assertNotEmpty( $r, "row #$i missing" );
385
386 $this->assertEquals( $expected, $r, "row #$i mismatches" );
387 }
388
389 $r = $res->fetchRow();
390 self::stripStringKeys( $r );
391
392 $this->assertFalse( $r, "found extra row (after #$i)" );
393 }
394
395 /**
396 * Utility method taking an array of elements and wrapping
397 * each element in it's own array. Useful for data providers
398 * that only return a single argument.
399 *
400 * @since 1.20
401 *
402 * @param array $elements
403 *
404 * @return array
405 */
406 protected function arrayWrap( array $elements ) {
407 return array_map(
408 function( $element ) {
409 return array( $element );
410 },
411 $elements
412 );
413 }
414
415 /**
416 * Assert that two arrays are equal. By default this means that both arrays need to hold
417 * the same set of values. Using additional arguments, order and associated key can also
418 * be set as relevant.
419 *
420 * @since 1.20
421 *
422 * @param array $expected
423 * @param array $actual
424 * @param boolean $ordered If the order of the values should match
425 * @param boolean $named If the keys should match
426 */
427 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
428 if ( !$ordered ) {
429 $this->objectAssociativeSort( $expected );
430 $this->objectAssociativeSort( $actual );
431 }
432
433 if ( !$named ) {
434 $expected = array_values( $expected );
435 $actual = array_values( $actual );
436 }
437
438 call_user_func_array(
439 array( $this, 'assertEquals' ),
440 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
441 );
442 }
443
444 /**
445 * Does an associative sort that works for objects.
446 *
447 * @since 1.20
448 *
449 * @param array $array
450 */
451 protected function objectAssociativeSort( array &$array ) {
452 uasort(
453 $array,
454 function( $a, $b ) {
455 return serialize( $a ) > serialize( $b ) ? 1 : -1;
456 }
457 );
458 }
459
460 /**
461 * Utility function for eliminating all string keys from an array.
462 * Useful to turn a database result row as returned by fetchRow() into
463 * a pure indexed array.
464 *
465 * @since 1.20
466 *
467 * @param $r mixed the array to remove string keys from.
468 */
469 protected static function stripStringKeys( &$r ) {
470 if ( !is_array( $r ) ) {
471 return;
472 }
473
474 foreach ( $r as $k => $v ) {
475 if ( is_string( $k ) ) {
476 unset( $r[$k] );
477 }
478 }
479 }
480
481 }