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',
38 public function testEdit() {
39 $name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
41 // -- test new page --------------------------------------------
42 $apiResult = $this->doApiRequestWithToken( [
45 'text' => 'some text',
47 $apiResult = $apiResult[0];
49 // Validate API result data
50 $this->assertArrayHasKey( 'edit', $apiResult );
51 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
52 $this->assertSame( 'Success', $apiResult['edit']['result'] );
54 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
55 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
57 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
59 // -- test existing page, no change ----------------------------
60 $data = $this->doApiRequestWithToken( [
63 'text' => 'some text',
66 $this->assertSame( 'Success', $data[0]['edit']['result'] );
68 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
69 $this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
71 // -- test existing page, with change --------------------------
72 $data = $this->doApiRequestWithToken( [
75 'text' => 'different text'
78 $this->assertSame( 'Success', $data[0]['edit']['result'] );
80 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
81 $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
83 $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
84 $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
85 $this->assertNotEquals(
86 $data[0]['edit']['newrevid'],
87 $data[0]['edit']['oldrevid'],
88 "revision id should change after edit"
95 public static function provideEditAppend() {
98 'foo', 'append', 'bar', "foobar"
101 'foo', 'prepend', 'bar', "barfoo"
103 [ # 2: append to empty page
104 '', 'append', 'foo', "foo"
106 [ # 3: prepend to empty page
107 '', 'prepend', 'foo', "foo"
109 [ # 4: append to non-existing page
110 null, 'append', 'foo', "foo"
112 [ # 5: prepend to non-existing page
113 null, 'prepend', 'foo', "foo"
119 * @dataProvider provideEditAppend
121 public function testEditAppend( $text, $op, $append, $expected ) {
125 // assume NS_HELP defaults to wikitext
126 $name = "Help:ApiEditPageTest_testEditAppend_$count";
128 // -- create page (or not) -----------------------------------------
129 if ( $text !== null ) {
130 list( $re ) = $this->doApiRequestWithToken( [
133 'text' => $text, ] );
135 $this->assertSame( 'Success', $re['edit']['result'] ); // sanity
138 // -- try append/prepend --------------------------------------------
139 list( $re ) = $this->doApiRequestWithToken( [
142 $op . 'text' => $append, ] );
144 $this->assertSame( 'Success', $re['edit']['result'] );
146 // -- validate -----------------------------------------------------
147 $page = new WikiPage( Title
::newFromText( $name ) );
148 $content = $page->getContent();
149 $this->assertNotNull( $content, 'Page should have been created' );
151 $text = $content->getNativeData();
153 $this->assertSame( $expected, $text );
157 * Test editing of sections
159 public function testEditSection() {
160 $name = 'Help:ApiEditPageTest_testEditSection';
161 $page = WikiPage
::factory( Title
::newFromText( $name ) );
162 $text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
163 // Preload the page with some text
164 $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ), 'summary' );
166 list( $re ) = $this->doApiRequestWithToken( [
170 'text' => "==section 1==\nnew content 1",
172 $this->assertSame( 'Success', $re['edit']['result'] );
173 $newtext = WikiPage
::factory( Title
::newFromText( $name ) )
174 ->getContent( Revision
::RAW
)
176 $this->assertSame( "==section 1==\nnew content 1\n\n==section 2==\ncontent2", $newtext );
178 // Test that we raise a 'nosuchsection' error
180 $this->doApiRequestWithToken( [
186 $this->fail( "Should have raised an ApiUsageException" );
187 } catch ( ApiUsageException
$e ) {
188 $this->assertTrue( self
::apiExceptionHasCode( $e, 'nosuchsection' ) );
193 * Test action=edit§ion=new
194 * Run it twice so we test adding a new section on a
195 * page that doesn't exist (T54830) and one that
198 public function testEditNewSection() {
199 $name = 'Help:ApiEditPageTest_testEditNewSection';
201 // Test on a page that does not already exist
202 $this->assertFalse( Title
::newFromText( $name )->exists() );
203 list( $re ) = $this->doApiRequestWithToken( [
208 'summary' => 'header',
211 $this->assertSame( 'Success', $re['edit']['result'] );
212 // Check the page text is correct
213 $text = WikiPage
::factory( Title
::newFromText( $name ) )
214 ->getContent( Revision
::RAW
)
216 $this->assertSame( "== header ==\n\ntest", $text );
218 // Now on one that does
219 $this->assertTrue( Title
::newFromText( $name )->exists() );
220 list( $re2 ) = $this->doApiRequestWithToken( [
225 'summary' => 'header',
228 $this->assertSame( 'Success', $re2['edit']['result'] );
229 $text = WikiPage
::factory( Title
::newFromText( $name ) )
230 ->getContent( Revision
::RAW
)
232 $this->assertSame( "== header ==\n\ntest\n\n== header ==\n\ntest", $text );
236 * Ensure we can edit through a redirect, if adding a section
238 public function testEdit_redirect() {
242 // assume NS_HELP defaults to wikitext
243 $name = "Help:ApiEditPageTest_testEdit_redirect_$count";
244 $title = Title
::newFromText( $name );
245 $page = WikiPage
::factory( $title );
247 $rname = "Help:ApiEditPageTest_testEdit_redirect_r$count";
248 $rtitle = Title
::newFromText( $rname );
249 $rpage = WikiPage
::factory( $rtitle );
251 // base edit for content
252 $page->doEditContent( new WikitextContent( "Foo" ),
253 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
254 $this->forceRevisionDate( $page, '20120101000000' );
255 $baseTime = $page->getRevision()->getTimestamp();
257 // base edit for redirect
258 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
259 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
260 $this->forceRevisionDate( $rpage, '20120101000000' );
262 // conflicting edit to redirect
263 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
264 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
265 $this->forceRevisionDate( $rpage, '20120101020202' );
267 // try to save edit, following the redirect
268 list( $re, , ) = $this->doApiRequestWithToken( [
271 'text' => 'nix bar!',
272 'basetimestamp' => $baseTime,
277 $this->assertSame( 'Success', $re['edit']['result'],
278 "no problems expected when following redirect" );
282 * Ensure we cannot edit through a redirect, if attempting to overwrite content
284 public function testEdit_redirectText() {
288 // assume NS_HELP defaults to wikitext
289 $name = "Help:ApiEditPageTest_testEdit_redirectText_$count";
290 $title = Title
::newFromText( $name );
291 $page = WikiPage
::factory( $title );
293 $rname = "Help:ApiEditPageTest_testEdit_redirectText_r$count";
294 $rtitle = Title
::newFromText( $rname );
295 $rpage = WikiPage
::factory( $rtitle );
297 // base edit for content
298 $page->doEditContent( new WikitextContent( "Foo" ),
299 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
300 $this->forceRevisionDate( $page, '20120101000000' );
301 $baseTime = $page->getRevision()->getTimestamp();
303 // base edit for redirect
304 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
305 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
306 $this->forceRevisionDate( $rpage, '20120101000000' );
308 // conflicting edit to redirect
309 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
310 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
311 $this->forceRevisionDate( $rpage, '20120101020202' );
313 // try to save edit, following the redirect but without creating a section
315 $this->doApiRequestWithToken( [
318 'text' => 'nix bar!',
319 'basetimestamp' => $baseTime,
323 $this->fail( 'redirect-appendonly error expected' );
324 } catch ( ApiUsageException
$ex ) {
325 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'redirect-appendonly' ) );
329 public function testEditConflict() {
333 // assume NS_HELP defaults to wikitext
334 $name = "Help:ApiEditPageTest_testEditConflict_$count";
335 $title = Title
::newFromText( $name );
337 $page = WikiPage
::factory( $title );
340 $page->doEditContent( new WikitextContent( "Foo" ),
341 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
342 $this->forceRevisionDate( $page, '20120101000000' );
343 $baseTime = $page->getRevision()->getTimestamp();
346 $page->doEditContent( new WikitextContent( "Foo bar" ),
347 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
348 $this->forceRevisionDate( $page, '20120101020202' );
350 // try to save edit, expect conflict
352 $this->doApiRequestWithToken( [
355 'text' => 'nix bar!',
356 'basetimestamp' => $baseTime,
359 $this->fail( 'edit conflict expected' );
360 } catch ( ApiUsageException
$ex ) {
361 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'editconflict' ) );
366 * Ensure that editing using section=new will prevent simple conflicts
368 public function testEditConflict_newSection() {
372 // assume NS_HELP defaults to wikitext
373 $name = "Help:ApiEditPageTest_testEditConflict_newSection_$count";
374 $title = Title
::newFromText( $name );
376 $page = WikiPage
::factory( $title );
379 $page->doEditContent( new WikitextContent( "Foo" ),
380 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
381 $this->forceRevisionDate( $page, '20120101000000' );
382 $baseTime = $page->getRevision()->getTimestamp();
385 $page->doEditContent( new WikitextContent( "Foo bar" ),
386 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
387 $this->forceRevisionDate( $page, '20120101020202' );
389 // try to save edit, expect no conflict
390 list( $re, , ) = $this->doApiRequestWithToken( [
393 'text' => 'nix bar!',
394 'basetimestamp' => $baseTime,
398 $this->assertSame( 'Success', $re['edit']['result'],
399 "no edit conflict expected here" );
402 public function testEditConflict_bug41990() {
407 * T43990: if the target page has a newer revision than the redirect, then editing the
408 * redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
409 * caused an edit conflict to be detected.
412 // assume NS_HELP defaults to wikitext
413 $name = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_$count";
414 $title = Title
::newFromText( $name );
415 $page = WikiPage
::factory( $title );
417 $rname = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_r$count";
418 $rtitle = Title
::newFromText( $rname );
419 $rpage = WikiPage
::factory( $rtitle );
421 // base edit for content
422 $page->doEditContent( new WikitextContent( "Foo" ),
423 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
424 $this->forceRevisionDate( $page, '20120101000000' );
426 // base edit for redirect
427 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
428 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
429 $this->forceRevisionDate( $rpage, '20120101000000' );
431 // new edit to content
432 $page->doEditContent( new WikitextContent( "Foo bar" ),
433 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
434 $this->forceRevisionDate( $rpage, '20120101020202' );
436 // try to save edit; should work, following the redirect.
437 list( $re, , ) = $this->doApiRequestWithToken( [
440 'text' => 'nix bar!',
445 $this->assertSame( 'Success', $re['edit']['result'],
446 "no edit conflict expected here" );
450 * @param WikiPage $page
451 * @param string|int $timestamp
453 protected function forceRevisionDate( WikiPage
$page, $timestamp ) {
454 $dbw = wfGetDB( DB_MASTER
);
456 $dbw->update( 'revision',
457 [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ],
458 [ 'rev_id' => $page->getLatest() ] );
463 public function testCheckDirectApiEditingDisallowed_forNonTextContent() {
464 $this->setExpectedException(
465 ApiUsageException
::class,
466 'Direct editing via API is not supported for content model ' .
467 'testing used by Dummy:ApiEditPageTest_nonTextPageEdit'
470 $this->doApiRequestWithToken( [
472 'title' => 'Dummy:ApiEditPageTest_nonTextPageEdit',
473 'text' => '{"animals":["kittens!"]}'
477 public function testSupportsDirectApiEditing_withContentHandlerOverride() {
478 $name = 'DummyNonText:ApiEditPageTest_testNonTextEdit';
479 $data = serialize( 'some bla bla text' );
481 $result = $this->doApiRequestWithToken( [
487 $apiResult = $result[0];
489 // Validate API result data
490 $this->assertArrayHasKey( 'edit', $apiResult );
491 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
492 $this->assertSame( 'Success', $apiResult['edit']['result'] );
494 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
495 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
497 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
499 // validate resulting revision
500 $page = WikiPage
::factory( Title
::newFromText( $name ) );
501 $this->assertSame( "testing-nontext", $page->getContentModel() );
502 $this->assertSame( $data, $page->getContent()->serialize() );
506 * This test verifies that after changing the content model
507 * of a page, undoing that edit via the API will also
508 * undo the content model change.
510 public function testUndoAfterContentModelChange() {
511 $name = 'Help:' . __FUNCTION__
;
512 $uploader = self
::$users['uploader']->getUser();
513 $sysop = self
::$users['sysop']->getUser();
515 $apiResult = $this->doApiRequestWithToken( [
518 'text' => 'some text',
519 ], null, $sysop )[0];
522 $this->assertArrayHasKey( 'edit', $apiResult );
523 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
524 $this->assertSame( 'Success', $apiResult['edit']['result'] );
525 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
526 // Content model is wikitext
527 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
529 // Convert the page to JSON
530 $apiResult = $this->doApiRequestWithToken( [
534 'contentmodel' => 'json',
535 ], null, $uploader )[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 $this->assertSame( 'json', $apiResult['edit']['contentmodel'] );
544 $apiResult = $this->doApiRequestWithToken( [
547 'undo' => $apiResult['edit']['newrevid']
548 ], null, $sysop )[0];
551 $this->assertArrayHasKey( 'edit', $apiResult );
552 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
553 $this->assertSame( 'Success', $apiResult['edit']['result'] );
554 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
555 // Check that the contentmodel is back to wikitext now.
556 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
559 // The tests below are mostly not commented because they do exactly what
560 // you'd expect from the name.
562 public function testCorrectContentFormat() {
563 $name = 'Help:' . ucfirst( __FUNCTION__
);
565 $this->doApiRequestWithToken( [
568 'text' => 'some text',
569 'contentmodel' => 'wikitext',
570 'contentformat' => 'text/x-wiki',
573 $this->assertTrue( Title
::newFromText( $name )->exists() );
576 public function testUnsupportedContentFormat() {
577 $name = 'Help:' . ucfirst( __FUNCTION__
);
579 $this->setExpectedException( ApiUsageException
::class,
580 'Unrecognized value for parameter "contentformat": nonexistent format.' );
583 $this->doApiRequestWithToken( [
586 'text' => 'some text',
587 'contentformat' => 'nonexistent format',
590 $this->assertFalse( Title
::newFromText( $name )->exists() );
594 public function testMismatchedContentFormat() {
595 $name = 'Help:' . ucfirst( __FUNCTION__
);
597 $this->setExpectedException( ApiUsageException
::class,
598 'The requested format text/plain is not supported for content ' .
599 "model wikitext used by $name." );
602 $this->doApiRequestWithToken( [
605 'text' => 'some text',
606 'contentmodel' => 'wikitext',
607 'contentformat' => 'text/plain',
610 $this->assertFalse( Title
::newFromText( $name )->exists() );
614 public function testUndoToInvalidRev() {
615 $name = 'Help:' . ucfirst( __FUNCTION__
);
617 $revId = $this->editPage( $name, 'Some text' )->value
['revision']
621 $this->setExpectedException( ApiUsageException
::class,
622 "There is no revision with ID $revId." );
624 $this->doApiRequestWithToken( [
632 * Tests what happens if the undo parameter is a valid revision, but
633 * the undoafter parameter doesn't refer to a revision that exists in the
636 public function testUndoAfterToInvalidRev() {
637 // We can't just pick a large number for undoafter (as in
638 // testUndoToInvalidRev above), because then MediaWiki will helpfully
639 // assume we switched around undo and undoafter and we'll test the code
640 // path for undo being invalid, not undoafter. So instead we delete
641 // the revision from the database. In real life this case could come
642 // up if a revision number was skipped, e.g., if two transactions try
643 // to insert new revision rows at once and the first one to succeed
645 $name = 'Help:' . ucfirst( __FUNCTION__
);
646 $titleObj = Title
::newFromText( $name );
648 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
649 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
650 $revId3 = $this->editPage( $name, '3' )->value
['revision']->getId();
652 // Make the middle revision disappear
653 $dbw = wfGetDB( DB_MASTER
);
654 $dbw->delete( 'revision', [ 'rev_id' => $revId2 ], __METHOD__
);
655 $dbw->update( 'revision', [ 'rev_parent_id' => $revId1 ],
656 [ 'rev_id' => $revId3 ], __METHOD__
);
658 $this->setExpectedException( ApiUsageException
::class,
659 "There is no revision with ID $revId2." );
661 $this->doApiRequestWithToken( [
665 'undoafter' => $revId2,
670 * Tests what happens if the undo parameter is a valid revision, but
671 * undoafter is hidden (rev_deleted).
673 public function testUndoAfterToHiddenRev() {
674 $name = 'Help:' . ucfirst( __FUNCTION__
);
675 $titleObj = Title
::newFromText( $name );
677 $this->editPage( $name, '0' );
679 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
681 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
683 // Hide the middle revision
684 $list = RevisionDeleter
::createList( 'revision',
685 RequestContext
::getMain(), $titleObj, [ $revId1 ] );
686 $list->setVisibility( [
687 'value' => [ Revision
::DELETED_TEXT
=> 1 ],
688 'comment' => 'Bye-bye',
691 $this->setExpectedException( ApiUsageException
::class,
692 "There is no revision with ID $revId1." );
694 $this->doApiRequestWithToken( [
698 'undoafter' => $revId1,
703 * Test undo when a revision with a higher id has an earlier timestamp.
704 * This can happen if importing an old revision.
706 public function testUndoWithSwappedRevisions() {
707 $name = 'Help:' . ucfirst( __FUNCTION__
);
708 $titleObj = Title
::newFromText( $name );
710 $this->editPage( $name, '0' );
712 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
714 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
716 // Now monkey with the timestamp
717 $dbw = wfGetDB( DB_MASTER
);
720 [ 'rev_timestamp' => $dbw->timestamp( time() - 86400 ) ],
721 [ 'rev_id' => $revId1 ],
725 $this->doApiRequestWithToken( [
729 'undoafter' => $revId1,
732 $text = ( new WikiPage( $titleObj ) )->getContent()->getNativeData();
734 // This is wrong! It should be 1. But let's test for our incorrect
735 // behavior for now, so if someone fixes it they'll fix the test as
736 // well to expect 1. If we disabled the test, it might stay disabled
737 // even once the bug is fixed, which would be a shame.
738 $this->assertSame( '2', $text );
741 public function testUndoWithConflicts() {
742 $name = 'Help:' . ucfirst( __FUNCTION__
);
744 $this->setExpectedException( ApiUsageException
::class,
745 'The edit could not be undone due to conflicting intermediate edits.' );
747 $this->editPage( $name, '1' );
749 $revId = $this->editPage( $name, '2' )->value
['revision']->getId();
751 $this->editPage( $name, '3' );
753 $this->doApiRequestWithToken( [
759 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
761 $this->assertSame( '3', $text );
765 * undoafter is supposed to be less than undo. If not, we reverse their
766 * meaning, so that the two are effectively interchangeable.
768 public function testReversedUndoAfter() {
769 $name = 'Help:' . ucfirst( __FUNCTION__
);
771 $this->editPage( $name, '0' );
772 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
773 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
775 $this->doApiRequestWithToken( [
779 'undoafter' => $revId2,
782 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
784 $this->assertSame( '1', $text );
787 public function testUndoToRevFromDifferentPage() {
788 $name = 'Help:' . ucfirst( __FUNCTION__
);
790 $this->editPage( "$name-1", 'Some text' );
791 $revId = $this->editPage( "$name-1", 'Some more text' )
792 ->value
['revision']->getId();
794 $this->editPage( "$name-2", 'Some text' );
796 $this->setExpectedException( ApiUsageException
::class,
797 "r$revId is not a revision of $name-2." );
799 $this->doApiRequestWithToken( [
801 'title' => "$name-2",
806 public function testUndoAfterToRevFromDifferentPage() {
807 $name = 'Help:' . ucfirst( __FUNCTION__
);
809 $revId1 = $this->editPage( "$name-1", 'Some text' )
810 ->value
['revision']->getId();
812 $revId2 = $this->editPage( "$name-2", 'Some text' )
813 ->value
['revision']->getId();
815 $this->setExpectedException( ApiUsageException
::class,
816 "r$revId1 is not a revision of $name-2." );
818 $this->doApiRequestWithToken( [
820 'title' => "$name-2",
822 'undoafter' => $revId1,
826 public function testMd5Text() {
827 $name = 'Help:' . ucfirst( __FUNCTION__
);
829 $this->assertFalse( Title
::newFromText( $name )->exists() );
831 $this->doApiRequestWithToken( [
834 'text' => 'Some text',
835 'md5' => md5( 'Some text' ),
838 $this->assertTrue( Title
::newFromText( $name )->exists() );
841 public function testMd5PrependText() {
842 $name = 'Help:' . ucfirst( __FUNCTION__
);
844 $this->editPage( $name, 'Some text' );
846 $this->doApiRequestWithToken( [
849 'prependtext' => 'Alert: ',
850 'md5' => md5( 'Alert: ' ),
853 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
854 ->getContent()->getNativeData();
855 $this->assertSame( 'Alert: Some text', $text );
858 public function testMd5AppendText() {
859 $name = 'Help:' . ucfirst( __FUNCTION__
);
861 $this->editPage( $name, 'Some text' );
863 $this->doApiRequestWithToken( [
866 'appendtext' => ' is nice',
867 'md5' => md5( ' is nice' ),
870 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
871 ->getContent()->getNativeData();
872 $this->assertSame( 'Some text is nice', $text );
875 public function testMd5PrependAndAppendText() {
876 $name = 'Help:' . ucfirst( __FUNCTION__
);
878 $this->editPage( $name, 'Some text' );
880 $this->doApiRequestWithToken( [
883 'prependtext' => 'Alert: ',
884 'appendtext' => ' is nice',
885 'md5' => md5( 'Alert: is nice' ),
888 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
889 ->getContent()->getNativeData();
890 $this->assertSame( 'Alert: Some text is nice', $text );
893 public function testIncorrectMd5Text() {
894 $name = 'Help:' . ucfirst( __FUNCTION__
);
896 $this->setExpectedException( ApiUsageException
::class,
897 'The supplied MD5 hash was incorrect.' );
899 $this->doApiRequestWithToken( [
902 'text' => 'Some text',
907 public function testIncorrectMd5PrependText() {
908 $name = 'Help:' . ucfirst( __FUNCTION__
);
910 $this->setExpectedException( ApiUsageException
::class,
911 'The supplied MD5 hash was incorrect.' );
913 $this->doApiRequestWithToken( [
916 'prependtext' => 'Some ',
917 'appendtext' => 'text',
918 'md5' => md5( 'Some ' ),
922 public function testIncorrectMd5AppendText() {
923 $name = 'Help:' . ucfirst( __FUNCTION__
);
925 $this->setExpectedException( ApiUsageException
::class,
926 'The supplied MD5 hash was incorrect.' );
928 $this->doApiRequestWithToken( [
931 'prependtext' => 'Some ',
932 'appendtext' => 'text',
933 'md5' => md5( 'text' ),
937 public function testCreateOnly() {
938 $name = 'Help:' . ucfirst( __FUNCTION__
);
940 $this->setExpectedException( ApiUsageException
::class,
941 'The article you tried to create has been created already.' );
943 $this->editPage( $name, 'Some text' );
944 $this->assertTrue( Title
::newFromText( $name )->exists() );
947 $this->doApiRequestWithToken( [
950 'text' => 'Some more text',
954 // Validate that content was not changed
955 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
956 ->getContent()->getNativeData();
958 $this->assertSame( 'Some text', $text );
962 public function testNoCreate() {
963 $name = 'Help:' . ucfirst( __FUNCTION__
);
965 $this->setExpectedException( ApiUsageException
::class,
966 "The page you specified doesn't exist." );
968 $this->assertFalse( Title
::newFromText( $name )->exists() );
971 $this->doApiRequestWithToken( [
974 'text' => 'Some text',
978 $this->assertFalse( Title
::newFromText( $name )->exists() );
983 * Appending/prepending is currently only supported for TextContent. We
984 * test this right now, and when support is added this test should be
985 * replaced by tests that the support is correct.
987 public function testAppendWithNonTextContentHandler() {
988 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
990 $this->setExpectedException( ApiUsageException
::class,
991 "Can't append to pages using content model testing-nontext." );
993 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
994 function ( Title
$title, &$model ) use ( $name ) {
995 if ( $title->getPrefixedText() === $name ) {
996 $model = 'testing-nontext';
1002 $this->doApiRequestWithToken( [
1005 'appendtext' => 'Some text',
1009 public function testAppendInMediaWikiNamespace() {
1010 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1012 $this->assertFalse( Title
::newFromText( $name )->exists() );
1014 $this->doApiRequestWithToken( [
1017 'appendtext' => 'Some text',
1020 $this->assertTrue( Title
::newFromText( $name )->exists() );
1023 public function testAppendInMediaWikiNamespaceWithSerializationError() {
1024 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1026 $this->setExpectedException( ApiUsageException
::class,
1027 'Content serialization failed: Could not unserialize content' );
1029 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1030 function ( Title
$title, &$model ) use ( $name ) {
1031 if ( $title->getPrefixedText() === $name ) {
1032 $model = 'testing-serialize-error';
1038 $this->doApiRequestWithToken( [
1041 'appendtext' => 'Some text',
1045 public function testAppendNewSection() {
1046 $name = 'Help:' . ucfirst( __FUNCTION__
);
1048 $this->editPage( $name, 'Initial content' );
1050 $this->doApiRequestWithToken( [
1053 'appendtext' => '== New section ==',
1057 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1058 ->getContent()->getNativeData();
1060 $this->assertSame( "Initial content\n\n== New section ==", $text );
1063 public function testAppendNewSectionWithInvalidContentModel() {
1064 $name = 'Help:' . ucfirst( __FUNCTION__
);
1066 $this->setExpectedException( ApiUsageException
::class,
1067 'Sections are not supported for content model text.' );
1069 $this->editPage( $name, 'Initial content' );
1071 $this->doApiRequestWithToken( [
1074 'appendtext' => '== New section ==',
1076 'contentmodel' => 'text',
1080 public function testAppendNewSectionWithTitle() {
1081 $name = 'Help:' . ucfirst( __FUNCTION__
);
1083 $this->editPage( $name, 'Initial content' );
1085 $this->doApiRequestWithToken( [
1088 'sectiontitle' => 'My section',
1089 'appendtext' => 'More content',
1093 $page = new WikiPage( Title
::newFromText( $name ) );
1095 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1096 $page->getContent()->getNativeData() );
1097 $this->assertSame( '/* My section */ new section',
1098 $page->getRevision()->getComment() );
1101 public function testAppendNewSectionWithSummary() {
1102 $name = 'Help:' . ucfirst( __FUNCTION__
);
1104 $this->editPage( $name, 'Initial content' );
1106 $this->doApiRequestWithToken( [
1109 'appendtext' => 'More content',
1111 'summary' => 'Add new section',
1114 $page = new WikiPage( Title
::newFromText( $name ) );
1116 $this->assertSame( "Initial content\n\n== Add new section ==\n\nMore content",
1117 $page->getContent()->getNativeData() );
1118 // EditPage actually assumes the summary is the section name here
1119 $this->assertSame( '/* Add new section */ new section',
1120 $page->getRevision()->getComment() );
1123 public function testAppendNewSectionWithTitleAndSummary() {
1124 $name = 'Help:' . ucfirst( __FUNCTION__
);
1126 $this->editPage( $name, 'Initial content' );
1128 $this->doApiRequestWithToken( [
1131 'sectiontitle' => 'My section',
1132 'appendtext' => 'More content',
1134 'summary' => 'Add new section',
1137 $page = new WikiPage( Title
::newFromText( $name ) );
1139 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1140 $page->getContent()->getNativeData() );
1141 $this->assertSame( 'Add new section',
1142 $page->getRevision()->getComment() );
1145 public function testAppendToSection() {
1146 $name = 'Help:' . ucfirst( __FUNCTION__
);
1148 $this->editPage( $name, "== Section 1 ==\n\nContent\n\n" .
1149 "== Section 2 ==\n\nFascinating!" );
1151 $this->doApiRequestWithToken( [
1154 'appendtext' => ' and more content',
1158 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1159 ->getContent()->getNativeData();
1161 $this->assertSame( "== Section 1 ==\n\nContent and more content\n\n" .
1162 "== Section 2 ==\n\nFascinating!", $text );
1165 public function testAppendToFirstSection() {
1166 $name = 'Help:' . ucfirst( __FUNCTION__
);
1168 $this->editPage( $name, "Content\n\n== Section 1 ==\n\nFascinating!" );
1170 $this->doApiRequestWithToken( [
1173 'appendtext' => ' and more content',
1177 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1178 ->getContent()->getNativeData();
1180 $this->assertSame( "Content and more content\n\n== Section 1 ==\n\n" .
1181 "Fascinating!", $text );
1184 public function testAppendToNonexistentSection() {
1185 $name = 'Help:' . ucfirst( __FUNCTION__
);
1187 $this->setExpectedException( ApiUsageException
::class, 'There is no section 1.' );
1189 $this->editPage( $name, 'Content' );
1192 $this->doApiRequestWithToken( [
1195 'appendtext' => ' and more content',
1199 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1200 ->getContent()->getNativeData();
1202 $this->assertSame( 'Content', $text );
1206 public function testEditMalformedSection() {
1207 $name = 'Help:' . ucfirst( __FUNCTION__
);
1209 $this->setExpectedException( ApiUsageException
::class,
1210 'The "section" parameter must be a valid section ID or "new".' );
1211 $this->editPage( $name, 'Content' );
1214 $this->doApiRequestWithToken( [
1217 'text' => 'Different content',
1218 'section' => 'It is unlikely that this is valid',
1221 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1222 ->getContent()->getNativeData();
1224 $this->assertSame( 'Content', $text );
1228 public function testEditWithStartTimestamp() {
1229 $name = 'Help:' . ucfirst( __FUNCTION__
);
1230 $this->setExpectedException( ApiUsageException
::class,
1231 'The page has been deleted since you fetched its timestamp.' );
1233 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1235 $this->editPage( $name, 'Some text' );
1237 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1238 $pageObj->doDeleteArticle( 'Bye-bye' );
1240 $this->assertFalse( $pageObj->exists() );
1243 $this->doApiRequestWithToken( [
1246 'text' => 'Different text',
1247 'starttimestamp' => $startTime,
1250 $this->assertFalse( $pageObj->exists() );
1254 public function testEditMinor() {
1255 $name = 'Help:' . ucfirst( __FUNCTION__
);
1257 $this->editPage( $name, 'Some text' );
1259 $this->doApiRequestWithToken( [
1262 'text' => 'Different text',
1266 $revisionStore = \MediaWiki\MediaWikiServices
::getInstance()->getRevisionStore();
1267 $revision = $revisionStore->getRevisionByTitle( Title
::newFromText( $name ) );
1268 $this->assertTrue( $revision->isMinor() );
1271 public function testEditRecreate() {
1272 $name = 'Help:' . ucfirst( __FUNCTION__
);
1274 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1276 $this->editPage( $name, 'Some text' );
1278 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1279 $pageObj->doDeleteArticle( 'Bye-bye' );
1281 $this->assertFalse( $pageObj->exists() );
1283 $this->doApiRequestWithToken( [
1286 'text' => 'Different text',
1287 'starttimestamp' => $startTime,
1291 $this->assertTrue( Title
::newFromText( $name )->exists() );
1294 public function testEditWatch() {
1295 $name = 'Help:' . ucfirst( __FUNCTION__
);
1296 $user = self
::$users['sysop']->getUser();
1298 $this->doApiRequestWithToken( [
1301 'text' => 'Some text',
1305 $this->assertTrue( Title
::newFromText( $name )->exists() );
1306 $this->assertTrue( $user->isWatched( Title
::newFromText( $name ) ) );
1309 public function testEditUnwatch() {
1310 $name = 'Help:' . ucfirst( __FUNCTION__
);
1311 $user = self
::$users['sysop']->getUser();
1312 $titleObj = Title
::newFromText( $name );
1314 $user->addWatch( $titleObj );
1316 $this->assertFalse( $titleObj->exists() );
1317 $this->assertTrue( $user->isWatched( $titleObj ) );
1319 $this->doApiRequestWithToken( [
1322 'text' => 'Some text',
1326 $this->assertTrue( $titleObj->exists() );
1327 $this->assertFalse( $user->isWatched( $titleObj ) );
1330 public function testEditWithTag() {
1331 $name = 'Help:' . ucfirst( __FUNCTION__
);
1333 ChangeTags
::defineTag( 'custom tag' );
1335 $revId = $this->doApiRequestWithToken( [
1338 'text' => 'Some text',
1339 'tags' => 'custom tag',
1340 ] )[0]['edit']['newrevid'];
1342 $dbw = wfGetDB( DB_MASTER
);
1343 $this->assertSame( 'custom tag', $dbw->selectField(
1344 'change_tag', 'ct_tag', [ 'ct_rev_id' => $revId ], __METHOD__
) );
1347 public function testEditWithoutTagPermission() {
1348 $name = 'Help:' . ucfirst( __FUNCTION__
);
1350 $this->setExpectedException( ApiUsageException
::class,
1351 'You do not have permission to apply change tags along with your changes.' );
1353 $this->assertFalse( Title
::newFromText( $name )->exists() );
1355 ChangeTags
::defineTag( 'custom tag' );
1356 $this->setMwGlobals( 'wgRevokePermissions',
1357 [ 'user' => [ 'applychangetags' => true ] ] );
1359 $this->doApiRequestWithToken( [
1362 'text' => 'Some text',
1363 'tags' => 'custom tag',
1366 $this->assertFalse( Title
::newFromText( $name )->exists() );
1370 public function testEditAbortedByHook() {
1371 $name = 'Help:' . ucfirst( __FUNCTION__
);
1373 $this->setExpectedException( ApiUsageException
::class,
1374 'The modification you tried to make was aborted by an extension.' );
1376 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1377 'hook-APIEditBeforeSave-closure)' );
1379 $this->setTemporaryHook( 'APIEditBeforeSave',
1386 $this->doApiRequestWithToken( [
1389 'text' => 'Some text',
1392 $this->assertFalse( Title
::newFromText( $name )->exists() );
1396 public function testEditAbortedByHookWithCustomOutput() {
1397 $name = 'Help:' . ucfirst( __FUNCTION__
);
1399 $this->hideDeprecated( 'APIEditBeforeSave hook (used in ' .
1400 'hook-APIEditBeforeSave-closure)' );
1402 $this->setTemporaryHook( 'APIEditBeforeSave',
1403 function ( $unused1, $unused2, &$r ) {
1404 $r['msg'] = 'Some message';
1408 $result = $this->doApiRequestWithToken( [
1411 'text' => 'Some text',
1413 Wikimedia\restoreWarnings
();
1415 $this->assertSame( [ 'msg' => 'Some message', 'result' => 'Failure' ],
1416 $result[0]['edit'] );
1418 $this->assertFalse( Title
::newFromText( $name )->exists() );
1421 public function testEditAbortedByEditPageHookWithResult() {
1422 $name = 'Help:' . ucfirst( __FUNCTION__
);
1424 $this->setTemporaryHook( 'EditFilterMergedContent',
1425 function ( $unused1, $unused2, Status
$status ) {
1426 $status->apiHookResult
= [ 'msg' => 'A message for you!' ];
1430 $res = $this->doApiRequestWithToken( [
1433 'text' => 'Some text',
1436 $this->assertFalse( Title
::newFromText( $name )->exists() );
1437 $this->assertSame( [ 'edit' => [ 'msg' => 'A message for you!',
1438 'result' => 'Failure' ] ], $res[0] );
1441 public function testEditAbortedByEditPageHookWithNoResult() {
1442 $name = 'Help:' . ucfirst( __FUNCTION__
);
1444 $this->setExpectedException( ApiUsageException
::class,
1445 'The modification you tried to make was aborted by an extension.' );
1447 $this->setTemporaryHook( 'EditFilterMergedContent',
1454 $this->doApiRequestWithToken( [
1457 'text' => 'Some text',
1460 $this->assertFalse( Title
::newFromText( $name )->exists() );
1464 public function testEditWhileBlocked() {
1465 $name = 'Help:' . ucfirst( __FUNCTION__
);
1467 $this->setExpectedException( ApiUsageException
::class,
1468 'You have been blocked from editing.' );
1470 $block = new Block( [
1471 'address' => self
::$users['sysop']->getUser()->getName(),
1472 'by' => self
::$users['sysop']->getUser()->getId(),
1473 'reason' => 'Capriciousness',
1474 'timestamp' => '19370101000000',
1475 'expiry' => 'infinity',
1480 $this->doApiRequestWithToken( [
1483 'text' => 'Some text',
1487 self
::$users['sysop']->getUser()->clearInstanceCache();
1491 public function testEditWhileReadOnly() {
1492 $name = 'Help:' . ucfirst( __FUNCTION__
);
1494 $this->setExpectedException( ApiUsageException
::class,
1495 'The wiki is currently in read-only mode.' );
1497 $svc = \MediaWiki\MediaWikiServices
::getInstance()->getReadOnlyMode();
1498 $svc->setReason( "Read-only for testing" );
1501 $this->doApiRequestWithToken( [
1504 'text' => 'Some text',
1507 $svc->setReason( false );
1511 public function testCreateImageRedirectAnon() {
1512 $name = 'File:' . ucfirst( __FUNCTION__
);
1514 $this->setExpectedException( ApiUsageException
::class,
1515 "Anonymous users can't create image redirects." );
1517 $this->doApiRequestWithToken( [
1520 'text' => '#REDIRECT [[File:Other file.png]]',
1521 ], null, new User() );
1524 public function testCreateImageRedirectLoggedIn() {
1525 $name = 'File:' . ucfirst( __FUNCTION__
);
1527 $this->setExpectedException( ApiUsageException
::class,
1528 "You don't have permission to create image redirects." );
1530 $this->setMwGlobals( 'wgRevokePermissions',
1531 [ 'user' => [ 'upload' => true ] ] );
1533 $this->doApiRequestWithToken( [
1536 'text' => '#REDIRECT [[File:Other file.png]]',
1540 public function testTooBigEdit() {
1541 $name = 'Help:' . ucfirst( __FUNCTION__
);
1543 $this->setExpectedException( ApiUsageException
::class,
1544 'The content you supplied exceeds the article size limit of 1 kilobyte.' );
1546 $this->setMwGlobals( 'wgMaxArticleSize', 1 );
1548 $text = str_repeat( '!', 1025 );
1550 $this->doApiRequestWithToken( [
1557 public function testProhibitedAnonymousEdit() {
1558 $name = 'Help:' . ucfirst( __FUNCTION__
);
1560 $this->setExpectedException( ApiUsageException
::class,
1561 'The action you have requested is limited to users in the group: ' );
1563 $this->setMwGlobals( 'wgRevokePermissions', [ '*' => [ 'edit' => true ] ] );
1565 $this->doApiRequestWithToken( [
1568 'text' => 'Some text',
1569 ], null, new User() );
1572 public function testProhibitedChangeContentModel() {
1573 $name = 'Help:' . ucfirst( __FUNCTION__
);
1575 $this->setExpectedException( ApiUsageException
::class,
1576 "You don't have permission to change the content model of a page." );
1578 $this->setMwGlobals( 'wgRevokePermissions',
1579 [ 'user' => [ 'editcontentmodel' => true ] ] );
1581 $this->doApiRequestWithToken( [
1584 'text' => 'Some text',
1585 'contentmodel' => 'json',