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 // FIXME: fails under sqlite
1573 $this->markTestSkippedIfDbType( 'sqlite' );
1574 static $pageCounter = 0;
1577 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1578 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1580 $redirectTitle = is_string( $redirectTitle )
1581 ? Title
::newFromText( $redirectTitle )
1584 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1585 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1587 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1588 * Most of core checks the page table for redirect status, so we have to be ugly and
1589 * assert a select from the table here.
1591 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1594 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1595 $this->assertSelect(
1598 [ 'rd_from' => $pageId ],
1599 [ [ strval( $expected ) ] ]
1604 * @covers WikiPage::insertRedirectEntry
1606 public function testInsertRedirectEntry_insertsRedirectEntry() {
1607 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1608 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1610 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1611 $targetTitle->mInterwiki
= 'eninter';
1612 $page->insertRedirectEntry( $targetTitle, null );
1614 $this->assertSelect(
1616 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1617 [ 'rd_from' => $page->getId() ],
1619 strval( $page->getId() ),
1620 strval( $targetTitle->getNamespace() ),
1621 strval( $targetTitle->getDBkey() ),
1622 strval( $targetTitle->getFragment() ),
1623 strval( $targetTitle->getInterwiki() ),
1629 * @covers WikiPage::insertRedirectEntry
1631 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1632 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1633 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1635 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1636 $targetTitle->mInterwiki
= 'eninter';
1637 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1639 $this->assertSelect(
1641 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1642 [ 'rd_from' => $page->getId() ],
1644 strval( $page->getId() ),
1645 strval( $targetTitle->getNamespace() ),
1646 strval( $targetTitle->getDBkey() ),
1647 strval( $targetTitle->getFragment() ),
1648 strval( $targetTitle->getInterwiki() ),
1654 * @covers WikiPage::insertRedirectEntry
1656 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1657 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1658 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1660 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1661 $targetTitle->mInterwiki
= 'eninter';
1662 $page->insertRedirectEntry( $targetTitle, 215251 );
1664 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1667 private function getRow( array $overrides = [] ) {
1671 'page_is_redirect' => '1',
1672 'page_latest' => '99',
1673 'page_namespace' => '3',
1674 'page_title' => 'JaJaTitle',
1675 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1676 'page_touched' => '20120101020202',
1677 'page_links_updated' => '20140101020202',
1679 foreach ( $overrides as $key => $value ) {
1680 $row[$key] = $value;
1682 return (object)$row;
1685 public function provideNewFromRowSuccess() {
1686 yield
'basic row' => [
1688 function ( WikiPage
$wikiPage, self
$test ) {
1689 $test->assertSame( 44, $wikiPage->getId() );
1690 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1691 $test->assertTrue( $wikiPage->isRedirect() );
1692 $test->assertSame( 99, $wikiPage->getLatest() );
1693 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1694 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1697 'edit' => [ 'autoconfirmed', 'sysop' ],
1698 'move' => [ 'sysop' ],
1700 $wikiPage->getTitle()->getAllRestrictions()
1702 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1703 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1706 yield
'different timestamp formats' => [
1708 'page_touched' => '2012-01-01 02:02:02',
1709 'page_links_updated' => '2014-01-01 02:02:02',
1711 function ( WikiPage
$wikiPage, self
$test ) {
1712 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1713 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1716 yield
'no restrictions' => [
1718 'page_restrictions' => '',
1720 function ( WikiPage
$wikiPage, self
$test ) {
1726 $wikiPage->getTitle()->getAllRestrictions()
1730 yield
'not redirect' => [
1732 'page_is_redirect' => '0',
1734 function ( WikiPage
$wikiPage, self
$test ) {
1735 $test->assertFalse( $wikiPage->isRedirect() );
1741 * @covers WikiPage::newFromRow
1742 * @covers WikiPage::loadFromRow
1743 * @dataProvider provideNewFromRowSuccess
1745 * @param object $row
1746 * @param callable $assertions
1748 public function testNewFromRow( $row, $assertions ) {
1749 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1750 $assertions( $page, $this );
1753 public function provideTestNewFromId_returnsNullOnBadPageId() {
1759 * @covers WikiPage::newFromID
1760 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1762 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1763 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1767 * @covers WikiPage::newFromID
1769 public function testNewFromId_appearsToFetchCorrectRow() {
1770 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1771 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1772 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1773 $this->assertEquals(
1774 $createdPage->getContent()->getNativeData(),
1775 $fetchedPage->getContent()->getNativeData()
1780 * @covers WikiPage::newFromID
1782 public function testNewFromId_returnsNullOnNonExistingId() {
1783 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1786 public function provideTestInsertProtectNullRevision() {
1787 // phpcs:disable Generic.Files.LineLength
1790 [ 'edit' => 'sysop' ],
1791 [ 'edit' => '20200101040404' ],
1795 '(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)))'
1799 [ 'edit' => 'sysop', 'move' => 'something' ],
1800 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1804 '(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)))'
1810 * @dataProvider provideTestInsertProtectNullRevision
1811 * @covers WikiPage::insertProtectNullRevision
1812 * @covers WikiPage::protectDescription
1814 * @param string $revCommentMsg
1815 * @param array $limit
1816 * @param array $expiry
1817 * @param bool $cascade
1818 * @param string $reason
1819 * @param bool|null $user true if the test sysop should be used, or null
1820 * @param string $expectedComment
1822 public function testInsertProtectNullRevision(
1831 $this->setContentLang( 'qqx' );
1833 $page = $this->createPage( __METHOD__
, 'Goat' );
1835 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1837 $result = $page->insertProtectNullRevision(
1846 $this->assertTrue( $result instanceof Revision
);
1847 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1851 * @covers WikiPage::updateRevisionOn
1853 public function testUpdateRevisionOn_existingPage() {
1854 $user = $this->getTestSysop()->getUser();
1855 $page = $this->createPage( __METHOD__
, 'StartText' );
1857 $revision = new Revision(
1860 'page' => $page->getId(),
1861 'title' => $page->getTitle(),
1862 'comment' => __METHOD__
,
1863 'minor_edit' => true,
1864 'text' => __METHOD__
. '-text',
1865 'len' => strlen( __METHOD__
. '-text' ),
1866 'user' => $user->getId(),
1867 'user_text' => $user->getName(),
1868 'timestamp' => '20170707040404',
1869 'content_model' => CONTENT_MODEL_WIKITEXT
,
1870 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1874 $result = $page->updateRevisionOn( $this->db
, $revision );
1875 $this->assertTrue( $result );
1876 $this->assertSame( 9989, $page->getLatest() );
1877 $this->assertEquals( $revision, $page->getRevision() );
1881 * @covers WikiPage::updateRevisionOn
1883 public function testUpdateRevisionOn_NonExistingPage() {
1884 $user = $this->getTestSysop()->getUser();
1885 $page = $this->createPage( __METHOD__
, 'StartText' );
1886 $page->doDeleteArticle( 'reason' );
1888 $revision = new Revision(
1891 'page' => $page->getId(),
1892 'title' => $page->getTitle(),
1893 'comment' => __METHOD__
,
1894 'minor_edit' => true,
1895 'text' => __METHOD__
. '-text',
1896 'len' => strlen( __METHOD__
. '-text' ),
1897 'user' => $user->getId(),
1898 'user_text' => $user->getName(),
1899 'timestamp' => '20170707040404',
1900 'content_model' => CONTENT_MODEL_WIKITEXT
,
1901 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1905 $result = $page->updateRevisionOn( $this->db
, $revision );
1906 $this->assertFalse( $result );
1910 * @covers WikiPage::updateIfNewerOn
1912 public function testUpdateIfNewerOn_olderRevision() {
1913 $user = $this->getTestSysop()->getUser();
1914 $page = $this->createPage( __METHOD__
, 'StartText' );
1915 $initialRevision = $page->getRevision();
1917 $olderTimeStamp = wfTimestamp(
1919 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
1922 $olderRevison = new Revision(
1925 'page' => $page->getId(),
1926 'title' => $page->getTitle(),
1927 'comment' => __METHOD__
,
1928 'minor_edit' => true,
1929 'text' => __METHOD__
. '-text',
1930 'len' => strlen( __METHOD__
. '-text' ),
1931 'user' => $user->getId(),
1932 'user_text' => $user->getName(),
1933 'timestamp' => $olderTimeStamp,
1934 'content_model' => CONTENT_MODEL_WIKITEXT
,
1935 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1939 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
1940 $this->assertFalse( $result );
1944 * @covers WikiPage::updateIfNewerOn
1946 public function testUpdateIfNewerOn_newerRevision() {
1947 $user = $this->getTestSysop()->getUser();
1948 $page = $this->createPage( __METHOD__
, 'StartText' );
1949 $initialRevision = $page->getRevision();
1951 $newerTimeStamp = wfTimestamp(
1953 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
1956 $newerRevision = new Revision(
1959 'page' => $page->getId(),
1960 'title' => $page->getTitle(),
1961 'comment' => __METHOD__
,
1962 'minor_edit' => true,
1963 'text' => __METHOD__
. '-text',
1964 'len' => strlen( __METHOD__
. '-text' ),
1965 'user' => $user->getId(),
1966 'user_text' => $user->getName(),
1967 'timestamp' => $newerTimeStamp,
1968 'content_model' => CONTENT_MODEL_WIKITEXT
,
1969 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1972 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
1973 $this->assertTrue( $result );
1977 * @covers WikiPage::insertOn
1979 public function testInsertOn() {
1980 $title = Title
::newFromText( __METHOD__
);
1981 $page = new WikiPage( $title );
1983 $startTimeStamp = wfTimestampNow();
1984 $result = $page->insertOn( $this->db
);
1985 $endTimeStamp = wfTimestampNow();
1987 $this->assertInternalType( 'int', $result );
1988 $this->assertTrue( $result > 0 );
1990 $condition = [ 'page_id' => $result ];
1992 // Check the default fields have been filled
1993 $this->assertSelect(
1998 'page_restrictions',
2016 // Check the page_random field has been filled
2017 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2018 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2020 // Assert the touched timestamp in the DB is roughly when we inserted the page
2021 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2023 wfTimestamp( TS_UNIX
, $startTimeStamp )
2024 <= wfTimestamp( TS_UNIX
, $pageTouched )
2027 wfTimestamp( TS_UNIX
, $endTimeStamp )
2028 >= wfTimestamp( TS_UNIX
, $pageTouched )
2031 // Try inserting the same page again and checking the result is false (no change)
2032 $result = $page->insertOn( $this->db
);
2033 $this->assertFalse( $result );
2037 * @covers WikiPage::insertOn
2039 public function testInsertOn_idSpecified() {
2040 $title = Title
::newFromText( __METHOD__
);
2041 $page = new WikiPage( $title );
2044 $result = $page->insertOn( $this->db
, $id );
2046 $this->assertSame( $id, $result );
2048 $condition = [ 'page_id' => $result ];
2050 // Check there is actually a row in the db
2051 $this->assertSelect(
2059 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2060 // Note: Once the current dates passes the date in these tests they will fail.
2061 yield
'move something' => [
2063 [ 'move' => 'something' ],
2065 [ 'edit' => [], 'move' => [ 'something' ] ],
2068 yield
'move something, edit blank' => [
2070 [ 'move' => 'something', 'edit' => '' ],
2072 [ 'edit' => [], 'move' => [ 'something' ] ],
2075 yield
'edit sysop, with expiry' => [
2077 [ 'edit' => 'sysop' ],
2078 [ 'edit' => '21330101020202' ],
2079 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2080 [ 'edit' => '21330101020202' ],
2082 yield
'move and edit, move with expiry' => [
2084 [ 'move' => 'something', 'edit' => 'another' ],
2085 [ 'move' => '22220202010101' ],
2086 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2087 [ 'move' => '22220202010101' ],
2089 yield
'move and edit, edit with infinity expiry' => [
2091 [ 'move' => 'something', 'edit' => 'another' ],
2092 [ 'edit' => 'infinity' ],
2093 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2094 [ 'edit' => 'infinity' ],
2096 yield
'non existing, create something' => [
2098 [ 'create' => 'something' ],
2100 [ 'create' => [ 'something' ] ],
2103 yield
'non existing, create something with expiry' => [
2105 [ 'create' => 'something' ],
2106 [ 'create' => '23451212112233' ],
2107 [ 'create' => [ 'something' ] ],
2108 [ 'create' => '23451212112233' ],
2113 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2114 * @covers WikiPage::doUpdateRestrictions
2116 public function testDoUpdateRestrictions_setBasicRestrictions(
2120 array $expectedRestrictions,
2121 array $expectedRestrictionExpiries
2123 if ( $pageExists ) {
2124 $page = $this->createPage( __METHOD__
, 'ABC' );
2126 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2128 $user = $this->getTestSysop()->getUser();
2131 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2133 $logId = $status->getValue();
2134 $allRestrictions = $page->getTitle()->getAllRestrictions();
2136 $this->assertTrue( $status->isGood() );
2137 $this->assertInternalType( 'int', $logId );
2138 $this->assertSame( $expectedRestrictions, $allRestrictions );
2139 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2140 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2143 // Make sure the log entry looks good
2144 // log_params is not checked here
2145 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2146 $this->assertSelect(
2147 [ 'logging' ] +
$actorQuery['tables'],
2150 'log_user' => $actorQuery['fields']['log_user'],
2151 'log_user_text' => $actorQuery['fields']['log_user_text'],
2155 [ 'log_id' => $logId ],
2158 (string)$user->getId(),
2160 (string)$page->getTitle()->getNamespace(),
2161 $page->getTitle()->getDBkey(),
2164 $actorQuery['joins']
2169 * @covers WikiPage::doUpdateRestrictions
2171 public function testDoUpdateRestrictions_failsOnReadOnly() {
2172 $page = $this->createPage( __METHOD__
, 'ABC' );
2173 $user = $this->getTestSysop()->getUser();
2177 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2178 ->disableOriginalConstructor()
2179 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2181 $readOnly->expects( $this->once() )
2182 ->method( 'isReadOnly' )
2183 ->will( $this->returnValue( true ) );
2184 $readOnly->expects( $this->once() )
2185 ->method( 'getReason' )
2186 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2187 $this->setService( 'ReadOnlyMode', $readOnly );
2189 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2190 $this->assertFalse( $status->isOK() );
2191 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2195 * @covers WikiPage::doUpdateRestrictions
2197 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2198 $page = $this->createPage( __METHOD__
, 'ABC' );
2199 $user = $this->getTestSysop()->getUser();
2201 $limit = [ 'edit' => 'sysop' ];
2203 $status = $page->doUpdateRestrictions(
2212 // The first entry should have a logId as it did something
2213 $this->assertTrue( $status->isGood() );
2214 $this->assertInternalType( 'int', $status->getValue() );
2216 $status = $page->doUpdateRestrictions(
2225 // The second entry should not have a logId as nothing changed
2226 $this->assertTrue( $status->isGood() );
2227 $this->assertNull( $status->getValue() );
2231 * @covers WikiPage::doUpdateRestrictions
2233 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2234 $page = $this->createPage( __METHOD__
, 'ABC' );
2235 $user = $this->getTestSysop()->getUser();
2239 $status = $page->doUpdateRestrictions(
2240 [ 'edit' => 'sysop' ],
2247 $this->assertTrue( $status->isGood() );
2248 $this->assertInternalType( 'int', $status->getValue() );
2249 $this->assertSelect(
2251 [ 'log_type', 'log_action' ],
2252 [ 'log_id' => $status->getValue() ],
2253 [ [ 'protect', 'protect' ] ]
2256 // Modify the protection
2257 $status = $page->doUpdateRestrictions(
2258 [ 'edit' => 'somethingElse' ],
2265 $this->assertTrue( $status->isGood() );
2266 $this->assertInternalType( 'int', $status->getValue() );
2267 $this->assertSelect(
2269 [ 'log_type', 'log_action' ],
2270 [ 'log_id' => $status->getValue() ],
2271 [ [ 'protect', 'modify' ] ]
2274 // Remove the protection
2275 $status = $page->doUpdateRestrictions(
2283 $this->assertTrue( $status->isGood() );
2284 $this->assertInternalType( 'int', $status->getValue() );
2285 $this->assertSelect(
2287 [ 'log_type', 'log_action' ],
2288 [ 'log_id' => $status->getValue() ],
2289 [ [ 'protect', 'unprotect' ] ]
2294 * @covers WikiPage::newPageUpdater
2295 * @covers WikiPage::getDerivedDataUpdater
2297 public function testNewPageUpdater() {
2298 $user = $this->getTestUser()->getUser();
2299 $page = $this->newPage( __METHOD__
, __METHOD__
);
2301 /** @var Content $content */
2302 $content = $this->getMockBuilder( WikitextContent
::class )
2303 ->setConstructorArgs( [ 'Hello World' ] )
2304 ->setMethods( [ 'getParserOutput' ] )
2306 $content->expects( $this->once() )
2307 ->method( 'getParserOutput' )
2308 ->willReturn( new ParserOutput( 'HTML' ) );
2310 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2312 // provide context, so the cache can be kept in place
2313 $slotsUpdate = new revisionSlotsUpdate();
2314 $slotsUpdate->modifyContent( 'main', $content );
2316 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2317 $updater->setContent( 'main', $content );
2318 $revision = $updater->saveRevision(
2319 CommentStoreComment
::newUnsavedComment( 'test' ),
2323 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2325 $this->assertSame( $revision->getId(), $page->getLatest() );
2327 // Parsed output must remain cached throughout.
2328 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2332 * @covers WikiPage::newPageUpdater
2333 * @covers WikiPage::getDerivedDataUpdater
2335 public function testGetDerivedDataUpdater() {
2336 $admin = $this->getTestSysop()->getUser();
2338 /** @var object $page */
2339 $page = $this->createPage( __METHOD__
, __METHOD__
);
2340 $page = TestingAccessWrapper
::newFromObject( $page );
2342 $revision = $page->getRevision()->getRevisionRecord();
2343 $user = $revision->getUser();
2345 $slotsUpdate = new RevisionSlotsUpdate();
2346 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2348 // get a virgin updater
2349 $updater1 = $page->getDerivedDataUpdater( $user );
2350 $this->assertFalse( $updater1->isUpdatePrepared() );
2352 $updater1->prepareUpdate( $revision );
2354 // Re-use updater with same revision or content, even if base changed
2355 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2357 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2358 [ 'main' => $revision->getContent( 'main' ) ]
2360 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2362 // Don't re-use for edit if base revision ID changed
2363 $this->assertNotSame(
2365 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2368 // Don't re-use with different user
2369 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2370 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2372 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2373 $updater2b->prepareContent( $user, $slotsUpdate, false );
2374 $this->assertNotSame( $updater2a, $updater2b );
2376 // Don't re-use with different content
2377 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2378 $updater3->prepareUpdate( $revision );
2379 $this->assertNotSame( $updater2b, $updater3 );
2381 // Don't re-use if no context given
2382 $updater4 = $page->getDerivedDataUpdater( $admin );
2383 $updater4->prepareUpdate( $revision );
2384 $this->assertNotSame( $updater3, $updater4 );
2386 // Don't re-use if AGAIN no context given
2387 $updater5 = $page->getDerivedDataUpdater( $admin );
2388 $this->assertNotSame( $updater4, $updater5 );
2390 // Don't re-use cached "virgin" unprepared updater
2391 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2392 $this->assertNotSame( $updater5, $updater6 );