3 use MediaWiki\Edit\PreparedEdit
;
4 use MediaWiki\MediaWikiServices
;
5 use MediaWiki\Revision\SlotRecord
;
6 use MediaWiki\Storage\RevisionSlotsUpdate
;
7 use PHPUnit\Framework\MockObject\MockObject
;
8 use Wikimedia\TestingAccessWrapper
;
13 abstract class WikiPageDbTestBase
extends MediaWikiLangTestCase
{
15 private $pagesToDelete;
17 public function __construct( $name = null, array $data = [], $dataName = '' ) {
18 parent
::__construct( $name, $data, $dataName );
20 $this->tablesUsed
= array_merge(
43 protected function addCoreDBData() {
44 // Blank out. This would fail with a modified schema, and we don't need it.
50 abstract protected function getMcrMigrationStage();
55 abstract protected function getMcrTablesToReset();
57 protected function setUp() {
60 $this->tablesUsed +
= $this->getMcrTablesToReset();
62 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
64 'wgMultiContentRevisionSchemaMigrationStage',
65 $this->getMcrMigrationStage()
67 $this->pagesToDelete
= [];
69 $this->overrideMwServices();
72 protected function tearDown() {
73 foreach ( $this->pagesToDelete
as $p ) {
74 /* @var $p WikiPage */
78 $p->doDeleteArticle( "testing done." );
80 } catch ( MWException
$ex ) {
87 abstract protected function getContentHandlerUseDB();
90 * @param Title|string $title
91 * @param string|null $model
94 private function newPage( $title, $model = null ) {
95 if ( is_string( $title ) ) {
96 $ns = $this->getDefaultWikitextNS();
97 $title = Title
::newFromText( $title, $ns );
100 $p = new WikiPage( $title );
102 $this->pagesToDelete
[] = $p;
108 * @param string|Title|WikiPage $page
109 * @param string|Content|Content[] $content
110 * @param int|null $model
114 protected function createPage( $page, $content, $model = null, $user = null ) {
115 if ( is_string( $page ) ||
$page instanceof Title
) {
116 $page = $this->newPage( $page, $model );
120 $user = $this->getTestUser()->getUser();
123 if ( is_string( $content ) ) {
124 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $model );
127 if ( !is_array( $content ) ) {
128 $content = [ 'main' => $content ];
131 $updater = $page->newPageUpdater( $user );
133 foreach ( $content as $role => $cnt ) {
134 $updater->setContent( $role, $cnt );
137 $updater->saveRevision( CommentStoreComment
::newUnsavedComment( "testing" ) );
143 * @covers WikiPage::prepareContentForEdit
145 public function testPrepareContentForEdit() {
146 $user = $this->getTestUser()->getUser();
147 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
149 $page = $this->createPage( __METHOD__
, __METHOD__
, null, $user );
150 $title = $page->getTitle();
152 $content = ContentHandler
::makeContent(
153 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
154 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
156 CONTENT_MODEL_WIKITEXT
158 $content2 = ContentHandler
::makeContent(
159 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
160 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
162 CONTENT_MODEL_WIKITEXT
165 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
167 $this->assertInstanceOf(
168 ParserOptions
::class,
172 $this->assertContains( '</a>', $edit->output
->getText(), "output" );
173 $this->assertContains(
174 'consetetur sadipscing elitr',
175 $edit->output
->getText(),
179 $this->assertTrue( $content->equals( $edit->newContent
), "newContent field" );
180 $this->assertTrue( $content->equals( $edit->pstContent
), "pstContent field" );
181 $this->assertSame( $edit->output
, $edit->output
, "output field" );
182 $this->assertSame( $edit->popts
, $edit->popts
, "popts field" );
183 $this->assertSame( null, $edit->revid
, "revid field" );
185 // Re-using the prepared info if possible
186 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
187 $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
188 $this->assertSame( $edit->pstContent
, $sameEdit->pstContent
, 're-use output' );
189 $this->assertSame( $edit->output
, $sameEdit->output
, 're-use output' );
191 // Not re-using the same PreparedEdit if not possible
192 $rev = $page->getRevision();
193 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
194 $this->assertPreparedEditNotEquals( $edit, $edit2 );
195 $this->assertContains( 'At vero eos', $edit2->pstContent
->serialize(), "content" );
197 // Check pre-safe transform
198 $this->assertContains( '[[gubergren]]', $edit2->pstContent
->serialize() );
199 $this->assertNotContains( '~~~~', $edit2->pstContent
->serialize() );
201 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
202 $this->assertPreparedEditNotEquals( $edit2, $edit3 );
204 // TODO: test with passing revision, then same without revision.
208 * @covers WikiPage::doEditUpdates
210 public function testDoEditUpdates() {
211 $user = $this->getTestUser()->getUser();
213 // NOTE: if site stats get out of whack and drop below 0,
214 // that causes a DB error during tear-down. So bump the
215 // numbers high enough to not drop below 0.
216 $siteStatsUpdate = SiteStatsUpdate
::factory(
217 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
219 $siteStatsUpdate->doUpdate();
221 $page = $this->createPage( __METHOD__
, __METHOD__
);
223 $revision = new Revision(
226 'page' => $page->getId(),
227 'title' => $page->getTitle(),
228 'comment' => __METHOD__
,
229 'minor_edit' => true,
230 'text' => __METHOD__
. ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
231 'user' => $user->getId(),
232 'user_text' => $user->getName(),
233 'timestamp' => '20170707040404',
234 'content_model' => CONTENT_MODEL_WIKITEXT
,
235 'content_format' => CONTENT_FORMAT_WIKITEXT
,
239 $page->doEditUpdates( $revision, $user );
241 // TODO: test various options; needs temporary hooks
243 $dbr = wfGetDB( DB_REPLICA
);
244 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
245 $n = $res->numRows();
248 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
252 * @covers WikiPage::doEditContent
253 * @covers WikiPage::prepareContentForEdit
255 public function testDoEditContent() {
256 $this->setMwGlobals( 'wgPageCreationLog', true );
258 $page = $this->newPage( __METHOD__
);
259 $title = $page->getTitle();
261 $user1 = $this->getTestUser()->getUser();
262 // Use the confirmed group for user2 to make sure the user is different
263 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
265 $content = ContentHandler
::makeContent(
266 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
267 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
269 CONTENT_MODEL_WIKITEXT
272 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
274 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW
, false, $user1 );
276 $this->assertTrue( $status->isOK(), 'OK' );
277 $this->assertTrue( $status->value
['new'], 'new' );
278 $this->assertNotNull( $status->value
['revision'], 'revision' );
279 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
280 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
281 $this->assertTrue( $status->value
['revision']->getContent()->equals( $content ), 'equals' );
283 $rev = $page->getRevision();
284 $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
286 $this->assertNotNull( $rev->getRecentChange() );
287 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
289 // make sure that cached ParserOutput gets re-used throughout
290 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
292 $id = $page->getId();
294 // Test page creation logging
297 [ 'log_type', 'log_action' ],
298 [ 'log_page' => $id ],
299 [ [ 'create', 'create' ] ]
302 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
303 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
304 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
305 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
307 # ------------------------
308 $dbr = wfGetDB( DB_REPLICA
);
309 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
310 $n = $res->numRows();
313 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
315 # ------------------------
316 $page = new WikiPage( $title );
318 $retrieved = $page->getContent();
319 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
321 # ------------------------
322 $page = new WikiPage( $title );
324 // try null edit, with a different user
325 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE
, false, $user2 );
326 $this->assertTrue( $status->isOK(), 'OK' );
327 $this->assertFalse( $status->value
['new'], 'new' );
328 $this->assertNull( $status->value
['revision'], 'revision' );
329 $this->assertNotNull( $page->getRevision() );
330 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
332 # ------------------------
333 $content = ContentHandler
::makeContent(
334 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
335 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
337 CONTENT_MODEL_WIKITEXT
340 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE
);
341 $this->assertTrue( $status->isOK(), 'OK' );
342 $this->assertFalse( $status->value
['new'], 'new' );
343 $this->assertNotNull( $status->value
['revision'], 'revision' );
344 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
345 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
347 $status->value
['revision']->getContent()->equals( $content ),
348 'not equals (PST must substitute signature)'
351 $rev = $page->getRevision();
352 $this->assertNotNull( $rev->getRecentChange() );
353 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
355 # ------------------------
356 $page = new WikiPage( $title );
358 $retrieved = $page->getContent();
359 $newText = $retrieved->serialize();
360 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
361 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
363 # ------------------------
364 $dbr = wfGetDB( DB_REPLICA
);
365 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
366 $n = $res->numRows();
369 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
373 * @covers WikiPage::doEditContent
375 public function testDoEditContent_twice() {
376 $title = Title
::newFromText( __METHOD__
);
377 $page = WikiPage
::factory( $title );
378 $content = ContentHandler
::makeContent( '$1 van $2', $title );
380 // Make sure we can do the exact same save twice.
381 // This tests checks that internal caches are reset as appropriate.
382 $status1 = $page->doEditContent( $content, __METHOD__
);
383 $status2 = $page->doEditContent( $content, __METHOD__
);
385 $this->assertTrue( $status1->isOK(), 'OK' );
386 $this->assertTrue( $status2->isOK(), 'OK' );
388 $this->assertTrue( isset( $status1->value
['revision'] ), 'OK' );
389 $this->assertFalse( isset( $status2->value
['revision'] ), 'OK' );
393 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
394 * TODO: Revision deletion
396 * @covers WikiPage::doDeleteArticle
397 * @covers WikiPage::doDeleteArticleReal
399 public function testDoDeleteArticle() {
400 $page = $this->createPage(
402 "[[original text]] foo",
403 CONTENT_MODEL_WIKITEXT
405 $id = $page->getId();
407 $page->doDeleteArticle( "testing deletion" );
410 $page->getTitle()->getArticleID() > 0,
411 "Title object should now have page id 0"
413 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
416 "WikiPage::exists should return false after page was deleted"
420 "WikiPage::getContent should return null after page was deleted"
423 $t = Title
::newFromText( $page->getTitle()->getPrefixedText() );
426 "Title::exists should return false after page was deleted"
430 JobQueueGroup
::destroySingletons();
432 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
435 # ------------------------
436 $dbr = wfGetDB( DB_REPLICA
);
437 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
438 $n = $res->numRows();
441 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
445 * @covers WikiPage::doDeleteArticleReal
447 public function testDoDeleteArticleReal_user0() {
448 $page = $this->createPage(
450 "[[original text]] foo",
451 CONTENT_MODEL_WIKITEXT
453 $id = $page->getId();
456 $status = $page->doDeleteArticleReal(
457 /* reason */ "testing user 0 deletion",
458 /* suppress */ false,
461 /* errorStack */ $errorStack,
464 $logId = $status->getValue();
465 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
466 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
468 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
472 'log_comment' => $commentQuery['fields']['log_comment_text'],
473 'log_user' => $actorQuery['fields']['log_user'],
474 'log_user_text' => $actorQuery['fields']['log_user_text'],
478 [ 'log_id' => $logId ],
482 'testing user 0 deletion',
485 (string)$page->getTitle()->getNamespace(),
486 $page->getTitle()->getDBkey(),
489 $actorQuery['joins'] +
$commentQuery['joins']
494 * @covers WikiPage::doDeleteArticleReal
496 public function testDoDeleteArticleReal_userSysop() {
497 $page = $this->createPage(
499 "[[original text]] foo",
500 CONTENT_MODEL_WIKITEXT
502 $id = $page->getId();
504 $user = $this->getTestSysop()->getUser();
506 $status = $page->doDeleteArticleReal(
507 /* reason */ "testing sysop deletion",
508 /* suppress */ false,
511 /* errorStack */ $errorStack,
514 $logId = $status->getValue();
515 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
516 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
518 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
522 'log_comment' => $commentQuery['fields']['log_comment_text'],
523 'log_user' => $actorQuery['fields']['log_user'],
524 'log_user_text' => $actorQuery['fields']['log_user_text'],
528 [ 'log_id' => $logId ],
532 'testing sysop deletion',
533 (string)$user->getId(),
535 (string)$page->getTitle()->getNamespace(),
536 $page->getTitle()->getDBkey(),
539 $actorQuery['joins'] +
$commentQuery['joins']
544 * TODO: Test more stuff about suppression.
546 * @covers WikiPage::doDeleteArticleReal
548 public function testDoDeleteArticleReal_suppress() {
549 $page = $this->createPage(
551 "[[original text]] foo",
552 CONTENT_MODEL_WIKITEXT
554 $id = $page->getId();
556 $user = $this->getTestSysop()->getUser();
558 $status = $page->doDeleteArticleReal(
559 /* reason */ "testing deletion",
563 /* errorStack */ $errorStack,
566 $logId = $status->getValue();
567 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
568 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
570 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
574 'log_comment' => $commentQuery['fields']['log_comment_text'],
575 'log_user' => $actorQuery['fields']['log_user'],
576 'log_user_text' => $actorQuery['fields']['log_user_text'],
580 [ 'log_id' => $logId ],
585 (string)$user->getId(),
587 (string)$page->getTitle()->getNamespace(),
588 $page->getTitle()->getDBkey(),
591 $actorQuery['joins'] +
$commentQuery['joins']
595 $page->getContent( Revision
::FOR_PUBLIC
),
596 "WikiPage::getContent should return null after the page was suppressed for general users"
600 $page->getContent( Revision
::FOR_THIS_USER
, null ),
601 "WikiPage::getContent should return null after the page was suppressed for user zero"
605 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
606 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
611 * @covers WikiPage::doDeleteUpdates
613 public function testDoDeleteUpdates() {
614 $user = $this->getTestUser()->getUser();
615 $page = $this->createPage(
617 "[[original text]] foo",
618 CONTENT_MODEL_WIKITEXT
620 $id = $page->getId();
621 $page->loadPageData(); // make sure the current revision is cached.
623 // Similar to MovePage logic
624 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
625 $page->doDeleteUpdates( $page->getId(), $page->getContent(), $page->getRevision(), $user );
628 JobQueueGroup
::destroySingletons();
630 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
633 # ------------------------
634 $dbr = wfGetDB( DB_REPLICA
);
635 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
636 $n = $res->numRows();
639 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
643 * @param string $name
645 * @return ContentHandler
647 protected function defineMockContentModelForUpdateTesting( $name ) {
648 /** @var ContentHandler|MockObject $handler */
649 $handler = $this->getMockBuilder( TextContentHandler
::class )
650 ->setConstructorArgs( [ $name ] )
652 [ 'getSecondaryDataUpdates', 'getDeletionUpdates', 'unserializeContent' ]
656 $dataUpdate = new MWCallableUpdate( 'time' );
657 $dataUpdate->_name
= "$name data update";
659 $deletionUpdate = new MWCallableUpdate( 'time' );
660 $deletionUpdate->_name
= "$name deletion update";
662 $handler->method( 'getSecondaryDataUpdates' )->willReturn( [ $dataUpdate ] );
663 $handler->method( 'getDeletionUpdates' )->willReturn( [ $deletionUpdate ] );
664 $handler->method( 'unserializeContent' )->willReturnCallback(
665 function ( $text ) use ( $handler ) {
666 return $this->createMockContent( $handler, $text );
670 $this->mergeMwGlobalArrayValue(
671 'wgContentHandlers', [
672 $name => function () use ( $handler ){
682 * @param ContentHandler $handler
683 * @param string $text
687 protected function createMockContent( ContentHandler
$handler, $text ) {
688 /** @var Content|MockObject $content */
689 $content = $this->getMockBuilder( TextContent
::class )
690 ->setConstructorArgs( [ $text ] )
691 ->setMethods( [ 'getModel', 'getContentHandler' ] )
694 $content->method( 'getModel' )->willReturn( $handler->getModelID() );
695 $content->method( 'getContentHandler' )->willReturn( $handler );
700 public function testGetDeletionUpdates() {
701 $m1 = $this->defineMockContentModelForUpdateTesting( 'M1' );
703 $mainContent1 = $this->createMockContent( $m1, 'main 1' );
705 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
706 $page = $this->createPage(
708 [ 'main' => $mainContent1 ]
711 $dataUpdates = $page->getDeletionUpdates( $page->getRevisionRecord() );
712 $this->assertNotEmpty( $dataUpdates );
714 $updateNames = array_map( function ( $du ) {
715 return isset( $du->_name
) ?
$du->_name
: get_class( $du );
718 $this->assertContains( LinksDeletionUpdate
::class, $updateNames );
719 $this->assertContains( 'M1 deletion update', $updateNames );
723 * @covers WikiPage::getRevision
725 public function testGetRevision() {
726 $page = $this->newPage( __METHOD__
);
728 $rev = $page->getRevision();
729 $this->assertNull( $rev );
732 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
734 $rev = $page->getRevision();
736 $this->assertEquals( $page->getLatest(), $rev->getId() );
737 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
741 * @covers WikiPage::getContent
743 public function testGetContent() {
744 $page = $this->newPage( __METHOD__
);
746 $content = $page->getContent();
747 $this->assertNull( $content );
750 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
752 $content = $page->getContent();
753 $this->assertEquals( "some text", $content->getNativeData() );
757 * @covers WikiPage::exists
759 public function testExists() {
760 $page = $this->newPage( __METHOD__
);
761 $this->assertFalse( $page->exists() );
764 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
765 $this->assertTrue( $page->exists() );
767 $page = new WikiPage( $page->getTitle() );
768 $this->assertTrue( $page->exists() );
771 $page->doDeleteArticle( "done testing" );
772 $this->assertFalse( $page->exists() );
774 $page = new WikiPage( $page->getTitle() );
775 $this->assertFalse( $page->exists() );
778 public function provideHasViewableContent() {
780 [ 'WikiPageTest_testHasViewableContent', false, true ],
781 [ 'Special:WikiPageTest_testHasViewableContent', false ],
782 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
783 [ 'Special:Userlogin', true ],
784 [ 'MediaWiki:help', true ],
789 * @dataProvider provideHasViewableContent
790 * @covers WikiPage::hasViewableContent
792 public function testHasViewableContent( $title, $viewable, $create = false ) {
793 $page = $this->newPage( $title );
794 $this->assertEquals( $viewable, $page->hasViewableContent() );
797 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
798 $this->assertTrue( $page->hasViewableContent() );
800 $page = new WikiPage( $page->getTitle() );
801 $this->assertTrue( $page->hasViewableContent() );
805 public function provideGetRedirectTarget() {
807 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
809 'WikiPageTest_testGetRedirectTarget_2',
810 CONTENT_MODEL_WIKITEXT
,
811 "#REDIRECT [[hello world]]",
814 // The below added to protect against Media namespace
815 // redirects which throw a fatal: (T203942)
817 'WikiPageTest_testGetRedirectTarget_3',
818 CONTENT_MODEL_WIKITEXT
,
819 "#REDIRECT [[Media:hello_world]]",
822 // Test fragments longer than 255 bytes (T207876)
824 'WikiPageTest_testGetRedirectTarget_4',
825 CONTENT_MODEL_WIKITEXT
,
826 // phpcs:ignore Generic.Files.LineLength
827 '#REDIRECT [[Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴]]',
828 // phpcs:ignore Generic.Files.LineLength
829 'Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴...'
835 * @dataProvider provideGetRedirectTarget
836 * @covers WikiPage::getRedirectTarget
838 public function testGetRedirectTarget( $title, $model, $text, $target ) {
839 $this->setMwGlobals( [
840 'wgCapitalLinks' => true,
843 $page = $this->createPage( $title, $text, $model );
845 # sanity check, because this test seems to fail for no reason for some people.
846 $c = $page->getContent();
847 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
849 # now, test the actual redirect
850 $t = $page->getRedirectTarget();
851 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getFullText() );
855 * @dataProvider provideGetRedirectTarget
856 * @covers WikiPage::isRedirect
858 public function testIsRedirect( $title, $model, $text, $target ) {
859 $page = $this->createPage( $title, $text, $model );
860 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
863 public function provideIsCountable() {
867 [ 'WikiPageTest_testIsCountable',
868 CONTENT_MODEL_WIKITEXT
,
873 [ 'WikiPageTest_testIsCountable',
874 CONTENT_MODEL_WIKITEXT
,
881 [ 'WikiPageTest_testIsCountable',
882 CONTENT_MODEL_WIKITEXT
,
887 [ 'WikiPageTest_testIsCountable',
888 CONTENT_MODEL_WIKITEXT
,
895 [ 'WikiPageTest_testIsCountable',
896 CONTENT_MODEL_WIKITEXT
,
901 [ 'WikiPageTest_testIsCountable',
902 CONTENT_MODEL_WIKITEXT
,
908 // not a content namespace
909 [ 'Talk:WikiPageTest_testIsCountable',
910 CONTENT_MODEL_WIKITEXT
,
915 [ 'Talk:WikiPageTest_testIsCountable',
916 CONTENT_MODEL_WIKITEXT
,
922 // not a content namespace, different model
923 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
929 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
939 * @dataProvider provideIsCountable
940 * @covers WikiPage::isCountable
942 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
943 global $wgContentHandlerUseDB;
945 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
947 $title = Title
::newFromText( $title );
949 if ( !$wgContentHandlerUseDB
951 && ContentHandler
::getDefaultModelFor( $title ) != $model
953 $this->markTestSkipped( "Can not use non-default content model $model for "
954 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
957 $page = $this->createPage( $title, $text, $model );
959 $editInfo = $page->prepareContentForEdit( $page->getContent() );
961 $v = $page->isCountable();
962 $w = $page->isCountable( $editInfo );
967 "isCountable( null ) returned unexpected value " . var_export( $v, true )
968 . " instead of " . var_export( $expected, true )
969 . " in mode `$mode` for text \"$text\""
975 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
976 . " instead of " . var_export( $expected, true )
977 . " in mode `$mode` for text \"$text\""
981 public function provideGetParserOutput() {
984 CONTENT_MODEL_WIKITEXT
,
986 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
993 * @dataProvider provideGetParserOutput
994 * @covers WikiPage::getParserOutput
996 public function testGetParserOutput( $model, $text, $expectedHtml ) {
997 $page = $this->createPage( __METHOD__
, $text, $model );
999 $opt = $page->makeParserOptions( 'canonical' );
1000 $po = $page->getParserOutput( $opt );
1001 $text = $po->getText();
1003 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
1004 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
1006 $this->assertEquals( $expectedHtml, $text );
1012 * @covers WikiPage::getParserOutput
1014 public function testGetParserOutput_nonexisting() {
1015 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1017 $opt = new ParserOptions();
1018 $po = $page->getParserOutput( $opt );
1020 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
1024 * @covers WikiPage::getParserOutput
1026 public function testGetParserOutput_badrev() {
1027 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
1029 $opt = new ParserOptions();
1030 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
1032 // @todo would be neat to also test deleted revision
1034 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
1037 public static $sections =
1051 public function dataReplaceSection() {
1052 // NOTE: assume the Help namespace to contain wikitext
1054 [ 'Help:WikiPageTest_testReplaceSection',
1055 CONTENT_MODEL_WIKITEXT
,
1060 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
1062 [ 'Help:WikiPageTest_testReplaceSection',
1063 CONTENT_MODEL_WIKITEXT
,
1070 [ 'Help:WikiPageTest_testReplaceSection',
1071 CONTENT_MODEL_WIKITEXT
,
1074 "== TEST ==\nmore fun",
1076 trim( preg_replace( '/^== test ==.*== foo ==/sm',
1077 "== TEST ==\nmore fun\n\n== foo ==",
1080 [ 'Help:WikiPageTest_testReplaceSection',
1081 CONTENT_MODEL_WIKITEXT
,
1086 trim( self
::$sections )
1088 [ 'Help:WikiPageTest_testReplaceSection',
1089 CONTENT_MODEL_WIKITEXT
,
1094 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
1100 * @dataProvider dataReplaceSection
1101 * @covers WikiPage::replaceSectionContent
1103 public function testReplaceSectionContent( $title, $model, $text, $section,
1104 $with, $sectionTitle, $expected
1106 $page = $this->createPage( $title, $text, $model );
1108 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1109 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
1111 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1115 * @dataProvider dataReplaceSection
1116 * @covers WikiPage::replaceSectionAtRev
1118 public function testReplaceSectionAtRev( $title, $model, $text, $section,
1119 $with, $sectionTitle, $expected
1121 $page = $this->createPage( $title, $text, $model );
1122 $baseRevId = $page->getLatest();
1124 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1125 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1127 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1131 * @covers WikiPage::getOldestRevision
1133 public function testGetOldestRevision() {
1134 $page = $this->newPage( __METHOD__
);
1135 $page->doEditContent(
1136 new WikitextContent( 'one' ),
1140 $rev1 = $page->getRevision();
1142 $page = new WikiPage( $page->getTitle() );
1143 $page->doEditContent(
1144 new WikitextContent( 'two' ),
1149 $page = new WikiPage( $page->getTitle() );
1150 $page->doEditContent(
1151 new WikitextContent( 'three' ),
1157 $this->assertNotEquals(
1159 $page->getRevision()->getId(),
1160 '$page->getRevision()->getId()'
1164 $this->assertEquals(
1166 $page->getOldestRevision()->getId(),
1167 '$page->getOldestRevision()->getId()'
1172 * @covers WikiPage::doRollback
1173 * @covers WikiPage::commitRollback
1175 public function testDoRollback() {
1176 // FIXME: fails under postgres
1177 $this->markTestSkippedIfDbType( 'postgres' );
1179 $admin = $this->getTestSysop()->getUser();
1180 $user1 = $this->getTestUser()->getUser();
1181 // Use the confirmed group for user2 to make sure the user is different
1182 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1184 // make sure we can test autopatrolling
1185 $this->setMwGlobals( 'wgUseRCPatrol', true );
1187 // TODO: MCR: test rollback of multiple slots!
1188 $page = $this->newPage( __METHOD__
);
1192 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1193 "section one", EDIT_NEW
, false, $admin );
1196 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1197 "adding section two", 0, false, $user1 );
1199 $text .= "\n\nthree";
1200 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1201 "adding section three", 0, false, $user2 );
1203 /** @var Revision $rev1 */
1204 /** @var Revision $rev2 */
1205 /** @var Revision $rev3 */
1206 $rev1 = $status1->getValue()['revision'];
1207 $rev2 = $status2->getValue()['revision'];
1208 $rev3 = $status3->getValue()['revision'];
1211 * We are having issues with doRollback spuriously failing. Apparently
1212 * the last revision somehow goes missing or not committed under some
1213 * circumstances. So, make sure the revisions have the correct usernames.
1215 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1216 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1217 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1218 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1220 // Now, try the actual rollback
1221 $token = $admin->getEditToken( 'rollback' );
1222 $rollbackErrors = $page->doRollback(
1231 if ( $rollbackErrors ) {
1233 "Rollback failed:\n" .
1234 print_r( $rollbackErrors, true ) . ";\n" .
1235 print_r( $resultDetails, true )
1239 $page = new WikiPage( $page->getTitle() );
1240 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1241 "rollback did not revert to the correct revision" );
1242 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1244 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1245 $page->getRevision()->getRevisionRecord()
1248 $this->assertNotNull( $rc, 'RecentChanges entry' );
1249 $this->assertEquals(
1250 RecentChange
::PRC_AUTOPATROLLED
,
1251 $rc->getAttribute( 'rc_patrolled' ),
1255 // TODO: MCR: assert origin once we write slot data
1256 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( SlotRecord::MAIN );
1257 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1258 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1262 * @covers WikiPage::doRollback
1263 * @covers WikiPage::commitRollback
1265 public function testDoRollbackFailureSameContent() {
1266 $admin = $this->getTestSysop()->getUser();
1269 $page = $this->newPage( __METHOD__
);
1270 $page->doEditContent(
1271 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1277 $rev1 = $page->getRevision();
1279 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1281 $page = new WikiPage( $page->getTitle() );
1282 $page->doEditContent(
1283 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1284 "adding section two",
1290 # now, do a the rollback from the same user was doing the edit before
1291 $resultDetails = [];
1292 $token = $user1->getEditToken( 'rollback' );
1293 $errors = $page->doRollback(
1295 "testing revert same user",
1302 $this->assertEquals( [], $errors, "Rollback failed same user" );
1304 # now, try the rollback
1305 $resultDetails = [];
1306 $token = $admin->getEditToken( 'rollback' );
1307 $errors = $page->doRollback(
1316 $this->assertEquals(
1326 "Rollback not failed"
1329 $page = new WikiPage( $page->getTitle() );
1330 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1331 "rollback did not revert to the correct revision" );
1332 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1336 * Tests tagging for edits that do rollback action
1337 * @covers WikiPage::doRollback
1339 public function testDoRollbackTagging() {
1340 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1341 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1344 $admin = new User();
1345 $admin->setName( 'Administrator' );
1346 $admin->addToDatabase();
1348 $text = 'First line';
1349 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1350 $page->doEditContent(
1351 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1358 $secondUser = new User();
1359 $secondUser->setName( '92.65.217.32' );
1360 $text .= '\n\nSecond line';
1361 $page = new WikiPage( $page->getTitle() );
1362 $page->doEditContent(
1363 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1364 'Adding second line',
1370 // Now, try the rollback
1371 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1372 $token = $admin->getEditToken( 'rollback' );
1373 $errors = $page->doRollback(
1374 $secondUser->getName(),
1382 // If doRollback completed without errors
1383 if ( $errors === [] ) {
1384 $tags = $resultDetails[ 'tags' ];
1385 $this->assertContains( 'mw-rollback', $tags );
1389 public function provideGetAutoDeleteReason() {
1399 [ "first edit", null ],
1401 "/first edit.*only contributor/",
1407 [ "first edit", null ],
1408 [ "second edit", null ],
1410 "/second edit.*only contributor/",
1416 [ "first edit", "127.0.2.22" ],
1417 [ "second edit", "127.0.3.33" ],
1427 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1428 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1429 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1430 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1431 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1435 '/first edit:.*\.\.\."/',
1441 [ "first edit", "127.0.2.22" ],
1442 [ "", "127.0.3.33" ],
1444 "/before blanking.*first edit/",
1452 * @dataProvider provideGetAutoDeleteReason
1453 * @covers WikiPage::getAutoDeleteReason
1455 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1458 // NOTE: assume Help namespace to contain wikitext
1459 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1463 foreach ( $edits as $edit ) {
1466 if ( !empty( $edit[1] ) ) {
1467 $user->setName( $edit[1] );
1472 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1474 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1479 $reason = $page->getAutoDeleteReason( $hasHistory );
1481 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1482 $this->assertEquals( $expectedResult, $reason );
1484 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1485 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1488 $this->assertEquals( $expectedHistory, $hasHistory,
1489 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1491 $page->doDeleteArticle( "done" );
1494 public function providePreSaveTransform() {
1496 [ 'hello this is ~~~',
1497 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1499 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1500 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1506 * @covers WikiPage::factory
1508 public function testWikiPageFactory() {
1509 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1510 $page = WikiPage
::factory( $title );
1511 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1513 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1514 $page = WikiPage
::factory( $title );
1515 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1517 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1518 $page = WikiPage
::factory( $title );
1519 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1523 * @covers WikiPage::loadPageData
1524 * @covers WikiPage::wasLoadedFrom
1526 public function testLoadPageData() {
1527 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1528 $page = WikiPage
::factory( $title );
1530 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1531 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1532 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1533 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1535 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1536 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1537 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1538 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1539 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1541 $page->loadPageData( IDBAccessObject
::READ_LATEST
);
1542 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1543 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1544 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1545 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1547 $page->loadPageData( IDBAccessObject
::READ_LOCKING
);
1548 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1549 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1550 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1551 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1553 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
1554 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1555 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1556 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1557 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1561 * @dataProvider provideCommentMigrationOnDeletion
1563 * @param int $writeStage
1564 * @param int $readStage
1566 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1567 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1568 $this->overrideMwServices();
1570 $dbr = wfGetDB( DB_REPLICA
);
1572 $page = $this->createPage(
1575 CONTENT_MODEL_WIKITEXT
1577 $revid = $page->getLatest();
1578 if ( $writeStage > MIGRATION_OLD
) {
1579 $comment_id = $dbr->selectField(
1580 'revision_comment_temp',
1581 'revcomment_comment_id',
1582 [ 'revcomment_rev' => $revid ],
1587 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1588 $this->overrideMwServices();
1590 $page->doDeleteArticle( "testing deletion" );
1592 if ( $readStage > MIGRATION_OLD
) {
1593 // Didn't leave behind any 'revision_comment_temp' rows
1594 $n = $dbr->selectField(
1595 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1597 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1599 // Copied or upgraded the comment_id, as applicable
1600 $ar_comment_id = $dbr->selectField(
1603 [ 'ar_rev_id' => $revid ],
1606 if ( $writeStage > MIGRATION_OLD
) {
1607 $this->assertSame( $comment_id, $ar_comment_id );
1609 $this->assertNotEquals( 0, $ar_comment_id );
1613 // Copied rev_comment, if applicable
1614 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1615 $ar_comment = $dbr->selectField(
1618 [ 'ar_rev_id' => $revid ],
1621 $this->assertSame( 'testing', $ar_comment );
1625 public function provideCommentMigrationOnDeletion() {
1627 [ MIGRATION_OLD
, MIGRATION_OLD
],
1628 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1629 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1630 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1631 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1632 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1633 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1634 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1635 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1636 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1637 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1638 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1639 [ MIGRATION_NEW
, MIGRATION_NEW
],
1644 * @covers WikiPage::updateCategoryCounts
1646 public function testUpdateCategoryCounts() {
1647 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1649 // Add an initial category
1650 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1652 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1653 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1654 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1656 // Add a new category
1657 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1659 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1660 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1661 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1663 // Add and remove a category
1664 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1666 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1667 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1668 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1671 public function provideUpdateRedirectOn() {
1672 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1673 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1674 yield
[ 'SomeText', false, null, false, true, 0 ];
1675 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1679 * @dataProvider provideUpdateRedirectOn
1680 * @covers WikiPage::updateRedirectOn
1682 * @param string $initialText
1683 * @param bool $initialRedirectState
1684 * @param string|null $redirectTitle
1685 * @param bool|null $lastRevIsRedirect
1686 * @param bool $expectedSuccess
1687 * @param int $expectedRowCount
1689 public function testUpdateRedirectOn(
1691 $initialRedirectState,
1697 // FIXME: fails under sqlite and postgres
1698 $this->markTestSkippedIfDbType( 'sqlite' );
1699 $this->markTestSkippedIfDbType( 'postgres' );
1700 static $pageCounter = 0;
1703 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1704 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1706 $redirectTitle = is_string( $redirectTitle )
1707 ? Title
::newFromText( $redirectTitle )
1710 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1711 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1713 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1714 * Most of core checks the page table for redirect status, so we have to be ugly and
1715 * assert a select from the table here.
1717 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1720 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1721 $this->assertSelect(
1724 [ 'rd_from' => $pageId ],
1725 [ [ strval( $expected ) ] ]
1730 * @covers WikiPage::insertRedirectEntry
1732 public function testInsertRedirectEntry_insertsRedirectEntry() {
1733 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1734 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1736 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1737 $targetTitle->mInterwiki
= 'eninter';
1738 $page->insertRedirectEntry( $targetTitle, null );
1740 $this->assertSelect(
1742 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1743 [ 'rd_from' => $page->getId() ],
1745 strval( $page->getId() ),
1746 strval( $targetTitle->getNamespace() ),
1747 strval( $targetTitle->getDBkey() ),
1748 strval( $targetTitle->getFragment() ),
1749 strval( $targetTitle->getInterwiki() ),
1755 * @covers WikiPage::insertRedirectEntry
1757 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1758 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1759 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1761 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1762 $targetTitle->mInterwiki
= 'eninter';
1763 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1765 $this->assertSelect(
1767 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1768 [ 'rd_from' => $page->getId() ],
1770 strval( $page->getId() ),
1771 strval( $targetTitle->getNamespace() ),
1772 strval( $targetTitle->getDBkey() ),
1773 strval( $targetTitle->getFragment() ),
1774 strval( $targetTitle->getInterwiki() ),
1780 * @covers WikiPage::insertRedirectEntry
1782 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1783 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1784 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1786 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1787 $targetTitle->mInterwiki
= 'eninter';
1788 $page->insertRedirectEntry( $targetTitle, 215251 );
1790 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1793 private function getRow( array $overrides = [] ) {
1797 'page_is_redirect' => '1',
1798 'page_latest' => '99',
1799 'page_namespace' => '3',
1800 'page_title' => 'JaJaTitle',
1801 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1802 'page_touched' => '20120101020202',
1803 'page_links_updated' => '20140101020202',
1805 foreach ( $overrides as $key => $value ) {
1806 $row[$key] = $value;
1808 return (object)$row;
1811 public function provideNewFromRowSuccess() {
1812 yield
'basic row' => [
1814 function ( WikiPage
$wikiPage, self
$test ) {
1815 $test->assertSame( 44, $wikiPage->getId() );
1816 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1817 $test->assertTrue( $wikiPage->isRedirect() );
1818 $test->assertSame( 99, $wikiPage->getLatest() );
1819 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1820 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1823 'edit' => [ 'autoconfirmed', 'sysop' ],
1824 'move' => [ 'sysop' ],
1826 $wikiPage->getTitle()->getAllRestrictions()
1828 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1829 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1832 yield
'different timestamp formats' => [
1834 'page_touched' => '2012-01-01 02:02:02',
1835 'page_links_updated' => '2014-01-01 02:02:02',
1837 function ( WikiPage
$wikiPage, self
$test ) {
1838 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1839 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1842 yield
'no restrictions' => [
1844 'page_restrictions' => '',
1846 function ( WikiPage
$wikiPage, self
$test ) {
1852 $wikiPage->getTitle()->getAllRestrictions()
1856 yield
'not redirect' => [
1858 'page_is_redirect' => '0',
1860 function ( WikiPage
$wikiPage, self
$test ) {
1861 $test->assertFalse( $wikiPage->isRedirect() );
1867 * @covers WikiPage::newFromRow
1868 * @covers WikiPage::loadFromRow
1869 * @dataProvider provideNewFromRowSuccess
1871 * @param object $row
1872 * @param callable $assertions
1874 public function testNewFromRow( $row, $assertions ) {
1875 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1876 $assertions( $page, $this );
1879 public function provideTestNewFromId_returnsNullOnBadPageId() {
1885 * @covers WikiPage::newFromID
1886 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1888 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1889 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1893 * @covers WikiPage::newFromID
1895 public function testNewFromId_appearsToFetchCorrectRow() {
1896 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1897 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1898 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1899 $this->assertEquals(
1900 $createdPage->getContent()->getNativeData(),
1901 $fetchedPage->getContent()->getNativeData()
1906 * @covers WikiPage::newFromID
1908 public function testNewFromId_returnsNullOnNonExistingId() {
1909 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1912 public function provideTestInsertProtectNullRevision() {
1913 // phpcs:disable Generic.Files.LineLength
1916 [ 'edit' => 'sysop' ],
1917 [ 'edit' => '20200101040404' ],
1921 '(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)))'
1925 [ 'edit' => 'sysop', 'move' => 'something' ],
1926 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1930 '(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)))'
1936 * @dataProvider provideTestInsertProtectNullRevision
1937 * @covers WikiPage::insertProtectNullRevision
1938 * @covers WikiPage::protectDescription
1940 * @param string $revCommentMsg
1941 * @param array $limit
1942 * @param array $expiry
1943 * @param bool $cascade
1944 * @param string $reason
1945 * @param bool|null $user true if the test sysop should be used, or null
1946 * @param string $expectedComment
1948 public function testInsertProtectNullRevision(
1957 $this->setContentLang( 'qqx' );
1959 $page = $this->createPage( __METHOD__
, 'Goat' );
1961 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1963 $result = $page->insertProtectNullRevision(
1972 $this->assertTrue( $result instanceof Revision
);
1973 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1977 * @covers WikiPage::updateRevisionOn
1979 public function testUpdateRevisionOn_existingPage() {
1980 $user = $this->getTestSysop()->getUser();
1981 $page = $this->createPage( __METHOD__
, 'StartText' );
1983 $revision = new Revision(
1986 'page' => $page->getId(),
1987 'title' => $page->getTitle(),
1988 'comment' => __METHOD__
,
1989 'minor_edit' => true,
1990 'text' => __METHOD__
. '-text',
1991 'len' => strlen( __METHOD__
. '-text' ),
1992 'user' => $user->getId(),
1993 'user_text' => $user->getName(),
1994 'timestamp' => '20170707040404',
1995 'content_model' => CONTENT_MODEL_WIKITEXT
,
1996 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2000 $result = $page->updateRevisionOn( $this->db
, $revision );
2001 $this->assertTrue( $result );
2002 $this->assertSame( 9989, $page->getLatest() );
2003 $this->assertEquals( $revision, $page->getRevision() );
2007 * @covers WikiPage::updateRevisionOn
2009 public function testUpdateRevisionOn_NonExistingPage() {
2010 $user = $this->getTestSysop()->getUser();
2011 $page = $this->createPage( __METHOD__
, 'StartText' );
2012 $page->doDeleteArticle( 'reason' );
2014 $revision = new Revision(
2017 'page' => $page->getId(),
2018 'title' => $page->getTitle(),
2019 'comment' => __METHOD__
,
2020 'minor_edit' => true,
2021 'text' => __METHOD__
. '-text',
2022 'len' => strlen( __METHOD__
. '-text' ),
2023 'user' => $user->getId(),
2024 'user_text' => $user->getName(),
2025 'timestamp' => '20170707040404',
2026 'content_model' => CONTENT_MODEL_WIKITEXT
,
2027 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2031 $result = $page->updateRevisionOn( $this->db
, $revision );
2032 $this->assertFalse( $result );
2036 * @covers WikiPage::updateIfNewerOn
2038 public function testUpdateIfNewerOn_olderRevision() {
2039 $user = $this->getTestSysop()->getUser();
2040 $page = $this->createPage( __METHOD__
, 'StartText' );
2041 $initialRevision = $page->getRevision();
2043 $olderTimeStamp = wfTimestamp(
2045 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
2048 $olderRevison = new Revision(
2051 'page' => $page->getId(),
2052 'title' => $page->getTitle(),
2053 'comment' => __METHOD__
,
2054 'minor_edit' => true,
2055 'text' => __METHOD__
. '-text',
2056 'len' => strlen( __METHOD__
. '-text' ),
2057 'user' => $user->getId(),
2058 'user_text' => $user->getName(),
2059 'timestamp' => $olderTimeStamp,
2060 'content_model' => CONTENT_MODEL_WIKITEXT
,
2061 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2065 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
2066 $this->assertFalse( $result );
2070 * @covers WikiPage::updateIfNewerOn
2072 public function testUpdateIfNewerOn_newerRevision() {
2073 $user = $this->getTestSysop()->getUser();
2074 $page = $this->createPage( __METHOD__
, 'StartText' );
2075 $initialRevision = $page->getRevision();
2077 $newerTimeStamp = wfTimestamp(
2079 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
2082 $newerRevision = new Revision(
2085 'page' => $page->getId(),
2086 'title' => $page->getTitle(),
2087 'comment' => __METHOD__
,
2088 'minor_edit' => true,
2089 'text' => __METHOD__
. '-text',
2090 'len' => strlen( __METHOD__
. '-text' ),
2091 'user' => $user->getId(),
2092 'user_text' => $user->getName(),
2093 'timestamp' => $newerTimeStamp,
2094 'content_model' => CONTENT_MODEL_WIKITEXT
,
2095 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2098 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
2099 $this->assertTrue( $result );
2103 * @covers WikiPage::insertOn
2105 public function testInsertOn() {
2106 $title = Title
::newFromText( __METHOD__
);
2107 $page = new WikiPage( $title );
2109 $startTimeStamp = wfTimestampNow();
2110 $result = $page->insertOn( $this->db
);
2111 $endTimeStamp = wfTimestampNow();
2113 $this->assertInternalType( 'int', $result );
2114 $this->assertTrue( $result > 0 );
2116 $condition = [ 'page_id' => $result ];
2118 // Check the default fields have been filled
2119 $this->assertSelect(
2124 'page_restrictions',
2142 // Check the page_random field has been filled
2143 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2144 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2146 // Assert the touched timestamp in the DB is roughly when we inserted the page
2147 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2149 wfTimestamp( TS_UNIX
, $startTimeStamp )
2150 <= wfTimestamp( TS_UNIX
, $pageTouched )
2153 wfTimestamp( TS_UNIX
, $endTimeStamp )
2154 >= wfTimestamp( TS_UNIX
, $pageTouched )
2157 // Try inserting the same page again and checking the result is false (no change)
2158 $result = $page->insertOn( $this->db
);
2159 $this->assertFalse( $result );
2163 * @covers WikiPage::insertOn
2165 public function testInsertOn_idSpecified() {
2166 $title = Title
::newFromText( __METHOD__
);
2167 $page = new WikiPage( $title );
2170 $result = $page->insertOn( $this->db
, $id );
2172 $this->assertSame( $id, $result );
2174 $condition = [ 'page_id' => $result ];
2176 // Check there is actually a row in the db
2177 $this->assertSelect(
2185 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2186 // Note: Once the current dates passes the date in these tests they will fail.
2187 yield
'move something' => [
2189 [ 'move' => 'something' ],
2191 [ 'edit' => [], 'move' => [ 'something' ] ],
2194 yield
'move something, edit blank' => [
2196 [ 'move' => 'something', 'edit' => '' ],
2198 [ 'edit' => [], 'move' => [ 'something' ] ],
2201 yield
'edit sysop, with expiry' => [
2203 [ 'edit' => 'sysop' ],
2204 [ 'edit' => '21330101020202' ],
2205 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2206 [ 'edit' => '21330101020202' ],
2208 yield
'move and edit, move with expiry' => [
2210 [ 'move' => 'something', 'edit' => 'another' ],
2211 [ 'move' => '22220202010101' ],
2212 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2213 [ 'move' => '22220202010101' ],
2215 yield
'move and edit, edit with infinity expiry' => [
2217 [ 'move' => 'something', 'edit' => 'another' ],
2218 [ 'edit' => 'infinity' ],
2219 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2220 [ 'edit' => 'infinity' ],
2222 yield
'non existing, create something' => [
2224 [ 'create' => 'something' ],
2226 [ 'create' => [ 'something' ] ],
2229 yield
'non existing, create something with expiry' => [
2231 [ 'create' => 'something' ],
2232 [ 'create' => '23451212112233' ],
2233 [ 'create' => [ 'something' ] ],
2234 [ 'create' => '23451212112233' ],
2239 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2240 * @covers WikiPage::doUpdateRestrictions
2242 public function testDoUpdateRestrictions_setBasicRestrictions(
2246 array $expectedRestrictions,
2247 array $expectedRestrictionExpiries
2249 if ( $pageExists ) {
2250 $page = $this->createPage( __METHOD__
, 'ABC' );
2252 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2254 $user = $this->getTestSysop()->getUser();
2257 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2259 $logId = $status->getValue();
2260 $allRestrictions = $page->getTitle()->getAllRestrictions();
2262 $this->assertTrue( $status->isGood() );
2263 $this->assertInternalType( 'int', $logId );
2264 $this->assertSame( $expectedRestrictions, $allRestrictions );
2265 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2266 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2269 // Make sure the log entry looks good
2270 // log_params is not checked here
2271 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2272 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
2273 $this->assertSelect(
2274 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'],
2276 'log_comment' => $commentQuery['fields']['log_comment_text'],
2277 'log_user' => $actorQuery['fields']['log_user'],
2278 'log_user_text' => $actorQuery['fields']['log_user_text'],
2282 [ 'log_id' => $logId ],
2285 (string)$user->getId(),
2287 (string)$page->getTitle()->getNamespace(),
2288 $page->getTitle()->getDBkey(),
2291 $actorQuery['joins'] +
$commentQuery['joins']
2296 * @covers WikiPage::doUpdateRestrictions
2298 public function testDoUpdateRestrictions_failsOnReadOnly() {
2299 $page = $this->createPage( __METHOD__
, 'ABC' );
2300 $user = $this->getTestSysop()->getUser();
2304 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2305 ->disableOriginalConstructor()
2306 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2308 $readOnly->expects( $this->once() )
2309 ->method( 'isReadOnly' )
2310 ->will( $this->returnValue( true ) );
2311 $readOnly->expects( $this->once() )
2312 ->method( 'getReason' )
2313 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2314 $this->setService( 'ReadOnlyMode', $readOnly );
2316 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2317 $this->assertFalse( $status->isOK() );
2318 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2322 * @covers WikiPage::doUpdateRestrictions
2324 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2325 $page = $this->createPage( __METHOD__
, 'ABC' );
2326 $user = $this->getTestSysop()->getUser();
2328 $limit = [ 'edit' => 'sysop' ];
2330 $status = $page->doUpdateRestrictions(
2339 // The first entry should have a logId as it did something
2340 $this->assertTrue( $status->isGood() );
2341 $this->assertInternalType( 'int', $status->getValue() );
2343 $status = $page->doUpdateRestrictions(
2352 // The second entry should not have a logId as nothing changed
2353 $this->assertTrue( $status->isGood() );
2354 $this->assertNull( $status->getValue() );
2358 * @covers WikiPage::doUpdateRestrictions
2360 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2361 $page = $this->createPage( __METHOD__
, 'ABC' );
2362 $user = $this->getTestSysop()->getUser();
2366 $status = $page->doUpdateRestrictions(
2367 [ 'edit' => 'sysop' ],
2374 $this->assertTrue( $status->isGood() );
2375 $this->assertInternalType( 'int', $status->getValue() );
2376 $this->assertSelect(
2378 [ 'log_type', 'log_action' ],
2379 [ 'log_id' => $status->getValue() ],
2380 [ [ 'protect', 'protect' ] ]
2383 // Modify the protection
2384 $status = $page->doUpdateRestrictions(
2385 [ 'edit' => 'somethingElse' ],
2392 $this->assertTrue( $status->isGood() );
2393 $this->assertInternalType( 'int', $status->getValue() );
2394 $this->assertSelect(
2396 [ 'log_type', 'log_action' ],
2397 [ 'log_id' => $status->getValue() ],
2398 [ [ 'protect', 'modify' ] ]
2401 // Remove the protection
2402 $status = $page->doUpdateRestrictions(
2410 $this->assertTrue( $status->isGood() );
2411 $this->assertInternalType( 'int', $status->getValue() );
2412 $this->assertSelect(
2414 [ 'log_type', 'log_action' ],
2415 [ 'log_id' => $status->getValue() ],
2416 [ [ 'protect', 'unprotect' ] ]
2421 * @covers WikiPage::newPageUpdater
2422 * @covers WikiPage::getDerivedDataUpdater
2424 public function testNewPageUpdater() {
2425 $user = $this->getTestUser()->getUser();
2426 $page = $this->newPage( __METHOD__
, __METHOD__
);
2428 /** @var Content $content */
2429 $content = $this->getMockBuilder( WikitextContent
::class )
2430 ->setConstructorArgs( [ 'Hello World' ] )
2431 ->setMethods( [ 'getParserOutput' ] )
2433 $content->expects( $this->once() )
2434 ->method( 'getParserOutput' )
2435 ->willReturn( new ParserOutput( 'HTML' ) );
2437 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2439 // provide context, so the cache can be kept in place
2440 $slotsUpdate = new revisionSlotsUpdate();
2441 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
2443 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2444 $updater->setContent( SlotRecord
::MAIN
, $content );
2445 $revision = $updater->saveRevision(
2446 CommentStoreComment
::newUnsavedComment( 'test' ),
2450 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2452 $this->assertSame( $revision->getId(), $page->getLatest() );
2454 // Parsed output must remain cached throughout.
2455 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2459 * @covers WikiPage::newPageUpdater
2460 * @covers WikiPage::getDerivedDataUpdater
2462 public function testGetDerivedDataUpdater() {
2463 $admin = $this->getTestSysop()->getUser();
2465 /** @var object $page */
2466 $page = $this->createPage( __METHOD__
, __METHOD__
);
2467 $page = TestingAccessWrapper
::newFromObject( $page );
2469 $revision = $page->getRevision()->getRevisionRecord();
2470 $user = $revision->getUser();
2472 $slotsUpdate = new RevisionSlotsUpdate();
2473 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, new WikitextContent( 'Hello World' ) );
2475 // get a virgin updater
2476 $updater1 = $page->getDerivedDataUpdater( $user );
2477 $this->assertFalse( $updater1->isUpdatePrepared() );
2479 $updater1->prepareUpdate( $revision );
2481 // Re-use updater with same revision or content, even if base changed
2482 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2484 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2485 [ SlotRecord
::MAIN
=> $revision->getContent( SlotRecord
::MAIN
) ]
2487 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2489 // Don't re-use for edit if base revision ID changed
2490 $this->assertNotSame(
2492 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2495 // Don't re-use with different user
2496 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2497 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2499 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2500 $updater2b->prepareContent( $user, $slotsUpdate, false );
2501 $this->assertNotSame( $updater2a, $updater2b );
2503 // Don't re-use with different content
2504 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2505 $updater3->prepareUpdate( $revision );
2506 $this->assertNotSame( $updater2b, $updater3 );
2508 // Don't re-use if no context given
2509 $updater4 = $page->getDerivedDataUpdater( $admin );
2510 $updater4->prepareUpdate( $revision );
2511 $this->assertNotSame( $updater3, $updater4 );
2513 // Don't re-use if AGAIN no context given
2514 $updater5 = $page->getDerivedDataUpdater( $admin );
2515 $this->assertNotSame( $updater4, $updater5 );
2517 // Don't re-use cached "virgin" unprepared updater
2518 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2519 $this->assertNotSame( $updater5, $updater6 );
2522 protected function assertPreparedEditEquals(
2523 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2525 // suppress differences caused by a clock tick between generating the two PreparedEdits
2526 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2527 $edit2 = clone $edit2;
2528 $edit2->timestamp
= $edit->timestamp
;
2530 $this->assertEquals( $edit, $edit2, $message );
2533 protected function assertPreparedEditNotEquals(
2534 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2536 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2537 $edit2 = clone $edit2;
2538 $edit2->timestamp
= $edit->timestamp
;
2540 $this->assertNotEquals( $edit, $edit2, $message );