3 use MediaWiki\Edit\PreparedEdit
;
4 use MediaWiki\MediaWikiServices
;
5 use MediaWiki\Storage\RevisionSlotsUpdate
;
6 use Wikimedia\TestingAccessWrapper
;
11 abstract class WikiPageDbTestBase
extends MediaWikiLangTestCase
{
13 private $pagesToDelete;
15 public function __construct( $name = null, array $data = [], $dataName = '' ) {
16 parent
::__construct( $name, $data, $dataName );
18 $this->tablesUsed
= array_merge(
41 protected function addCoreDBData() {
42 // Blank out. This would fail with a modified schema, and we don't need it.
48 abstract protected function getMcrMigrationStage();
53 abstract protected function getMcrTablesToReset();
55 protected function setUp() {
58 $this->tablesUsed +
= $this->getMcrTablesToReset();
60 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
62 'wgMultiContentRevisionSchemaMigrationStage',
63 $this->getMcrMigrationStage()
65 $this->pagesToDelete
= [];
67 $this->overrideMwServices();
70 protected function tearDown() {
71 foreach ( $this->pagesToDelete
as $p ) {
72 /* @var $p WikiPage */
76 $p->doDeleteArticle( "testing done." );
78 } catch ( MWException
$ex ) {
85 abstract protected function getContentHandlerUseDB();
88 * @param Title|string $title
89 * @param string|null $model
92 private function newPage( $title, $model = null ) {
93 if ( is_string( $title ) ) {
94 $ns = $this->getDefaultWikitextNS();
95 $title = Title
::newFromText( $title, $ns );
98 $p = new WikiPage( $title );
100 $this->pagesToDelete
[] = $p;
106 * @param string|Title|WikiPage $page
107 * @param string $text
108 * @param int|null $model
112 protected function createPage( $page, $text, $model = null, $user = null ) {
113 if ( is_string( $page ) ||
$page instanceof Title
) {
114 $page = $this->newPage( $page, $model );
117 $content = ContentHandler
::makeContent( $text, $page->getTitle(), $model );
118 $page->doEditContent( $content, "testing", EDIT_NEW
, false, $user );
124 * @covers WikiPage::prepareContentForEdit
126 public function testPrepareContentForEdit() {
127 $user = $this->getTestUser()->getUser();
128 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
130 $page = $this->createPage( __METHOD__
, __METHOD__
, null, $user );
131 $title = $page->getTitle();
133 $content = ContentHandler
::makeContent(
134 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
135 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
137 CONTENT_MODEL_WIKITEXT
139 $content2 = ContentHandler
::makeContent(
140 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
141 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
143 CONTENT_MODEL_WIKITEXT
146 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
148 $this->assertInstanceOf(
149 ParserOptions
::class,
153 $this->assertContains( '</a>', $edit->output
->getText(), "output" );
154 $this->assertContains(
155 'consetetur sadipscing elitr',
156 $edit->output
->getText(),
160 $this->assertTrue( $content->equals( $edit->newContent
), "newContent field" );
161 $this->assertTrue( $content->equals( $edit->pstContent
), "pstContent field" );
162 $this->assertSame( $edit->output
, $edit->output
, "output field" );
163 $this->assertSame( $edit->popts
, $edit->popts
, "popts field" );
164 $this->assertSame( null, $edit->revid
, "revid field" );
166 // Re-using the prepared info if possible
167 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
168 $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
169 $this->assertSame( $edit->pstContent
, $sameEdit->pstContent
, 're-use output' );
170 $this->assertSame( $edit->output
, $sameEdit->output
, 're-use output' );
172 // Not re-using the same PreparedEdit if not possible
173 $rev = $page->getRevision();
174 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
175 $this->assertPreparedEditNotEquals( $edit, $edit2 );
176 $this->assertContains( 'At vero eos', $edit2->pstContent
->serialize(), "content" );
178 // Check pre-safe transform
179 $this->assertContains( '[[gubergren]]', $edit2->pstContent
->serialize() );
180 $this->assertNotContains( '~~~~', $edit2->pstContent
->serialize() );
182 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
183 $this->assertPreparedEditNotEquals( $edit2, $edit3 );
185 // TODO: test with passing revision, then same without revision.
189 * @covers WikiPage::doEditUpdates
191 public function testDoEditUpdates() {
192 $user = $this->getTestUser()->getUser();
194 // NOTE: if site stats get out of whack and drop below 0,
195 // that causes a DB error during tear-down. So bump the
196 // numbers high enough to not drop below 0.
197 $siteStatsUpdate = SiteStatsUpdate
::factory(
198 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
200 $siteStatsUpdate->doUpdate();
202 $page = $this->createPage( __METHOD__
, __METHOD__
);
204 $revision = new Revision(
207 'page' => $page->getId(),
208 'title' => $page->getTitle(),
209 'comment' => __METHOD__
,
210 'minor_edit' => true,
211 'text' => __METHOD__
. ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
212 'user' => $user->getId(),
213 'user_text' => $user->getName(),
214 'timestamp' => '20170707040404',
215 'content_model' => CONTENT_MODEL_WIKITEXT
,
216 'content_format' => CONTENT_FORMAT_WIKITEXT
,
220 $page->doEditUpdates( $revision, $user );
222 // TODO: test various options; needs temporary hooks
224 $dbr = wfGetDB( DB_REPLICA
);
225 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
226 $n = $res->numRows();
229 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
233 * @covers WikiPage::doEditContent
234 * @covers WikiPage::prepareContentForEdit
236 public function testDoEditContent() {
237 $this->setMwGlobals( 'wgPageCreationLog', true );
239 $page = $this->newPage( __METHOD__
);
240 $title = $page->getTitle();
242 $user1 = $this->getTestUser()->getUser();
243 // Use the confirmed group for user2 to make sure the user is different
244 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
246 $content = ContentHandler
::makeContent(
247 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
248 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
250 CONTENT_MODEL_WIKITEXT
253 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
255 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW
, false, $user1 );
257 $this->assertTrue( $status->isOK(), 'OK' );
258 $this->assertTrue( $status->value
['new'], 'new' );
259 $this->assertNotNull( $status->value
['revision'], 'revision' );
260 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
261 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
262 $this->assertTrue( $status->value
['revision']->getContent()->equals( $content ), 'equals' );
264 $rev = $page->getRevision();
265 $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
267 $this->assertNotNull( $rev->getRecentChange() );
268 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
270 // make sure that cached ParserOutput gets re-used throughout
271 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
273 $id = $page->getId();
275 // Test page creation logging
278 [ 'log_type', 'log_action' ],
279 [ 'log_page' => $id ],
280 [ [ 'create', 'create' ] ]
283 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
284 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
285 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
286 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
288 # ------------------------
289 $dbr = wfGetDB( DB_REPLICA
);
290 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
291 $n = $res->numRows();
294 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
296 # ------------------------
297 $page = new WikiPage( $title );
299 $retrieved = $page->getContent();
300 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
302 # ------------------------
303 $page = new WikiPage( $title );
305 // try null edit, with a different user
306 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE
, false, $user2 );
307 $this->assertTrue( $status->isOK(), 'OK' );
308 $this->assertFalse( $status->value
['new'], 'new' );
309 $this->assertNull( $status->value
['revision'], 'revision' );
310 $this->assertNotNull( $page->getRevision() );
311 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
313 # ------------------------
314 $content = ContentHandler
::makeContent(
315 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
316 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
318 CONTENT_MODEL_WIKITEXT
321 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE
);
322 $this->assertTrue( $status->isOK(), 'OK' );
323 $this->assertFalse( $status->value
['new'], 'new' );
324 $this->assertNotNull( $status->value
['revision'], 'revision' );
325 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
326 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
328 $status->value
['revision']->getContent()->equals( $content ),
329 'not equals (PST must substitute signature)'
332 $rev = $page->getRevision();
333 $this->assertNotNull( $rev->getRecentChange() );
334 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
336 # ------------------------
337 $page = new WikiPage( $title );
339 $retrieved = $page->getContent();
340 $newText = $retrieved->serialize();
341 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
342 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
344 # ------------------------
345 $dbr = wfGetDB( DB_REPLICA
);
346 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
347 $n = $res->numRows();
350 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
354 * @covers WikiPage::doEditContent
356 public function testDoEditContent_twice() {
357 $title = Title
::newFromText( __METHOD__
);
358 $page = WikiPage
::factory( $title );
359 $content = ContentHandler
::makeContent( '$1 van $2', $title );
361 // Make sure we can do the exact same save twice.
362 // This tests checks that internal caches are reset as appropriate.
363 $status1 = $page->doEditContent( $content, __METHOD__
);
364 $status2 = $page->doEditContent( $content, __METHOD__
);
366 $this->assertTrue( $status1->isOK(), 'OK' );
367 $this->assertTrue( $status2->isOK(), 'OK' );
369 $this->assertTrue( isset( $status1->value
['revision'] ), 'OK' );
370 $this->assertFalse( isset( $status2->value
['revision'] ), 'OK' );
374 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
375 * TODO: Revision deletion
377 * @covers WikiPage::doDeleteArticle
378 * @covers WikiPage::doDeleteArticleReal
380 public function testDoDeleteArticle() {
381 $page = $this->createPage(
383 "[[original text]] foo",
384 CONTENT_MODEL_WIKITEXT
386 $id = $page->getId();
388 $page->doDeleteArticle( "testing deletion" );
391 $page->getTitle()->getArticleID() > 0,
392 "Title object should now have page id 0"
394 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
397 "WikiPage::exists should return false after page was deleted"
401 "WikiPage::getContent should return null after page was deleted"
404 $t = Title
::newFromText( $page->getTitle()->getPrefixedText() );
407 "Title::exists should return false after page was deleted"
411 JobQueueGroup
::destroySingletons();
413 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
416 # ------------------------
417 $dbr = wfGetDB( DB_REPLICA
);
418 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
419 $n = $res->numRows();
422 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
426 * @covers WikiPage::doDeleteArticleReal
428 public function testDoDeleteArticleReal_user0() {
429 $page = $this->createPage(
431 "[[original text]] foo",
432 CONTENT_MODEL_WIKITEXT
434 $id = $page->getId();
437 $status = $page->doDeleteArticleReal(
438 /* reason */ "testing user 0 deletion",
439 /* suppress */ false,
442 /* errorStack */ $errorStack,
445 $logId = $status->getValue();
446 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
448 [ 'logging' ] +
$actorQuery['tables'], /* table */
453 'log_user' => $actorQuery['fields']['log_user'],
454 'log_user_text' => $actorQuery['fields']['log_user_text'],
458 [ 'log_id' => $logId ],
462 'testing user 0 deletion',
465 (string)$page->getTitle()->getNamespace(),
466 $page->getTitle()->getDBkey(),
474 * @covers WikiPage::doDeleteArticleReal
476 public function testDoDeleteArticleReal_userSysop() {
477 $page = $this->createPage(
479 "[[original text]] foo",
480 CONTENT_MODEL_WIKITEXT
482 $id = $page->getId();
484 $user = $this->getTestSysop()->getUser();
486 $status = $page->doDeleteArticleReal(
487 /* reason */ "testing sysop deletion",
488 /* suppress */ false,
491 /* errorStack */ $errorStack,
494 $logId = $status->getValue();
495 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
497 [ 'logging' ] +
$actorQuery['tables'], /* table */
502 'log_user' => $actorQuery['fields']['log_user'],
503 'log_user_text' => $actorQuery['fields']['log_user_text'],
507 [ 'log_id' => $logId ],
511 'testing sysop deletion',
512 (string)$user->getId(),
514 (string)$page->getTitle()->getNamespace(),
515 $page->getTitle()->getDBkey(),
523 * TODO: Test more stuff about suppression.
525 * @covers WikiPage::doDeleteArticleReal
527 public function testDoDeleteArticleReal_suppress() {
528 $page = $this->createPage(
530 "[[original text]] foo",
531 CONTENT_MODEL_WIKITEXT
533 $id = $page->getId();
535 $user = $this->getTestSysop()->getUser();
537 $status = $page->doDeleteArticleReal(
538 /* reason */ "testing deletion",
542 /* errorStack */ $errorStack,
545 $logId = $status->getValue();
546 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
548 [ 'logging' ] +
$actorQuery['tables'], /* table */
553 'log_user' => $actorQuery['fields']['log_user'],
554 'log_user_text' => $actorQuery['fields']['log_user_text'],
558 [ 'log_id' => $logId ],
563 (string)$user->getId(),
565 (string)$page->getTitle()->getNamespace(),
566 $page->getTitle()->getDBkey(),
573 $page->getContent( Revision
::FOR_PUBLIC
),
574 "WikiPage::getContent should return null after the page was suppressed for general users"
578 $page->getContent( Revision
::FOR_THIS_USER
, null ),
579 "WikiPage::getContent should return null after the page was suppressed for user zero"
583 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
584 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
589 * @covers WikiPage::doDeleteUpdates
591 public function testDoDeleteUpdates() {
592 $page = $this->createPage(
594 "[[original text]] foo",
595 CONTENT_MODEL_WIKITEXT
597 $id = $page->getId();
599 // Similar to MovePage logic
600 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
601 $page->doDeleteUpdates( $id );
604 JobQueueGroup
::destroySingletons();
606 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
609 # ------------------------
610 $dbr = wfGetDB( DB_REPLICA
);
611 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
612 $n = $res->numRows();
615 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
619 * @covers WikiPage::getRevision
621 public function testGetRevision() {
622 $page = $this->newPage( __METHOD__
);
624 $rev = $page->getRevision();
625 $this->assertNull( $rev );
628 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
630 $rev = $page->getRevision();
632 $this->assertEquals( $page->getLatest(), $rev->getId() );
633 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
637 * @covers WikiPage::getContent
639 public function testGetContent() {
640 $page = $this->newPage( __METHOD__
);
642 $content = $page->getContent();
643 $this->assertNull( $content );
646 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
648 $content = $page->getContent();
649 $this->assertEquals( "some text", $content->getNativeData() );
653 * @covers WikiPage::exists
655 public function testExists() {
656 $page = $this->newPage( __METHOD__
);
657 $this->assertFalse( $page->exists() );
660 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
661 $this->assertTrue( $page->exists() );
663 $page = new WikiPage( $page->getTitle() );
664 $this->assertTrue( $page->exists() );
667 $page->doDeleteArticle( "done testing" );
668 $this->assertFalse( $page->exists() );
670 $page = new WikiPage( $page->getTitle() );
671 $this->assertFalse( $page->exists() );
674 public function provideHasViewableContent() {
676 [ 'WikiPageTest_testHasViewableContent', false, true ],
677 [ 'Special:WikiPageTest_testHasViewableContent', false ],
678 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
679 [ 'Special:Userlogin', true ],
680 [ 'MediaWiki:help', true ],
685 * @dataProvider provideHasViewableContent
686 * @covers WikiPage::hasViewableContent
688 public function testHasViewableContent( $title, $viewable, $create = false ) {
689 $page = $this->newPage( $title );
690 $this->assertEquals( $viewable, $page->hasViewableContent() );
693 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
694 $this->assertTrue( $page->hasViewableContent() );
696 $page = new WikiPage( $page->getTitle() );
697 $this->assertTrue( $page->hasViewableContent() );
701 public function provideGetRedirectTarget() {
703 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
705 'WikiPageTest_testGetRedirectTarget_2',
706 CONTENT_MODEL_WIKITEXT
,
707 "#REDIRECT [[hello world]]",
714 * @dataProvider provideGetRedirectTarget
715 * @covers WikiPage::getRedirectTarget
717 public function testGetRedirectTarget( $title, $model, $text, $target ) {
718 $this->setMwGlobals( [
719 'wgCapitalLinks' => true,
722 $page = $this->createPage( $title, $text, $model );
724 # sanity check, because this test seems to fail for no reason for some people.
725 $c = $page->getContent();
726 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
728 # now, test the actual redirect
729 $t = $page->getRedirectTarget();
730 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getPrefixedText() );
734 * @dataProvider provideGetRedirectTarget
735 * @covers WikiPage::isRedirect
737 public function testIsRedirect( $title, $model, $text, $target ) {
738 $page = $this->createPage( $title, $text, $model );
739 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
742 public function provideIsCountable() {
746 [ 'WikiPageTest_testIsCountable',
747 CONTENT_MODEL_WIKITEXT
,
752 [ 'WikiPageTest_testIsCountable',
753 CONTENT_MODEL_WIKITEXT
,
760 [ 'WikiPageTest_testIsCountable',
761 CONTENT_MODEL_WIKITEXT
,
766 [ 'WikiPageTest_testIsCountable',
767 CONTENT_MODEL_WIKITEXT
,
774 [ 'WikiPageTest_testIsCountable',
775 CONTENT_MODEL_WIKITEXT
,
780 [ 'WikiPageTest_testIsCountable',
781 CONTENT_MODEL_WIKITEXT
,
787 // not a content namespace
788 [ 'Talk:WikiPageTest_testIsCountable',
789 CONTENT_MODEL_WIKITEXT
,
794 [ 'Talk:WikiPageTest_testIsCountable',
795 CONTENT_MODEL_WIKITEXT
,
801 // not a content namespace, different model
802 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
808 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
818 * @dataProvider provideIsCountable
819 * @covers WikiPage::isCountable
821 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
822 global $wgContentHandlerUseDB;
824 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
826 $title = Title
::newFromText( $title );
828 if ( !$wgContentHandlerUseDB
830 && ContentHandler
::getDefaultModelFor( $title ) != $model
832 $this->markTestSkipped( "Can not use non-default content model $model for "
833 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
836 $page = $this->createPage( $title, $text, $model );
838 $editInfo = $page->prepareContentForEdit( $page->getContent() );
840 $v = $page->isCountable();
841 $w = $page->isCountable( $editInfo );
846 "isCountable( null ) returned unexpected value " . var_export( $v, true )
847 . " instead of " . var_export( $expected, true )
848 . " in mode `$mode` for text \"$text\""
854 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
855 . " instead of " . var_export( $expected, true )
856 . " in mode `$mode` for text \"$text\""
860 public function provideGetParserOutput() {
863 CONTENT_MODEL_WIKITEXT
,
865 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
872 * @dataProvider provideGetParserOutput
873 * @covers WikiPage::getParserOutput
875 public function testGetParserOutput( $model, $text, $expectedHtml ) {
876 $page = $this->createPage( __METHOD__
, $text, $model );
878 $opt = $page->makeParserOptions( 'canonical' );
879 $po = $page->getParserOutput( $opt );
880 $text = $po->getText();
882 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
883 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
885 $this->assertEquals( $expectedHtml, $text );
891 * @covers WikiPage::getParserOutput
893 public function testGetParserOutput_nonexisting() {
894 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
896 $opt = new ParserOptions();
897 $po = $page->getParserOutput( $opt );
899 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
903 * @covers WikiPage::getParserOutput
905 public function testGetParserOutput_badrev() {
906 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
908 $opt = new ParserOptions();
909 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
911 // @todo would be neat to also test deleted revision
913 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
916 public static $sections =
930 public function dataReplaceSection() {
931 // NOTE: assume the Help namespace to contain wikitext
933 [ 'Help:WikiPageTest_testReplaceSection',
934 CONTENT_MODEL_WIKITEXT
,
939 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
941 [ 'Help:WikiPageTest_testReplaceSection',
942 CONTENT_MODEL_WIKITEXT
,
949 [ 'Help:WikiPageTest_testReplaceSection',
950 CONTENT_MODEL_WIKITEXT
,
953 "== TEST ==\nmore fun",
955 trim( preg_replace( '/^== test ==.*== foo ==/sm',
956 "== TEST ==\nmore fun\n\n== foo ==",
959 [ 'Help:WikiPageTest_testReplaceSection',
960 CONTENT_MODEL_WIKITEXT
,
965 trim( self
::$sections )
967 [ 'Help:WikiPageTest_testReplaceSection',
968 CONTENT_MODEL_WIKITEXT
,
973 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
979 * @dataProvider dataReplaceSection
980 * @covers WikiPage::replaceSectionContent
982 public function testReplaceSectionContent( $title, $model, $text, $section,
983 $with, $sectionTitle, $expected
985 $page = $this->createPage( $title, $text, $model );
987 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
988 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
990 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
994 * @dataProvider dataReplaceSection
995 * @covers WikiPage::replaceSectionAtRev
997 public function testReplaceSectionAtRev( $title, $model, $text, $section,
998 $with, $sectionTitle, $expected
1000 $page = $this->createPage( $title, $text, $model );
1001 $baseRevId = $page->getLatest();
1003 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1004 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1006 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1010 * @covers WikiPage::getOldestRevision
1012 public function testGetOldestRevision() {
1013 $page = $this->newPage( __METHOD__
);
1014 $page->doEditContent(
1015 new WikitextContent( 'one' ),
1019 $rev1 = $page->getRevision();
1021 $page = new WikiPage( $page->getTitle() );
1022 $page->doEditContent(
1023 new WikitextContent( 'two' ),
1028 $page = new WikiPage( $page->getTitle() );
1029 $page->doEditContent(
1030 new WikitextContent( 'three' ),
1036 $this->assertNotEquals(
1038 $page->getRevision()->getId(),
1039 '$page->getRevision()->getId()'
1043 $this->assertEquals(
1045 $page->getOldestRevision()->getId(),
1046 '$page->getOldestRevision()->getId()'
1051 * @covers WikiPage::doRollback
1052 * @covers WikiPage::commitRollback
1054 public function testDoRollback() {
1055 // FIXME: fails under postgres
1056 $this->markTestSkippedIfDbType( 'postgres' );
1058 $admin = $this->getTestSysop()->getUser();
1059 $user1 = $this->getTestUser()->getUser();
1060 // Use the confirmed group for user2 to make sure the user is different
1061 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1063 // make sure we can test autopatrolling
1064 $this->setMwGlobals( 'wgUseRCPatrol', true );
1066 // TODO: MCR: test rollback of multiple slots!
1067 $page = $this->newPage( __METHOD__
);
1071 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1072 "section one", EDIT_NEW
, false, $admin );
1075 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1076 "adding section two", 0, false, $user1 );
1078 $text .= "\n\nthree";
1079 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1080 "adding section three", 0, false, $user2 );
1082 /** @var Revision $rev1 */
1083 /** @var Revision $rev2 */
1084 /** @var Revision $rev3 */
1085 $rev1 = $status1->getValue()['revision'];
1086 $rev2 = $status2->getValue()['revision'];
1087 $rev3 = $status3->getValue()['revision'];
1090 * We are having issues with doRollback spuriously failing. Apparently
1091 * the last revision somehow goes missing or not committed under some
1092 * circumstances. So, make sure the revisions have the correct usernames.
1094 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1095 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1096 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1097 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1099 // Now, try the actual rollback
1100 $token = $admin->getEditToken( 'rollback' );
1101 $rollbackErrors = $page->doRollback(
1110 if ( $rollbackErrors ) {
1112 "Rollback failed:\n" .
1113 print_r( $rollbackErrors, true ) . ";\n" .
1114 print_r( $resultDetails, true )
1118 $page = new WikiPage( $page->getTitle() );
1119 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1120 "rollback did not revert to the correct revision" );
1121 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1123 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1124 $page->getRevision()->getRevisionRecord()
1127 $this->assertNotNull( $rc, 'RecentChanges entry' );
1128 $this->assertEquals(
1129 RecentChange
::PRC_AUTOPATROLLED
,
1130 $rc->getAttribute( 'rc_patrolled' ),
1134 // TODO: MCR: assert origin once we write slot data
1135 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
1136 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1137 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1141 * @covers WikiPage::doRollback
1142 * @covers WikiPage::commitRollback
1144 public function testDoRollbackFailureSameContent() {
1145 $admin = $this->getTestSysop()->getUser();
1148 $page = $this->newPage( __METHOD__
);
1149 $page->doEditContent(
1150 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1156 $rev1 = $page->getRevision();
1158 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1160 $page = new WikiPage( $page->getTitle() );
1161 $page->doEditContent(
1162 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1163 "adding section two",
1169 # now, do a the rollback from the same user was doing the edit before
1170 $resultDetails = [];
1171 $token = $user1->getEditToken( 'rollback' );
1172 $errors = $page->doRollback(
1174 "testing revert same user",
1181 $this->assertEquals( [], $errors, "Rollback failed same user" );
1183 # now, try the rollback
1184 $resultDetails = [];
1185 $token = $admin->getEditToken( 'rollback' );
1186 $errors = $page->doRollback(
1195 $this->assertEquals(
1205 "Rollback not failed"
1208 $page = new WikiPage( $page->getTitle() );
1209 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1210 "rollback did not revert to the correct revision" );
1211 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1215 * Tests tagging for edits that do rollback action
1216 * @covers WikiPage::doRollback
1218 public function testDoRollbackTagging() {
1219 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1220 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1223 $admin = new User();
1224 $admin->setName( 'Administrator' );
1225 $admin->addToDatabase();
1227 $text = 'First line';
1228 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1229 $page->doEditContent(
1230 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1237 $secondUser = new User();
1238 $secondUser->setName( '92.65.217.32' );
1239 $text .= '\n\nSecond line';
1240 $page = new WikiPage( $page->getTitle() );
1241 $page->doEditContent(
1242 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1243 'Adding second line',
1249 // Now, try the rollback
1250 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1251 $token = $admin->getEditToken( 'rollback' );
1252 $errors = $page->doRollback(
1253 $secondUser->getName(),
1261 // If doRollback completed without errors
1262 if ( $errors === [] ) {
1263 $tags = $resultDetails[ 'tags' ];
1264 $this->assertContains( 'mw-rollback', $tags );
1268 public function provideGetAutoDeleteReason() {
1278 [ "first edit", null ],
1280 "/first edit.*only contributor/",
1286 [ "first edit", null ],
1287 [ "second edit", null ],
1289 "/second edit.*only contributor/",
1295 [ "first edit", "127.0.2.22" ],
1296 [ "second edit", "127.0.3.33" ],
1306 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1307 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1308 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1309 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1310 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1314 '/first edit:.*\.\.\."/',
1320 [ "first edit", "127.0.2.22" ],
1321 [ "", "127.0.3.33" ],
1323 "/before blanking.*first edit/",
1331 * @dataProvider provideGetAutoDeleteReason
1332 * @covers WikiPage::getAutoDeleteReason
1334 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1337 // NOTE: assume Help namespace to contain wikitext
1338 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1342 foreach ( $edits as $edit ) {
1345 if ( !empty( $edit[1] ) ) {
1346 $user->setName( $edit[1] );
1351 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1353 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1358 $reason = $page->getAutoDeleteReason( $hasHistory );
1360 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1361 $this->assertEquals( $expectedResult, $reason );
1363 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1364 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1367 $this->assertEquals( $expectedHistory, $hasHistory,
1368 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1370 $page->doDeleteArticle( "done" );
1373 public function providePreSaveTransform() {
1375 [ 'hello this is ~~~',
1376 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1378 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1379 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1385 * @covers WikiPage::factory
1387 public function testWikiPageFactory() {
1388 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1389 $page = WikiPage
::factory( $title );
1390 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1392 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1393 $page = WikiPage
::factory( $title );
1394 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1396 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1397 $page = WikiPage
::factory( $title );
1398 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1402 * @covers WikiPage::loadPageData
1403 * @covers WikiPage::wasLoadedFrom
1405 public function testLoadPageData() {
1406 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1407 $page = WikiPage
::factory( $title );
1409 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1410 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1411 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1412 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1414 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1415 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1416 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1417 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1418 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1420 $page->loadPageData( IDBAccessObject
::READ_LATEST
);
1421 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1422 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1423 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1424 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1426 $page->loadPageData( IDBAccessObject
::READ_LOCKING
);
1427 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1428 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1429 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1430 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1432 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
1433 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1434 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1435 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1436 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1440 * @dataProvider provideCommentMigrationOnDeletion
1442 * @param int $writeStage
1443 * @param int $readStage
1445 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1446 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1447 $this->overrideMwServices();
1449 $dbr = wfGetDB( DB_REPLICA
);
1451 $page = $this->createPage(
1454 CONTENT_MODEL_WIKITEXT
1456 $revid = $page->getLatest();
1457 if ( $writeStage > MIGRATION_OLD
) {
1458 $comment_id = $dbr->selectField(
1459 'revision_comment_temp',
1460 'revcomment_comment_id',
1461 [ 'revcomment_rev' => $revid ],
1466 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1467 $this->overrideMwServices();
1469 $page->doDeleteArticle( "testing deletion" );
1471 if ( $readStage > MIGRATION_OLD
) {
1472 // Didn't leave behind any 'revision_comment_temp' rows
1473 $n = $dbr->selectField(
1474 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1476 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1478 // Copied or upgraded the comment_id, as applicable
1479 $ar_comment_id = $dbr->selectField(
1482 [ 'ar_rev_id' => $revid ],
1485 if ( $writeStage > MIGRATION_OLD
) {
1486 $this->assertSame( $comment_id, $ar_comment_id );
1488 $this->assertNotEquals( 0, $ar_comment_id );
1492 // Copied rev_comment, if applicable
1493 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1494 $ar_comment = $dbr->selectField(
1497 [ 'ar_rev_id' => $revid ],
1500 $this->assertSame( 'testing', $ar_comment );
1504 public function provideCommentMigrationOnDeletion() {
1506 [ MIGRATION_OLD
, MIGRATION_OLD
],
1507 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1508 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1509 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1510 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1511 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1512 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1513 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1514 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1515 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1516 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1517 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1518 [ MIGRATION_NEW
, MIGRATION_NEW
],
1523 * @covers WikiPage::updateCategoryCounts
1525 public function testUpdateCategoryCounts() {
1526 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1528 // Add an initial category
1529 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1531 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1532 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1533 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1535 // Add a new category
1536 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1538 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1539 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1540 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1542 // Add and remove a category
1543 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1545 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1546 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1547 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1550 public function provideUpdateRedirectOn() {
1551 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1552 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1553 yield
[ 'SomeText', false, null, false, true, 0 ];
1554 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1558 * @dataProvider provideUpdateRedirectOn
1559 * @covers WikiPage::updateRedirectOn
1561 * @param string $initialText
1562 * @param bool $initialRedirectState
1563 * @param string|null $redirectTitle
1564 * @param bool|null $lastRevIsRedirect
1565 * @param bool $expectedSuccess
1566 * @param int $expectedRowCount
1568 public function testUpdateRedirectOn(
1570 $initialRedirectState,
1576 // FIXME: fails under sqlite and postgres
1577 $this->markTestSkippedIfDbType( 'sqlite' );
1578 $this->markTestSkippedIfDbType( 'postgres' );
1579 static $pageCounter = 0;
1582 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1583 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1585 $redirectTitle = is_string( $redirectTitle )
1586 ? Title
::newFromText( $redirectTitle )
1589 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1590 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1592 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1593 * Most of core checks the page table for redirect status, so we have to be ugly and
1594 * assert a select from the table here.
1596 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1599 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1600 $this->assertSelect(
1603 [ 'rd_from' => $pageId ],
1604 [ [ strval( $expected ) ] ]
1609 * @covers WikiPage::insertRedirectEntry
1611 public function testInsertRedirectEntry_insertsRedirectEntry() {
1612 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1613 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1615 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1616 $targetTitle->mInterwiki
= 'eninter';
1617 $page->insertRedirectEntry( $targetTitle, null );
1619 $this->assertSelect(
1621 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1622 [ 'rd_from' => $page->getId() ],
1624 strval( $page->getId() ),
1625 strval( $targetTitle->getNamespace() ),
1626 strval( $targetTitle->getDBkey() ),
1627 strval( $targetTitle->getFragment() ),
1628 strval( $targetTitle->getInterwiki() ),
1634 * @covers WikiPage::insertRedirectEntry
1636 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1637 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1638 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1640 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1641 $targetTitle->mInterwiki
= 'eninter';
1642 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1644 $this->assertSelect(
1646 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1647 [ 'rd_from' => $page->getId() ],
1649 strval( $page->getId() ),
1650 strval( $targetTitle->getNamespace() ),
1651 strval( $targetTitle->getDBkey() ),
1652 strval( $targetTitle->getFragment() ),
1653 strval( $targetTitle->getInterwiki() ),
1659 * @covers WikiPage::insertRedirectEntry
1661 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1662 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1663 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1665 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1666 $targetTitle->mInterwiki
= 'eninter';
1667 $page->insertRedirectEntry( $targetTitle, 215251 );
1669 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1672 private function getRow( array $overrides = [] ) {
1676 'page_is_redirect' => '1',
1677 'page_latest' => '99',
1678 'page_namespace' => '3',
1679 'page_title' => 'JaJaTitle',
1680 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1681 'page_touched' => '20120101020202',
1682 'page_links_updated' => '20140101020202',
1684 foreach ( $overrides as $key => $value ) {
1685 $row[$key] = $value;
1687 return (object)$row;
1690 public function provideNewFromRowSuccess() {
1691 yield
'basic row' => [
1693 function ( WikiPage
$wikiPage, self
$test ) {
1694 $test->assertSame( 44, $wikiPage->getId() );
1695 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1696 $test->assertTrue( $wikiPage->isRedirect() );
1697 $test->assertSame( 99, $wikiPage->getLatest() );
1698 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1699 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1702 'edit' => [ 'autoconfirmed', 'sysop' ],
1703 'move' => [ 'sysop' ],
1705 $wikiPage->getTitle()->getAllRestrictions()
1707 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1708 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1711 yield
'different timestamp formats' => [
1713 'page_touched' => '2012-01-01 02:02:02',
1714 'page_links_updated' => '2014-01-01 02:02:02',
1716 function ( WikiPage
$wikiPage, self
$test ) {
1717 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1718 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1721 yield
'no restrictions' => [
1723 'page_restrictions' => '',
1725 function ( WikiPage
$wikiPage, self
$test ) {
1731 $wikiPage->getTitle()->getAllRestrictions()
1735 yield
'not redirect' => [
1737 'page_is_redirect' => '0',
1739 function ( WikiPage
$wikiPage, self
$test ) {
1740 $test->assertFalse( $wikiPage->isRedirect() );
1746 * @covers WikiPage::newFromRow
1747 * @covers WikiPage::loadFromRow
1748 * @dataProvider provideNewFromRowSuccess
1750 * @param object $row
1751 * @param callable $assertions
1753 public function testNewFromRow( $row, $assertions ) {
1754 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1755 $assertions( $page, $this );
1758 public function provideTestNewFromId_returnsNullOnBadPageId() {
1764 * @covers WikiPage::newFromID
1765 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1767 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1768 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1772 * @covers WikiPage::newFromID
1774 public function testNewFromId_appearsToFetchCorrectRow() {
1775 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1776 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1777 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1778 $this->assertEquals(
1779 $createdPage->getContent()->getNativeData(),
1780 $fetchedPage->getContent()->getNativeData()
1785 * @covers WikiPage::newFromID
1787 public function testNewFromId_returnsNullOnNonExistingId() {
1788 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1791 public function provideTestInsertProtectNullRevision() {
1792 // phpcs:disable Generic.Files.LineLength
1795 [ 'edit' => 'sysop' ],
1796 [ 'edit' => '20200101040404' ],
1800 '(goat-message-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Reason(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04)))'
1804 [ 'edit' => 'sysop', 'move' => 'something' ],
1805 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1809 '(goat-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Goat(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04))(word-separator)(protect-summary-desc: (restriction-move), (protect-level-something), (protect-expiring: 05:05, 1 (january) 2021, 1 (january) 2021, 05:05)))'
1815 * @dataProvider provideTestInsertProtectNullRevision
1816 * @covers WikiPage::insertProtectNullRevision
1817 * @covers WikiPage::protectDescription
1819 * @param string $revCommentMsg
1820 * @param array $limit
1821 * @param array $expiry
1822 * @param bool $cascade
1823 * @param string $reason
1824 * @param bool|null $user true if the test sysop should be used, or null
1825 * @param string $expectedComment
1827 public function testInsertProtectNullRevision(
1836 $this->setContentLang( 'qqx' );
1838 $page = $this->createPage( __METHOD__
, 'Goat' );
1840 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1842 $result = $page->insertProtectNullRevision(
1851 $this->assertTrue( $result instanceof Revision
);
1852 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1856 * @covers WikiPage::updateRevisionOn
1858 public function testUpdateRevisionOn_existingPage() {
1859 $user = $this->getTestSysop()->getUser();
1860 $page = $this->createPage( __METHOD__
, 'StartText' );
1862 $revision = new Revision(
1865 'page' => $page->getId(),
1866 'title' => $page->getTitle(),
1867 'comment' => __METHOD__
,
1868 'minor_edit' => true,
1869 'text' => __METHOD__
. '-text',
1870 'len' => strlen( __METHOD__
. '-text' ),
1871 'user' => $user->getId(),
1872 'user_text' => $user->getName(),
1873 'timestamp' => '20170707040404',
1874 'content_model' => CONTENT_MODEL_WIKITEXT
,
1875 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1879 $result = $page->updateRevisionOn( $this->db
, $revision );
1880 $this->assertTrue( $result );
1881 $this->assertSame( 9989, $page->getLatest() );
1882 $this->assertEquals( $revision, $page->getRevision() );
1886 * @covers WikiPage::updateRevisionOn
1888 public function testUpdateRevisionOn_NonExistingPage() {
1889 $user = $this->getTestSysop()->getUser();
1890 $page = $this->createPage( __METHOD__
, 'StartText' );
1891 $page->doDeleteArticle( 'reason' );
1893 $revision = new Revision(
1896 'page' => $page->getId(),
1897 'title' => $page->getTitle(),
1898 'comment' => __METHOD__
,
1899 'minor_edit' => true,
1900 'text' => __METHOD__
. '-text',
1901 'len' => strlen( __METHOD__
. '-text' ),
1902 'user' => $user->getId(),
1903 'user_text' => $user->getName(),
1904 'timestamp' => '20170707040404',
1905 'content_model' => CONTENT_MODEL_WIKITEXT
,
1906 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1910 $result = $page->updateRevisionOn( $this->db
, $revision );
1911 $this->assertFalse( $result );
1915 * @covers WikiPage::updateIfNewerOn
1917 public function testUpdateIfNewerOn_olderRevision() {
1918 $user = $this->getTestSysop()->getUser();
1919 $page = $this->createPage( __METHOD__
, 'StartText' );
1920 $initialRevision = $page->getRevision();
1922 $olderTimeStamp = wfTimestamp(
1924 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
1927 $olderRevison = new Revision(
1930 'page' => $page->getId(),
1931 'title' => $page->getTitle(),
1932 'comment' => __METHOD__
,
1933 'minor_edit' => true,
1934 'text' => __METHOD__
. '-text',
1935 'len' => strlen( __METHOD__
. '-text' ),
1936 'user' => $user->getId(),
1937 'user_text' => $user->getName(),
1938 'timestamp' => $olderTimeStamp,
1939 'content_model' => CONTENT_MODEL_WIKITEXT
,
1940 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1944 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
1945 $this->assertFalse( $result );
1949 * @covers WikiPage::updateIfNewerOn
1951 public function testUpdateIfNewerOn_newerRevision() {
1952 $user = $this->getTestSysop()->getUser();
1953 $page = $this->createPage( __METHOD__
, 'StartText' );
1954 $initialRevision = $page->getRevision();
1956 $newerTimeStamp = wfTimestamp(
1958 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
1961 $newerRevision = new Revision(
1964 'page' => $page->getId(),
1965 'title' => $page->getTitle(),
1966 'comment' => __METHOD__
,
1967 'minor_edit' => true,
1968 'text' => __METHOD__
. '-text',
1969 'len' => strlen( __METHOD__
. '-text' ),
1970 'user' => $user->getId(),
1971 'user_text' => $user->getName(),
1972 'timestamp' => $newerTimeStamp,
1973 'content_model' => CONTENT_MODEL_WIKITEXT
,
1974 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1977 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
1978 $this->assertTrue( $result );
1982 * @covers WikiPage::insertOn
1984 public function testInsertOn() {
1985 $title = Title
::newFromText( __METHOD__
);
1986 $page = new WikiPage( $title );
1988 $startTimeStamp = wfTimestampNow();
1989 $result = $page->insertOn( $this->db
);
1990 $endTimeStamp = wfTimestampNow();
1992 $this->assertInternalType( 'int', $result );
1993 $this->assertTrue( $result > 0 );
1995 $condition = [ 'page_id' => $result ];
1997 // Check the default fields have been filled
1998 $this->assertSelect(
2003 'page_restrictions',
2021 // Check the page_random field has been filled
2022 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2023 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2025 // Assert the touched timestamp in the DB is roughly when we inserted the page
2026 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2028 wfTimestamp( TS_UNIX
, $startTimeStamp )
2029 <= wfTimestamp( TS_UNIX
, $pageTouched )
2032 wfTimestamp( TS_UNIX
, $endTimeStamp )
2033 >= wfTimestamp( TS_UNIX
, $pageTouched )
2036 // Try inserting the same page again and checking the result is false (no change)
2037 $result = $page->insertOn( $this->db
);
2038 $this->assertFalse( $result );
2042 * @covers WikiPage::insertOn
2044 public function testInsertOn_idSpecified() {
2045 $title = Title
::newFromText( __METHOD__
);
2046 $page = new WikiPage( $title );
2049 $result = $page->insertOn( $this->db
, $id );
2051 $this->assertSame( $id, $result );
2053 $condition = [ 'page_id' => $result ];
2055 // Check there is actually a row in the db
2056 $this->assertSelect(
2064 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2065 // Note: Once the current dates passes the date in these tests they will fail.
2066 yield
'move something' => [
2068 [ 'move' => 'something' ],
2070 [ 'edit' => [], 'move' => [ 'something' ] ],
2073 yield
'move something, edit blank' => [
2075 [ 'move' => 'something', 'edit' => '' ],
2077 [ 'edit' => [], 'move' => [ 'something' ] ],
2080 yield
'edit sysop, with expiry' => [
2082 [ 'edit' => 'sysop' ],
2083 [ 'edit' => '21330101020202' ],
2084 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2085 [ 'edit' => '21330101020202' ],
2087 yield
'move and edit, move with expiry' => [
2089 [ 'move' => 'something', 'edit' => 'another' ],
2090 [ 'move' => '22220202010101' ],
2091 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2092 [ 'move' => '22220202010101' ],
2094 yield
'move and edit, edit with infinity expiry' => [
2096 [ 'move' => 'something', 'edit' => 'another' ],
2097 [ 'edit' => 'infinity' ],
2098 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2099 [ 'edit' => 'infinity' ],
2101 yield
'non existing, create something' => [
2103 [ 'create' => 'something' ],
2105 [ 'create' => [ 'something' ] ],
2108 yield
'non existing, create something with expiry' => [
2110 [ 'create' => 'something' ],
2111 [ 'create' => '23451212112233' ],
2112 [ 'create' => [ 'something' ] ],
2113 [ 'create' => '23451212112233' ],
2118 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2119 * @covers WikiPage::doUpdateRestrictions
2121 public function testDoUpdateRestrictions_setBasicRestrictions(
2125 array $expectedRestrictions,
2126 array $expectedRestrictionExpiries
2128 if ( $pageExists ) {
2129 $page = $this->createPage( __METHOD__
, 'ABC' );
2131 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2133 $user = $this->getTestSysop()->getUser();
2136 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2138 $logId = $status->getValue();
2139 $allRestrictions = $page->getTitle()->getAllRestrictions();
2141 $this->assertTrue( $status->isGood() );
2142 $this->assertInternalType( 'int', $logId );
2143 $this->assertSame( $expectedRestrictions, $allRestrictions );
2144 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2145 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2148 // Make sure the log entry looks good
2149 // log_params is not checked here
2150 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2151 $this->assertSelect(
2152 [ 'logging' ] +
$actorQuery['tables'],
2155 'log_user' => $actorQuery['fields']['log_user'],
2156 'log_user_text' => $actorQuery['fields']['log_user_text'],
2160 [ 'log_id' => $logId ],
2163 (string)$user->getId(),
2165 (string)$page->getTitle()->getNamespace(),
2166 $page->getTitle()->getDBkey(),
2169 $actorQuery['joins']
2174 * @covers WikiPage::doUpdateRestrictions
2176 public function testDoUpdateRestrictions_failsOnReadOnly() {
2177 $page = $this->createPage( __METHOD__
, 'ABC' );
2178 $user = $this->getTestSysop()->getUser();
2182 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2183 ->disableOriginalConstructor()
2184 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2186 $readOnly->expects( $this->once() )
2187 ->method( 'isReadOnly' )
2188 ->will( $this->returnValue( true ) );
2189 $readOnly->expects( $this->once() )
2190 ->method( 'getReason' )
2191 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2192 $this->setService( 'ReadOnlyMode', $readOnly );
2194 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2195 $this->assertFalse( $status->isOK() );
2196 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2200 * @covers WikiPage::doUpdateRestrictions
2202 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2203 $page = $this->createPage( __METHOD__
, 'ABC' );
2204 $user = $this->getTestSysop()->getUser();
2206 $limit = [ 'edit' => 'sysop' ];
2208 $status = $page->doUpdateRestrictions(
2217 // The first entry should have a logId as it did something
2218 $this->assertTrue( $status->isGood() );
2219 $this->assertInternalType( 'int', $status->getValue() );
2221 $status = $page->doUpdateRestrictions(
2230 // The second entry should not have a logId as nothing changed
2231 $this->assertTrue( $status->isGood() );
2232 $this->assertNull( $status->getValue() );
2236 * @covers WikiPage::doUpdateRestrictions
2238 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2239 $page = $this->createPage( __METHOD__
, 'ABC' );
2240 $user = $this->getTestSysop()->getUser();
2244 $status = $page->doUpdateRestrictions(
2245 [ 'edit' => 'sysop' ],
2252 $this->assertTrue( $status->isGood() );
2253 $this->assertInternalType( 'int', $status->getValue() );
2254 $this->assertSelect(
2256 [ 'log_type', 'log_action' ],
2257 [ 'log_id' => $status->getValue() ],
2258 [ [ 'protect', 'protect' ] ]
2261 // Modify the protection
2262 $status = $page->doUpdateRestrictions(
2263 [ 'edit' => 'somethingElse' ],
2270 $this->assertTrue( $status->isGood() );
2271 $this->assertInternalType( 'int', $status->getValue() );
2272 $this->assertSelect(
2274 [ 'log_type', 'log_action' ],
2275 [ 'log_id' => $status->getValue() ],
2276 [ [ 'protect', 'modify' ] ]
2279 // Remove the protection
2280 $status = $page->doUpdateRestrictions(
2288 $this->assertTrue( $status->isGood() );
2289 $this->assertInternalType( 'int', $status->getValue() );
2290 $this->assertSelect(
2292 [ 'log_type', 'log_action' ],
2293 [ 'log_id' => $status->getValue() ],
2294 [ [ 'protect', 'unprotect' ] ]
2299 * @covers WikiPage::newPageUpdater
2300 * @covers WikiPage::getDerivedDataUpdater
2302 public function testNewPageUpdater() {
2303 $user = $this->getTestUser()->getUser();
2304 $page = $this->newPage( __METHOD__
, __METHOD__
);
2306 /** @var Content $content */
2307 $content = $this->getMockBuilder( WikitextContent
::class )
2308 ->setConstructorArgs( [ 'Hello World' ] )
2309 ->setMethods( [ 'getParserOutput' ] )
2311 $content->expects( $this->once() )
2312 ->method( 'getParserOutput' )
2313 ->willReturn( new ParserOutput( 'HTML' ) );
2315 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2317 // provide context, so the cache can be kept in place
2318 $slotsUpdate = new revisionSlotsUpdate();
2319 $slotsUpdate->modifyContent( 'main', $content );
2321 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2322 $updater->setContent( 'main', $content );
2323 $revision = $updater->saveRevision(
2324 CommentStoreComment
::newUnsavedComment( 'test' ),
2328 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2330 $this->assertSame( $revision->getId(), $page->getLatest() );
2332 // Parsed output must remain cached throughout.
2333 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2337 * @covers WikiPage::newPageUpdater
2338 * @covers WikiPage::getDerivedDataUpdater
2340 public function testGetDerivedDataUpdater() {
2341 $admin = $this->getTestSysop()->getUser();
2343 /** @var object $page */
2344 $page = $this->createPage( __METHOD__
, __METHOD__
);
2345 $page = TestingAccessWrapper
::newFromObject( $page );
2347 $revision = $page->getRevision()->getRevisionRecord();
2348 $user = $revision->getUser();
2350 $slotsUpdate = new RevisionSlotsUpdate();
2351 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2353 // get a virgin updater
2354 $updater1 = $page->getDerivedDataUpdater( $user );
2355 $this->assertFalse( $updater1->isUpdatePrepared() );
2357 $updater1->prepareUpdate( $revision );
2359 // Re-use updater with same revision or content, even if base changed
2360 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2362 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2363 [ 'main' => $revision->getContent( 'main' ) ]
2365 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2367 // Don't re-use for edit if base revision ID changed
2368 $this->assertNotSame(
2370 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2373 // Don't re-use with different user
2374 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2375 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2377 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2378 $updater2b->prepareContent( $user, $slotsUpdate, false );
2379 $this->assertNotSame( $updater2a, $updater2b );
2381 // Don't re-use with different content
2382 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2383 $updater3->prepareUpdate( $revision );
2384 $this->assertNotSame( $updater2b, $updater3 );
2386 // Don't re-use if no context given
2387 $updater4 = $page->getDerivedDataUpdater( $admin );
2388 $updater4->prepareUpdate( $revision );
2389 $this->assertNotSame( $updater3, $updater4 );
2391 // Don't re-use if AGAIN no context given
2392 $updater5 = $page->getDerivedDataUpdater( $admin );
2393 $this->assertNotSame( $updater4, $updater5 );
2395 // Don't re-use cached "virgin" unprepared updater
2396 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2397 $this->assertNotSame( $updater5, $updater6 );
2400 protected function assertPreparedEditEquals(
2401 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2403 // suppress differences caused by a clock tick between generating the two PreparedEdits
2404 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2405 $edit2 = clone $edit2;
2406 $edit2->timestamp
= $edit->timestamp
;
2408 $this->assertEquals( $edit, $edit2, $message );
2411 protected function assertPreparedEditNotEquals(
2412 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2414 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2415 $edit2 = clone $edit2;
2416 $edit2->timestamp
= $edit->timestamp
;
2418 $this->assertNotEquals( $edit, $edit2, $message );