4 * Tests for MediaWiki api.php?action=edit.
6 * @author Daniel Kinzler
14 class ApiEditPageTest
extends ApiTestCase
{
16 protected function setUp() {
17 global $wgExtraNamespaces, $wgNamespaceContentModels, $wgContentHandlers, $wgContLang;
21 $this->setMwGlobals( [
22 'wgExtraNamespaces' => $wgExtraNamespaces,
23 'wgNamespaceContentModels' => $wgNamespaceContentModels,
24 'wgContentHandlers' => $wgContentHandlers,
25 'wgContLang' => $wgContLang,
28 $wgExtraNamespaces[12312] = 'Dummy';
29 $wgExtraNamespaces[12313] = 'Dummy_talk';
30 $wgExtraNamespaces[12314] = 'DummyNonText';
31 $wgExtraNamespaces[12315] = 'DummyNonText_talk';
33 $wgNamespaceContentModels[12312] = "testing";
34 $wgNamespaceContentModels[12314] = "testing-nontext";
36 $wgContentHandlers["testing"] = 'DummyContentHandlerForTesting';
37 $wgContentHandlers["testing-nontext"] = 'DummyNonTextContentHandler';
38 $wgContentHandlers["testing-serialize-error"] =
39 'DummySerializeErrorContentHandler';
41 MWNamespace
::clearCaches();
42 $wgContLang->resetNamespaces(); # reset namespace cache
45 protected function tearDown() {
48 MWNamespace
::clearCaches();
49 $wgContLang->resetNamespaces(); # reset namespace cache
54 public function testEdit() {
55 $name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
57 // -- test new page --------------------------------------------
58 $apiResult = $this->doApiRequestWithToken( [
61 'text' => 'some text',
63 $apiResult = $apiResult[0];
65 // Validate API result data
66 $this->assertArrayHasKey( 'edit', $apiResult );
67 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
68 $this->assertSame( 'Success', $apiResult['edit']['result'] );
70 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
71 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
73 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
75 // -- test existing page, no change ----------------------------
76 $data = $this->doApiRequestWithToken( [
79 'text' => 'some text',
82 $this->assertSame( 'Success', $data[0]['edit']['result'] );
84 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
85 $this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
87 // -- test existing page, with change --------------------------
88 $data = $this->doApiRequestWithToken( [
91 'text' => 'different text'
94 $this->assertSame( 'Success', $data[0]['edit']['result'] );
96 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
97 $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
99 $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
100 $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
101 $this->assertNotEquals(
102 $data[0]['edit']['newrevid'],
103 $data[0]['edit']['oldrevid'],
104 "revision id should change after edit"
111 public static function provideEditAppend() {
114 'foo', 'append', 'bar', "foobar"
117 'foo', 'prepend', 'bar', "barfoo"
119 [ # 2: append to empty page
120 '', 'append', 'foo', "foo"
122 [ # 3: prepend to empty page
123 '', 'prepend', 'foo', "foo"
125 [ # 4: append to non-existing page
126 null, 'append', 'foo', "foo"
128 [ # 5: prepend to non-existing page
129 null, 'prepend', 'foo', "foo"
135 * @dataProvider provideEditAppend
137 public function testEditAppend( $text, $op, $append, $expected ) {
141 // assume NS_HELP defaults to wikitext
142 $name = "Help:ApiEditPageTest_testEditAppend_$count";
144 // -- create page (or not) -----------------------------------------
145 if ( $text !== null ) {
146 list( $re ) = $this->doApiRequestWithToken( [
149 'text' => $text, ] );
151 $this->assertSame( 'Success', $re['edit']['result'] ); // sanity
154 // -- try append/prepend --------------------------------------------
155 list( $re ) = $this->doApiRequestWithToken( [
158 $op . 'text' => $append, ] );
160 $this->assertSame( 'Success', $re['edit']['result'] );
162 // -- validate -----------------------------------------------------
163 $page = new WikiPage( Title
::newFromText( $name ) );
164 $content = $page->getContent();
165 $this->assertNotNull( $content, 'Page should have been created' );
167 $text = $content->getNativeData();
169 $this->assertSame( $expected, $text );
173 * Test editing of sections
175 public function testEditSection() {
176 $name = 'Help:ApiEditPageTest_testEditSection';
177 $page = WikiPage
::factory( Title
::newFromText( $name ) );
178 $text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
179 // Preload the page with some text
180 $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ), 'summary' );
182 list( $re ) = $this->doApiRequestWithToken( [
186 'text' => "==section 1==\nnew content 1",
188 $this->assertSame( 'Success', $re['edit']['result'] );
189 $newtext = WikiPage
::factory( Title
::newFromText( $name ) )
190 ->getContent( Revision
::RAW
)
192 $this->assertSame( "==section 1==\nnew content 1\n\n==section 2==\ncontent2", $newtext );
194 // Test that we raise a 'nosuchsection' error
196 $this->doApiRequestWithToken( [
202 $this->fail( "Should have raised an ApiUsageException" );
203 } catch ( ApiUsageException
$e ) {
204 $this->assertTrue( self
::apiExceptionHasCode( $e, 'nosuchsection' ) );
209 * Test action=edit§ion=new
210 * Run it twice so we test adding a new section on a
211 * page that doesn't exist (T54830) and one that
214 public function testEditNewSection() {
215 $name = 'Help:ApiEditPageTest_testEditNewSection';
217 // Test on a page that does not already exist
218 $this->assertFalse( Title
::newFromText( $name )->exists() );
219 list( $re ) = $this->doApiRequestWithToken( [
224 'summary' => 'header',
227 $this->assertSame( 'Success', $re['edit']['result'] );
228 // Check the page text is correct
229 $text = WikiPage
::factory( Title
::newFromText( $name ) )
230 ->getContent( Revision
::RAW
)
232 $this->assertSame( "== header ==\n\ntest", $text );
234 // Now on one that does
235 $this->assertTrue( Title
::newFromText( $name )->exists() );
236 list( $re2 ) = $this->doApiRequestWithToken( [
241 'summary' => 'header',
244 $this->assertSame( 'Success', $re2['edit']['result'] );
245 $text = WikiPage
::factory( Title
::newFromText( $name ) )
246 ->getContent( Revision
::RAW
)
248 $this->assertSame( "== header ==\n\ntest\n\n== header ==\n\ntest", $text );
252 * Ensure we can edit through a redirect, if adding a section
254 public function testEdit_redirect() {
258 // assume NS_HELP defaults to wikitext
259 $name = "Help:ApiEditPageTest_testEdit_redirect_$count";
260 $title = Title
::newFromText( $name );
261 $page = WikiPage
::factory( $title );
263 $rname = "Help:ApiEditPageTest_testEdit_redirect_r$count";
264 $rtitle = Title
::newFromText( $rname );
265 $rpage = WikiPage
::factory( $rtitle );
267 // base edit for content
268 $page->doEditContent( new WikitextContent( "Foo" ),
269 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
270 $this->forceRevisionDate( $page, '20120101000000' );
271 $baseTime = $page->getRevision()->getTimestamp();
273 // base edit for redirect
274 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
275 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
276 $this->forceRevisionDate( $rpage, '20120101000000' );
278 // conflicting edit to redirect
279 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
280 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
281 $this->forceRevisionDate( $rpage, '20120101020202' );
283 // try to save edit, following the redirect
284 list( $re, , ) = $this->doApiRequestWithToken( [
287 'text' => 'nix bar!',
288 'basetimestamp' => $baseTime,
293 $this->assertSame( 'Success', $re['edit']['result'],
294 "no problems expected when following redirect" );
298 * Ensure we cannot edit through a redirect, if attempting to overwrite content
300 public function testEdit_redirectText() {
304 // assume NS_HELP defaults to wikitext
305 $name = "Help:ApiEditPageTest_testEdit_redirectText_$count";
306 $title = Title
::newFromText( $name );
307 $page = WikiPage
::factory( $title );
309 $rname = "Help:ApiEditPageTest_testEdit_redirectText_r$count";
310 $rtitle = Title
::newFromText( $rname );
311 $rpage = WikiPage
::factory( $rtitle );
313 // base edit for content
314 $page->doEditContent( new WikitextContent( "Foo" ),
315 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
316 $this->forceRevisionDate( $page, '20120101000000' );
317 $baseTime = $page->getRevision()->getTimestamp();
319 // base edit for redirect
320 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
321 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
322 $this->forceRevisionDate( $rpage, '20120101000000' );
324 // conflicting edit to redirect
325 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
326 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
327 $this->forceRevisionDate( $rpage, '20120101020202' );
329 // try to save edit, following the redirect but without creating a section
331 $this->doApiRequestWithToken( [
334 'text' => 'nix bar!',
335 'basetimestamp' => $baseTime,
339 $this->fail( 'redirect-appendonly error expected' );
340 } catch ( ApiUsageException
$ex ) {
341 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'redirect-appendonly' ) );
345 public function testEditConflict() {
349 // assume NS_HELP defaults to wikitext
350 $name = "Help:ApiEditPageTest_testEditConflict_$count";
351 $title = Title
::newFromText( $name );
353 $page = WikiPage
::factory( $title );
356 $page->doEditContent( new WikitextContent( "Foo" ),
357 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
358 $this->forceRevisionDate( $page, '20120101000000' );
359 $baseTime = $page->getRevision()->getTimestamp();
362 $page->doEditContent( new WikitextContent( "Foo bar" ),
363 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
364 $this->forceRevisionDate( $page, '20120101020202' );
366 // try to save edit, expect conflict
368 $this->doApiRequestWithToken( [
371 'text' => 'nix bar!',
372 'basetimestamp' => $baseTime,
375 $this->fail( 'edit conflict expected' );
376 } catch ( ApiUsageException
$ex ) {
377 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'editconflict' ) );
382 * Ensure that editing using section=new will prevent simple conflicts
384 public function testEditConflict_newSection() {
388 // assume NS_HELP defaults to wikitext
389 $name = "Help:ApiEditPageTest_testEditConflict_newSection_$count";
390 $title = Title
::newFromText( $name );
392 $page = WikiPage
::factory( $title );
395 $page->doEditContent( new WikitextContent( "Foo" ),
396 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
397 $this->forceRevisionDate( $page, '20120101000000' );
398 $baseTime = $page->getRevision()->getTimestamp();
401 $page->doEditContent( new WikitextContent( "Foo bar" ),
402 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
403 $this->forceRevisionDate( $page, '20120101020202' );
405 // try to save edit, expect no conflict
406 list( $re, , ) = $this->doApiRequestWithToken( [
409 'text' => 'nix bar!',
410 'basetimestamp' => $baseTime,
414 $this->assertSame( 'Success', $re['edit']['result'],
415 "no edit conflict expected here" );
418 public function testEditConflict_bug41990() {
423 * T43990: if the target page has a newer revision than the redirect, then editing the
424 * redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
425 * caused an edit conflict to be detected.
428 // assume NS_HELP defaults to wikitext
429 $name = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_$count";
430 $title = Title
::newFromText( $name );
431 $page = WikiPage
::factory( $title );
433 $rname = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_r$count";
434 $rtitle = Title
::newFromText( $rname );
435 $rpage = WikiPage
::factory( $rtitle );
437 // base edit for content
438 $page->doEditContent( new WikitextContent( "Foo" ),
439 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
440 $this->forceRevisionDate( $page, '20120101000000' );
442 // base edit for redirect
443 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
444 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
445 $this->forceRevisionDate( $rpage, '20120101000000' );
447 // new edit to content
448 $page->doEditContent( new WikitextContent( "Foo bar" ),
449 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
450 $this->forceRevisionDate( $rpage, '20120101020202' );
452 // try to save edit; should work, following the redirect.
453 list( $re, , ) = $this->doApiRequestWithToken( [
456 'text' => 'nix bar!',
461 $this->assertSame( 'Success', $re['edit']['result'],
462 "no edit conflict expected here" );
466 * @param WikiPage $page
467 * @param string|int $timestamp
469 protected function forceRevisionDate( WikiPage
$page, $timestamp ) {
470 $dbw = wfGetDB( DB_MASTER
);
472 $dbw->update( 'revision',
473 [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ],
474 [ 'rev_id' => $page->getLatest() ] );
479 public function testCheckDirectApiEditingDisallowed_forNonTextContent() {
480 $this->setExpectedException(
481 ApiUsageException
::class,
482 'Direct editing via API is not supported for content model ' .
483 'testing used by Dummy:ApiEditPageTest_nonTextPageEdit'
486 $this->doApiRequestWithToken( [
488 'title' => 'Dummy:ApiEditPageTest_nonTextPageEdit',
489 'text' => '{"animals":["kittens!"]}'
493 public function testSupportsDirectApiEditing_withContentHandlerOverride() {
494 $name = 'DummyNonText:ApiEditPageTest_testNonTextEdit';
495 $data = serialize( 'some bla bla text' );
497 $result = $this->doApiRequestWithToken( [
503 $apiResult = $result[0];
505 // Validate API result data
506 $this->assertArrayHasKey( 'edit', $apiResult );
507 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
508 $this->assertSame( 'Success', $apiResult['edit']['result'] );
510 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
511 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
513 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
515 // validate resulting revision
516 $page = WikiPage
::factory( Title
::newFromText( $name ) );
517 $this->assertSame( "testing-nontext", $page->getContentModel() );
518 $this->assertSame( $data, $page->getContent()->serialize() );
522 * This test verifies that after changing the content model
523 * of a page, undoing that edit via the API will also
524 * undo the content model change.
526 public function testUndoAfterContentModelChange() {
527 $name = 'Help:' . __FUNCTION__
;
528 $uploader = self
::$users['uploader']->getUser();
529 $sysop = self
::$users['sysop']->getUser();
531 $apiResult = $this->doApiRequestWithToken( [
534 'text' => 'some text',
535 ], null, $sysop )[0];
538 $this->assertArrayHasKey( 'edit', $apiResult );
539 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
540 $this->assertSame( 'Success', $apiResult['edit']['result'] );
541 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
542 // Content model is wikitext
543 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
545 // Convert the page to JSON
546 $apiResult = $this->doApiRequestWithToken( [
550 'contentmodel' => 'json',
551 ], null, $uploader )[0];
554 $this->assertArrayHasKey( 'edit', $apiResult );
555 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
556 $this->assertSame( 'Success', $apiResult['edit']['result'] );
557 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
558 $this->assertSame( 'json', $apiResult['edit']['contentmodel'] );
560 $apiResult = $this->doApiRequestWithToken( [
563 'undo' => $apiResult['edit']['newrevid']
564 ], null, $sysop )[0];
567 $this->assertArrayHasKey( 'edit', $apiResult );
568 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
569 $this->assertSame( 'Success', $apiResult['edit']['result'] );
570 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
571 // Check that the contentmodel is back to wikitext now.
572 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
575 // The tests below are mostly not commented because they do exactly what
576 // you'd expect from the name.
578 public function testCorrectContentFormat() {
579 $name = 'Help:' . ucfirst( __FUNCTION__
);
581 $this->doApiRequestWithToken( [
584 'text' => 'some text',
585 'contentmodel' => 'wikitext',
586 'contentformat' => 'text/x-wiki',
589 $this->assertTrue( Title
::newFromText( $name )->exists() );
592 public function testUnsupportedContentFormat() {
593 $name = 'Help:' . ucfirst( __FUNCTION__
);
595 $this->setExpectedException( ApiUsageException
::class,
596 'Unrecognized value for parameter "contentformat": nonexistent format.' );
599 $this->doApiRequestWithToken( [
602 'text' => 'some text',
603 'contentformat' => 'nonexistent format',
606 $this->assertFalse( Title
::newFromText( $name )->exists() );
610 public function testMismatchedContentFormat() {
611 $name = 'Help:' . ucfirst( __FUNCTION__
);
613 $this->setExpectedException( ApiUsageException
::class,
614 'The requested format text/plain is not supported for content ' .
615 "model wikitext used by $name." );
618 $this->doApiRequestWithToken( [
621 'text' => 'some text',
622 'contentmodel' => 'wikitext',
623 'contentformat' => 'text/plain',
626 $this->assertFalse( Title
::newFromText( $name )->exists() );
630 public function testUndoToInvalidRev() {
631 $name = 'Help:' . ucfirst( __FUNCTION__
);
633 $revId = $this->editPage( $name, 'Some text' )->value
['revision']
637 $this->setExpectedException( ApiUsageException
::class,
638 "There is no revision with ID $revId." );
640 $this->doApiRequestWithToken( [
648 * Tests what happens if the undo parameter is a valid revision, but
649 * the undoafter parameter doesn't refer to a revision that exists in the
652 public function testUndoAfterToInvalidRev() {
653 // We can't just pick a large number for undoafter (as in
654 // testUndoToInvalidRev above), because then MediaWiki will helpfully
655 // assume we switched around undo and undoafter and we'll test the code
656 // path for undo being invalid, not undoafter. So instead we delete
657 // the revision from the database. In real life this case could come
658 // up if a revision number was skipped, e.g., if two transactions try
659 // to insert new revision rows at once and the first one to succeed
661 $name = 'Help:' . ucfirst( __FUNCTION__
);
662 $titleObj = Title
::newFromText( $name );
664 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
665 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
666 $revId3 = $this->editPage( $name, '3' )->value
['revision']->getId();
668 // Make the middle revision disappear
669 $dbw = wfGetDB( DB_MASTER
);
670 $dbw->delete( 'revision', [ 'rev_id' => $revId2 ], __METHOD__
);
671 $dbw->update( 'revision', [ 'rev_parent_id' => $revId1 ],
672 [ 'rev_id' => $revId3 ], __METHOD__
);
674 $this->setExpectedException( ApiUsageException
::class,
675 "There is no revision with ID $revId2." );
677 $this->doApiRequestWithToken( [
681 'undoafter' => $revId2,
686 * Tests what happens if the undo parameter is a valid revision, but
687 * undoafter is hidden (rev_deleted).
689 public function testUndoAfterToHiddenRev() {
690 $name = 'Help:' . ucfirst( __FUNCTION__
);
691 $titleObj = Title
::newFromText( $name );
693 $this->editPage( $name, '0' );
695 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
697 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
699 // Hide the middle revision
700 $list = RevisionDeleter
::createList( 'revision',
701 RequestContext
::getMain(), $titleObj, [ $revId1 ] );
702 $list->setVisibility( [
703 'value' => [ Revision
::DELETED_TEXT
=> 1 ],
704 'comment' => 'Bye-bye',
707 $this->setExpectedException( ApiUsageException
::class,
708 "There is no revision with ID $revId1." );
710 $this->doApiRequestWithToken( [
714 'undoafter' => $revId1,
719 * Test undo when a revision with a higher id has an earlier timestamp.
720 * This can happen if importing an old revision.
722 public function testUndoWithSwappedRevisions() {
723 $name = 'Help:' . ucfirst( __FUNCTION__
);
724 $titleObj = Title
::newFromText( $name );
726 $this->editPage( $name, '0' );
728 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
730 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
732 // Now monkey with the timestamp
733 $dbw = wfGetDB( DB_MASTER
);
736 [ 'rev_timestamp' => wfTimestamp( TS_MW
, time() - 86400 ) ],
737 [ 'rev_id' => $revId1 ],
741 $this->doApiRequestWithToken( [
745 'undoafter' => $revId1,
748 $text = ( new WikiPage( $titleObj ) )->getContent()->getNativeData();
750 // This is wrong! It should be 1. But let's test for our incorrect
751 // behavior for now, so if someone fixes it they'll fix the test as
752 // well to expect 1. If we disabled the test, it might stay disabled
753 // even once the bug is fixed, which would be a shame.
754 $this->assertSame( '2', $text );
757 public function testUndoWithConflicts() {
758 $name = 'Help:' . ucfirst( __FUNCTION__
);
760 $this->setExpectedException( ApiUsageException
::class,
761 'The edit could not be undone due to conflicting intermediate edits.' );
763 $this->editPage( $name, '1' );
765 $revId = $this->editPage( $name, '2' )->value
['revision']->getId();
767 $this->editPage( $name, '3' );
769 $this->doApiRequestWithToken( [
775 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
777 $this->assertSame( '3', $text );
781 * undoafter is supposed to be less than undo. If not, we reverse their
782 * meaning, so that the two are effectively interchangeable.
784 public function testReversedUndoAfter() {
785 $name = 'Help:' . ucfirst( __FUNCTION__
);
787 $this->editPage( $name, '0' );
788 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
789 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
791 $this->doApiRequestWithToken( [
795 'undoafter' => $revId2,
798 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
800 $this->assertSame( '1', $text );
803 public function testUndoToRevFromDifferentPage() {
804 $name = 'Help:' . ucfirst( __FUNCTION__
);
806 $this->editPage( "$name-1", 'Some text' );
807 $revId = $this->editPage( "$name-1", 'Some more text' )
808 ->value
['revision']->getId();
810 $this->editPage( "$name-2", 'Some text' );
812 $this->setExpectedException( ApiUsageException
::class,
813 "r$revId is not a revision of $name-2." );
815 $this->doApiRequestWithToken( [
817 'title' => "$name-2",
822 public function testUndoAfterToRevFromDifferentPage() {
823 $name = 'Help:' . ucfirst( __FUNCTION__
);
825 $revId1 = $this->editPage( "$name-1", 'Some text' )
826 ->value
['revision']->getId();
828 $revId2 = $this->editPage( "$name-2", 'Some text' )
829 ->value
['revision']->getId();
831 $this->setExpectedException( ApiUsageException
::class,
832 "r$revId1 is not a revision of $name-2." );
834 $this->doApiRequestWithToken( [
836 'title' => "$name-2",
838 'undoafter' => $revId1,
842 public function testMd5Text() {
843 $name = 'Help:' . ucfirst( __FUNCTION__
);
845 $this->assertFalse( Title
::newFromText( $name )->exists() );
847 $this->doApiRequestWithToken( [
850 'text' => 'Some text',
851 'md5' => md5( 'Some text' ),
854 $this->assertTrue( Title
::newFromText( $name )->exists() );
857 public function testMd5PrependText() {
858 $name = 'Help:' . ucfirst( __FUNCTION__
);
860 $this->editPage( $name, 'Some text' );
862 $this->doApiRequestWithToken( [
865 'prependtext' => 'Alert: ',
866 'md5' => md5( 'Alert: ' ),
869 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
870 ->getContent()->getNativeData();
871 $this->assertSame( 'Alert: Some text', $text );
874 public function testMd5AppendText() {
875 $name = 'Help:' . ucfirst( __FUNCTION__
);
877 $this->editPage( $name, 'Some text' );
879 $this->doApiRequestWithToken( [
882 'appendtext' => ' is nice',
883 'md5' => md5( ' is nice' ),
886 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
887 ->getContent()->getNativeData();
888 $this->assertSame( 'Some text is nice', $text );
891 public function testMd5PrependAndAppendText() {
892 $name = 'Help:' . ucfirst( __FUNCTION__
);
894 $this->editPage( $name, 'Some text' );
896 $this->doApiRequestWithToken( [
899 'prependtext' => 'Alert: ',
900 'appendtext' => ' is nice',
901 'md5' => md5( 'Alert: is nice' ),
904 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
905 ->getContent()->getNativeData();
906 $this->assertSame( 'Alert: Some text is nice', $text );
909 public function testIncorrectMd5Text() {
910 $name = 'Help:' . ucfirst( __FUNCTION__
);
912 $this->setExpectedException( ApiUsageException
::class,
913 'The supplied MD5 hash was incorrect.' );
915 $this->doApiRequestWithToken( [
918 'text' => 'Some text',
923 public function testIncorrectMd5PrependText() {
924 $name = 'Help:' . ucfirst( __FUNCTION__
);
926 $this->setExpectedException( ApiUsageException
::class,
927 'The supplied MD5 hash was incorrect.' );
929 $this->doApiRequestWithToken( [
932 'prependtext' => 'Some ',
933 'appendtext' => 'text',
934 'md5' => md5( 'Some ' ),
938 public function testIncorrectMd5AppendText() {
939 $name = 'Help:' . ucfirst( __FUNCTION__
);
941 $this->setExpectedException( ApiUsageException
::class,
942 'The supplied MD5 hash was incorrect.' );
944 $this->doApiRequestWithToken( [
947 'prependtext' => 'Some ',
948 'appendtext' => 'text',
949 'md5' => md5( 'text' ),
953 public function testCreateOnly() {
954 $name = 'Help:' . ucfirst( __FUNCTION__
);
956 $this->setExpectedException( ApiUsageException
::class,
957 'The article you tried to create has been created already.' );
959 $this->editPage( $name, 'Some text' );
960 $this->assertTrue( Title
::newFromText( $name )->exists() );
963 $this->doApiRequestWithToken( [
966 'text' => 'Some more text',
970 // Validate that content was not changed
971 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
972 ->getContent()->getNativeData();
974 $this->assertSame( 'Some text', $text );
978 public function testNoCreate() {
979 $name = 'Help:' . ucfirst( __FUNCTION__
);
981 $this->setExpectedException( ApiUsageException
::class,
982 "The page you specified doesn't exist." );
984 $this->assertFalse( Title
::newFromText( $name )->exists() );
987 $this->doApiRequestWithToken( [
990 'text' => 'Some text',
994 $this->assertFalse( Title
::newFromText( $name )->exists() );
999 * Appending/prepending is currently only supported for TextContent. We
1000 * test this right now, and when support is added this test should be
1001 * replaced by tests that the support is correct.
1003 public function testAppendWithNonTextContentHandler() {
1004 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1006 $this->setExpectedException( ApiUsageException
::class,
1007 "Can't append to pages using content model testing-nontext." );
1009 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1010 function ( Title
$title, &$model ) use ( $name ) {
1011 if ( $title->getPrefixedText() === $name ) {
1012 $model = 'testing-nontext';
1018 $this->doApiRequestWithToken( [
1021 'appendtext' => 'Some text',
1025 public function testAppendInMediaWikiNamespace() {
1026 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1028 $this->assertFalse( Title
::newFromText( $name )->exists() );
1030 $this->doApiRequestWithToken( [
1033 'appendtext' => 'Some text',
1036 $this->assertTrue( Title
::newFromText( $name )->exists() );
1039 public function testAppendInMediaWikiNamespaceWithSerializationError() {
1040 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1042 $this->setExpectedException( ApiUsageException
::class,
1043 'Content serialization failed: Could not unserialize content' );
1045 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1046 function ( Title
$title, &$model ) use ( $name ) {
1047 if ( $title->getPrefixedText() === $name ) {
1048 $model = 'testing-serialize-error';
1054 $this->doApiRequestWithToken( [
1057 'appendtext' => 'Some text',
1061 public function testAppendNewSection() {
1062 $name = 'Help:' . ucfirst( __FUNCTION__
);
1064 $this->editPage( $name, 'Initial content' );
1066 $this->doApiRequestWithToken( [
1069 'appendtext' => '== New section ==',
1073 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1074 ->getContent()->getNativeData();
1076 $this->assertSame( "Initial content\n\n== New section ==", $text );
1079 public function testAppendNewSectionWithInvalidContentModel() {
1080 $name = 'Help:' . ucfirst( __FUNCTION__
);
1082 $this->setExpectedException( ApiUsageException
::class,
1083 'Sections are not supported for content model text.' );
1085 $this->editPage( $name, 'Initial content' );
1087 $this->doApiRequestWithToken( [
1090 'appendtext' => '== New section ==',
1092 'contentmodel' => 'text',
1096 public function testAppendNewSectionWithTitle() {
1097 $name = 'Help:' . ucfirst( __FUNCTION__
);
1099 $this->editPage( $name, 'Initial content' );
1101 $this->doApiRequestWithToken( [
1104 'sectiontitle' => 'My section',
1105 'appendtext' => 'More content',
1109 $page = new WikiPage( Title
::newFromText( $name ) );
1111 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1112 $page->getContent()->getNativeData() );
1113 $this->assertSame( '/* My section */ new section',
1114 $page->getRevision()->getComment() );
1117 public function testAppendNewSectionWithSummary() {
1118 $name = 'Help:' . ucfirst( __FUNCTION__
);
1120 $this->editPage( $name, 'Initial content' );
1122 $this->doApiRequestWithToken( [
1125 'appendtext' => 'More content',
1127 'summary' => 'Add new section',
1130 $page = new WikiPage( Title
::newFromText( $name ) );
1132 $this->assertSame( "Initial content\n\n== Add new section ==\n\nMore content",
1133 $page->getContent()->getNativeData() );
1134 // EditPage actually assumes the summary is the section name here
1135 $this->assertSame( '/* Add new section */ new section',
1136 $page->getRevision()->getComment() );
1139 public function testAppendNewSectionWithTitleAndSummary() {
1140 $name = 'Help:' . ucfirst( __FUNCTION__
);
1142 $this->editPage( $name, 'Initial content' );
1144 $this->doApiRequestWithToken( [
1147 'sectiontitle' => 'My section',
1148 'appendtext' => 'More content',
1150 'summary' => 'Add new section',
1153 $page = new WikiPage( Title
::newFromText( $name ) );
1155 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1156 $page->getContent()->getNativeData() );
1157 $this->assertSame( 'Add new section',
1158 $page->getRevision()->getComment() );
1161 public function testAppendToSection() {
1162 $name = 'Help:' . ucfirst( __FUNCTION__
);
1164 $this->editPage( $name, "== Section 1 ==\n\nContent\n\n" .
1165 "== Section 2 ==\n\nFascinating!" );
1167 $this->doApiRequestWithToken( [
1170 'appendtext' => ' and more content',
1174 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1175 ->getContent()->getNativeData();
1177 $this->assertSame( "== Section 1 ==\n\nContent and more content\n\n" .
1178 "== Section 2 ==\n\nFascinating!", $text );
1181 public function testAppendToFirstSection() {
1182 $name = 'Help:' . ucfirst( __FUNCTION__
);
1184 $this->editPage( $name, "Content\n\n== Section 1 ==\n\nFascinating!" );
1186 $this->doApiRequestWithToken( [
1189 'appendtext' => ' and more content',
1193 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1194 ->getContent()->getNativeData();
1196 $this->assertSame( "Content and more content\n\n== Section 1 ==\n\n" .
1197 "Fascinating!", $text );
1200 public function testAppendToNonexistentSection() {
1201 $name = 'Help:' . ucfirst( __FUNCTION__
);
1203 $this->setExpectedException( ApiUsageException
::class, 'There is no section 1.' );
1205 $this->editPage( $name, 'Content' );
1208 $this->doApiRequestWithToken( [
1211 'appendtext' => ' and more content',
1215 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1216 ->getContent()->getNativeData();
1218 $this->assertSame( 'Content', $text );
1222 public function testEditMalformedSection() {
1223 $name = 'Help:' . ucfirst( __FUNCTION__
);
1225 $this->setExpectedException( ApiUsageException
::class,
1226 'The "section" parameter must be a valid section ID or "new".' );
1227 $this->editPage( $name, 'Content' );
1230 $this->doApiRequestWithToken( [
1233 'text' => 'Different content',
1234 'section' => 'It is unlikely that this is valid',
1237 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1238 ->getContent()->getNativeData();
1240 $this->assertSame( 'Content', $text );
1244 public function testEditWithStartTimestamp() {
1245 $name = 'Help:' . ucfirst( __FUNCTION__
);
1246 $this->setExpectedException( ApiUsageException
::class,
1247 'The page has been deleted since you fetched its timestamp.' );
1249 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1251 $this->editPage( $name, 'Some text' );
1253 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1254 $pageObj->doDeleteArticle( 'Bye-bye' );
1256 $this->assertFalse( $pageObj->exists() );
1259 $this->doApiRequestWithToken( [
1262 'text' => 'Different text',
1263 'starttimestamp' => $startTime,
1266 $this->assertFalse( $pageObj->exists() );
1270 public function testEditMinor() {
1271 $name = 'Help:' . ucfirst( __FUNCTION__
);
1273 $this->editPage( $name, 'Some text' );
1275 $this->doApiRequestWithToken( [
1278 'text' => 'Different text',
1282 $revisionStore = \MediaWiki\MediaWikiServices
::getInstance()->getRevisionStore();
1283 $revision = $revisionStore->getRevisionByTitle( Title
::newFromText( $name ) );
1284 $this->assertTrue( $revision->isMinor() );
1287 public function testEditRecreate() {
1288 $name = 'Help:' . ucfirst( __FUNCTION__
);
1290 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1292 $this->editPage( $name, 'Some text' );
1294 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1295 $pageObj->doDeleteArticle( 'Bye-bye' );
1297 $this->assertFalse( $pageObj->exists() );
1299 $this->doApiRequestWithToken( [
1302 'text' => 'Different text',
1303 'starttimestamp' => $startTime,
1307 $this->assertTrue( Title
::newFromText( $name )->exists() );
1310 public function testEditWatch() {
1311 $name = 'Help:' . ucfirst( __FUNCTION__
);
1312 $user = self
::$users['sysop']->getUser();
1314 $this->doApiRequestWithToken( [
1317 'text' => 'Some text',
1321 $this->assertTrue( Title
::newFromText( $name )->exists() );
1322 $this->assertTrue( $user->isWatched( Title
::newFromText( $name ) ) );
1325 public function testEditUnwatch() {
1326 $name = 'Help:' . ucfirst( __FUNCTION__
);
1327 $user = self
::$users['sysop']->getUser();
1328 $titleObj = Title
::newFromText( $name );
1330 $user->addWatch( $titleObj );
1332 $this->assertFalse( $titleObj->exists() );
1333 $this->assertTrue( $user->isWatched( $titleObj ) );
1335 $this->doApiRequestWithToken( [
1338 'text' => 'Some text',
1342 $this->assertTrue( $titleObj->exists() );
1343 $this->assertFalse( $user->isWatched( $titleObj ) );
1346 public function testEditWithTag() {
1347 $name = 'Help:' . ucfirst( __FUNCTION__
);
1349 ChangeTags
::defineTag( 'custom tag' );
1351 $revId = $this->doApiRequestWithToken( [
1354 'text' => 'Some text',
1355 'tags' => 'custom tag',
1356 ] )[0]['edit']['newrevid'];
1358 $dbw = wfGetDB( DB_MASTER
);
1359 $this->assertSame( 'custom tag', $dbw->selectField(
1360 'change_tag', 'ct_tag', [ 'ct_rev_id' => $revId ], __METHOD__
) );
1363 public function testEditWithoutTagPermission() {
1364 $name = 'Help:' . ucfirst( __FUNCTION__
);
1366 $this->setExpectedException( ApiUsageException
::class,
1367 'You do not have permission to apply change tags along with your changes.' );
1369 $this->assertFalse( Title
::newFromText( $name )->exists() );
1371 ChangeTags
::defineTag( 'custom tag' );
1372 $this->setMwGlobals( 'wgRevokePermissions',
1373 [ 'user' => [ 'applychangetags' => true ] ] );
1375 $this->doApiRequestWithToken( [
1378 'text' => 'Some text',
1379 'tags' => 'custom tag',
1382 $this->assertFalse( Title
::newFromText( $name )->exists() );
1386 public function testEditAbortedByHook() {
1387 $name = 'Help:' . ucfirst( __FUNCTION__
);
1389 $this->setExpectedException( ApiUsageException
::class,
1390 'The modification you tried to make was aborted by an extension.' );
1392 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1393 'hook-APIEditBeforeSave-closure)' );
1395 $this->setTemporaryHook( 'APIEditBeforeSave',
1402 $this->doApiRequestWithToken( [
1405 'text' => 'Some text',
1408 $this->assertFalse( Title
::newFromText( $name )->exists() );
1412 public function testEditAbortedByHookWithCustomOutput() {
1413 $name = 'Help:' . ucfirst( __FUNCTION__
);
1415 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1416 'hook-APIEditBeforeSave-closure)' );
1418 $this->setTemporaryHook( 'APIEditBeforeSave',
1419 function ( $unused1, $unused2, &$r ) {
1420 $r['msg'] = 'Some message';
1424 $result = $this->doApiRequestWithToken( [
1427 'text' => 'Some text',
1429 Wikimedia\restoreWarnings
();
1431 $this->assertSame( [ 'msg' => 'Some message', 'result' => 'Failure' ],
1432 $result[0]['edit'] );
1434 $this->assertFalse( Title
::newFromText( $name )->exists() );
1437 public function testEditAbortedByEditPageHookWithResult() {
1438 $name = 'Help:' . ucfirst( __FUNCTION__
);
1440 $this->setTemporaryHook( 'EditFilterMergedContent',
1441 function ( $unused1, $unused2, Status
$status ) {
1442 $status->apiHookResult
= [ 'msg' => 'A message for you!' ];
1446 $res = $this->doApiRequestWithToken( [
1449 'text' => 'Some text',
1452 $this->assertFalse( Title
::newFromText( $name )->exists() );
1453 $this->assertSame( [ 'edit' => [ 'msg' => 'A message for you!',
1454 'result' => 'Failure' ] ], $res[0] );
1457 public function testEditAbortedByEditPageHookWithNoResult() {
1458 $name = 'Help:' . ucfirst( __FUNCTION__
);
1460 $this->setExpectedException( ApiUsageException
::class,
1461 'The modification you tried to make was aborted by an extension.' );
1463 $this->setTemporaryHook( 'EditFilterMergedContent',
1470 $this->doApiRequestWithToken( [
1473 'text' => 'Some text',
1476 $this->assertFalse( Title
::newFromText( $name )->exists() );
1480 public function testEditWhileBlocked() {
1481 $name = 'Help:' . ucfirst( __FUNCTION__
);
1483 $this->setExpectedException( ApiUsageException
::class,
1484 'You have been blocked from editing.' );
1486 $block = new Block( [
1487 'address' => self
::$users['sysop']->getUser()->getName(),
1488 'by' => self
::$users['sysop']->getUser()->getId(),
1489 'reason' => 'Capriciousness',
1490 'timestamp' => '19370101000000',
1491 'expiry' => 'infinity',
1496 $this->doApiRequestWithToken( [
1499 'text' => 'Some text',
1503 self
::$users['sysop']->getUser()->clearInstanceCache();
1507 public function testEditWhileReadOnly() {
1508 $name = 'Help:' . ucfirst( __FUNCTION__
);
1510 $this->setExpectedException( ApiUsageException
::class,
1511 'The wiki is currently in read-only mode.' );
1513 $svc = \MediaWiki\MediaWikiServices
::getInstance()->getReadOnlyMode();
1514 $svc->setReason( "Read-only for testing" );
1517 $this->doApiRequestWithToken( [
1520 'text' => 'Some text',
1523 $svc->setReason( false );
1527 public function testCreateImageRedirectAnon() {
1528 $name = 'File:' . ucfirst( __FUNCTION__
);
1530 $this->setExpectedException( ApiUsageException
::class,
1531 "Anonymous users can't create image redirects." );
1533 $this->doApiRequestWithToken( [
1536 'text' => '#REDIRECT [[File:Other file.png]]',
1537 ], null, new User() );
1540 public function testCreateImageRedirectLoggedIn() {
1541 $name = 'File:' . ucfirst( __FUNCTION__
);
1543 $this->setExpectedException( ApiUsageException
::class,
1544 "You don't have permission to create image redirects." );
1546 $this->setMwGlobals( 'wgRevokePermissions',
1547 [ 'user' => [ 'upload' => true ] ] );
1549 $this->doApiRequestWithToken( [
1552 'text' => '#REDIRECT [[File:Other file.png]]',
1556 public function testTooBigEdit() {
1557 $name = 'Help:' . ucfirst( __FUNCTION__
);
1559 $this->setExpectedException( ApiUsageException
::class,
1560 'The content you supplied exceeds the article size limit of 1 kilobyte.' );
1562 $this->setMwGlobals( 'wgMaxArticleSize', 1 );
1564 $text = str_repeat( '!', 1025 );
1566 $this->doApiRequestWithToken( [
1573 public function testProhibitedAnonymousEdit() {
1574 $name = 'Help:' . ucfirst( __FUNCTION__
);
1576 $this->setExpectedException( ApiUsageException
::class,
1577 'The action you have requested is limited to users in the group: ' );
1579 $this->setMwGlobals( 'wgRevokePermissions', [ '*' => [ 'edit' => true ] ] );
1581 $this->doApiRequestWithToken( [
1584 'text' => 'Some text',
1585 ], null, new User() );
1588 public function testProhibitedChangeContentModel() {
1589 $name = 'Help:' . ucfirst( __FUNCTION__
);
1591 $this->setExpectedException( ApiUsageException
::class,
1592 "You don't have permission to change the content model of a page." );
1594 $this->setMwGlobals( 'wgRevokePermissions',
1595 [ 'user' => [ 'editcontentmodel' => true ] ] );
1597 $this->doApiRequestWithToken( [
1600 'text' => 'Some text',
1601 'contentmodel' => 'json',