More reversion of r77297, 2 of 2 commits to keep it readable in CR (hopefully)
[lhc/web/wiklou.git] / maintenance / tests / phpunit / includes / api / ApiUploadTest.php
1 <?php
2
3 /**
4 * @group Database
5 * @group Destructive
6 */
7
8 /**
9 * n.b. Ensure that you can write to the images/ directory as the
10 * user that will run tests.
11 */
12
13 // Note for reviewers: this intentionally duplicates functionality already in "ApiSetup" and so on.
14 // This framework works better IMO and has less strangeness (such as test cases inheriting from "ApiSetup"...)
15 // (and in the case of the other Upload tests, this flat out just actually works... )
16
17 // TODO: refactor into several files
18 // TODO: port the other Upload tests, and other API tests to this framework
19
20 require_once( dirname( __FILE__ ) . '/RandomImageGenerator.php' );
21 require_once( dirname( __FILE__ ) . '/../../../../../includes/User.php' );
22
23 /* Wraps the user object, so we can also retain full access to properties like password if we log in via the API */
24 class ApiTestUser {
25 public $username;
26 public $password;
27 public $email;
28 public $groups;
29 public $user;
30
31 function __construct( $username, $realname = 'Real Name', $email = 'sample@sample.com', $groups = array() ) {
32 $this->username = $username;
33 $this->realname = $realname;
34 $this->email = $email;
35 $this->groups = $groups;
36
37 // don't allow user to hardcode or select passwords -- people sometimes run tests
38 // on live wikis. Sometimes we create sysop users in these tests. A sysop user with
39 // a known password would be a Bad Thing.
40 $this->password = User::randomPassword();
41
42 $this->user = User::newFromName( $this->username );
43 $this->user->load();
44
45 // In an ideal world we'd have a new wiki (or mock data store) for every single test.
46 // But for now, we just need to create or update the user with the desired properties.
47 // we particularly need the new password, since we just generated it randomly.
48 // In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
49 if ( !$this->user->getID() ) {
50 // create the user
51 $this->user = User::createNew(
52 $this->username, array(
53 "email" => $this->email,
54 "real_name" => $this->realname
55 )
56 );
57 if ( !$this->user ) {
58 throw new Exception( "error creating user" );
59 }
60 }
61
62 // update the user to use the new random password and other details
63 $this->user->setPassword( $this->password );
64 $this->user->setEmail( $this->email );
65 $this->user->setRealName( $this->realname );
66 // remove all groups, replace with any groups specified
67 foreach ( $this->user->getGroups() as $group ) {
68 $this->user->removeGroup( $group );
69 }
70 if ( count( $this->groups ) ) {
71 foreach ( $this->groups as $group ) {
72 $this->user->addGroup( $group );
73 }
74 }
75 $this->user->saveSettings();
76
77 }
78
79 }
80
81 abstract class ApiTestCase extends PHPUnit_Framework_TestCase {
82 public static $users;
83
84 function setUp() {
85 global $wgContLang, $wgAuth, $wgMemc, $wgRequest, $wgUser;
86
87 $wgMemc = new FakeMemCachedClient();
88 $wgContLang = Language::factory( 'en' );
89 $wgAuth = new StubObject( 'wgAuth', 'AuthPlugin' );
90 $wgRequest = new FauxRequest( array() );
91
92 self::$users = array(
93 'sysop' => new ApiTestUser(
94 'Apitestsysop',
95 'Api Test Sysop',
96 'api_test_sysop@sample.com',
97 array( 'sysop' )
98 ),
99 'uploader' => new ApiTestUser(
100 'Apitestuser',
101 'Api Test User',
102 'api_test_user@sample.com',
103 array()
104 )
105 );
106
107 $wgUser = self::$users['sysop']->user;
108
109 }
110
111 protected function doApiRequest( $params, $session = null ) {
112 $_SESSION = isset( $session ) ? $session : array();
113
114 $request = new FauxRequest( $params, true, $_SESSION );
115 $module = new ApiMain( $request, true );
116 $module->execute();
117
118 return array( $module->getResultData(), $request, $_SESSION );
119 }
120
121 /**
122 * Add an edit token to the API request
123 * This is cheating a bit -- we grab a token in the correct format and then add it to the pseudo-session and to the
124 * request, without actually requesting a "real" edit token
125 * @param $params: key-value API params
126 * @param $session: session array
127 */
128 protected function doApiRequestWithToken( $params, $session ) {
129 if ( $session['wsToken'] ) {
130 // add edit token to fake session
131 $session['wsEditToken'] = $session['wsToken'];
132 // add token to request parameters
133 $params['token'] = md5( $session['wsToken'] ) . EDIT_TOKEN_SUFFIX;
134 return $this->doApiRequest( $params, $session );
135 } else {
136 throw new Exception( "request data not in right format" );
137 }
138 }
139
140 }
141
142 /**
143 * @group Database
144 * @group Destructive
145 */
146 class ApiUploadTest extends ApiTestCase {
147 /**
148 * Fixture -- run before every test
149 */
150 public function setUp() {
151 global $wgEnableUploads, $wgEnableAPI;
152 parent::setUp();
153
154 $wgEnableUploads = true;
155 $wgEnableAPI = true;
156 wfSetupSession();
157
158 ini_set( 'log_errors', 1 );
159 ini_set( 'error_reporting', 1 );
160 ini_set( 'display_errors', 1 );
161
162 $this->clearFakeUploads();
163 }
164
165 /**
166 * Fixture -- run after every test
167 * Clean up temporary files etc.
168 */
169 function tearDown() {
170 }
171
172
173 /**
174 * Testing login
175 * XXX this is a funny way of getting session context
176 */
177 function testLogin() {
178 $user = self::$users['uploader'];
179
180 $params = array(
181 'action' => 'login',
182 'lgname' => $user->username,
183 'lgpassword' => $user->password
184 );
185 list( $result, $request, $session ) = $this->doApiRequest( $params );
186 $this->assertArrayHasKey( "login", $result );
187 $this->assertArrayHasKey( "result", $result['login'] );
188 $this->assertEquals( "NeedToken", $result['login']['result'] );
189 $token = $result['login']['token'];
190
191 $params = array(
192 'action' => 'login',
193 'lgtoken' => $token,
194 'lgname' => $user->username,
195 'lgpassword' => $user->password
196 );
197 list( $result, $request, $session ) = $this->doApiRequest( $params );
198 $this->assertArrayHasKey( "login", $result );
199 $this->assertArrayHasKey( "result", $result['login'] );
200 $this->assertEquals( "Success", $result['login']['result'] );
201 $this->assertArrayHasKey( 'lgtoken', $result['login'] );
202
203 return $session;
204
205 }
206
207 /**
208 * @depends testLogin
209 */
210 public function testUploadRequiresToken( $session ) {
211 $exception = false;
212 try {
213 $this->doApiRequest( array(
214 'action' => 'upload'
215 ) );
216 } catch ( UsageException $e ) {
217 $exception = true;
218 $this->assertEquals( "The token parameter must be set", $e->getMessage() );
219 }
220 $this->assertTrue( $exception, "Got exception" );
221 }
222
223 /**
224 * @depends testLogin
225 */
226 public function testUploadMissingParams( $session ) {
227 global $wgUser;
228 $wgUser = self::$users['uploader']->user;
229
230 $exception = false;
231 try {
232 $this->doApiRequestWithToken( array(
233 'action' => 'upload',
234 ), $session );
235 } catch ( UsageException $e ) {
236 $exception = true;
237 $this->assertEquals( "One of the parameters sessionkey, file, url, statuskey is required",
238 $e->getMessage() );
239 }
240 $this->assertTrue( $exception, "Got exception" );
241 }
242
243
244 /**
245 * @depends testLogin
246 */
247 public function testUpload( $session ) {
248 global $wgUser;
249 $wgUser = self::$users['uploader']->user;
250
251 $extension = 'png';
252 $mimeType = 'image/png';
253
254 try {
255 $randomImageGenerator = new RandomImageGenerator();
256 }
257 catch ( Exception $e ) {
258 $this->markTestIncomplete( $e->getMessage() );
259 }
260
261 $filePaths = $randomImageGenerator->writeImages( 1, $extension, dirname( wfTempDir() ) );
262 $filePath = $filePaths[0];
263 $fileSize = filesize( $filePath );
264 $fileName = basename( $filePath );
265
266 $this->deleteFileByFileName( $fileName );
267 $this->deleteFileByContent( $filePath );
268
269 if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) {
270 $this->markTestIncomplete( "Couldn't upload file!\n" );
271 }
272
273 $params = array(
274 'action' => 'upload',
275 'filename' => $fileName,
276 'file' => 'dummy content',
277 'comment' => 'dummy comment',
278 'text' => "This is the page text for $fileName",
279 );
280
281 $exception = false;
282 try {
283 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
284 } catch ( UsageException $e ) {
285 $exception = true;
286 }
287 $this->assertTrue( isset( $result['upload'] ) );
288 $this->assertEquals( 'Success', $result['upload']['result'] );
289 $this->assertEquals( $fileSize, ( int )$result['upload']['imageinfo']['size'] );
290 $this->assertEquals( $mimeType, $result['upload']['imageinfo']['mime'] );
291 $this->assertFalse( $exception );
292
293 // clean up
294 $this->deleteFileByFilename( $fileName );
295 unlink( $filePath );
296 }
297
298
299 /**
300 * @depends testLogin
301 */
302 public function testUploadZeroLength( $session ) {
303 global $wgUser;
304 $wgUser = self::$users['uploader']->user;
305
306 $mimeType = 'image/png';
307
308 $filePath = tempnam( wfTempDir(), "" );
309 $fileName = "apiTestUploadZeroLength.png";
310
311 $this->deleteFileByFileName( $fileName );
312
313 if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) {
314 $this->markTestIncomplete( "Couldn't upload file!\n" );
315 }
316
317 $params = array(
318 'action' => 'upload',
319 'filename' => $fileName,
320 'file' => 'dummy content',
321 'comment' => 'dummy comment',
322 'text' => "This is the page text for $fileName",
323 );
324
325 $exception = false;
326 try {
327 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
328 } catch ( UsageException $e ) {
329 $this->assertContains( 'The file you submitted was empty', $e->getMessage() );
330 $exception = true;
331 }
332 $this->assertTrue( $exception );
333
334 // clean up
335 $this->deleteFileByFilename( $fileName );
336 unlink( $filePath );
337 }
338
339
340 /**
341 * @depends testLogin
342 */
343 public function testUploadSameFileName( $session ) {
344 global $wgUser;
345 $wgUser = self::$users['uploader']->user;
346
347 $extension = 'png';
348 $mimeType = 'image/png';
349
350 try {
351 $randomImageGenerator = new RandomImageGenerator();
352 }
353 catch ( Exception $e ) {
354 $this->markTestIncomplete( $e->getMessage() );
355 }
356
357 $filePaths = $randomImageGenerator->writeImages( 2, $extension, dirname( wfTempDir() ) );
358 // we'll reuse this filename
359 $fileName = basename( $filePaths[0] );
360
361 // clear any other files with the same name
362 $this->deleteFileByFileName( $fileName );
363
364 // we reuse these params
365 $params = array(
366 'action' => 'upload',
367 'filename' => $fileName,
368 'file' => 'dummy content',
369 'comment' => 'dummy comment',
370 'text' => "This is the page text for $fileName",
371 );
372
373 // first upload .... should succeed
374
375 if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePaths[0] ) ) {
376 $this->markTestIncomplete( "Couldn't upload file!\n" );
377 }
378
379 $exception = false;
380 try {
381 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
382 } catch ( UsageException $e ) {
383 $exception = true;
384 }
385 $this->assertTrue( isset( $result['upload'] ) );
386 $this->assertEquals( 'Success', $result['upload']['result'] );
387 $this->assertFalse( $exception );
388
389 // second upload with the same name (but different content)
390
391 if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePaths[1] ) ) {
392 $this->markTestIncomplete( "Couldn't upload file!\n" );
393 }
394
395 $exception = false;
396 try {
397 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
398 } catch ( UsageException $e ) {
399 $exception = true;
400 }
401 $this->assertTrue( isset( $result['upload'] ) );
402 $this->assertEquals( 'Warning', $result['upload']['result'] );
403 $this->assertTrue( isset( $result['upload']['warnings'] ) );
404 $this->assertTrue( isset( $result['upload']['warnings']['exists'] ) );
405 $this->assertFalse( $exception );
406
407 // clean up
408 $this->deleteFileByFilename( $fileName );
409 unlink( $filePaths[0] );
410 unlink( $filePaths[1] );
411 }
412
413
414 /**
415 * @depends testLogin
416 */
417 public function testUploadSameContent( $session ) {
418 global $wgUser;
419 $wgUser = self::$users['uploader']->user;
420
421 $extension = 'png';
422 $mimeType = 'image/png';
423
424 try {
425 $randomImageGenerator = new RandomImageGenerator();
426 }
427 catch ( Exception $e ) {
428 $this->markTestIncomplete( $e->getMessage() );
429 }
430 $filePaths = $randomImageGenerator->writeImages( 1, $extension, dirname( wfTempDir() ) );
431 $fileNames[0] = basename( $filePaths[0] );
432 $fileNames[1] = "SameContentAs" . $fileNames[0];
433
434 // clear any other files with the same name or content
435 $this->deleteFileByContent( $filePaths[0] );
436 $this->deleteFileByFileName( $fileNames[0] );
437 $this->deleteFileByFileName( $fileNames[1] );
438
439 // first upload .... should succeed
440
441 $params = array(
442 'action' => 'upload',
443 'filename' => $fileNames[0],
444 'file' => 'dummy content',
445 'comment' => 'dummy comment',
446 'text' => "This is the page text for " . $fileNames[0],
447 );
448
449 if (! $this->fakeUploadFile( 'file', $fileNames[0], $mimeType, $filePaths[0] ) ) {
450 $this->markTestIncomplete( "Couldn't upload file!\n" );
451 }
452
453 $exception = false;
454 try {
455 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
456 } catch ( UsageException $e ) {
457 $exception = true;
458 }
459 $this->assertTrue( isset( $result['upload'] ) );
460 $this->assertEquals( 'Success', $result['upload']['result'] );
461 $this->assertFalse( $exception );
462
463
464 // second upload with the same content (but different name)
465
466 if (! $this->fakeUploadFile( 'file', $fileNames[1], $mimeType, $filePaths[0] ) ) {
467 $this->markTestIncomplete( "Couldn't upload file!\n" );
468 }
469
470 $params = array(
471 'action' => 'upload',
472 'filename' => $fileNames[1],
473 'file' => 'dummy content',
474 'comment' => 'dummy comment',
475 'text' => "This is the page text for " . $fileNames[1],
476 );
477
478 $exception = false;
479 try {
480 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
481 } catch ( UsageException $e ) {
482 $exception = true;
483 }
484 $this->assertTrue( isset( $result['upload'] ) );
485 $this->assertEquals( 'Warning', $result['upload']['result'] );
486 $this->assertTrue( isset( $result['upload']['warnings'] ) );
487 $this->assertTrue( isset( $result['upload']['warnings']['duplicate'] ) );
488 $this->assertFalse( $exception );
489
490 // clean up
491 $this->deleteFileByFilename( $fileNames[0] );
492 $this->deleteFileByFilename( $fileNames[1] );
493 unlink( $filePaths[0] );
494 }
495
496
497 /**
498 * @depends testLogin
499 */
500 public function testUploadStash( $session ) {
501 global $wgUser;
502 $wgUser = self::$users['uploader']->user;
503
504 $extension = 'png';
505 $mimeType = 'image/png';
506
507 try {
508 $randomImageGenerator = new RandomImageGenerator();
509 }
510 catch ( Exception $e ) {
511 $this->markTestIncomplete( $e->getMessage() );
512 }
513
514 $filePaths = $randomImageGenerator->writeImages( 1, $extension, dirname( wfTempDir() ) );
515 $filePath = $filePaths[0];
516 $fileSize = filesize( $filePath );
517 $fileName = basename( $filePath );
518
519 $this->deleteFileByFileName( $fileName );
520 $this->deleteFileByContent( $filePath );
521
522 if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) {
523 $this->markTestIncomplete( "Couldn't upload file!\n" );
524 }
525
526 $params = array(
527 'action' => 'upload',
528 'stash' => 1,
529 'filename' => $fileName,
530 'file' => 'dummy content',
531 'comment' => 'dummy comment',
532 'text' => "This is the page text for $fileName",
533 );
534
535 $exception = false;
536 try {
537 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
538 } catch ( UsageException $e ) {
539 $exception = true;
540 }
541 $this->assertFalse( $exception );
542 $this->assertTrue( isset( $result['upload'] ) );
543 $this->assertEquals( 'Success', $result['upload']['result'] );
544 $this->assertEquals( $fileSize, ( int )$result['upload']['imageinfo']['size'] );
545 $this->assertEquals( $mimeType, $result['upload']['imageinfo']['mime'] );
546 $this->assertTrue( isset( $result['upload']['sessionkey'] ) );
547 $sessionkey = $result['upload']['sessionkey'];
548
549 // it should be visible from Special:UploadStash
550 // XXX ...but how to test this, with a fake WebRequest with the session?
551
552 // now we should try to release the file from stash
553 $params = array(
554 'action' => 'upload',
555 'sessionkey' => $sessionkey,
556 'filename' => $fileName,
557 'comment' => 'dummy comment',
558 'text' => "This is the page text for $fileName, altered",
559 );
560
561 $this->clearFakeUploads();
562 $exception = false;
563 try {
564 list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session );
565 } catch ( UsageException $e ) {
566 $exception = true;
567 }
568 $this->assertTrue( isset( $result['upload'] ) );
569 $this->assertEquals( 'Success', $result['upload']['result'] );
570 $this->assertFalse( $exception );
571
572 // clean up
573 $this->deleteFileByFilename( $fileName );
574 unlink( $filePath );
575 }
576
577
578
579 /**
580 * Helper function -- remove files and associated articles by Title
581 * @param $title Title: title to be removed
582 */
583 public function deleteFileByTitle( $title ) {
584 if ( $title->exists() ) {
585 $file = wfFindFile( $title, array( 'ignoreRedirect' => true ) );
586 $noOldArchive = ""; // yes this really needs to be set this way
587 $comment = "removing for test";
588 $restrictDeletedVersions = false;
589 $status = FileDeleteForm::doDelete( $title, $file, $noOldArchive, $comment, $restrictDeletedVersions );
590 if ( !$status->isGood() ) {
591 return false;
592 }
593 $article = new Article( $title );
594 $article->doDeleteArticle( "removing for test" );
595
596 // see if it now doesn't exist; reload
597 $title = Title::newFromText( $fileName, NS_FILE );
598 }
599 return ! ( $title && $title instanceof Title && $title->exists() );
600 }
601
602 /**
603 * Helper function -- remove files and associated articles with a particular filename
604 * @param $fileName String: filename to be removed
605 */
606 public function deleteFileByFileName( $fileName ) {
607 return $this->deleteFileByTitle( Title::newFromText( $fileName, NS_FILE ) );
608 }
609
610
611 /**
612 * Helper function -- given a file on the filesystem, find matching content in the db (and associated articles) and remove them.
613 * @param $filePath String: path to file on the filesystem
614 */
615 public function deleteFileByContent( $filePath ) {
616 $hash = File::sha1Base36( $filePath );
617 $dupes = RepoGroup::singleton()->findBySha1( $hash );
618 $success = true;
619 foreach ( $dupes as $dupe ) {
620 $success &= $this->deleteFileByTitle( $dupe->getTitle() );
621 }
622 return $success;
623 }
624
625 /**
626 * Fake an upload by dumping the file into temp space, and adding info to $_FILES.
627 * (This is what PHP would normally do).
628 * @param $fieldName String: name this would have in the upload form
629 * @param $fileName String: name to title this
630 * @param $type String: mime type
631 * @param $filePath String: path where to find file contents
632 */
633 function fakeUploadFile( $fieldName, $fileName, $type, $filePath ) {
634 $tmpName = tempnam( wfTempDir(), "" );
635 if ( !file_exists( $filePath ) ) {
636 throw new Exception( "$filePath doesn't exist!" );
637 };
638
639 if ( !copy( $filePath, $tmpName ) ) {
640 throw new Exception( "couldn't copy $filePath to $tmpName" );
641 }
642
643 clearstatcache();
644 $size = filesize( $tmpName );
645 if ( $size === false ) {
646 throw new Exception( "couldn't stat $tmpName" );
647 }
648
649 $_FILES[ $fieldName ] = array(
650 'name' => $fileName,
651 'type' => $type,
652 'tmp_name' => $tmpName,
653 'size' => $size,
654 'error' => null
655 );
656
657 return true;
658
659 }
660
661 /**
662 * Remove traces of previous fake uploads
663 */
664 function clearFakeUploads() {
665 $_FILES = array();
666 }
667
668
669 }
670