4 * Tests for MediaWiki api.php?action=edit.
6 * @author Daniel Kinzler
14 class ApiEditPageTest
extends ApiTestCase
{
16 protected function setUp() {
19 $this->setMwGlobals( [
20 'wgExtraNamespaces' => [
22 12313 => 'Dummy_talk',
23 12314 => 'DummyNonText',
24 12315 => 'DummyNonText_talk',
26 'wgNamespaceContentModels' => [
28 12314 => 'testing-nontext',
31 $this->mergeMwGlobalArrayValue( 'wgContentHandlers', [
32 'testing' => 'DummyContentHandlerForTesting',
33 'testing-nontext' => 'DummyNonTextContentHandler',
34 'testing-serialize-error' => 'DummySerializeErrorContentHandler',
36 $this->tablesUsed
= array_merge(
38 [ 'change_tag', 'change_tag_def', 'logging' ]
42 public function testEdit() {
43 $name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
45 // -- test new page --------------------------------------------
46 $apiResult = $this->doApiRequestWithToken( [
49 'text' => 'some text',
51 $apiResult = $apiResult[0];
53 // Validate API result data
54 $this->assertArrayHasKey( 'edit', $apiResult );
55 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
56 $this->assertSame( 'Success', $apiResult['edit']['result'] );
58 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
59 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
61 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
63 // -- test existing page, no change ----------------------------
64 $data = $this->doApiRequestWithToken( [
67 'text' => 'some text',
70 $this->assertSame( 'Success', $data[0]['edit']['result'] );
72 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
73 $this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
75 // -- test existing page, with change --------------------------
76 $data = $this->doApiRequestWithToken( [
79 'text' => 'different text'
82 $this->assertSame( 'Success', $data[0]['edit']['result'] );
84 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
85 $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
87 $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
88 $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
89 $this->assertNotEquals(
90 $data[0]['edit']['newrevid'],
91 $data[0]['edit']['oldrevid'],
92 "revision id should change after edit"
99 public static function provideEditAppend() {
102 'foo', 'append', 'bar', "foobar"
105 'foo', 'prepend', 'bar', "barfoo"
107 [ # 2: append to empty page
108 '', 'append', 'foo', "foo"
110 [ # 3: prepend to empty page
111 '', 'prepend', 'foo', "foo"
113 [ # 4: append to non-existing page
114 null, 'append', 'foo', "foo"
116 [ # 5: prepend to non-existing page
117 null, 'prepend', 'foo', "foo"
123 * @dataProvider provideEditAppend
125 public function testEditAppend( $text, $op, $append, $expected ) {
129 // assume NS_HELP defaults to wikitext
130 $name = "Help:ApiEditPageTest_testEditAppend_$count";
132 // -- create page (or not) -----------------------------------------
133 if ( $text !== null ) {
134 list( $re ) = $this->doApiRequestWithToken( [
137 'text' => $text, ] );
139 $this->assertSame( 'Success', $re['edit']['result'] ); // sanity
142 // -- try append/prepend --------------------------------------------
143 list( $re ) = $this->doApiRequestWithToken( [
146 $op . 'text' => $append, ] );
148 $this->assertSame( 'Success', $re['edit']['result'] );
150 // -- validate -----------------------------------------------------
151 $page = new WikiPage( Title
::newFromText( $name ) );
152 $content = $page->getContent();
153 $this->assertNotNull( $content, 'Page should have been created' );
155 $text = $content->getText();
157 $this->assertSame( $expected, $text );
161 * Test editing of sections
163 public function testEditSection() {
164 $name = 'Help:ApiEditPageTest_testEditSection';
165 $page = WikiPage
::factory( Title
::newFromText( $name ) );
166 $text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
167 // Preload the page with some text
168 $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ), 'summary' );
170 list( $re ) = $this->doApiRequestWithToken( [
174 'text' => "==section 1==\nnew content 1",
176 $this->assertSame( 'Success', $re['edit']['result'] );
177 $newtext = WikiPage
::factory( Title
::newFromText( $name ) )
178 ->getContent( Revision
::RAW
)
180 $this->assertSame( "==section 1==\nnew content 1\n\n==section 2==\ncontent2", $newtext );
182 // Test that we raise a 'nosuchsection' error
184 $this->doApiRequestWithToken( [
190 $this->fail( "Should have raised an ApiUsageException" );
191 } catch ( ApiUsageException
$e ) {
192 $this->assertTrue( self
::apiExceptionHasCode( $e, 'nosuchsection' ) );
197 * Test action=edit§ion=new
198 * Run it twice so we test adding a new section on a
199 * page that doesn't exist (T54830) and one that
202 public function testEditNewSection() {
203 $name = 'Help:ApiEditPageTest_testEditNewSection';
205 // Test on a page that does not already exist
206 $this->assertFalse( Title
::newFromText( $name )->exists() );
207 list( $re ) = $this->doApiRequestWithToken( [
212 'summary' => 'header',
215 $this->assertSame( 'Success', $re['edit']['result'] );
216 // Check the page text is correct
217 $text = WikiPage
::factory( Title
::newFromText( $name ) )
218 ->getContent( Revision
::RAW
)
220 $this->assertSame( "== header ==\n\ntest", $text );
222 // Now on one that does
223 $this->assertTrue( Title
::newFromText( $name )->exists() );
224 list( $re2 ) = $this->doApiRequestWithToken( [
229 'summary' => 'header',
232 $this->assertSame( 'Success', $re2['edit']['result'] );
233 $text = WikiPage
::factory( Title
::newFromText( $name ) )
234 ->getContent( Revision
::RAW
)
236 $this->assertSame( "== header ==\n\ntest\n\n== header ==\n\ntest", $text );
240 * Ensure we can edit through a redirect, if adding a section
242 public function testEdit_redirect() {
246 // assume NS_HELP defaults to wikitext
247 $name = "Help:ApiEditPageTest_testEdit_redirect_$count";
248 $title = Title
::newFromText( $name );
249 $page = WikiPage
::factory( $title );
251 $rname = "Help:ApiEditPageTest_testEdit_redirect_r$count";
252 $rtitle = Title
::newFromText( $rname );
253 $rpage = WikiPage
::factory( $rtitle );
255 // base edit for content
256 $page->doEditContent( new WikitextContent( "Foo" ),
257 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
258 $this->forceRevisionDate( $page, '20120101000000' );
259 $baseTime = $page->getRevision()->getTimestamp();
261 // base edit for redirect
262 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
263 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
264 $this->forceRevisionDate( $rpage, '20120101000000' );
266 // conflicting edit to redirect
267 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
268 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
269 $this->forceRevisionDate( $rpage, '20120101020202' );
271 // try to save edit, following the redirect
272 list( $re, , ) = $this->doApiRequestWithToken( [
275 'text' => 'nix bar!',
276 'basetimestamp' => $baseTime,
281 $this->assertSame( 'Success', $re['edit']['result'],
282 "no problems expected when following redirect" );
286 * Ensure we cannot edit through a redirect, if attempting to overwrite content
288 public function testEdit_redirectText() {
292 // assume NS_HELP defaults to wikitext
293 $name = "Help:ApiEditPageTest_testEdit_redirectText_$count";
294 $title = Title
::newFromText( $name );
295 $page = WikiPage
::factory( $title );
297 $rname = "Help:ApiEditPageTest_testEdit_redirectText_r$count";
298 $rtitle = Title
::newFromText( $rname );
299 $rpage = WikiPage
::factory( $rtitle );
301 // base edit for content
302 $page->doEditContent( new WikitextContent( "Foo" ),
303 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
304 $this->forceRevisionDate( $page, '20120101000000' );
305 $baseTime = $page->getRevision()->getTimestamp();
307 // base edit for redirect
308 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
309 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
310 $this->forceRevisionDate( $rpage, '20120101000000' );
312 // conflicting edit to redirect
313 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
314 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
315 $this->forceRevisionDate( $rpage, '20120101020202' );
317 // try to save edit, following the redirect but without creating a section
319 $this->doApiRequestWithToken( [
322 'text' => 'nix bar!',
323 'basetimestamp' => $baseTime,
327 $this->fail( 'redirect-appendonly error expected' );
328 } catch ( ApiUsageException
$ex ) {
329 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'redirect-appendonly' ) );
333 public function testEditConflict() {
337 // assume NS_HELP defaults to wikitext
338 $name = "Help:ApiEditPageTest_testEditConflict_$count";
339 $title = Title
::newFromText( $name );
341 $page = WikiPage
::factory( $title );
344 $page->doEditContent( new WikitextContent( "Foo" ),
345 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
346 $this->forceRevisionDate( $page, '20120101000000' );
347 $baseTime = $page->getRevision()->getTimestamp();
350 $page->doEditContent( new WikitextContent( "Foo bar" ),
351 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
352 $this->forceRevisionDate( $page, '20120101020202' );
354 // try to save edit, expect conflict
356 $this->doApiRequestWithToken( [
359 'text' => 'nix bar!',
360 'basetimestamp' => $baseTime,
363 $this->fail( 'edit conflict expected' );
364 } catch ( ApiUsageException
$ex ) {
365 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'editconflict' ) );
370 * Ensure that editing using section=new will prevent simple conflicts
372 public function testEditConflict_newSection() {
376 // assume NS_HELP defaults to wikitext
377 $name = "Help:ApiEditPageTest_testEditConflict_newSection_$count";
378 $title = Title
::newFromText( $name );
380 $page = WikiPage
::factory( $title );
383 $page->doEditContent( new WikitextContent( "Foo" ),
384 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
385 $this->forceRevisionDate( $page, '20120101000000' );
386 $baseTime = $page->getRevision()->getTimestamp();
389 $page->doEditContent( new WikitextContent( "Foo bar" ),
390 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
391 $this->forceRevisionDate( $page, '20120101020202' );
393 // try to save edit, expect no conflict
394 list( $re, , ) = $this->doApiRequestWithToken( [
397 'text' => 'nix bar!',
398 'basetimestamp' => $baseTime,
402 $this->assertSame( 'Success', $re['edit']['result'],
403 "no edit conflict expected here" );
406 public function testEditConflict_T43990() {
411 * T43990: if the target page has a newer revision than the redirect, then editing the
412 * redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
413 * caused an edit conflict to be detected.
416 // assume NS_HELP defaults to wikitext
417 $name = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_$count";
418 $title = Title
::newFromText( $name );
419 $page = WikiPage
::factory( $title );
421 $rname = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_r$count";
422 $rtitle = Title
::newFromText( $rname );
423 $rpage = WikiPage
::factory( $rtitle );
425 // base edit for content
426 $page->doEditContent( new WikitextContent( "Foo" ),
427 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
428 $this->forceRevisionDate( $page, '20120101000000' );
430 // base edit for redirect
431 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
432 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
433 $this->forceRevisionDate( $rpage, '20120101000000' );
435 // new edit to content
436 $page->doEditContent( new WikitextContent( "Foo bar" ),
437 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
438 $this->forceRevisionDate( $rpage, '20120101020202' );
440 // try to save edit; should work, following the redirect.
441 list( $re, , ) = $this->doApiRequestWithToken( [
444 'text' => 'nix bar!',
449 $this->assertSame( 'Success', $re['edit']['result'],
450 "no edit conflict expected here" );
454 * @param WikiPage $page
455 * @param string|int $timestamp
457 protected function forceRevisionDate( WikiPage
$page, $timestamp ) {
458 $dbw = wfGetDB( DB_MASTER
);
460 $dbw->update( 'revision',
461 [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ],
462 [ 'rev_id' => $page->getLatest() ] );
467 public function testCheckDirectApiEditingDisallowed_forNonTextContent() {
468 $this->setExpectedException(
469 ApiUsageException
::class,
470 'Direct editing via API is not supported for content model ' .
471 'testing used by Dummy:ApiEditPageTest_nonTextPageEdit'
474 $this->doApiRequestWithToken( [
476 'title' => 'Dummy:ApiEditPageTest_nonTextPageEdit',
477 'text' => '{"animals":["kittens!"]}'
481 public function testSupportsDirectApiEditing_withContentHandlerOverride() {
482 $name = 'DummyNonText:ApiEditPageTest_testNonTextEdit';
483 $data = serialize( 'some bla bla text' );
485 $result = $this->doApiRequestWithToken( [
491 $apiResult = $result[0];
493 // Validate API result data
494 $this->assertArrayHasKey( 'edit', $apiResult );
495 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
496 $this->assertSame( 'Success', $apiResult['edit']['result'] );
498 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
499 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
501 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
503 // validate resulting revision
504 $page = WikiPage
::factory( Title
::newFromText( $name ) );
505 $this->assertSame( "testing-nontext", $page->getContentModel() );
506 $this->assertSame( $data, $page->getContent()->serialize() );
510 * This test verifies that after changing the content model
511 * of a page, undoing that edit via the API will also
512 * undo the content model change.
514 public function testUndoAfterContentModelChange() {
515 $name = 'Help:' . __FUNCTION__
;
516 $uploader = self
::$users['uploader']->getUser();
517 $sysop = self
::$users['sysop']->getUser();
519 $apiResult = $this->doApiRequestWithToken( [
522 'text' => 'some text',
523 ], null, $sysop )[0];
526 $this->assertArrayHasKey( 'edit', $apiResult );
527 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
528 $this->assertSame( 'Success', $apiResult['edit']['result'] );
529 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
530 // Content model is wikitext
531 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
533 // Convert the page to JSON
534 $apiResult = $this->doApiRequestWithToken( [
538 'contentmodel' => 'json',
539 ], null, $uploader )[0];
542 $this->assertArrayHasKey( 'edit', $apiResult );
543 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
544 $this->assertSame( 'Success', $apiResult['edit']['result'] );
545 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
546 $this->assertSame( 'json', $apiResult['edit']['contentmodel'] );
548 $apiResult = $this->doApiRequestWithToken( [
551 'undo' => $apiResult['edit']['newrevid']
552 ], null, $sysop )[0];
555 $this->assertArrayHasKey( 'edit', $apiResult );
556 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
557 $this->assertSame( 'Success', $apiResult['edit']['result'] );
558 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
559 // Check that the contentmodel is back to wikitext now.
560 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
563 // The tests below are mostly not commented because they do exactly what
564 // you'd expect from the name.
566 public function testCorrectContentFormat() {
567 $name = 'Help:' . ucfirst( __FUNCTION__
);
569 $this->doApiRequestWithToken( [
572 'text' => 'some text',
573 'contentmodel' => 'wikitext',
574 'contentformat' => 'text/x-wiki',
577 $this->assertTrue( Title
::newFromText( $name )->exists() );
580 public function testUnsupportedContentFormat() {
581 $name = 'Help:' . ucfirst( __FUNCTION__
);
583 $this->setExpectedException( ApiUsageException
::class,
584 'Unrecognized value for parameter "contentformat": nonexistent format.' );
587 $this->doApiRequestWithToken( [
590 'text' => 'some text',
591 'contentformat' => 'nonexistent format',
594 $this->assertFalse( Title
::newFromText( $name )->exists() );
598 public function testMismatchedContentFormat() {
599 $name = 'Help:' . ucfirst( __FUNCTION__
);
601 $this->setExpectedException( ApiUsageException
::class,
602 'The requested format text/plain is not supported for content ' .
603 "model wikitext used by $name." );
606 $this->doApiRequestWithToken( [
609 'text' => 'some text',
610 'contentmodel' => 'wikitext',
611 'contentformat' => 'text/plain',
614 $this->assertFalse( Title
::newFromText( $name )->exists() );
618 public function testUndoToInvalidRev() {
619 $name = 'Help:' . ucfirst( __FUNCTION__
);
621 $revId = $this->editPage( $name, 'Some text' )->value
['revision']
625 $this->setExpectedException( ApiUsageException
::class,
626 "There is no revision with ID $revId." );
628 $this->doApiRequestWithToken( [
636 * Tests what happens if the undo parameter is a valid revision, but
637 * the undoafter parameter doesn't refer to a revision that exists in the
640 public function testUndoAfterToInvalidRev() {
641 // We can't just pick a large number for undoafter (as in
642 // testUndoToInvalidRev above), because then MediaWiki will helpfully
643 // assume we switched around undo and undoafter and we'll test the code
644 // path for undo being invalid, not undoafter. So instead we delete
645 // the revision from the database. In real life this case could come
646 // up if a revision number was skipped, e.g., if two transactions try
647 // to insert new revision rows at once and the first one to succeed
649 $name = 'Help:' . ucfirst( __FUNCTION__
);
650 $titleObj = Title
::newFromText( $name );
652 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
653 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
654 $revId3 = $this->editPage( $name, '3' )->value
['revision']->getId();
656 // Make the middle revision disappear
657 $dbw = wfGetDB( DB_MASTER
);
658 $dbw->delete( 'revision', [ 'rev_id' => $revId2 ], __METHOD__
);
659 $dbw->update( 'revision', [ 'rev_parent_id' => $revId1 ],
660 [ 'rev_id' => $revId3 ], __METHOD__
);
662 $this->setExpectedException( ApiUsageException
::class,
663 "There is no revision with ID $revId2." );
665 $this->doApiRequestWithToken( [
669 'undoafter' => $revId2,
674 * Tests what happens if the undo parameter is a valid revision, but
675 * undoafter is hidden (rev_deleted).
677 public function testUndoAfterToHiddenRev() {
678 $name = 'Help:' . ucfirst( __FUNCTION__
);
679 $titleObj = Title
::newFromText( $name );
681 $this->editPage( $name, '0' );
683 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
685 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
687 // Hide the middle revision
688 $list = RevisionDeleter
::createList( 'revision',
689 RequestContext
::getMain(), $titleObj, [ $revId1 ] );
690 $list->setVisibility( [
691 'value' => [ Revision
::DELETED_TEXT
=> 1 ],
692 'comment' => 'Bye-bye',
695 $this->setExpectedException( ApiUsageException
::class,
696 "There is no revision with ID $revId1." );
698 $this->doApiRequestWithToken( [
702 'undoafter' => $revId1,
707 * Test undo when a revision with a higher id has an earlier timestamp.
708 * This can happen if importing an old revision.
710 public function testUndoWithSwappedRevisions() {
711 $name = 'Help:' . ucfirst( __FUNCTION__
);
712 $titleObj = Title
::newFromText( $name );
714 $this->editPage( $name, '0' );
716 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
718 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
720 // Now monkey with the timestamp
721 $dbw = wfGetDB( DB_MASTER
);
724 [ 'rev_timestamp' => $dbw->timestamp( time() - 86400 ) ],
725 [ 'rev_id' => $revId1 ],
729 $this->doApiRequestWithToken( [
733 'undoafter' => $revId1,
736 $text = ( new WikiPage( $titleObj ) )->getContent()->getText();
738 // This is wrong! It should be 1. But let's test for our incorrect
739 // behavior for now, so if someone fixes it they'll fix the test as
740 // well to expect 1. If we disabled the test, it might stay disabled
741 // even once the bug is fixed, which would be a shame.
742 $this->assertSame( '2', $text );
745 public function testUndoWithConflicts() {
746 $name = 'Help:' . ucfirst( __FUNCTION__
);
748 $this->setExpectedException( ApiUsageException
::class,
749 'The edit could not be undone due to conflicting intermediate edits.' );
751 $this->editPage( $name, '1' );
753 $revId = $this->editPage( $name, '2' )->value
['revision']->getId();
755 $this->editPage( $name, '3' );
757 $this->doApiRequestWithToken( [
763 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
765 $this->assertSame( '3', $text );
769 * undoafter is supposed to be less than undo. If not, we reverse their
770 * meaning, so that the two are effectively interchangeable.
772 public function testReversedUndoAfter() {
773 $name = 'Help:' . ucfirst( __FUNCTION__
);
775 $this->editPage( $name, '0' );
776 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
777 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
779 $this->doApiRequestWithToken( [
783 'undoafter' => $revId2,
786 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
788 $this->assertSame( '1', $text );
791 public function testUndoToRevFromDifferentPage() {
792 $name = 'Help:' . ucfirst( __FUNCTION__
);
794 $this->editPage( "$name-1", 'Some text' );
795 $revId = $this->editPage( "$name-1", 'Some more text' )
796 ->value
['revision']->getId();
798 $this->editPage( "$name-2", 'Some text' );
800 $this->setExpectedException( ApiUsageException
::class,
801 "r$revId is not a revision of $name-2." );
803 $this->doApiRequestWithToken( [
805 'title' => "$name-2",
810 public function testUndoAfterToRevFromDifferentPage() {
811 $name = 'Help:' . ucfirst( __FUNCTION__
);
813 $revId1 = $this->editPage( "$name-1", 'Some text' )
814 ->value
['revision']->getId();
816 $revId2 = $this->editPage( "$name-2", 'Some text' )
817 ->value
['revision']->getId();
819 $this->setExpectedException( ApiUsageException
::class,
820 "r$revId1 is not a revision of $name-2." );
822 $this->doApiRequestWithToken( [
824 'title' => "$name-2",
826 'undoafter' => $revId1,
830 public function testMd5Text() {
831 $name = 'Help:' . ucfirst( __FUNCTION__
);
833 $this->assertFalse( Title
::newFromText( $name )->exists() );
835 $this->doApiRequestWithToken( [
838 'text' => 'Some text',
839 'md5' => md5( 'Some text' ),
842 $this->assertTrue( Title
::newFromText( $name )->exists() );
845 public function testMd5PrependText() {
846 $name = 'Help:' . ucfirst( __FUNCTION__
);
848 $this->editPage( $name, 'Some text' );
850 $this->doApiRequestWithToken( [
853 'prependtext' => 'Alert: ',
854 'md5' => md5( 'Alert: ' ),
857 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
858 ->getContent()->getText();
859 $this->assertSame( 'Alert: Some text', $text );
862 public function testMd5AppendText() {
863 $name = 'Help:' . ucfirst( __FUNCTION__
);
865 $this->editPage( $name, 'Some text' );
867 $this->doApiRequestWithToken( [
870 'appendtext' => ' is nice',
871 'md5' => md5( ' is nice' ),
874 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
875 ->getContent()->getText();
876 $this->assertSame( 'Some text is nice', $text );
879 public function testMd5PrependAndAppendText() {
880 $name = 'Help:' . ucfirst( __FUNCTION__
);
882 $this->editPage( $name, 'Some text' );
884 $this->doApiRequestWithToken( [
887 'prependtext' => 'Alert: ',
888 'appendtext' => ' is nice',
889 'md5' => md5( 'Alert: is nice' ),
892 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
893 ->getContent()->getText();
894 $this->assertSame( 'Alert: Some text is nice', $text );
897 public function testIncorrectMd5Text() {
898 $name = 'Help:' . ucfirst( __FUNCTION__
);
900 $this->setExpectedException( ApiUsageException
::class,
901 'The supplied MD5 hash was incorrect.' );
903 $this->doApiRequestWithToken( [
906 'text' => 'Some text',
911 public function testIncorrectMd5PrependText() {
912 $name = 'Help:' . ucfirst( __FUNCTION__
);
914 $this->setExpectedException( ApiUsageException
::class,
915 'The supplied MD5 hash was incorrect.' );
917 $this->doApiRequestWithToken( [
920 'prependtext' => 'Some ',
921 'appendtext' => 'text',
922 'md5' => md5( 'Some ' ),
926 public function testIncorrectMd5AppendText() {
927 $name = 'Help:' . ucfirst( __FUNCTION__
);
929 $this->setExpectedException( ApiUsageException
::class,
930 'The supplied MD5 hash was incorrect.' );
932 $this->doApiRequestWithToken( [
935 'prependtext' => 'Some ',
936 'appendtext' => 'text',
937 'md5' => md5( 'text' ),
941 public function testCreateOnly() {
942 $name = 'Help:' . ucfirst( __FUNCTION__
);
944 $this->setExpectedException( ApiUsageException
::class,
945 'The article you tried to create has been created already.' );
947 $this->editPage( $name, 'Some text' );
948 $this->assertTrue( Title
::newFromText( $name )->exists() );
951 $this->doApiRequestWithToken( [
954 'text' => 'Some more text',
958 // Validate that content was not changed
959 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
960 ->getContent()->getText();
962 $this->assertSame( 'Some text', $text );
966 public function testNoCreate() {
967 $name = 'Help:' . ucfirst( __FUNCTION__
);
969 $this->setExpectedException( ApiUsageException
::class,
970 "The page you specified doesn't exist." );
972 $this->assertFalse( Title
::newFromText( $name )->exists() );
975 $this->doApiRequestWithToken( [
978 'text' => 'Some text',
982 $this->assertFalse( Title
::newFromText( $name )->exists() );
987 * Appending/prepending is currently only supported for TextContent. We
988 * test this right now, and when support is added this test should be
989 * replaced by tests that the support is correct.
991 public function testAppendWithNonTextContentHandler() {
992 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
994 $this->setExpectedException( ApiUsageException
::class,
995 "Can't append to pages using content model testing-nontext." );
997 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
998 function ( Title
$title, &$model ) use ( $name ) {
999 if ( $title->getPrefixedText() === $name ) {
1000 $model = 'testing-nontext';
1006 $this->doApiRequestWithToken( [
1009 'appendtext' => 'Some text',
1013 public function testAppendInMediaWikiNamespace() {
1014 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1016 $this->assertFalse( Title
::newFromText( $name )->exists() );
1018 $this->doApiRequestWithToken( [
1021 'appendtext' => 'Some text',
1024 $this->assertTrue( Title
::newFromText( $name )->exists() );
1027 public function testAppendInMediaWikiNamespaceWithSerializationError() {
1028 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1030 $this->setExpectedException( ApiUsageException
::class,
1031 'Content serialization failed: Could not unserialize content' );
1033 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1034 function ( Title
$title, &$model ) use ( $name ) {
1035 if ( $title->getPrefixedText() === $name ) {
1036 $model = 'testing-serialize-error';
1042 $this->doApiRequestWithToken( [
1045 'appendtext' => 'Some text',
1049 public function testAppendNewSection() {
1050 $name = 'Help:' . ucfirst( __FUNCTION__
);
1052 $this->editPage( $name, 'Initial content' );
1054 $this->doApiRequestWithToken( [
1057 'appendtext' => '== New section ==',
1061 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1062 ->getContent()->getText();
1064 $this->assertSame( "Initial content\n\n== New section ==", $text );
1067 public function testAppendNewSectionWithInvalidContentModel() {
1068 $name = 'Help:' . ucfirst( __FUNCTION__
);
1070 $this->setExpectedException( ApiUsageException
::class,
1071 'Sections are not supported for content model text.' );
1073 $this->editPage( $name, 'Initial content' );
1075 $this->doApiRequestWithToken( [
1078 'appendtext' => '== New section ==',
1080 'contentmodel' => 'text',
1084 public function testAppendNewSectionWithTitle() {
1085 $name = 'Help:' . ucfirst( __FUNCTION__
);
1087 $this->editPage( $name, 'Initial content' );
1089 $this->doApiRequestWithToken( [
1092 'sectiontitle' => 'My section',
1093 'appendtext' => 'More content',
1097 $page = new WikiPage( Title
::newFromText( $name ) );
1099 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1100 $page->getContent()->getText() );
1101 $this->assertSame( '/* My section */ new section',
1102 $page->getRevision()->getComment() );
1105 public function testAppendNewSectionWithSummary() {
1106 $name = 'Help:' . ucfirst( __FUNCTION__
);
1108 $this->editPage( $name, 'Initial content' );
1110 $this->doApiRequestWithToken( [
1113 'appendtext' => 'More content',
1115 'summary' => 'Add new section',
1118 $page = new WikiPage( Title
::newFromText( $name ) );
1120 $this->assertSame( "Initial content\n\n== Add new section ==\n\nMore content",
1121 $page->getContent()->getText() );
1122 // EditPage actually assumes the summary is the section name here
1123 $this->assertSame( '/* Add new section */ new section',
1124 $page->getRevision()->getComment() );
1127 public function testAppendNewSectionWithTitleAndSummary() {
1128 $name = 'Help:' . ucfirst( __FUNCTION__
);
1130 $this->editPage( $name, 'Initial content' );
1132 $this->doApiRequestWithToken( [
1135 'sectiontitle' => 'My section',
1136 'appendtext' => 'More content',
1138 'summary' => 'Add new section',
1141 $page = new WikiPage( Title
::newFromText( $name ) );
1143 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1144 $page->getContent()->getText() );
1145 $this->assertSame( 'Add new section',
1146 $page->getRevision()->getComment() );
1149 public function testAppendToSection() {
1150 $name = 'Help:' . ucfirst( __FUNCTION__
);
1152 $this->editPage( $name, "== Section 1 ==\n\nContent\n\n" .
1153 "== Section 2 ==\n\nFascinating!" );
1155 $this->doApiRequestWithToken( [
1158 'appendtext' => ' and more content',
1162 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1163 ->getContent()->getText();
1165 $this->assertSame( "== Section 1 ==\n\nContent and more content\n\n" .
1166 "== Section 2 ==\n\nFascinating!", $text );
1169 public function testAppendToFirstSection() {
1170 $name = 'Help:' . ucfirst( __FUNCTION__
);
1172 $this->editPage( $name, "Content\n\n== Section 1 ==\n\nFascinating!" );
1174 $this->doApiRequestWithToken( [
1177 'appendtext' => ' and more content',
1181 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1182 ->getContent()->getText();
1184 $this->assertSame( "Content and more content\n\n== Section 1 ==\n\n" .
1185 "Fascinating!", $text );
1188 public function testAppendToNonexistentSection() {
1189 $name = 'Help:' . ucfirst( __FUNCTION__
);
1191 $this->setExpectedException( ApiUsageException
::class, 'There is no section 1.' );
1193 $this->editPage( $name, 'Content' );
1196 $this->doApiRequestWithToken( [
1199 'appendtext' => ' and more content',
1203 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1204 ->getContent()->getText();
1206 $this->assertSame( 'Content', $text );
1210 public function testEditMalformedSection() {
1211 $name = 'Help:' . ucfirst( __FUNCTION__
);
1213 $this->setExpectedException( ApiUsageException
::class,
1214 'The "section" parameter must be a valid section ID or "new".' );
1215 $this->editPage( $name, 'Content' );
1218 $this->doApiRequestWithToken( [
1221 'text' => 'Different content',
1222 'section' => 'It is unlikely that this is valid',
1225 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1226 ->getContent()->getText();
1228 $this->assertSame( 'Content', $text );
1232 public function testEditWithStartTimestamp() {
1233 $name = 'Help:' . ucfirst( __FUNCTION__
);
1234 $this->setExpectedException( ApiUsageException
::class,
1235 'The page has been deleted since you fetched its timestamp.' );
1237 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1239 $this->editPage( $name, 'Some text' );
1241 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1242 $pageObj->doDeleteArticle( 'Bye-bye' );
1244 $this->assertFalse( $pageObj->exists() );
1247 $this->doApiRequestWithToken( [
1250 'text' => 'Different text',
1251 'starttimestamp' => $startTime,
1254 $this->assertFalse( $pageObj->exists() );
1258 public function testEditMinor() {
1259 $name = 'Help:' . ucfirst( __FUNCTION__
);
1261 $this->editPage( $name, 'Some text' );
1263 $this->doApiRequestWithToken( [
1266 'text' => 'Different text',
1270 $revisionStore = \MediaWiki\MediaWikiServices
::getInstance()->getRevisionStore();
1271 $revision = $revisionStore->getRevisionByTitle( Title
::newFromText( $name ) );
1272 $this->assertTrue( $revision->isMinor() );
1275 public function testEditRecreate() {
1276 $name = 'Help:' . ucfirst( __FUNCTION__
);
1278 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1280 $this->editPage( $name, 'Some text' );
1282 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1283 $pageObj->doDeleteArticle( 'Bye-bye' );
1285 $this->assertFalse( $pageObj->exists() );
1287 $this->doApiRequestWithToken( [
1290 'text' => 'Different text',
1291 'starttimestamp' => $startTime,
1295 $this->assertTrue( Title
::newFromText( $name )->exists() );
1298 public function testEditWatch() {
1299 $name = 'Help:' . ucfirst( __FUNCTION__
);
1300 $user = self
::$users['sysop']->getUser();
1302 $this->doApiRequestWithToken( [
1305 'text' => 'Some text',
1309 $this->assertTrue( Title
::newFromText( $name )->exists() );
1310 $this->assertTrue( $user->isWatched( Title
::newFromText( $name ) ) );
1313 public function testEditUnwatch() {
1314 $name = 'Help:' . ucfirst( __FUNCTION__
);
1315 $user = self
::$users['sysop']->getUser();
1316 $titleObj = Title
::newFromText( $name );
1318 $user->addWatch( $titleObj );
1320 $this->assertFalse( $titleObj->exists() );
1321 $this->assertTrue( $user->isWatched( $titleObj ) );
1323 $this->doApiRequestWithToken( [
1326 'text' => 'Some text',
1330 $this->assertTrue( $titleObj->exists() );
1331 $this->assertFalse( $user->isWatched( $titleObj ) );
1334 public function testEditWithTag() {
1335 $name = 'Help:' . ucfirst( __FUNCTION__
);
1337 ChangeTags
::defineTag( 'custom tag' );
1339 $revId = $this->doApiRequestWithToken( [
1342 'text' => 'Some text',
1343 'tags' => 'custom tag',
1344 ] )[0]['edit']['newrevid'];
1346 $dbw = wfGetDB( DB_MASTER
);
1347 $this->assertSame( 'custom tag', $dbw->selectField(
1348 [ 'change_tag', 'change_tag_def' ],
1350 [ 'ct_rev_id' => $revId ],
1352 [ 'change_tag_def' => [ 'JOIN', 'ctd_id = ct_tag_id' ] ]
1357 public function testEditWithoutTagPermission() {
1358 $name = 'Help:' . ucfirst( __FUNCTION__
);
1360 $this->setExpectedException( ApiUsageException
::class,
1361 'You do not have permission to apply change tags along with your changes.' );
1363 $this->assertFalse( Title
::newFromText( $name )->exists() );
1365 ChangeTags
::defineTag( 'custom tag' );
1366 $this->setMwGlobals( 'wgRevokePermissions',
1367 [ 'user' => [ 'applychangetags' => true ] ] );
1369 $this->doApiRequestWithToken( [
1372 'text' => 'Some text',
1373 'tags' => 'custom tag',
1376 $this->assertFalse( Title
::newFromText( $name )->exists() );
1380 public function testEditAbortedByHook() {
1381 $name = 'Help:' . ucfirst( __FUNCTION__
);
1383 $this->setExpectedException( ApiUsageException
::class,
1384 'The modification you tried to make was aborted by an extension.' );
1386 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1387 'hook-APIEditBeforeSave-closure)' );
1389 $this->setTemporaryHook( 'APIEditBeforeSave',
1396 $this->doApiRequestWithToken( [
1399 'text' => 'Some text',
1402 $this->assertFalse( Title
::newFromText( $name )->exists() );
1406 public function testEditAbortedByHookWithCustomOutput() {
1407 $name = 'Help:' . ucfirst( __FUNCTION__
);
1409 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1410 'hook-APIEditBeforeSave-closure)' );
1412 $this->setTemporaryHook( 'APIEditBeforeSave',
1413 function ( $unused1, $unused2, &$r ) {
1414 $r['msg'] = 'Some message';
1418 $result = $this->doApiRequestWithToken( [
1421 'text' => 'Some text',
1423 Wikimedia\restoreWarnings
();
1425 $this->assertSame( [ 'msg' => 'Some message', 'result' => 'Failure' ],
1426 $result[0]['edit'] );
1428 $this->assertFalse( Title
::newFromText( $name )->exists() );
1431 public function testEditAbortedByEditPageHookWithResult() {
1432 $name = 'Help:' . ucfirst( __FUNCTION__
);
1434 $this->setTemporaryHook( 'EditFilterMergedContent',
1435 function ( $unused1, $unused2, Status
$status ) {
1436 $status->apiHookResult
= [ 'msg' => 'A message for you!' ];
1440 $res = $this->doApiRequestWithToken( [
1443 'text' => 'Some text',
1446 $this->assertFalse( Title
::newFromText( $name )->exists() );
1447 $this->assertSame( [ 'edit' => [ 'msg' => 'A message for you!',
1448 'result' => 'Failure' ] ], $res[0] );
1451 public function testEditAbortedByEditPageHookWithNoResult() {
1452 $name = 'Help:' . ucfirst( __FUNCTION__
);
1454 $this->setExpectedException( ApiUsageException
::class,
1455 'The modification you tried to make was aborted by an extension.' );
1457 $this->setTemporaryHook( 'EditFilterMergedContent',
1464 $this->doApiRequestWithToken( [
1467 'text' => 'Some text',
1470 $this->assertFalse( Title
::newFromText( $name )->exists() );
1474 public function testEditWhileBlocked() {
1475 $name = 'Help:' . ucfirst( __FUNCTION__
);
1477 $this->assertNull( Block
::newFromTarget( '127.0.0.1' ), 'Sanity check' );
1479 $block = new Block( [
1480 'address' => self
::$users['sysop']->getUser()->getName(),
1481 'by' => self
::$users['sysop']->getUser()->getId(),
1482 'reason' => 'Capriciousness',
1483 'timestamp' => '19370101000000',
1484 'expiry' => 'infinity',
1485 'enableAutoblock' => true,
1490 $this->doApiRequestWithToken( [
1493 'text' => 'Some text',
1495 $this->fail( 'Expected exception not thrown' );
1496 } catch ( ApiUsageException
$ex ) {
1497 $this->assertSame( 'You have been blocked from editing.', $ex->getMessage() );
1498 $this->assertNotNull( Block
::newFromTarget( '127.0.0.1' ), 'Autoblock spread' );
1501 self
::$users['sysop']->getUser()->clearInstanceCache();
1505 public function testEditWhileReadOnly() {
1506 $name = 'Help:' . ucfirst( __FUNCTION__
);
1508 $this->setExpectedException( ApiUsageException
::class,
1509 'The wiki is currently in read-only mode.' );
1511 $svc = \MediaWiki\MediaWikiServices
::getInstance()->getReadOnlyMode();
1512 $svc->setReason( "Read-only for testing" );
1515 $this->doApiRequestWithToken( [
1518 'text' => 'Some text',
1521 $svc->setReason( false );
1525 public function testCreateImageRedirectAnon() {
1526 $name = 'File:' . ucfirst( __FUNCTION__
);
1528 $this->setExpectedException( ApiUsageException
::class,
1529 "Anonymous users can't create image redirects." );
1531 $this->doApiRequestWithToken( [
1534 'text' => '#REDIRECT [[File:Other file.png]]',
1535 ], null, new User() );
1538 public function testCreateImageRedirectLoggedIn() {
1539 $name = 'File:' . ucfirst( __FUNCTION__
);
1541 $this->setExpectedException( ApiUsageException
::class,
1542 "You don't have permission to create image redirects." );
1544 $this->setMwGlobals( 'wgRevokePermissions',
1545 [ 'user' => [ 'upload' => true ] ] );
1547 $this->doApiRequestWithToken( [
1550 'text' => '#REDIRECT [[File:Other file.png]]',
1554 public function testTooBigEdit() {
1555 $name = 'Help:' . ucfirst( __FUNCTION__
);
1557 $this->setExpectedException( ApiUsageException
::class,
1558 'The content you supplied exceeds the article size limit of 1 kilobyte.' );
1560 $this->setMwGlobals( 'wgMaxArticleSize', 1 );
1562 $text = str_repeat( '!', 1025 );
1564 $this->doApiRequestWithToken( [
1571 public function testProhibitedAnonymousEdit() {
1572 $name = 'Help:' . ucfirst( __FUNCTION__
);
1574 $this->setExpectedException( ApiUsageException
::class,
1575 'The action you have requested is limited to users in the group: ' );
1577 $this->setMwGlobals( 'wgRevokePermissions', [ '*' => [ 'edit' => true ] ] );
1579 $this->doApiRequestWithToken( [
1582 'text' => 'Some text',
1583 ], null, new User() );
1586 public function testProhibitedChangeContentModel() {
1587 $name = 'Help:' . ucfirst( __FUNCTION__
);
1589 $this->setExpectedException( ApiUsageException
::class,
1590 "You don't have permission to change the content model of a page." );
1592 $this->setMwGlobals( 'wgRevokePermissions',
1593 [ 'user' => [ 'editcontentmodel' => true ] ] );
1595 $this->doApiRequestWithToken( [
1598 'text' => 'Some text',
1599 'contentmodel' => 'json',