3 use MediaWiki\Block\DatabaseBlock
;
6 * Tests for MediaWiki api.php?action=edit.
8 * @author Daniel Kinzler
16 class ApiEditPageTest
extends ApiTestCase
{
18 protected function setUp() {
21 $this->setMwGlobals( [
22 'wgExtraNamespaces' => [
24 12313 => 'Dummy_talk',
25 12314 => 'DummyNonText',
26 12315 => 'DummyNonText_talk',
28 'wgNamespaceContentModels' => [
30 12314 => 'testing-nontext',
33 $this->mergeMwGlobalArrayValue( 'wgContentHandlers', [
34 'testing' => 'DummyContentHandlerForTesting',
35 'testing-nontext' => 'DummyNonTextContentHandler',
36 'testing-serialize-error' => 'DummySerializeErrorContentHandler',
38 $this->tablesUsed
= array_merge(
40 [ 'change_tag', 'change_tag_def', 'logging' ]
42 $this->resetServices();
45 public function testEdit() {
46 $name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
48 // -- test new page --------------------------------------------
49 $apiResult = $this->doApiRequestWithToken( [
52 'text' => 'some text',
54 $apiResult = $apiResult[0];
56 // Validate API result data
57 $this->assertArrayHasKey( 'edit', $apiResult );
58 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
59 $this->assertSame( 'Success', $apiResult['edit']['result'] );
61 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
62 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
64 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
66 // -- test existing page, no change ----------------------------
67 $data = $this->doApiRequestWithToken( [
70 'text' => 'some text',
73 $this->assertSame( 'Success', $data[0]['edit']['result'] );
75 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
76 $this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
78 // -- test existing page, with change --------------------------
79 $data = $this->doApiRequestWithToken( [
82 'text' => 'different text'
85 $this->assertSame( 'Success', $data[0]['edit']['result'] );
87 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
88 $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
90 $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
91 $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
92 $this->assertNotEquals(
93 $data[0]['edit']['newrevid'],
94 $data[0]['edit']['oldrevid'],
95 "revision id should change after edit"
102 public static function provideEditAppend() {
105 'foo', 'append', 'bar', "foobar"
108 'foo', 'prepend', 'bar', "barfoo"
110 [ # 2: append to empty page
111 '', 'append', 'foo', "foo"
113 [ # 3: prepend to empty page
114 '', 'prepend', 'foo', "foo"
116 [ # 4: append to non-existing page
117 null, 'append', 'foo', "foo"
119 [ # 5: prepend to non-existing page
120 null, 'prepend', 'foo', "foo"
126 * @dataProvider provideEditAppend
128 public function testEditAppend( $text, $op, $append, $expected ) {
132 // assume NS_HELP defaults to wikitext
133 $name = "Help:ApiEditPageTest_testEditAppend_$count";
135 // -- create page (or not) -----------------------------------------
136 if ( $text !== null ) {
137 list( $re ) = $this->doApiRequestWithToken( [
140 'text' => $text, ] );
142 $this->assertSame( 'Success', $re['edit']['result'] ); // sanity
145 // -- try append/prepend --------------------------------------------
146 list( $re ) = $this->doApiRequestWithToken( [
149 $op . 'text' => $append, ] );
151 $this->assertSame( 'Success', $re['edit']['result'] );
153 // -- validate -----------------------------------------------------
154 $page = new WikiPage( Title
::newFromText( $name ) );
155 $content = $page->getContent();
156 $this->assertNotNull( $content, 'Page should have been created' );
158 $text = $content->getText();
160 $this->assertSame( $expected, $text );
164 * Test editing of sections
166 public function testEditSection() {
167 $name = 'Help:ApiEditPageTest_testEditSection';
168 $page = WikiPage
::factory( Title
::newFromText( $name ) );
169 $text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
170 // Preload the page with some text
171 $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ), 'summary' );
173 list( $re ) = $this->doApiRequestWithToken( [
177 'text' => "==section 1==\nnew content 1",
179 $this->assertSame( 'Success', $re['edit']['result'] );
180 $newtext = WikiPage
::factory( Title
::newFromText( $name ) )
181 ->getContent( Revision
::RAW
)
183 $this->assertSame( "==section 1==\nnew content 1\n\n==section 2==\ncontent2", $newtext );
185 // Test that we raise a 'nosuchsection' error
187 $this->doApiRequestWithToken( [
193 $this->fail( "Should have raised an ApiUsageException" );
194 } catch ( ApiUsageException
$e ) {
195 $this->assertTrue( self
::apiExceptionHasCode( $e, 'nosuchsection' ) );
200 * Test action=edit§ion=new
201 * Run it twice so we test adding a new section on a
202 * page that doesn't exist (T54830) and one that
205 public function testEditNewSection() {
206 $name = 'Help:ApiEditPageTest_testEditNewSection';
208 // Test on a page that does not already exist
209 $this->assertFalse( Title
::newFromText( $name )->exists() );
210 list( $re ) = $this->doApiRequestWithToken( [
215 'summary' => 'header',
218 $this->assertSame( 'Success', $re['edit']['result'] );
219 // Check the page text is correct
220 $text = WikiPage
::factory( Title
::newFromText( $name ) )
221 ->getContent( Revision
::RAW
)
223 $this->assertSame( "== header ==\n\ntest", $text );
225 // Now on one that does
226 $this->assertTrue( Title
::newFromText( $name )->exists() );
227 list( $re2 ) = $this->doApiRequestWithToken( [
232 'summary' => 'header',
235 $this->assertSame( 'Success', $re2['edit']['result'] );
236 $text = WikiPage
::factory( Title
::newFromText( $name ) )
237 ->getContent( Revision
::RAW
)
239 $this->assertSame( "== header ==\n\ntest\n\n== header ==\n\ntest", $text );
243 * Ensure we can edit through a redirect, if adding a section
245 public function testEdit_redirect() {
249 // assume NS_HELP defaults to wikitext
250 $name = "Help:ApiEditPageTest_testEdit_redirect_$count";
251 $title = Title
::newFromText( $name );
252 $page = WikiPage
::factory( $title );
254 $rname = "Help:ApiEditPageTest_testEdit_redirect_r$count";
255 $rtitle = Title
::newFromText( $rname );
256 $rpage = WikiPage
::factory( $rtitle );
258 // base edit for content
259 $page->doEditContent( new WikitextContent( "Foo" ),
260 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
261 $this->forceRevisionDate( $page, '20120101000000' );
262 $baseTime = $page->getRevision()->getTimestamp();
264 // base edit for redirect
265 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
266 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
267 $this->forceRevisionDate( $rpage, '20120101000000' );
269 // conflicting edit to redirect
270 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
271 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
272 $this->forceRevisionDate( $rpage, '20120101020202' );
274 // try to save edit, following the redirect
275 list( $re, , ) = $this->doApiRequestWithToken( [
278 'text' => 'nix bar!',
279 'basetimestamp' => $baseTime,
284 $this->assertSame( 'Success', $re['edit']['result'],
285 "no problems expected when following redirect" );
289 * Ensure we cannot edit through a redirect, if attempting to overwrite content
291 public function testEdit_redirectText() {
295 // assume NS_HELP defaults to wikitext
296 $name = "Help:ApiEditPageTest_testEdit_redirectText_$count";
297 $title = Title
::newFromText( $name );
298 $page = WikiPage
::factory( $title );
300 $rname = "Help:ApiEditPageTest_testEdit_redirectText_r$count";
301 $rtitle = Title
::newFromText( $rname );
302 $rpage = WikiPage
::factory( $rtitle );
304 // base edit for content
305 $page->doEditContent( new WikitextContent( "Foo" ),
306 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
307 $this->forceRevisionDate( $page, '20120101000000' );
308 $baseTime = $page->getRevision()->getTimestamp();
310 // base edit for redirect
311 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
312 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
313 $this->forceRevisionDate( $rpage, '20120101000000' );
315 // conflicting edit to redirect
316 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
317 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
318 $this->forceRevisionDate( $rpage, '20120101020202' );
320 // try to save edit, following the redirect but without creating a section
322 $this->doApiRequestWithToken( [
325 'text' => 'nix bar!',
326 'basetimestamp' => $baseTime,
330 $this->fail( 'redirect-appendonly error expected' );
331 } catch ( ApiUsageException
$ex ) {
332 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'redirect-appendonly' ) );
336 public function testEditConflict() {
340 // assume NS_HELP defaults to wikitext
341 $name = "Help:ApiEditPageTest_testEditConflict_$count";
342 $title = Title
::newFromText( $name );
344 $page = WikiPage
::factory( $title );
347 $page->doEditContent( new WikitextContent( "Foo" ),
348 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
349 $this->forceRevisionDate( $page, '20120101000000' );
350 $baseTime = $page->getRevision()->getTimestamp();
353 $page->doEditContent( new WikitextContent( "Foo bar" ),
354 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
355 $this->forceRevisionDate( $page, '20120101020202' );
357 // try to save edit, expect conflict
359 $this->doApiRequestWithToken( [
362 'text' => 'nix bar!',
363 'basetimestamp' => $baseTime,
366 $this->fail( 'edit conflict expected' );
367 } catch ( ApiUsageException
$ex ) {
368 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'editconflict' ) );
373 * Ensure that editing using section=new will prevent simple conflicts
375 public function testEditConflict_newSection() {
379 // assume NS_HELP defaults to wikitext
380 $name = "Help:ApiEditPageTest_testEditConflict_newSection_$count";
381 $title = Title
::newFromText( $name );
383 $page = WikiPage
::factory( $title );
386 $page->doEditContent( new WikitextContent( "Foo" ),
387 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
388 $this->forceRevisionDate( $page, '20120101000000' );
389 $baseTime = $page->getRevision()->getTimestamp();
392 $page->doEditContent( new WikitextContent( "Foo bar" ),
393 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
394 $this->forceRevisionDate( $page, '20120101020202' );
396 // try to save edit, expect no conflict
397 list( $re, , ) = $this->doApiRequestWithToken( [
400 'text' => 'nix bar!',
401 'basetimestamp' => $baseTime,
405 $this->assertSame( 'Success', $re['edit']['result'],
406 "no edit conflict expected here" );
409 public function testEditConflict_T43990() {
414 * T43990: if the target page has a newer revision than the redirect, then editing the
415 * redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
416 * caused an edit conflict to be detected.
419 // assume NS_HELP defaults to wikitext
420 $name = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_$count";
421 $title = Title
::newFromText( $name );
422 $page = WikiPage
::factory( $title );
424 $rname = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_r$count";
425 $rtitle = Title
::newFromText( $rname );
426 $rpage = WikiPage
::factory( $rtitle );
428 // base edit for content
429 $page->doEditContent( new WikitextContent( "Foo" ),
430 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
431 $this->forceRevisionDate( $page, '20120101000000' );
433 // base edit for redirect
434 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
435 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
436 $this->forceRevisionDate( $rpage, '20120101000000' );
438 // new edit to content
439 $page->doEditContent( new WikitextContent( "Foo bar" ),
440 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
441 $this->forceRevisionDate( $rpage, '20120101020202' );
443 // try to save edit; should work, following the redirect.
444 list( $re, , ) = $this->doApiRequestWithToken( [
447 'text' => 'nix bar!',
452 $this->assertSame( 'Success', $re['edit']['result'],
453 "no edit conflict expected here" );
457 * @param WikiPage $page
458 * @param string|int $timestamp
460 protected function forceRevisionDate( WikiPage
$page, $timestamp ) {
461 $dbw = wfGetDB( DB_MASTER
);
463 $dbw->update( 'revision',
464 [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ],
465 [ 'rev_id' => $page->getLatest() ] );
470 public function testCheckDirectApiEditingDisallowed_forNonTextContent() {
471 $this->setExpectedException(
472 ApiUsageException
::class,
473 'Direct editing via API is not supported for content model ' .
474 'testing used by Dummy:ApiEditPageTest_nonTextPageEdit'
477 $this->doApiRequestWithToken( [
479 'title' => 'Dummy:ApiEditPageTest_nonTextPageEdit',
480 'text' => '{"animals":["kittens!"]}'
484 public function testSupportsDirectApiEditing_withContentHandlerOverride() {
485 $name = 'DummyNonText:ApiEditPageTest_testNonTextEdit';
486 $data = serialize( 'some bla bla text' );
488 $result = $this->doApiRequestWithToken( [
494 $apiResult = $result[0];
496 // Validate API result data
497 $this->assertArrayHasKey( 'edit', $apiResult );
498 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
499 $this->assertSame( 'Success', $apiResult['edit']['result'] );
501 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
502 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
504 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
506 // validate resulting revision
507 $page = WikiPage
::factory( Title
::newFromText( $name ) );
508 $this->assertSame( "testing-nontext", $page->getContentModel() );
509 $this->assertSame( $data, $page->getContent()->serialize() );
513 * This test verifies that after changing the content model
514 * of a page, undoing that edit via the API will also
515 * undo the content model change.
517 public function testUndoAfterContentModelChange() {
518 $name = 'Help:' . __FUNCTION__
;
519 $uploader = self
::$users['uploader']->getUser();
520 $sysop = self
::$users['sysop']->getUser();
522 $apiResult = $this->doApiRequestWithToken( [
525 'text' => 'some text',
526 ], null, $sysop )[0];
529 $this->assertArrayHasKey( 'edit', $apiResult );
530 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
531 $this->assertSame( 'Success', $apiResult['edit']['result'] );
532 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
533 // Content model is wikitext
534 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
536 // Convert the page to JSON
537 $apiResult = $this->doApiRequestWithToken( [
541 'contentmodel' => 'json',
542 ], null, $uploader )[0];
545 $this->assertArrayHasKey( 'edit', $apiResult );
546 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
547 $this->assertSame( 'Success', $apiResult['edit']['result'] );
548 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
549 $this->assertSame( 'json', $apiResult['edit']['contentmodel'] );
551 $apiResult = $this->doApiRequestWithToken( [
554 'undo' => $apiResult['edit']['newrevid']
555 ], null, $sysop )[0];
558 $this->assertArrayHasKey( 'edit', $apiResult );
559 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
560 $this->assertSame( 'Success', $apiResult['edit']['result'] );
561 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
562 // Check that the contentmodel is back to wikitext now.
563 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
566 // The tests below are mostly not commented because they do exactly what
567 // you'd expect from the name.
569 public function testCorrectContentFormat() {
570 $name = 'Help:' . ucfirst( __FUNCTION__
);
572 $this->doApiRequestWithToken( [
575 'text' => 'some text',
576 'contentmodel' => 'wikitext',
577 'contentformat' => 'text/x-wiki',
580 $this->assertTrue( Title
::newFromText( $name )->exists() );
583 public function testUnsupportedContentFormat() {
584 $name = 'Help:' . ucfirst( __FUNCTION__
);
586 $this->setExpectedException( ApiUsageException
::class,
587 'Unrecognized value for parameter "contentformat": nonexistent format.' );
590 $this->doApiRequestWithToken( [
593 'text' => 'some text',
594 'contentformat' => 'nonexistent format',
597 $this->assertFalse( Title
::newFromText( $name )->exists() );
601 public function testMismatchedContentFormat() {
602 $name = 'Help:' . ucfirst( __FUNCTION__
);
604 $this->setExpectedException( ApiUsageException
::class,
605 'The requested format text/plain is not supported for content ' .
606 "model wikitext used by $name." );
609 $this->doApiRequestWithToken( [
612 'text' => 'some text',
613 'contentmodel' => 'wikitext',
614 'contentformat' => 'text/plain',
617 $this->assertFalse( Title
::newFromText( $name )->exists() );
621 public function testUndoToInvalidRev() {
622 $name = 'Help:' . ucfirst( __FUNCTION__
);
624 $revId = $this->editPage( $name, 'Some text' )->value
['revision']
628 $this->setExpectedException( ApiUsageException
::class,
629 "There is no revision with ID $revId." );
631 $this->doApiRequestWithToken( [
639 * Tests what happens if the undo parameter is a valid revision, but
640 * the undoafter parameter doesn't refer to a revision that exists in the
643 public function testUndoAfterToInvalidRev() {
644 // We can't just pick a large number for undoafter (as in
645 // testUndoToInvalidRev above), because then MediaWiki will helpfully
646 // assume we switched around undo and undoafter and we'll test the code
647 // path for undo being invalid, not undoafter. So instead we delete
648 // the revision from the database. In real life this case could come
649 // up if a revision number was skipped, e.g., if two transactions try
650 // to insert new revision rows at once and the first one to succeed
652 $name = 'Help:' . ucfirst( __FUNCTION__
);
653 $titleObj = Title
::newFromText( $name );
655 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
656 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
657 $revId3 = $this->editPage( $name, '3' )->value
['revision']->getId();
659 // Make the middle revision disappear
660 $dbw = wfGetDB( DB_MASTER
);
661 $dbw->delete( 'revision', [ 'rev_id' => $revId2 ], __METHOD__
);
662 $dbw->update( 'revision', [ 'rev_parent_id' => $revId1 ],
663 [ 'rev_id' => $revId3 ], __METHOD__
);
665 $this->setExpectedException( ApiUsageException
::class,
666 "There is no revision with ID $revId2." );
668 $this->doApiRequestWithToken( [
672 'undoafter' => $revId2,
677 * Tests what happens if the undo parameter is a valid revision, but
678 * undoafter is hidden (rev_deleted).
680 public function testUndoAfterToHiddenRev() {
681 $name = 'Help:' . ucfirst( __FUNCTION__
);
682 $titleObj = Title
::newFromText( $name );
684 $this->editPage( $name, '0' );
686 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
688 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
690 // Hide the middle revision
691 $list = RevisionDeleter
::createList( 'revision',
692 RequestContext
::getMain(), $titleObj, [ $revId1 ] );
693 $list->setVisibility( [
694 'value' => [ Revision
::DELETED_TEXT
=> 1 ],
695 'comment' => 'Bye-bye',
698 $this->setExpectedException( ApiUsageException
::class,
699 "There is no revision with ID $revId1." );
701 $this->doApiRequestWithToken( [
705 'undoafter' => $revId1,
710 * Test undo when a revision with a higher id has an earlier timestamp.
711 * This can happen if importing an old revision.
713 public function testUndoWithSwappedRevisions() {
714 $name = 'Help:' . ucfirst( __FUNCTION__
);
715 $titleObj = Title
::newFromText( $name );
717 $this->editPage( $name, '0' );
719 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
721 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
723 // Now monkey with the timestamp
724 $dbw = wfGetDB( DB_MASTER
);
727 [ 'rev_timestamp' => $dbw->timestamp( time() - 86400 ) ],
728 [ 'rev_id' => $revId1 ],
732 $this->doApiRequestWithToken( [
736 'undoafter' => $revId1,
739 $text = ( new WikiPage( $titleObj ) )->getContent()->getText();
741 // This is wrong! It should be 1. But let's test for our incorrect
742 // behavior for now, so if someone fixes it they'll fix the test as
743 // well to expect 1. If we disabled the test, it might stay disabled
744 // even once the bug is fixed, which would be a shame.
745 $this->assertSame( '2', $text );
748 public function testUndoWithConflicts() {
749 $name = 'Help:' . ucfirst( __FUNCTION__
);
751 $this->setExpectedException( ApiUsageException
::class,
752 'The edit could not be undone due to conflicting intermediate edits.' );
754 $this->editPage( $name, '1' );
756 $revId = $this->editPage( $name, '2' )->value
['revision']->getId();
758 $this->editPage( $name, '3' );
760 $this->doApiRequestWithToken( [
766 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
768 $this->assertSame( '3', $text );
772 * undoafter is supposed to be less than undo. If not, we reverse their
773 * meaning, so that the two are effectively interchangeable.
775 public function testReversedUndoAfter() {
776 $name = 'Help:' . ucfirst( __FUNCTION__
);
778 $this->editPage( $name, '0' );
779 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
780 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
782 $this->doApiRequestWithToken( [
786 'undoafter' => $revId2,
789 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
791 $this->assertSame( '1', $text );
794 public function testUndoToRevFromDifferentPage() {
795 $name = 'Help:' . ucfirst( __FUNCTION__
);
797 $this->editPage( "$name-1", 'Some text' );
798 $revId = $this->editPage( "$name-1", 'Some more text' )
799 ->value
['revision']->getId();
801 $this->editPage( "$name-2", 'Some text' );
803 $this->setExpectedException( ApiUsageException
::class,
804 "r$revId is not a revision of $name-2." );
806 $this->doApiRequestWithToken( [
808 'title' => "$name-2",
813 public function testUndoAfterToRevFromDifferentPage() {
814 $name = 'Help:' . ucfirst( __FUNCTION__
);
816 $revId1 = $this->editPage( "$name-1", 'Some text' )
817 ->value
['revision']->getId();
819 $revId2 = $this->editPage( "$name-2", 'Some text' )
820 ->value
['revision']->getId();
822 $this->setExpectedException( ApiUsageException
::class,
823 "r$revId1 is not a revision of $name-2." );
825 $this->doApiRequestWithToken( [
827 'title' => "$name-2",
829 'undoafter' => $revId1,
833 public function testMd5Text() {
834 $name = 'Help:' . ucfirst( __FUNCTION__
);
836 $this->assertFalse( Title
::newFromText( $name )->exists() );
838 $this->doApiRequestWithToken( [
841 'text' => 'Some text',
842 'md5' => md5( 'Some text' ),
845 $this->assertTrue( Title
::newFromText( $name )->exists() );
848 public function testMd5PrependText() {
849 $name = 'Help:' . ucfirst( __FUNCTION__
);
851 $this->editPage( $name, 'Some text' );
853 $this->doApiRequestWithToken( [
856 'prependtext' => 'Alert: ',
857 'md5' => md5( 'Alert: ' ),
860 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
861 ->getContent()->getText();
862 $this->assertSame( 'Alert: Some text', $text );
865 public function testMd5AppendText() {
866 $name = 'Help:' . ucfirst( __FUNCTION__
);
868 $this->editPage( $name, 'Some text' );
870 $this->doApiRequestWithToken( [
873 'appendtext' => ' is nice',
874 'md5' => md5( ' is nice' ),
877 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
878 ->getContent()->getText();
879 $this->assertSame( 'Some text is nice', $text );
882 public function testMd5PrependAndAppendText() {
883 $name = 'Help:' . ucfirst( __FUNCTION__
);
885 $this->editPage( $name, 'Some text' );
887 $this->doApiRequestWithToken( [
890 'prependtext' => 'Alert: ',
891 'appendtext' => ' is nice',
892 'md5' => md5( 'Alert: is nice' ),
895 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
896 ->getContent()->getText();
897 $this->assertSame( 'Alert: Some text is nice', $text );
900 public function testIncorrectMd5Text() {
901 $name = 'Help:' . ucfirst( __FUNCTION__
);
903 $this->setExpectedException( ApiUsageException
::class,
904 'The supplied MD5 hash was incorrect.' );
906 $this->doApiRequestWithToken( [
909 'text' => 'Some text',
914 public function testIncorrectMd5PrependText() {
915 $name = 'Help:' . ucfirst( __FUNCTION__
);
917 $this->setExpectedException( ApiUsageException
::class,
918 'The supplied MD5 hash was incorrect.' );
920 $this->doApiRequestWithToken( [
923 'prependtext' => 'Some ',
924 'appendtext' => 'text',
925 'md5' => md5( 'Some ' ),
929 public function testIncorrectMd5AppendText() {
930 $name = 'Help:' . ucfirst( __FUNCTION__
);
932 $this->setExpectedException( ApiUsageException
::class,
933 'The supplied MD5 hash was incorrect.' );
935 $this->doApiRequestWithToken( [
938 'prependtext' => 'Some ',
939 'appendtext' => 'text',
940 'md5' => md5( 'text' ),
944 public function testCreateOnly() {
945 $name = 'Help:' . ucfirst( __FUNCTION__
);
947 $this->setExpectedException( ApiUsageException
::class,
948 'The article you tried to create has been created already.' );
950 $this->editPage( $name, 'Some text' );
951 $this->assertTrue( Title
::newFromText( $name )->exists() );
954 $this->doApiRequestWithToken( [
957 'text' => 'Some more text',
961 // Validate that content was not changed
962 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
963 ->getContent()->getText();
965 $this->assertSame( 'Some text', $text );
969 public function testNoCreate() {
970 $name = 'Help:' . ucfirst( __FUNCTION__
);
972 $this->setExpectedException( ApiUsageException
::class,
973 "The page you specified doesn't exist." );
975 $this->assertFalse( Title
::newFromText( $name )->exists() );
978 $this->doApiRequestWithToken( [
981 'text' => 'Some text',
985 $this->assertFalse( Title
::newFromText( $name )->exists() );
990 * Appending/prepending is currently only supported for TextContent. We
991 * test this right now, and when support is added this test should be
992 * replaced by tests that the support is correct.
994 public function testAppendWithNonTextContentHandler() {
995 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
997 $this->setExpectedException( ApiUsageException
::class,
998 "Can't append to pages using content model testing-nontext." );
1000 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1001 function ( Title
$title, &$model ) use ( $name ) {
1002 if ( $title->getPrefixedText() === $name ) {
1003 $model = 'testing-nontext';
1009 $this->doApiRequestWithToken( [
1012 'appendtext' => 'Some text',
1016 public function testAppendInMediaWikiNamespace() {
1017 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1019 $this->assertFalse( Title
::newFromText( $name )->exists() );
1021 $this->doApiRequestWithToken( [
1024 'appendtext' => 'Some text',
1027 $this->assertTrue( Title
::newFromText( $name )->exists() );
1030 public function testAppendInMediaWikiNamespaceWithSerializationError() {
1031 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1033 $this->setExpectedException( ApiUsageException
::class,
1034 'Content serialization failed: Could not unserialize content' );
1036 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1037 function ( Title
$title, &$model ) use ( $name ) {
1038 if ( $title->getPrefixedText() === $name ) {
1039 $model = 'testing-serialize-error';
1045 $this->doApiRequestWithToken( [
1048 'appendtext' => 'Some text',
1052 public function testAppendNewSection() {
1053 $name = 'Help:' . ucfirst( __FUNCTION__
);
1055 $this->editPage( $name, 'Initial content' );
1057 $this->doApiRequestWithToken( [
1060 'appendtext' => '== New section ==',
1064 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1065 ->getContent()->getText();
1067 $this->assertSame( "Initial content\n\n== New section ==", $text );
1070 public function testAppendNewSectionWithInvalidContentModel() {
1071 $name = 'Help:' . ucfirst( __FUNCTION__
);
1073 $this->setExpectedException( ApiUsageException
::class,
1074 'Sections are not supported for content model text.' );
1076 $this->editPage( $name, 'Initial content' );
1078 $this->doApiRequestWithToken( [
1081 'appendtext' => '== New section ==',
1083 'contentmodel' => 'text',
1087 public function testAppendNewSectionWithTitle() {
1088 $name = 'Help:' . ucfirst( __FUNCTION__
);
1090 $this->editPage( $name, 'Initial content' );
1092 $this->doApiRequestWithToken( [
1095 'sectiontitle' => 'My section',
1096 'appendtext' => 'More content',
1100 $page = new WikiPage( Title
::newFromText( $name ) );
1102 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1103 $page->getContent()->getText() );
1104 $this->assertSame( '/* My section */ new section',
1105 $page->getRevision()->getComment() );
1108 public function testAppendNewSectionWithSummary() {
1109 $name = 'Help:' . ucfirst( __FUNCTION__
);
1111 $this->editPage( $name, 'Initial content' );
1113 $this->doApiRequestWithToken( [
1116 'appendtext' => 'More content',
1118 'summary' => 'Add new section',
1121 $page = new WikiPage( Title
::newFromText( $name ) );
1123 $this->assertSame( "Initial content\n\n== Add new section ==\n\nMore content",
1124 $page->getContent()->getText() );
1125 // EditPage actually assumes the summary is the section name here
1126 $this->assertSame( '/* Add new section */ new section',
1127 $page->getRevision()->getComment() );
1130 public function testAppendNewSectionWithTitleAndSummary() {
1131 $name = 'Help:' . ucfirst( __FUNCTION__
);
1133 $this->editPage( $name, 'Initial content' );
1135 $this->doApiRequestWithToken( [
1138 'sectiontitle' => 'My section',
1139 'appendtext' => 'More content',
1141 'summary' => 'Add new section',
1144 $page = new WikiPage( Title
::newFromText( $name ) );
1146 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1147 $page->getContent()->getText() );
1148 $this->assertSame( 'Add new section',
1149 $page->getRevision()->getComment() );
1152 public function testAppendToSection() {
1153 $name = 'Help:' . ucfirst( __FUNCTION__
);
1155 $this->editPage( $name, "== Section 1 ==\n\nContent\n\n" .
1156 "== Section 2 ==\n\nFascinating!" );
1158 $this->doApiRequestWithToken( [
1161 'appendtext' => ' and more content',
1165 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1166 ->getContent()->getText();
1168 $this->assertSame( "== Section 1 ==\n\nContent and more content\n\n" .
1169 "== Section 2 ==\n\nFascinating!", $text );
1172 public function testAppendToFirstSection() {
1173 $name = 'Help:' . ucfirst( __FUNCTION__
);
1175 $this->editPage( $name, "Content\n\n== Section 1 ==\n\nFascinating!" );
1177 $this->doApiRequestWithToken( [
1180 'appendtext' => ' and more content',
1184 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1185 ->getContent()->getText();
1187 $this->assertSame( "Content and more content\n\n== Section 1 ==\n\n" .
1188 "Fascinating!", $text );
1191 public function testAppendToNonexistentSection() {
1192 $name = 'Help:' . ucfirst( __FUNCTION__
);
1194 $this->setExpectedException( ApiUsageException
::class, 'There is no section 1.' );
1196 $this->editPage( $name, 'Content' );
1199 $this->doApiRequestWithToken( [
1202 'appendtext' => ' and more content',
1206 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1207 ->getContent()->getText();
1209 $this->assertSame( 'Content', $text );
1213 public function testEditMalformedSection() {
1214 $name = 'Help:' . ucfirst( __FUNCTION__
);
1216 $this->setExpectedException( ApiUsageException
::class,
1217 'The "section" parameter must be a valid section ID or "new".' );
1218 $this->editPage( $name, 'Content' );
1221 $this->doApiRequestWithToken( [
1224 'text' => 'Different content',
1225 'section' => 'It is unlikely that this is valid',
1228 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1229 ->getContent()->getText();
1231 $this->assertSame( 'Content', $text );
1235 public function testEditWithStartTimestamp() {
1236 $name = 'Help:' . ucfirst( __FUNCTION__
);
1237 $this->setExpectedException( ApiUsageException
::class,
1238 'The page has been deleted since you fetched its timestamp.' );
1240 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1242 $this->editPage( $name, 'Some text' );
1244 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1245 $pageObj->doDeleteArticle( 'Bye-bye' );
1247 $this->assertFalse( $pageObj->exists() );
1250 $this->doApiRequestWithToken( [
1253 'text' => 'Different text',
1254 'starttimestamp' => $startTime,
1257 $this->assertFalse( $pageObj->exists() );
1261 public function testEditMinor() {
1262 $name = 'Help:' . ucfirst( __FUNCTION__
);
1264 $this->editPage( $name, 'Some text' );
1266 $this->doApiRequestWithToken( [
1269 'text' => 'Different text',
1273 $revisionStore = \MediaWiki\MediaWikiServices
::getInstance()->getRevisionStore();
1274 $revision = $revisionStore->getRevisionByTitle( Title
::newFromText( $name ) );
1275 $this->assertTrue( $revision->isMinor() );
1278 public function testEditRecreate() {
1279 $name = 'Help:' . ucfirst( __FUNCTION__
);
1281 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1283 $this->editPage( $name, 'Some text' );
1285 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1286 $pageObj->doDeleteArticle( 'Bye-bye' );
1288 $this->assertFalse( $pageObj->exists() );
1290 $this->doApiRequestWithToken( [
1293 'text' => 'Different text',
1294 'starttimestamp' => $startTime,
1298 $this->assertTrue( Title
::newFromText( $name )->exists() );
1301 public function testEditWatch() {
1302 $name = 'Help:' . ucfirst( __FUNCTION__
);
1303 $user = self
::$users['sysop']->getUser();
1305 $this->doApiRequestWithToken( [
1308 'text' => 'Some text',
1312 $this->assertTrue( Title
::newFromText( $name )->exists() );
1313 $this->assertTrue( $user->isWatched( Title
::newFromText( $name ) ) );
1316 public function testEditUnwatch() {
1317 $name = 'Help:' . ucfirst( __FUNCTION__
);
1318 $user = self
::$users['sysop']->getUser();
1319 $titleObj = Title
::newFromText( $name );
1321 $user->addWatch( $titleObj );
1323 $this->assertFalse( $titleObj->exists() );
1324 $this->assertTrue( $user->isWatched( $titleObj ) );
1326 $this->doApiRequestWithToken( [
1329 'text' => 'Some text',
1333 $this->assertTrue( $titleObj->exists() );
1334 $this->assertFalse( $user->isWatched( $titleObj ) );
1337 public function testEditWithTag() {
1338 $name = 'Help:' . ucfirst( __FUNCTION__
);
1340 ChangeTags
::defineTag( 'custom tag' );
1342 $revId = $this->doApiRequestWithToken( [
1345 'text' => 'Some text',
1346 'tags' => 'custom tag',
1347 ] )[0]['edit']['newrevid'];
1349 $dbw = wfGetDB( DB_MASTER
);
1350 $this->assertSame( 'custom tag', $dbw->selectField(
1351 [ 'change_tag', 'change_tag_def' ],
1353 [ 'ct_rev_id' => $revId ],
1355 [ 'change_tag_def' => [ 'JOIN', 'ctd_id = ct_tag_id' ] ]
1360 public function testEditWithoutTagPermission() {
1361 $name = 'Help:' . ucfirst( __FUNCTION__
);
1363 $this->setExpectedException( ApiUsageException
::class,
1364 'You do not have permission to apply change tags along with your changes.' );
1366 $this->assertFalse( Title
::newFromText( $name )->exists() );
1368 ChangeTags
::defineTag( 'custom tag' );
1369 $this->setMwGlobals( 'wgRevokePermissions',
1370 [ 'user' => [ 'applychangetags' => true ] ] );
1371 // Supply services with updated globals
1372 $this->resetServices();
1375 $this->doApiRequestWithToken( [
1378 'text' => 'Some text',
1379 'tags' => 'custom tag',
1382 $this->assertFalse( Title
::newFromText( $name )->exists() );
1386 public function testEditAbortedByEditPageHookWithResult() {
1387 $name = 'Help:' . ucfirst( __FUNCTION__
);
1389 $this->setTemporaryHook( 'EditFilterMergedContent',
1390 function ( $unused1, $unused2, Status
$status ) {
1391 $status->apiHookResult
= [ 'msg' => 'A message for you!' ];
1395 $res = $this->doApiRequestWithToken( [
1398 'text' => 'Some text',
1401 $this->assertFalse( Title
::newFromText( $name )->exists() );
1402 $this->assertSame( [ 'edit' => [ 'msg' => 'A message for you!',
1403 'result' => 'Failure' ] ], $res[0] );
1406 public function testEditAbortedByEditPageHookWithNoResult() {
1407 $name = 'Help:' . ucfirst( __FUNCTION__
);
1409 $this->setExpectedException( ApiUsageException
::class,
1410 'The modification you tried to make was aborted by an extension.' );
1412 $this->setTemporaryHook( 'EditFilterMergedContent',
1419 $this->doApiRequestWithToken( [
1422 'text' => 'Some text',
1425 $this->assertFalse( Title
::newFromText( $name )->exists() );
1429 public function testEditWhileBlocked() {
1430 $name = 'Help:' . ucfirst( __FUNCTION__
);
1432 $this->assertNull( DatabaseBlock
::newFromTarget( '127.0.0.1' ), 'Sanity check' );
1434 $block = new DatabaseBlock( [
1435 'address' => self
::$users['sysop']->getUser()->getName(),
1436 'by' => self
::$users['sysop']->getUser()->getId(),
1437 'reason' => 'Capriciousness',
1438 'timestamp' => '19370101000000',
1439 'expiry' => 'infinity',
1440 'enableAutoblock' => true,
1445 $this->doApiRequestWithToken( [
1448 'text' => 'Some text',
1450 $this->fail( 'Expected exception not thrown' );
1451 } catch ( ApiUsageException
$ex ) {
1452 $this->assertSame( 'You have been blocked from editing.', $ex->getMessage() );
1453 $this->assertNotNull( DatabaseBlock
::newFromTarget( '127.0.0.1' ), 'Autoblock spread' );
1456 self
::$users['sysop']->getUser()->clearInstanceCache();
1460 public function testEditWhileReadOnly() {
1461 $name = 'Help:' . ucfirst( __FUNCTION__
);
1463 $this->setExpectedException( ApiUsageException
::class,
1464 'The wiki is currently in read-only mode.' );
1466 $svc = \MediaWiki\MediaWikiServices
::getInstance()->getReadOnlyMode();
1467 $svc->setReason( "Read-only for testing" );
1470 $this->doApiRequestWithToken( [
1473 'text' => 'Some text',
1476 $svc->setReason( false );
1480 public function testCreateImageRedirectAnon() {
1481 $name = 'File:' . ucfirst( __FUNCTION__
);
1483 $this->setExpectedException( ApiUsageException
::class,
1484 "Anonymous users can't create image redirects." );
1486 $this->doApiRequestWithToken( [
1489 'text' => '#REDIRECT [[File:Other file.png]]',
1490 ], null, new User() );
1493 public function testCreateImageRedirectLoggedIn() {
1494 $name = 'File:' . ucfirst( __FUNCTION__
);
1496 $this->setExpectedException( ApiUsageException
::class,
1497 "You don't have permission to create image redirects." );
1499 $this->setMwGlobals( 'wgRevokePermissions',
1500 [ 'user' => [ 'upload' => true ] ] );
1501 // Supply services with updated globals
1502 $this->resetServices();
1504 $this->doApiRequestWithToken( [
1507 'text' => '#REDIRECT [[File:Other file.png]]',
1511 public function testTooBigEdit() {
1512 $name = 'Help:' . ucfirst( __FUNCTION__
);
1514 $this->setExpectedException( ApiUsageException
::class,
1515 'The content you supplied exceeds the article size limit of 1 kilobyte.' );
1517 $this->setMwGlobals( 'wgMaxArticleSize', 1 );
1518 // Supply services with updated globals
1519 $this->resetServices();
1521 $text = str_repeat( '!', 1025 );
1523 $this->doApiRequestWithToken( [
1530 public function testProhibitedAnonymousEdit() {
1531 $name = 'Help:' . ucfirst( __FUNCTION__
);
1533 $this->setExpectedException( ApiUsageException
::class,
1534 'The action you have requested is limited to users in the group: ' );
1536 $this->setMwGlobals( 'wgRevokePermissions', [ '*' => [ 'edit' => true ] ] );
1537 // Supply services with updated globals
1538 $this->resetServices();
1540 $this->doApiRequestWithToken( [
1543 'text' => 'Some text',
1544 ], null, new User() );
1547 public function testProhibitedChangeContentModel() {
1548 $name = 'Help:' . ucfirst( __FUNCTION__
);
1550 $this->setExpectedException( ApiUsageException
::class,
1551 "You don't have permission to change the content model of a page." );
1553 $this->setMwGlobals( 'wgRevokePermissions',
1554 [ 'user' => [ 'editcontentmodel' => true ] ] );
1555 // Supply services with updated globals
1556 $this->resetServices();
1558 $this->doApiRequestWithToken( [
1561 'text' => 'Some text',
1562 'contentmodel' => 'json',