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