3 use MediaWiki\MediaWikiServices
;
4 use MediaWiki\Storage\RevisionSlotsUpdate
;
5 use Wikimedia\TestingAccessWrapper
;
10 abstract class WikiPageDbTestBase
extends MediaWikiLangTestCase
{
12 private $pagesToDelete;
14 public function __construct( $name = null, array $data = [], $dataName = '' ) {
15 parent
::__construct( $name, $data, $dataName );
17 $this->tablesUsed
= array_merge(
40 protected function addCoreDBData() {
41 // Blank out. This would fail with a modified schema, and we don't need it.
47 abstract protected function getMcrMigrationStage();
52 abstract protected function getMcrTablesToReset();
54 protected function setUp() {
57 $this->tablesUsed +
= $this->getMcrTablesToReset();
59 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
61 'wgMultiContentRevisionSchemaMigrationStage',
62 $this->getMcrMigrationStage()
64 $this->pagesToDelete
= [];
66 $this->overrideMwServices();
69 protected function tearDown() {
70 foreach ( $this->pagesToDelete
as $p ) {
71 /* @var $p WikiPage */
75 $p->doDeleteArticle( "testing done." );
77 } catch ( MWException
$ex ) {
84 abstract protected function getContentHandlerUseDB();
87 * @param Title|string $title
88 * @param string|null $model
91 private function newPage( $title, $model = null ) {
92 if ( is_string( $title ) ) {
93 $ns = $this->getDefaultWikitextNS();
94 $title = Title
::newFromText( $title, $ns );
97 $p = new WikiPage( $title );
99 $this->pagesToDelete
[] = $p;
105 * @param string|Title|WikiPage $page
106 * @param string $text
107 * @param int|null $model
111 protected function createPage( $page, $text, $model = null, $user = null ) {
112 if ( is_string( $page ) ||
$page instanceof Title
) {
113 $page = $this->newPage( $page, $model );
116 $content = ContentHandler
::makeContent( $text, $page->getTitle(), $model );
117 $page->doEditContent( $content, "testing", EDIT_NEW
, false, $user );
123 * @covers WikiPage::prepareContentForEdit
125 public function testPrepareContentForEdit() {
126 $user = $this->getTestUser()->getUser();
127 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
129 $page = $this->createPage( __METHOD__
, __METHOD__
, null, $user );
130 $title = $page->getTitle();
132 $content = ContentHandler
::makeContent(
133 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
134 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
136 CONTENT_MODEL_WIKITEXT
138 $content2 = ContentHandler
::makeContent(
139 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
140 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
142 CONTENT_MODEL_WIKITEXT
145 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
147 $this->assertInstanceOf(
148 ParserOptions
::class,
152 $this->assertContains( '</a>', $edit->output
->getText(), "output" );
153 $this->assertContains(
154 'consetetur sadipscing elitr',
155 $edit->output
->getText(),
159 $this->assertTrue( $content->equals( $edit->newContent
), "newContent field" );
160 $this->assertTrue( $content->equals( $edit->pstContent
), "pstContent field" );
161 $this->assertSame( $edit->output
, $edit->output
, "output field" );
162 $this->assertSame( $edit->popts
, $edit->popts
, "popts field" );
163 $this->assertSame( null, $edit->revid
, "revid field" );
165 // Re-using the prepared info if possible
166 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
167 $this->assertEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
168 $this->assertSame( $edit->pstContent
, $sameEdit->pstContent
, 're-use output' );
169 $this->assertSame( $edit->output
, $sameEdit->output
, 're-use output' );
171 // Not re-using the same PreparedEdit if not possible
172 $rev = $page->getRevision();
173 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
174 $this->assertNotEquals( $edit, $edit2 );
175 $this->assertContains( 'At vero eos', $edit2->pstContent
->serialize(), "content" );
177 // Check pre-safe transform
178 $this->assertContains( '[[gubergren]]', $edit2->pstContent
->serialize() );
179 $this->assertNotContains( '~~~~', $edit2->pstContent
->serialize() );
181 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
182 $this->assertNotEquals( $edit2, $edit3 );
184 // TODO: test with passing revision, then same without revision.
188 * @covers WikiPage::doEditUpdates
190 public function testDoEditUpdates() {
191 $user = $this->getTestUser()->getUser();
193 // NOTE: if site stats get out of whack and drop below 0,
194 // that causes a DB error during tear-down. So bump the
195 // numbers high enough to not drop below 0.
196 $siteStatsUpdate = SiteStatsUpdate
::factory(
197 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
199 $siteStatsUpdate->doUpdate();
201 $page = $this->createPage( __METHOD__
, __METHOD__
);
203 $revision = new Revision(
206 'page' => $page->getId(),
207 'title' => $page->getTitle(),
208 'comment' => __METHOD__
,
209 'minor_edit' => true,
210 'text' => __METHOD__
. ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
211 'user' => $user->getId(),
212 'user_text' => $user->getName(),
213 'timestamp' => '20170707040404',
214 'content_model' => CONTENT_MODEL_WIKITEXT
,
215 'content_format' => CONTENT_FORMAT_WIKITEXT
,
219 $page->doEditUpdates( $revision, $user );
221 // TODO: test various options; needs temporary hooks
223 $dbr = wfGetDB( DB_REPLICA
);
224 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
225 $n = $res->numRows();
228 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
232 * @covers WikiPage::doEditContent
233 * @covers WikiPage::prepareContentForEdit
235 public function testDoEditContent() {
236 $this->setMwGlobals( 'wgPageCreationLog', true );
238 $page = $this->newPage( __METHOD__
);
239 $title = $page->getTitle();
241 $user1 = $this->getTestUser()->getUser();
242 // Use the confirmed group for user2 to make sure the user is different
243 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
245 $content = ContentHandler
::makeContent(
246 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
247 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
249 CONTENT_MODEL_WIKITEXT
252 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
254 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW
, false, $user1 );
256 $this->assertTrue( $status->isOK(), 'OK' );
257 $this->assertTrue( $status->value
['new'], 'new' );
258 $this->assertNotNull( $status->value
['revision'], 'revision' );
259 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
260 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
261 $this->assertTrue( $status->value
['revision']->getContent()->equals( $content ), 'equals' );
263 $rev = $page->getRevision();
264 $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
266 $this->assertNotNull( $rev->getRecentChange() );
267 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
269 // make sure that cached ParserOutput gets re-used throughout
270 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
272 $id = $page->getId();
274 // Test page creation logging
277 [ 'log_type', 'log_action' ],
278 [ 'log_page' => $id ],
279 [ [ 'create', 'create' ] ]
282 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
283 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
284 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
285 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
287 # ------------------------
288 $dbr = wfGetDB( DB_REPLICA
);
289 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
290 $n = $res->numRows();
293 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
295 # ------------------------
296 $page = new WikiPage( $title );
298 $retrieved = $page->getContent();
299 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
301 # ------------------------
302 $page = new WikiPage( $title );
304 // try null edit, with a different user
305 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE
, false, $user2 );
306 $this->assertTrue( $status->isOK(), 'OK' );
307 $this->assertFalse( $status->value
['new'], 'new' );
308 $this->assertNull( $status->value
['revision'], 'revision' );
309 $this->assertNotNull( $page->getRevision() );
310 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
312 # ------------------------
313 $content = ContentHandler
::makeContent(
314 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
315 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
317 CONTENT_MODEL_WIKITEXT
320 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE
);
321 $this->assertTrue( $status->isOK(), 'OK' );
322 $this->assertFalse( $status->value
['new'], 'new' );
323 $this->assertNotNull( $status->value
['revision'], 'revision' );
324 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
325 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
327 $status->value
['revision']->getContent()->equals( $content ),
328 'not equals (PST must substitute signature)'
331 $rev = $page->getRevision();
332 $this->assertNotNull( $rev->getRecentChange() );
333 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
335 # ------------------------
336 $page = new WikiPage( $title );
338 $retrieved = $page->getContent();
339 $newText = $retrieved->serialize();
340 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
341 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
343 # ------------------------
344 $dbr = wfGetDB( DB_REPLICA
);
345 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
346 $n = $res->numRows();
349 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
353 * @covers WikiPage::doEditContent
355 public function testDoEditContent_twice() {
356 $title = Title
::newFromText( __METHOD__
);
357 $page = WikiPage
::factory( $title );
358 $content = ContentHandler
::makeContent( '$1 van $2', $title );
360 // Make sure we can do the exact same save twice.
361 // This tests checks that internal caches are reset as appropriate.
362 $status1 = $page->doEditContent( $content, __METHOD__
);
363 $status2 = $page->doEditContent( $content, __METHOD__
);
365 $this->assertTrue( $status1->isOK(), 'OK' );
366 $this->assertTrue( $status2->isOK(), 'OK' );
368 $this->assertTrue( isset( $status1->value
['revision'] ), 'OK' );
369 $this->assertFalse( isset( $status2->value
['revision'] ), 'OK' );
373 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
374 * TODO: Revision deletion
376 * @covers WikiPage::doDeleteArticle
377 * @covers WikiPage::doDeleteArticleReal
379 public function testDoDeleteArticle() {
380 $page = $this->createPage(
382 "[[original text]] foo",
383 CONTENT_MODEL_WIKITEXT
385 $id = $page->getId();
387 $page->doDeleteArticle( "testing deletion" );
390 $page->getTitle()->getArticleID() > 0,
391 "Title object should now have page id 0"
393 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
396 "WikiPage::exists should return false after page was deleted"
400 "WikiPage::getContent should return null after page was deleted"
403 $t = Title
::newFromText( $page->getTitle()->getPrefixedText() );
406 "Title::exists should return false after page was deleted"
410 JobQueueGroup
::destroySingletons();
412 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
415 # ------------------------
416 $dbr = wfGetDB( DB_REPLICA
);
417 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
418 $n = $res->numRows();
421 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
425 * @covers WikiPage::doDeleteArticleReal
427 public function testDoDeleteArticleReal_user0() {
428 $page = $this->createPage(
430 "[[original text]] foo",
431 CONTENT_MODEL_WIKITEXT
433 $id = $page->getId();
436 $status = $page->doDeleteArticleReal(
437 /* reason */ "testing user 0 deletion",
438 /* suppress */ false,
441 /* errorStack */ $errorStack,
444 $logId = $status->getValue();
445 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
447 [ 'logging' ] +
$actorQuery['tables'], /* table */
452 'log_user' => $actorQuery['fields']['log_user'],
453 'log_user_text' => $actorQuery['fields']['log_user_text'],
457 [ 'log_id' => $logId ],
461 'testing user 0 deletion',
464 (string)$page->getTitle()->getNamespace(),
465 $page->getTitle()->getDBkey(),
473 * @covers WikiPage::doDeleteArticleReal
475 public function testDoDeleteArticleReal_userSysop() {
476 $page = $this->createPage(
478 "[[original text]] foo",
479 CONTENT_MODEL_WIKITEXT
481 $id = $page->getId();
483 $user = $this->getTestSysop()->getUser();
485 $status = $page->doDeleteArticleReal(
486 /* reason */ "testing sysop deletion",
487 /* suppress */ false,
490 /* errorStack */ $errorStack,
493 $logId = $status->getValue();
494 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
496 [ 'logging' ] +
$actorQuery['tables'], /* table */
501 'log_user' => $actorQuery['fields']['log_user'],
502 'log_user_text' => $actorQuery['fields']['log_user_text'],
506 [ 'log_id' => $logId ],
510 'testing sysop deletion',
511 (string)$user->getId(),
513 (string)$page->getTitle()->getNamespace(),
514 $page->getTitle()->getDBkey(),
522 * TODO: Test more stuff about suppression.
524 * @covers WikiPage::doDeleteArticleReal
526 public function testDoDeleteArticleReal_suppress() {
527 $page = $this->createPage(
529 "[[original text]] foo",
530 CONTENT_MODEL_WIKITEXT
532 $id = $page->getId();
534 $user = $this->getTestSysop()->getUser();
536 $status = $page->doDeleteArticleReal(
537 /* reason */ "testing deletion",
541 /* errorStack */ $errorStack,
544 $logId = $status->getValue();
545 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
547 [ 'logging' ] +
$actorQuery['tables'], /* table */
552 'log_user' => $actorQuery['fields']['log_user'],
553 'log_user_text' => $actorQuery['fields']['log_user_text'],
557 [ 'log_id' => $logId ],
562 (string)$user->getId(),
564 (string)$page->getTitle()->getNamespace(),
565 $page->getTitle()->getDBkey(),
572 $page->getContent( Revision
::FOR_PUBLIC
),
573 "WikiPage::getContent should return null after the page was suppressed for general users"
577 $page->getContent( Revision
::FOR_THIS_USER
, null ),
578 "WikiPage::getContent should return null after the page was suppressed for user zero"
582 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
583 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
588 * @covers WikiPage::doDeleteUpdates
590 public function testDoDeleteUpdates() {
591 $page = $this->createPage(
593 "[[original text]] foo",
594 CONTENT_MODEL_WIKITEXT
596 $id = $page->getId();
598 // Similar to MovePage logic
599 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
600 $page->doDeleteUpdates( $id );
603 JobQueueGroup
::destroySingletons();
605 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
608 # ------------------------
609 $dbr = wfGetDB( DB_REPLICA
);
610 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
611 $n = $res->numRows();
614 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
618 * @covers WikiPage::getRevision
620 public function testGetRevision() {
621 $page = $this->newPage( __METHOD__
);
623 $rev = $page->getRevision();
624 $this->assertNull( $rev );
627 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
629 $rev = $page->getRevision();
631 $this->assertEquals( $page->getLatest(), $rev->getId() );
632 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
636 * @covers WikiPage::getContent
638 public function testGetContent() {
639 $page = $this->newPage( __METHOD__
);
641 $content = $page->getContent();
642 $this->assertNull( $content );
645 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
647 $content = $page->getContent();
648 $this->assertEquals( "some text", $content->getNativeData() );
652 * @covers WikiPage::exists
654 public function testExists() {
655 $page = $this->newPage( __METHOD__
);
656 $this->assertFalse( $page->exists() );
659 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
660 $this->assertTrue( $page->exists() );
662 $page = new WikiPage( $page->getTitle() );
663 $this->assertTrue( $page->exists() );
666 $page->doDeleteArticle( "done testing" );
667 $this->assertFalse( $page->exists() );
669 $page = new WikiPage( $page->getTitle() );
670 $this->assertFalse( $page->exists() );
673 public function provideHasViewableContent() {
675 [ 'WikiPageTest_testHasViewableContent', false, true ],
676 [ 'Special:WikiPageTest_testHasViewableContent', false ],
677 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
678 [ 'Special:Userlogin', true ],
679 [ 'MediaWiki:help', true ],
684 * @dataProvider provideHasViewableContent
685 * @covers WikiPage::hasViewableContent
687 public function testHasViewableContent( $title, $viewable, $create = false ) {
688 $page = $this->newPage( $title );
689 $this->assertEquals( $viewable, $page->hasViewableContent() );
692 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
693 $this->assertTrue( $page->hasViewableContent() );
695 $page = new WikiPage( $page->getTitle() );
696 $this->assertTrue( $page->hasViewableContent() );
700 public function provideGetRedirectTarget() {
702 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
704 'WikiPageTest_testGetRedirectTarget_2',
705 CONTENT_MODEL_WIKITEXT
,
706 "#REDIRECT [[hello world]]",
713 * @dataProvider provideGetRedirectTarget
714 * @covers WikiPage::getRedirectTarget
716 public function testGetRedirectTarget( $title, $model, $text, $target ) {
717 $this->setMwGlobals( [
718 'wgCapitalLinks' => true,
721 $page = $this->createPage( $title, $text, $model );
723 # sanity check, because this test seems to fail for no reason for some people.
724 $c = $page->getContent();
725 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
727 # now, test the actual redirect
728 $t = $page->getRedirectTarget();
729 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getPrefixedText() );
733 * @dataProvider provideGetRedirectTarget
734 * @covers WikiPage::isRedirect
736 public function testIsRedirect( $title, $model, $text, $target ) {
737 $page = $this->createPage( $title, $text, $model );
738 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
741 public function provideIsCountable() {
745 [ 'WikiPageTest_testIsCountable',
746 CONTENT_MODEL_WIKITEXT
,
751 [ 'WikiPageTest_testIsCountable',
752 CONTENT_MODEL_WIKITEXT
,
759 [ 'WikiPageTest_testIsCountable',
760 CONTENT_MODEL_WIKITEXT
,
765 [ 'WikiPageTest_testIsCountable',
766 CONTENT_MODEL_WIKITEXT
,
773 [ 'WikiPageTest_testIsCountable',
774 CONTENT_MODEL_WIKITEXT
,
779 [ 'WikiPageTest_testIsCountable',
780 CONTENT_MODEL_WIKITEXT
,
786 // not a content namespace
787 [ 'Talk:WikiPageTest_testIsCountable',
788 CONTENT_MODEL_WIKITEXT
,
793 [ 'Talk:WikiPageTest_testIsCountable',
794 CONTENT_MODEL_WIKITEXT
,
800 // not a content namespace, different model
801 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
807 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
817 * @dataProvider provideIsCountable
818 * @covers WikiPage::isCountable
820 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
821 global $wgContentHandlerUseDB;
823 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
825 $title = Title
::newFromText( $title );
827 if ( !$wgContentHandlerUseDB
829 && ContentHandler
::getDefaultModelFor( $title ) != $model
831 $this->markTestSkipped( "Can not use non-default content model $model for "
832 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
835 $page = $this->createPage( $title, $text, $model );
837 $editInfo = $page->prepareContentForEdit( $page->getContent() );
839 $v = $page->isCountable();
840 $w = $page->isCountable( $editInfo );
845 "isCountable( null ) returned unexpected value " . var_export( $v, true )
846 . " instead of " . var_export( $expected, true )
847 . " in mode `$mode` for text \"$text\""
853 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
854 . " instead of " . var_export( $expected, true )
855 . " in mode `$mode` for text \"$text\""
859 public function provideGetParserOutput() {
862 CONTENT_MODEL_WIKITEXT
,
864 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
871 * @dataProvider provideGetParserOutput
872 * @covers WikiPage::getParserOutput
874 public function testGetParserOutput( $model, $text, $expectedHtml ) {
875 $page = $this->createPage( __METHOD__
, $text, $model );
877 $opt = $page->makeParserOptions( 'canonical' );
878 $po = $page->getParserOutput( $opt );
879 $text = $po->getText();
881 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
882 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
884 $this->assertEquals( $expectedHtml, $text );
890 * @covers WikiPage::getParserOutput
892 public function testGetParserOutput_nonexisting() {
893 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
895 $opt = new ParserOptions();
896 $po = $page->getParserOutput( $opt );
898 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
902 * @covers WikiPage::getParserOutput
904 public function testGetParserOutput_badrev() {
905 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
907 $opt = new ParserOptions();
908 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
910 // @todo would be neat to also test deleted revision
912 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
915 public static $sections =
929 public function dataReplaceSection() {
930 // NOTE: assume the Help namespace to contain wikitext
932 [ 'Help:WikiPageTest_testReplaceSection',
933 CONTENT_MODEL_WIKITEXT
,
938 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
940 [ 'Help:WikiPageTest_testReplaceSection',
941 CONTENT_MODEL_WIKITEXT
,
948 [ 'Help:WikiPageTest_testReplaceSection',
949 CONTENT_MODEL_WIKITEXT
,
952 "== TEST ==\nmore fun",
954 trim( preg_replace( '/^== test ==.*== foo ==/sm',
955 "== TEST ==\nmore fun\n\n== foo ==",
958 [ 'Help:WikiPageTest_testReplaceSection',
959 CONTENT_MODEL_WIKITEXT
,
964 trim( self
::$sections )
966 [ 'Help:WikiPageTest_testReplaceSection',
967 CONTENT_MODEL_WIKITEXT
,
972 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
978 * @dataProvider dataReplaceSection
979 * @covers WikiPage::replaceSectionContent
981 public function testReplaceSectionContent( $title, $model, $text, $section,
982 $with, $sectionTitle, $expected
984 $page = $this->createPage( $title, $text, $model );
986 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
987 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
989 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
993 * @dataProvider dataReplaceSection
994 * @covers WikiPage::replaceSectionAtRev
996 public function testReplaceSectionAtRev( $title, $model, $text, $section,
997 $with, $sectionTitle, $expected
999 $page = $this->createPage( $title, $text, $model );
1000 $baseRevId = $page->getLatest();
1002 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1003 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1005 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1009 * @covers WikiPage::getOldestRevision
1011 public function testGetOldestRevision() {
1012 $page = $this->newPage( __METHOD__
);
1013 $page->doEditContent(
1014 new WikitextContent( 'one' ),
1018 $rev1 = $page->getRevision();
1020 $page = new WikiPage( $page->getTitle() );
1021 $page->doEditContent(
1022 new WikitextContent( 'two' ),
1027 $page = new WikiPage( $page->getTitle() );
1028 $page->doEditContent(
1029 new WikitextContent( 'three' ),
1035 $this->assertNotEquals(
1037 $page->getRevision()->getId(),
1038 '$page->getRevision()->getId()'
1042 $this->assertEquals(
1044 $page->getOldestRevision()->getId(),
1045 '$page->getOldestRevision()->getId()'
1050 * @covers WikiPage::doRollback
1051 * @covers WikiPage::commitRollback
1053 public function testDoRollback() {
1054 $admin = $this->getTestSysop()->getUser();
1055 $user1 = $this->getTestUser()->getUser();
1056 // Use the confirmed group for user2 to make sure the user is different
1057 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1059 // make sure we can test autopatrolling
1060 $this->setMwGlobals( 'wgUseRCPatrol', true );
1062 // TODO: MCR: test rollback of multiple slots!
1063 $page = $this->newPage( __METHOD__
);
1067 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1068 "section one", EDIT_NEW
, false, $admin );
1071 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1072 "adding section two", 0, false, $user1 );
1074 $text .= "\n\nthree";
1075 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1076 "adding section three", 0, false, $user2 );
1078 /** @var Revision $rev1 */
1079 /** @var Revision $rev2 */
1080 /** @var Revision $rev3 */
1081 $rev1 = $status1->getValue()['revision'];
1082 $rev2 = $status2->getValue()['revision'];
1083 $rev3 = $status3->getValue()['revision'];
1086 * We are having issues with doRollback spuriously failing. Apparently
1087 * the last revision somehow goes missing or not committed under some
1088 * circumstances. So, make sure the revisions have the correct usernames.
1090 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1091 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1092 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1093 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1095 // Now, try the actual rollback
1096 $token = $admin->getEditToken( 'rollback' );
1097 $rollbackErrors = $page->doRollback(
1106 if ( $rollbackErrors ) {
1108 "Rollback failed:\n" .
1109 print_r( $rollbackErrors, true ) . ";\n" .
1110 print_r( $resultDetails, true )
1114 $page = new WikiPage( $page->getTitle() );
1115 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1116 "rollback did not revert to the correct revision" );
1117 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1119 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1120 $page->getRevision()->getRevisionRecord()
1123 $this->assertNotNull( $rc, 'RecentChanges entry' );
1124 $this->assertEquals(
1125 RecentChange
::PRC_AUTOPATROLLED
,
1126 $rc->getAttribute( 'rc_patrolled' ),
1130 // TODO: MCR: assert origin once we write slot data
1131 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
1132 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1133 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1137 * @covers WikiPage::doRollback
1138 * @covers WikiPage::commitRollback
1140 public function testDoRollbackFailureSameContent() {
1141 $admin = $this->getTestSysop()->getUser();
1144 $page = $this->newPage( __METHOD__
);
1145 $page->doEditContent(
1146 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1152 $rev1 = $page->getRevision();
1154 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1156 $page = new WikiPage( $page->getTitle() );
1157 $page->doEditContent(
1158 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1159 "adding section two",
1165 # now, do a the rollback from the same user was doing the edit before
1166 $resultDetails = [];
1167 $token = $user1->getEditToken( 'rollback' );
1168 $errors = $page->doRollback(
1170 "testing revert same user",
1177 $this->assertEquals( [], $errors, "Rollback failed same user" );
1179 # now, try the rollback
1180 $resultDetails = [];
1181 $token = $admin->getEditToken( 'rollback' );
1182 $errors = $page->doRollback(
1191 $this->assertEquals(
1201 "Rollback not failed"
1204 $page = new WikiPage( $page->getTitle() );
1205 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1206 "rollback did not revert to the correct revision" );
1207 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1211 * Tests tagging for edits that do rollback action
1212 * @covers WikiPage::doRollback
1214 public function testDoRollbackTagging() {
1215 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1216 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1219 $admin = new User();
1220 $admin->setName( 'Administrator' );
1221 $admin->addToDatabase();
1223 $text = 'First line';
1224 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1225 $page->doEditContent(
1226 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1233 $secondUser = new User();
1234 $secondUser->setName( '92.65.217.32' );
1235 $text .= '\n\nSecond line';
1236 $page = new WikiPage( $page->getTitle() );
1237 $page->doEditContent(
1238 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1239 'Adding second line',
1245 // Now, try the rollback
1246 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1247 $token = $admin->getEditToken( 'rollback' );
1248 $errors = $page->doRollback(
1249 $secondUser->getName(),
1257 // If doRollback completed without errors
1258 if ( $errors === [] ) {
1259 $tags = $resultDetails[ 'tags' ];
1260 $this->assertContains( 'mw-rollback', $tags );
1264 public function provideGetAutoDeleteReason() {
1274 [ "first edit", null ],
1276 "/first edit.*only contributor/",
1282 [ "first edit", null ],
1283 [ "second edit", null ],
1285 "/second edit.*only contributor/",
1291 [ "first edit", "127.0.2.22" ],
1292 [ "second edit", "127.0.3.33" ],
1302 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1303 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1304 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1305 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1306 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1310 '/first edit:.*\.\.\."/',
1316 [ "first edit", "127.0.2.22" ],
1317 [ "", "127.0.3.33" ],
1319 "/before blanking.*first edit/",
1327 * @dataProvider provideGetAutoDeleteReason
1328 * @covers WikiPage::getAutoDeleteReason
1330 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1333 // NOTE: assume Help namespace to contain wikitext
1334 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1338 foreach ( $edits as $edit ) {
1341 if ( !empty( $edit[1] ) ) {
1342 $user->setName( $edit[1] );
1347 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1349 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1354 $reason = $page->getAutoDeleteReason( $hasHistory );
1356 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1357 $this->assertEquals( $expectedResult, $reason );
1359 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1360 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1363 $this->assertEquals( $expectedHistory, $hasHistory,
1364 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1366 $page->doDeleteArticle( "done" );
1369 public function providePreSaveTransform() {
1371 [ 'hello this is ~~~',
1372 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1374 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1375 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1381 * @covers WikiPage::factory
1383 public function testWikiPageFactory() {
1384 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1385 $page = WikiPage
::factory( $title );
1386 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1388 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1389 $page = WikiPage
::factory( $title );
1390 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1392 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1393 $page = WikiPage
::factory( $title );
1394 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1398 * @covers WikiPage::loadPageData
1399 * @covers WikiPage::wasLoadedFrom
1401 public function testLoadPageData() {
1402 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1403 $page = WikiPage
::factory( $title );
1405 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1406 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1407 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1408 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1410 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1411 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1412 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1413 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1414 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1416 $page->loadPageData( IDBAccessObject
::READ_LATEST
);
1417 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1418 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1419 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1420 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1422 $page->loadPageData( IDBAccessObject
::READ_LOCKING
);
1423 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1424 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1425 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1426 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1428 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
1429 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1430 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1431 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1432 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1436 * @dataProvider provideCommentMigrationOnDeletion
1438 * @param int $writeStage
1439 * @param int $readStage
1441 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1442 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1443 $this->overrideMwServices();
1445 $dbr = wfGetDB( DB_REPLICA
);
1447 $page = $this->createPage(
1450 CONTENT_MODEL_WIKITEXT
1452 $revid = $page->getLatest();
1453 if ( $writeStage > MIGRATION_OLD
) {
1454 $comment_id = $dbr->selectField(
1455 'revision_comment_temp',
1456 'revcomment_comment_id',
1457 [ 'revcomment_rev' => $revid ],
1462 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1463 $this->overrideMwServices();
1465 $page->doDeleteArticle( "testing deletion" );
1467 if ( $readStage > MIGRATION_OLD
) {
1468 // Didn't leave behind any 'revision_comment_temp' rows
1469 $n = $dbr->selectField(
1470 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1472 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1474 // Copied or upgraded the comment_id, as applicable
1475 $ar_comment_id = $dbr->selectField(
1478 [ 'ar_rev_id' => $revid ],
1481 if ( $writeStage > MIGRATION_OLD
) {
1482 $this->assertSame( $comment_id, $ar_comment_id );
1484 $this->assertNotEquals( 0, $ar_comment_id );
1488 // Copied rev_comment, if applicable
1489 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1490 $ar_comment = $dbr->selectField(
1493 [ 'ar_rev_id' => $revid ],
1496 $this->assertSame( 'testing', $ar_comment );
1500 public function provideCommentMigrationOnDeletion() {
1502 [ MIGRATION_OLD
, MIGRATION_OLD
],
1503 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1504 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1505 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1506 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1507 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1508 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1509 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1510 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1511 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1512 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1513 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1514 [ MIGRATION_NEW
, MIGRATION_NEW
],
1519 * @covers WikiPage::updateCategoryCounts
1521 public function testUpdateCategoryCounts() {
1522 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1524 // Add an initial category
1525 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1527 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1528 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1529 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1531 // Add a new category
1532 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1534 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1535 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1536 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1538 // Add and remove a category
1539 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1541 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1542 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1543 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1546 public function provideUpdateRedirectOn() {
1547 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1548 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1549 yield
[ 'SomeText', false, null, false, true, 0 ];
1550 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1554 * @dataProvider provideUpdateRedirectOn
1555 * @covers WikiPage::updateRedirectOn
1557 * @param string $initialText
1558 * @param bool $initialRedirectState
1559 * @param string|null $redirectTitle
1560 * @param bool|null $lastRevIsRedirect
1561 * @param bool $expectedSuccess
1562 * @param int $expectedRowCount
1564 public function testUpdateRedirectOn(
1566 $initialRedirectState,
1572 static $pageCounter = 0;
1575 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1576 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1578 $redirectTitle = is_string( $redirectTitle )
1579 ? Title
::newFromText( $redirectTitle )
1582 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1583 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1585 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1586 * Most of core checks the page table for redirect status, so we have to be ugly and
1587 * assert a select from the table here.
1589 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1592 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1593 $this->assertSelect(
1596 [ 'rd_from' => $pageId ],
1597 [ [ strval( $expected ) ] ]
1602 * @covers WikiPage::insertRedirectEntry
1604 public function testInsertRedirectEntry_insertsRedirectEntry() {
1605 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1606 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1608 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1609 $targetTitle->mInterwiki
= 'eninter';
1610 $page->insertRedirectEntry( $targetTitle, null );
1612 $this->assertSelect(
1614 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1615 [ 'rd_from' => $page->getId() ],
1617 strval( $page->getId() ),
1618 strval( $targetTitle->getNamespace() ),
1619 strval( $targetTitle->getDBkey() ),
1620 strval( $targetTitle->getFragment() ),
1621 strval( $targetTitle->getInterwiki() ),
1627 * @covers WikiPage::insertRedirectEntry
1629 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1630 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1631 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1633 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1634 $targetTitle->mInterwiki
= 'eninter';
1635 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1637 $this->assertSelect(
1639 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1640 [ 'rd_from' => $page->getId() ],
1642 strval( $page->getId() ),
1643 strval( $targetTitle->getNamespace() ),
1644 strval( $targetTitle->getDBkey() ),
1645 strval( $targetTitle->getFragment() ),
1646 strval( $targetTitle->getInterwiki() ),
1652 * @covers WikiPage::insertRedirectEntry
1654 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1655 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1656 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1658 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1659 $targetTitle->mInterwiki
= 'eninter';
1660 $page->insertRedirectEntry( $targetTitle, 215251 );
1662 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1665 private function getRow( array $overrides = [] ) {
1669 'page_is_redirect' => '1',
1670 'page_latest' => '99',
1671 'page_namespace' => '3',
1672 'page_title' => 'JaJaTitle',
1673 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1674 'page_touched' => '20120101020202',
1675 'page_links_updated' => '20140101020202',
1677 foreach ( $overrides as $key => $value ) {
1678 $row[$key] = $value;
1680 return (object)$row;
1683 public function provideNewFromRowSuccess() {
1684 yield
'basic row' => [
1686 function ( WikiPage
$wikiPage, self
$test ) {
1687 $test->assertSame( 44, $wikiPage->getId() );
1688 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1689 $test->assertTrue( $wikiPage->isRedirect() );
1690 $test->assertSame( 99, $wikiPage->getLatest() );
1691 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1692 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1695 'edit' => [ 'autoconfirmed', 'sysop' ],
1696 'move' => [ 'sysop' ],
1698 $wikiPage->getTitle()->getAllRestrictions()
1700 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1701 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1704 yield
'different timestamp formats' => [
1706 'page_touched' => '2012-01-01 02:02:02',
1707 'page_links_updated' => '2014-01-01 02:02:02',
1709 function ( WikiPage
$wikiPage, self
$test ) {
1710 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1711 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1714 yield
'no restrictions' => [
1716 'page_restrictions' => '',
1718 function ( WikiPage
$wikiPage, self
$test ) {
1724 $wikiPage->getTitle()->getAllRestrictions()
1728 yield
'not redirect' => [
1730 'page_is_redirect' => '0',
1732 function ( WikiPage
$wikiPage, self
$test ) {
1733 $test->assertFalse( $wikiPage->isRedirect() );
1739 * @covers WikiPage::newFromRow
1740 * @covers WikiPage::loadFromRow
1741 * @dataProvider provideNewFromRowSuccess
1743 * @param object $row
1744 * @param callable $assertions
1746 public function testNewFromRow( $row, $assertions ) {
1747 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1748 $assertions( $page, $this );
1751 public function provideTestNewFromId_returnsNullOnBadPageId() {
1757 * @covers WikiPage::newFromID
1758 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1760 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1761 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1765 * @covers WikiPage::newFromID
1767 public function testNewFromId_appearsToFetchCorrectRow() {
1768 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1769 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1770 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1771 $this->assertEquals(
1772 $createdPage->getContent()->getNativeData(),
1773 $fetchedPage->getContent()->getNativeData()
1778 * @covers WikiPage::newFromID
1780 public function testNewFromId_returnsNullOnNonExistingId() {
1781 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1784 public function provideTestInsertProtectNullRevision() {
1785 // phpcs:disable Generic.Files.LineLength
1788 [ 'edit' => 'sysop' ],
1789 [ 'edit' => '20200101040404' ],
1793 '(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)))'
1797 [ 'edit' => 'sysop', 'move' => 'something' ],
1798 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1802 '(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)))'
1808 * @dataProvider provideTestInsertProtectNullRevision
1809 * @covers WikiPage::insertProtectNullRevision
1810 * @covers WikiPage::protectDescription
1812 * @param string $revCommentMsg
1813 * @param array $limit
1814 * @param array $expiry
1815 * @param bool $cascade
1816 * @param string $reason
1817 * @param bool|null $user true if the test sysop should be used, or null
1818 * @param string $expectedComment
1820 public function testInsertProtectNullRevision(
1829 $this->setContentLang( 'qqx' );
1831 $page = $this->createPage( __METHOD__
, 'Goat' );
1833 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1835 $result = $page->insertProtectNullRevision(
1844 $this->assertTrue( $result instanceof Revision
);
1845 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1849 * @covers WikiPage::updateRevisionOn
1851 public function testUpdateRevisionOn_existingPage() {
1852 $user = $this->getTestSysop()->getUser();
1853 $page = $this->createPage( __METHOD__
, 'StartText' );
1855 $revision = new Revision(
1858 'page' => $page->getId(),
1859 'title' => $page->getTitle(),
1860 'comment' => __METHOD__
,
1861 'minor_edit' => true,
1862 'text' => __METHOD__
. '-text',
1863 'len' => strlen( __METHOD__
. '-text' ),
1864 'user' => $user->getId(),
1865 'user_text' => $user->getName(),
1866 'timestamp' => '20170707040404',
1867 'content_model' => CONTENT_MODEL_WIKITEXT
,
1868 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1872 $result = $page->updateRevisionOn( $this->db
, $revision );
1873 $this->assertTrue( $result );
1874 $this->assertSame( 9989, $page->getLatest() );
1875 $this->assertEquals( $revision, $page->getRevision() );
1879 * @covers WikiPage::updateRevisionOn
1881 public function testUpdateRevisionOn_NonExistingPage() {
1882 $user = $this->getTestSysop()->getUser();
1883 $page = $this->createPage( __METHOD__
, 'StartText' );
1884 $page->doDeleteArticle( 'reason' );
1886 $revision = new Revision(
1889 'page' => $page->getId(),
1890 'title' => $page->getTitle(),
1891 'comment' => __METHOD__
,
1892 'minor_edit' => true,
1893 'text' => __METHOD__
. '-text',
1894 'len' => strlen( __METHOD__
. '-text' ),
1895 'user' => $user->getId(),
1896 'user_text' => $user->getName(),
1897 'timestamp' => '20170707040404',
1898 'content_model' => CONTENT_MODEL_WIKITEXT
,
1899 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1903 $result = $page->updateRevisionOn( $this->db
, $revision );
1904 $this->assertFalse( $result );
1908 * @covers WikiPage::updateIfNewerOn
1910 public function testUpdateIfNewerOn_olderRevision() {
1911 $user = $this->getTestSysop()->getUser();
1912 $page = $this->createPage( __METHOD__
, 'StartText' );
1913 $initialRevision = $page->getRevision();
1915 $olderTimeStamp = wfTimestamp(
1917 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
1920 $olderRevison = new Revision(
1923 'page' => $page->getId(),
1924 'title' => $page->getTitle(),
1925 'comment' => __METHOD__
,
1926 'minor_edit' => true,
1927 'text' => __METHOD__
. '-text',
1928 'len' => strlen( __METHOD__
. '-text' ),
1929 'user' => $user->getId(),
1930 'user_text' => $user->getName(),
1931 'timestamp' => $olderTimeStamp,
1932 'content_model' => CONTENT_MODEL_WIKITEXT
,
1933 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1937 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
1938 $this->assertFalse( $result );
1942 * @covers WikiPage::updateIfNewerOn
1944 public function testUpdateIfNewerOn_newerRevision() {
1945 $user = $this->getTestSysop()->getUser();
1946 $page = $this->createPage( __METHOD__
, 'StartText' );
1947 $initialRevision = $page->getRevision();
1949 $newerTimeStamp = wfTimestamp(
1951 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
1954 $newerRevision = new Revision(
1957 'page' => $page->getId(),
1958 'title' => $page->getTitle(),
1959 'comment' => __METHOD__
,
1960 'minor_edit' => true,
1961 'text' => __METHOD__
. '-text',
1962 'len' => strlen( __METHOD__
. '-text' ),
1963 'user' => $user->getId(),
1964 'user_text' => $user->getName(),
1965 'timestamp' => $newerTimeStamp,
1966 'content_model' => CONTENT_MODEL_WIKITEXT
,
1967 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1970 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
1971 $this->assertTrue( $result );
1975 * @covers WikiPage::insertOn
1977 public function testInsertOn() {
1978 $title = Title
::newFromText( __METHOD__
);
1979 $page = new WikiPage( $title );
1981 $startTimeStamp = wfTimestampNow();
1982 $result = $page->insertOn( $this->db
);
1983 $endTimeStamp = wfTimestampNow();
1985 $this->assertInternalType( 'int', $result );
1986 $this->assertTrue( $result > 0 );
1988 $condition = [ 'page_id' => $result ];
1990 // Check the default fields have been filled
1991 $this->assertSelect(
1996 'page_restrictions',
2014 // Check the page_random field has been filled
2015 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2016 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2018 // Assert the touched timestamp in the DB is roughly when we inserted the page
2019 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2021 wfTimestamp( TS_UNIX
, $startTimeStamp )
2022 <= wfTimestamp( TS_UNIX
, $pageTouched )
2025 wfTimestamp( TS_UNIX
, $endTimeStamp )
2026 >= wfTimestamp( TS_UNIX
, $pageTouched )
2029 // Try inserting the same page again and checking the result is false (no change)
2030 $result = $page->insertOn( $this->db
);
2031 $this->assertFalse( $result );
2035 * @covers WikiPage::insertOn
2037 public function testInsertOn_idSpecified() {
2038 $title = Title
::newFromText( __METHOD__
);
2039 $page = new WikiPage( $title );
2042 $result = $page->insertOn( $this->db
, $id );
2044 $this->assertSame( $id, $result );
2046 $condition = [ 'page_id' => $result ];
2048 // Check there is actually a row in the db
2049 $this->assertSelect(
2057 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2058 // Note: Once the current dates passes the date in these tests they will fail.
2059 yield
'move something' => [
2061 [ 'move' => 'something' ],
2063 [ 'edit' => [], 'move' => [ 'something' ] ],
2066 yield
'move something, edit blank' => [
2068 [ 'move' => 'something', 'edit' => '' ],
2070 [ 'edit' => [], 'move' => [ 'something' ] ],
2073 yield
'edit sysop, with expiry' => [
2075 [ 'edit' => 'sysop' ],
2076 [ 'edit' => '21330101020202' ],
2077 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2078 [ 'edit' => '21330101020202' ],
2080 yield
'move and edit, move with expiry' => [
2082 [ 'move' => 'something', 'edit' => 'another' ],
2083 [ 'move' => '22220202010101' ],
2084 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2085 [ 'move' => '22220202010101' ],
2087 yield
'move and edit, edit with infinity expiry' => [
2089 [ 'move' => 'something', 'edit' => 'another' ],
2090 [ 'edit' => 'infinity' ],
2091 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2092 [ 'edit' => 'infinity' ],
2094 yield
'non existing, create something' => [
2096 [ 'create' => 'something' ],
2098 [ 'create' => [ 'something' ] ],
2101 yield
'non existing, create something with expiry' => [
2103 [ 'create' => 'something' ],
2104 [ 'create' => '23451212112233' ],
2105 [ 'create' => [ 'something' ] ],
2106 [ 'create' => '23451212112233' ],
2111 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2112 * @covers WikiPage::doUpdateRestrictions
2114 public function testDoUpdateRestrictions_setBasicRestrictions(
2118 array $expectedRestrictions,
2119 array $expectedRestrictionExpiries
2121 if ( $pageExists ) {
2122 $page = $this->createPage( __METHOD__
, 'ABC' );
2124 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2126 $user = $this->getTestSysop()->getUser();
2129 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2131 $logId = $status->getValue();
2132 $allRestrictions = $page->getTitle()->getAllRestrictions();
2134 $this->assertTrue( $status->isGood() );
2135 $this->assertInternalType( 'int', $logId );
2136 $this->assertSame( $expectedRestrictions, $allRestrictions );
2137 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2138 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2141 // Make sure the log entry looks good
2142 // log_params is not checked here
2143 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2144 $this->assertSelect(
2145 [ 'logging' ] +
$actorQuery['tables'],
2148 'log_user' => $actorQuery['fields']['log_user'],
2149 'log_user_text' => $actorQuery['fields']['log_user_text'],
2153 [ 'log_id' => $logId ],
2156 (string)$user->getId(),
2158 (string)$page->getTitle()->getNamespace(),
2159 $page->getTitle()->getDBkey(),
2162 $actorQuery['joins']
2167 * @covers WikiPage::doUpdateRestrictions
2169 public function testDoUpdateRestrictions_failsOnReadOnly() {
2170 $page = $this->createPage( __METHOD__
, 'ABC' );
2171 $user = $this->getTestSysop()->getUser();
2175 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2176 ->disableOriginalConstructor()
2177 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2179 $readOnly->expects( $this->once() )
2180 ->method( 'isReadOnly' )
2181 ->will( $this->returnValue( true ) );
2182 $readOnly->expects( $this->once() )
2183 ->method( 'getReason' )
2184 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2185 $this->setService( 'ReadOnlyMode', $readOnly );
2187 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2188 $this->assertFalse( $status->isOK() );
2189 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2193 * @covers WikiPage::doUpdateRestrictions
2195 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2196 $page = $this->createPage( __METHOD__
, 'ABC' );
2197 $user = $this->getTestSysop()->getUser();
2199 $limit = [ 'edit' => 'sysop' ];
2201 $status = $page->doUpdateRestrictions(
2210 // The first entry should have a logId as it did something
2211 $this->assertTrue( $status->isGood() );
2212 $this->assertInternalType( 'int', $status->getValue() );
2214 $status = $page->doUpdateRestrictions(
2223 // The second entry should not have a logId as nothing changed
2224 $this->assertTrue( $status->isGood() );
2225 $this->assertNull( $status->getValue() );
2229 * @covers WikiPage::doUpdateRestrictions
2231 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2232 $page = $this->createPage( __METHOD__
, 'ABC' );
2233 $user = $this->getTestSysop()->getUser();
2237 $status = $page->doUpdateRestrictions(
2238 [ 'edit' => 'sysop' ],
2245 $this->assertTrue( $status->isGood() );
2246 $this->assertInternalType( 'int', $status->getValue() );
2247 $this->assertSelect(
2249 [ 'log_type', 'log_action' ],
2250 [ 'log_id' => $status->getValue() ],
2251 [ [ 'protect', 'protect' ] ]
2254 // Modify the protection
2255 $status = $page->doUpdateRestrictions(
2256 [ 'edit' => 'somethingElse' ],
2263 $this->assertTrue( $status->isGood() );
2264 $this->assertInternalType( 'int', $status->getValue() );
2265 $this->assertSelect(
2267 [ 'log_type', 'log_action' ],
2268 [ 'log_id' => $status->getValue() ],
2269 [ [ 'protect', 'modify' ] ]
2272 // Remove the protection
2273 $status = $page->doUpdateRestrictions(
2281 $this->assertTrue( $status->isGood() );
2282 $this->assertInternalType( 'int', $status->getValue() );
2283 $this->assertSelect(
2285 [ 'log_type', 'log_action' ],
2286 [ 'log_id' => $status->getValue() ],
2287 [ [ 'protect', 'unprotect' ] ]
2292 * @covers WikiPage::newPageUpdater
2293 * @covers WikiPage::getDerivedDataUpdater
2295 public function testNewPageUpdater() {
2296 $user = $this->getTestUser()->getUser();
2297 $page = $this->newPage( __METHOD__
, __METHOD__
);
2299 /** @var Content $content */
2300 $content = $this->getMockBuilder( WikitextContent
::class )
2301 ->setConstructorArgs( [ 'Hello World' ] )
2302 ->setMethods( [ 'getParserOutput' ] )
2304 $content->expects( $this->once() )
2305 ->method( 'getParserOutput' )
2306 ->willReturn( new ParserOutput( 'HTML' ) );
2308 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2310 // provide context, so the cache can be kept in place
2311 $slotsUpdate = new revisionSlotsUpdate();
2312 $slotsUpdate->modifyContent( 'main', $content );
2314 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2315 $updater->setContent( 'main', $content );
2316 $revision = $updater->saveRevision(
2317 CommentStoreComment
::newUnsavedComment( 'test' ),
2321 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2323 $this->assertSame( $revision->getId(), $page->getLatest() );
2325 // Parsed output must remain cached throughout.
2326 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2330 * @covers WikiPage::newPageUpdater
2331 * @covers WikiPage::getDerivedDataUpdater
2333 public function testGetDerivedDataUpdater() {
2334 $admin = $this->getTestSysop()->getUser();
2336 /** @var object $page */
2337 $page = $this->createPage( __METHOD__
, __METHOD__
);
2338 $page = TestingAccessWrapper
::newFromObject( $page );
2340 $revision = $page->getRevision()->getRevisionRecord();
2341 $user = $revision->getUser();
2343 $slotsUpdate = new RevisionSlotsUpdate();
2344 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2346 // get a virgin updater
2347 $updater1 = $page->getDerivedDataUpdater( $user );
2348 $this->assertFalse( $updater1->isUpdatePrepared() );
2350 $updater1->prepareUpdate( $revision );
2352 // Re-use updater with same revision or content, even if base changed
2353 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2355 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2356 [ 'main' => $revision->getContent( 'main' ) ]
2358 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2360 // Don't re-use for edit if base revision ID changed
2361 $this->assertNotSame(
2363 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2366 // Don't re-use with different user
2367 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2368 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2370 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2371 $updater2b->prepareContent( $user, $slotsUpdate, false );
2372 $this->assertNotSame( $updater2a, $updater2b );
2374 // Don't re-use with different content
2375 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2376 $updater3->prepareUpdate( $revision );
2377 $this->assertNotSame( $updater2b, $updater3 );
2379 // Don't re-use if no context given
2380 $updater4 = $page->getDerivedDataUpdater( $admin );
2381 $updater4->prepareUpdate( $revision );
2382 $this->assertNotSame( $updater3, $updater4 );
2384 // Don't re-use if AGAIN no context given
2385 $updater5 = $page->getDerivedDataUpdater( $admin );
2386 $this->assertNotSame( $updater4, $updater5 );
2388 // Don't re-use cached "virgin" unprepared updater
2389 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2390 $this->assertNotSame( $updater5, $updater6 );