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" ) );
138 if ( !$updater->wasSuccessful() ) {
139 $this->fail( $updater->getStatus()->getWikiText() );
146 * @covers WikiPage::prepareContentForEdit
148 public function testPrepareContentForEdit() {
149 $user = $this->getTestUser()->getUser();
150 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
152 $page = $this->createPage( __METHOD__
, __METHOD__
, null, $user );
153 $title = $page->getTitle();
155 $content = ContentHandler
::makeContent(
156 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
157 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
159 CONTENT_MODEL_WIKITEXT
161 $content2 = ContentHandler
::makeContent(
162 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
163 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
165 CONTENT_MODEL_WIKITEXT
168 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
170 $this->assertInstanceOf(
171 ParserOptions
::class,
175 $this->assertContains( '</a>', $edit->output
->getText(), "output" );
176 $this->assertContains(
177 'consetetur sadipscing elitr',
178 $edit->output
->getText(),
182 $this->assertTrue( $content->equals( $edit->newContent
), "newContent field" );
183 $this->assertTrue( $content->equals( $edit->pstContent
), "pstContent field" );
184 $this->assertSame( $edit->output
, $edit->output
, "output field" );
185 $this->assertSame( $edit->popts
, $edit->popts
, "popts field" );
186 $this->assertSame( null, $edit->revid
, "revid field" );
188 // Re-using the prepared info if possible
189 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
190 $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
191 $this->assertSame( $edit->pstContent
, $sameEdit->pstContent
, 're-use output' );
192 $this->assertSame( $edit->output
, $sameEdit->output
, 're-use output' );
194 // Not re-using the same PreparedEdit if not possible
195 $rev = $page->getRevision();
196 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
197 $this->assertPreparedEditNotEquals( $edit, $edit2 );
198 $this->assertContains( 'At vero eos', $edit2->pstContent
->serialize(), "content" );
200 // Check pre-safe transform
201 $this->assertContains( '[[gubergren]]', $edit2->pstContent
->serialize() );
202 $this->assertNotContains( '~~~~', $edit2->pstContent
->serialize() );
204 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
205 $this->assertPreparedEditNotEquals( $edit2, $edit3 );
207 // TODO: test with passing revision, then same without revision.
211 * @covers WikiPage::doEditUpdates
213 public function testDoEditUpdates() {
214 $user = $this->getTestUser()->getUser();
216 // NOTE: if site stats get out of whack and drop below 0,
217 // that causes a DB error during tear-down. So bump the
218 // numbers high enough to not drop below 0.
219 $siteStatsUpdate = SiteStatsUpdate
::factory(
220 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
222 $siteStatsUpdate->doUpdate();
224 $page = $this->createPage( __METHOD__
, __METHOD__
);
226 $revision = new Revision(
229 'page' => $page->getId(),
230 'title' => $page->getTitle(),
231 'comment' => __METHOD__
,
232 'minor_edit' => true,
233 'text' => __METHOD__
. ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
234 'user' => $user->getId(),
235 'user_text' => $user->getName(),
236 'timestamp' => '20170707040404',
237 'content_model' => CONTENT_MODEL_WIKITEXT
,
238 'content_format' => CONTENT_FORMAT_WIKITEXT
,
242 $page->doEditUpdates( $revision, $user );
244 // TODO: test various options; needs temporary hooks
246 $dbr = wfGetDB( DB_REPLICA
);
247 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
248 $n = $res->numRows();
251 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
255 * @covers WikiPage::doEditContent
256 * @covers WikiPage::prepareContentForEdit
258 public function testDoEditContent() {
259 $this->setMwGlobals( 'wgPageCreationLog', true );
261 $page = $this->newPage( __METHOD__
);
262 $title = $page->getTitle();
264 $user1 = $this->getTestUser()->getUser();
265 // Use the confirmed group for user2 to make sure the user is different
266 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
268 $content = ContentHandler
::makeContent(
269 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
270 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
272 CONTENT_MODEL_WIKITEXT
275 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
277 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW
, false, $user1 );
279 $this->assertTrue( $status->isOK(), 'OK' );
280 $this->assertTrue( $status->value
['new'], 'new' );
281 $this->assertNotNull( $status->value
['revision'], 'revision' );
282 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
283 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
284 $this->assertTrue( $status->value
['revision']->getContent()->equals( $content ), 'equals' );
286 $rev = $page->getRevision();
287 $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
289 $this->assertNotNull( $rev->getRecentChange() );
290 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
292 // make sure that cached ParserOutput gets re-used throughout
293 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
295 $id = $page->getId();
297 // Test page creation logging
300 [ 'log_type', 'log_action' ],
301 [ 'log_page' => $id ],
302 [ [ 'create', 'create' ] ]
305 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
306 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
307 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
308 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
310 # ------------------------
311 $dbr = wfGetDB( DB_REPLICA
);
312 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
313 $n = $res->numRows();
316 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
318 # ------------------------
319 $page = new WikiPage( $title );
321 $retrieved = $page->getContent();
322 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
324 # ------------------------
325 $page = new WikiPage( $title );
327 // try null edit, with a different user
328 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE
, false, $user2 );
329 $this->assertTrue( $status->isOK(), 'OK' );
330 $this->assertFalse( $status->value
['new'], 'new' );
331 $this->assertNull( $status->value
['revision'], 'revision' );
332 $this->assertNotNull( $page->getRevision() );
333 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
335 # ------------------------
336 $content = ContentHandler
::makeContent(
337 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
338 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
340 CONTENT_MODEL_WIKITEXT
343 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE
);
344 $this->assertTrue( $status->isOK(), 'OK' );
345 $this->assertFalse( $status->value
['new'], 'new' );
346 $this->assertNotNull( $status->value
['revision'], 'revision' );
347 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
348 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
350 $status->value
['revision']->getContent()->equals( $content ),
351 'not equals (PST must substitute signature)'
354 $rev = $page->getRevision();
355 $this->assertNotNull( $rev->getRecentChange() );
356 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
358 # ------------------------
359 $page = new WikiPage( $title );
361 $retrieved = $page->getContent();
362 $newText = $retrieved->serialize();
363 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
364 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
366 # ------------------------
367 $dbr = wfGetDB( DB_REPLICA
);
368 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
369 $n = $res->numRows();
372 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
376 * @covers WikiPage::doEditContent
378 public function testDoEditContent_twice() {
379 $title = Title
::newFromText( __METHOD__
);
380 $page = WikiPage
::factory( $title );
381 $content = ContentHandler
::makeContent( '$1 van $2', $title );
383 // Make sure we can do the exact same save twice.
384 // This tests checks that internal caches are reset as appropriate.
385 $status1 = $page->doEditContent( $content, __METHOD__
);
386 $status2 = $page->doEditContent( $content, __METHOD__
);
388 $this->assertTrue( $status1->isOK(), 'OK' );
389 $this->assertTrue( $status2->isOK(), 'OK' );
391 $this->assertTrue( isset( $status1->value
['revision'] ), 'OK' );
392 $this->assertFalse( isset( $status2->value
['revision'] ), 'OK' );
396 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
397 * TODO: Revision deletion
399 * @covers WikiPage::doDeleteArticle
400 * @covers WikiPage::doDeleteArticleReal
402 public function testDoDeleteArticle() {
403 $page = $this->createPage(
405 "[[original text]] foo",
406 CONTENT_MODEL_WIKITEXT
408 $id = $page->getId();
410 $page->doDeleteArticle( "testing deletion" );
413 $page->getTitle()->getArticleID() > 0,
414 "Title object should now have page id 0"
416 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
419 "WikiPage::exists should return false after page was deleted"
423 "WikiPage::getContent should return null after page was deleted"
426 $t = Title
::newFromText( $page->getTitle()->getPrefixedText() );
429 "Title::exists should return false after page was deleted"
433 JobQueueGroup
::destroySingletons();
435 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
438 # ------------------------
439 $dbr = wfGetDB( DB_REPLICA
);
440 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
441 $n = $res->numRows();
444 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
448 * @covers WikiPage::doDeleteArticleReal
450 public function testDoDeleteArticleReal_user0() {
451 $page = $this->createPage(
453 "[[original text]] foo",
454 CONTENT_MODEL_WIKITEXT
456 $id = $page->getId();
459 $status = $page->doDeleteArticleReal(
460 /* reason */ "testing user 0 deletion",
461 /* suppress */ false,
464 /* errorStack */ $errorStack,
467 $logId = $status->getValue();
468 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
469 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
471 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
475 'log_comment' => $commentQuery['fields']['log_comment_text'],
476 'log_user' => $actorQuery['fields']['log_user'],
477 'log_user_text' => $actorQuery['fields']['log_user_text'],
481 [ 'log_id' => $logId ],
485 'testing user 0 deletion',
488 (string)$page->getTitle()->getNamespace(),
489 $page->getTitle()->getDBkey(),
492 $actorQuery['joins'] +
$commentQuery['joins']
497 * @covers WikiPage::doDeleteArticleReal
499 public function testDoDeleteArticleReal_userSysop() {
500 $page = $this->createPage(
502 "[[original text]] foo",
503 CONTENT_MODEL_WIKITEXT
505 $id = $page->getId();
507 $user = $this->getTestSysop()->getUser();
509 $status = $page->doDeleteArticleReal(
510 /* reason */ "testing sysop deletion",
511 /* suppress */ false,
514 /* errorStack */ $errorStack,
517 $logId = $status->getValue();
518 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
519 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
521 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
525 'log_comment' => $commentQuery['fields']['log_comment_text'],
526 'log_user' => $actorQuery['fields']['log_user'],
527 'log_user_text' => $actorQuery['fields']['log_user_text'],
531 [ 'log_id' => $logId ],
535 'testing sysop deletion',
536 (string)$user->getId(),
538 (string)$page->getTitle()->getNamespace(),
539 $page->getTitle()->getDBkey(),
542 $actorQuery['joins'] +
$commentQuery['joins']
547 * TODO: Test more stuff about suppression.
549 * @covers WikiPage::doDeleteArticleReal
551 public function testDoDeleteArticleReal_suppress() {
552 $page = $this->createPage(
554 "[[original text]] foo",
555 CONTENT_MODEL_WIKITEXT
557 $id = $page->getId();
559 $user = $this->getTestSysop()->getUser();
561 $status = $page->doDeleteArticleReal(
562 /* reason */ "testing deletion",
566 /* errorStack */ $errorStack,
569 $logId = $status->getValue();
570 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
571 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
573 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'], /* table */
577 'log_comment' => $commentQuery['fields']['log_comment_text'],
578 'log_user' => $actorQuery['fields']['log_user'],
579 'log_user_text' => $actorQuery['fields']['log_user_text'],
583 [ 'log_id' => $logId ],
588 (string)$user->getId(),
590 (string)$page->getTitle()->getNamespace(),
591 $page->getTitle()->getDBkey(),
594 $actorQuery['joins'] +
$commentQuery['joins']
598 $page->getContent( Revision
::FOR_PUBLIC
),
599 "WikiPage::getContent should return null after the page was suppressed for general users"
603 $page->getContent( Revision
::FOR_THIS_USER
, null ),
604 "WikiPage::getContent should return null after the page was suppressed for user zero"
608 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
609 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
614 * @covers WikiPage::doDeleteUpdates
616 public function testDoDeleteUpdates() {
617 $user = $this->getTestUser()->getUser();
618 $page = $this->createPage(
620 "[[original text]] foo",
621 CONTENT_MODEL_WIKITEXT
623 $id = $page->getId();
624 $page->loadPageData(); // make sure the current revision is cached.
626 // Similar to MovePage logic
627 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
628 $page->doDeleteUpdates( $page->getId(), $page->getContent(), $page->getRevision(), $user );
631 JobQueueGroup
::destroySingletons();
633 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
636 # ------------------------
637 $dbr = wfGetDB( DB_REPLICA
);
638 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
639 $n = $res->numRows();
642 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
646 * @param string $name
648 * @return ContentHandler
650 protected function defineMockContentModelForUpdateTesting( $name ) {
651 /** @var ContentHandler|MockObject $handler */
652 $handler = $this->getMockBuilder( TextContentHandler
::class )
653 ->setConstructorArgs( [ $name ] )
655 [ 'getSecondaryDataUpdates', 'getDeletionUpdates', 'unserializeContent' ]
659 $dataUpdate = new MWCallableUpdate( 'time' );
660 $dataUpdate->_name
= "$name data update";
662 $deletionUpdate = new MWCallableUpdate( 'time' );
663 $deletionUpdate->_name
= "$name deletion update";
665 $handler->method( 'getSecondaryDataUpdates' )->willReturn( [ $dataUpdate ] );
666 $handler->method( 'getDeletionUpdates' )->willReturn( [ $deletionUpdate ] );
667 $handler->method( 'unserializeContent' )->willReturnCallback(
668 function ( $text ) use ( $handler ) {
669 return $this->createMockContent( $handler, $text );
673 $this->mergeMwGlobalArrayValue(
674 'wgContentHandlers', [
675 $name => function () use ( $handler ){
685 * @param ContentHandler $handler
686 * @param string $text
690 protected function createMockContent( ContentHandler
$handler, $text ) {
691 /** @var Content|MockObject $content */
692 $content = $this->getMockBuilder( TextContent
::class )
693 ->setConstructorArgs( [ $text ] )
694 ->setMethods( [ 'getModel', 'getContentHandler' ] )
697 $content->method( 'getModel' )->willReturn( $handler->getModelID() );
698 $content->method( 'getContentHandler' )->willReturn( $handler );
703 public function testGetDeletionUpdates() {
704 $m1 = $this->defineMockContentModelForUpdateTesting( 'M1' );
706 $mainContent1 = $this->createMockContent( $m1, 'main 1' );
708 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
709 $page = $this->createPage(
711 [ 'main' => $mainContent1 ]
714 $dataUpdates = $page->getDeletionUpdates( $page->getRevisionRecord() );
715 $this->assertNotEmpty( $dataUpdates );
717 $updateNames = array_map( function ( $du ) {
718 return isset( $du->_name
) ?
$du->_name
: get_class( $du );
721 $this->assertContains( LinksDeletionUpdate
::class, $updateNames );
722 $this->assertContains( 'M1 deletion update', $updateNames );
726 * @covers WikiPage::getRevision
728 public function testGetRevision() {
729 $page = $this->newPage( __METHOD__
);
731 $rev = $page->getRevision();
732 $this->assertNull( $rev );
735 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
737 $rev = $page->getRevision();
739 $this->assertEquals( $page->getLatest(), $rev->getId() );
740 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
744 * @covers WikiPage::getContent
746 public function testGetContent() {
747 $page = $this->newPage( __METHOD__
);
749 $content = $page->getContent();
750 $this->assertNull( $content );
753 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
755 $content = $page->getContent();
756 $this->assertEquals( "some text", $content->getNativeData() );
760 * @covers WikiPage::exists
762 public function testExists() {
763 $page = $this->newPage( __METHOD__
);
764 $this->assertFalse( $page->exists() );
767 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
768 $this->assertTrue( $page->exists() );
770 $page = new WikiPage( $page->getTitle() );
771 $this->assertTrue( $page->exists() );
774 $page->doDeleteArticle( "done testing" );
775 $this->assertFalse( $page->exists() );
777 $page = new WikiPage( $page->getTitle() );
778 $this->assertFalse( $page->exists() );
781 public function provideHasViewableContent() {
783 [ 'WikiPageTest_testHasViewableContent', false, true ],
784 [ 'Special:WikiPageTest_testHasViewableContent', false ],
785 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
786 [ 'Special:Userlogin', true ],
787 [ 'MediaWiki:help', true ],
792 * @dataProvider provideHasViewableContent
793 * @covers WikiPage::hasViewableContent
795 public function testHasViewableContent( $title, $viewable, $create = false ) {
796 $page = $this->newPage( $title );
797 $this->assertEquals( $viewable, $page->hasViewableContent() );
800 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
801 $this->assertTrue( $page->hasViewableContent() );
803 $page = new WikiPage( $page->getTitle() );
804 $this->assertTrue( $page->hasViewableContent() );
808 public function provideGetRedirectTarget() {
810 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
812 'WikiPageTest_testGetRedirectTarget_2',
813 CONTENT_MODEL_WIKITEXT
,
814 "#REDIRECT [[hello world]]",
817 // The below added to protect against Media namespace
818 // redirects which throw a fatal: (T203942)
820 'WikiPageTest_testGetRedirectTarget_3',
821 CONTENT_MODEL_WIKITEXT
,
822 "#REDIRECT [[Media:hello_world]]",
825 // Test fragments longer than 255 bytes (T207876)
827 'WikiPageTest_testGetRedirectTarget_4',
828 CONTENT_MODEL_WIKITEXT
,
829 // phpcs:ignore Generic.Files.LineLength
830 '#REDIRECT [[Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴]]',
831 // phpcs:ignore Generic.Files.LineLength
832 'Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴...'
838 * @dataProvider provideGetRedirectTarget
839 * @covers WikiPage::getRedirectTarget
841 public function testGetRedirectTarget( $title, $model, $text, $target ) {
842 $this->setMwGlobals( [
843 'wgCapitalLinks' => true,
846 $page = $this->createPage( $title, $text, $model );
848 # sanity check, because this test seems to fail for no reason for some people.
849 $c = $page->getContent();
850 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
852 # now, test the actual redirect
853 $t = $page->getRedirectTarget();
854 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getFullText() );
858 * @dataProvider provideGetRedirectTarget
859 * @covers WikiPage::isRedirect
861 public function testIsRedirect( $title, $model, $text, $target ) {
862 $page = $this->createPage( $title, $text, $model );
863 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
866 public function provideIsCountable() {
870 [ 'WikiPageTest_testIsCountable',
871 CONTENT_MODEL_WIKITEXT
,
876 [ 'WikiPageTest_testIsCountable',
877 CONTENT_MODEL_WIKITEXT
,
884 [ 'WikiPageTest_testIsCountable',
885 CONTENT_MODEL_WIKITEXT
,
890 [ 'WikiPageTest_testIsCountable',
891 CONTENT_MODEL_WIKITEXT
,
898 [ 'WikiPageTest_testIsCountable',
899 CONTENT_MODEL_WIKITEXT
,
904 [ 'WikiPageTest_testIsCountable',
905 CONTENT_MODEL_WIKITEXT
,
911 // not a content namespace
912 [ 'Talk:WikiPageTest_testIsCountable',
913 CONTENT_MODEL_WIKITEXT
,
918 [ 'Talk:WikiPageTest_testIsCountable',
919 CONTENT_MODEL_WIKITEXT
,
925 // not a content namespace, different model
926 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
932 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
942 * @dataProvider provideIsCountable
943 * @covers WikiPage::isCountable
945 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
946 global $wgContentHandlerUseDB;
948 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
950 $title = Title
::newFromText( $title );
952 if ( !$wgContentHandlerUseDB
954 && ContentHandler
::getDefaultModelFor( $title ) != $model
956 $this->markTestSkipped( "Can not use non-default content model $model for "
957 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
960 $page = $this->createPage( $title, $text, $model );
962 $editInfo = $page->prepareContentForEdit( $page->getContent() );
964 $v = $page->isCountable();
965 $w = $page->isCountable( $editInfo );
970 "isCountable( null ) returned unexpected value " . var_export( $v, true )
971 . " instead of " . var_export( $expected, true )
972 . " in mode `$mode` for text \"$text\""
978 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
979 . " instead of " . var_export( $expected, true )
980 . " in mode `$mode` for text \"$text\""
984 public function provideGetParserOutput() {
987 CONTENT_MODEL_WIKITEXT
,
989 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
996 * @dataProvider provideGetParserOutput
997 * @covers WikiPage::getParserOutput
999 public function testGetParserOutput( $model, $text, $expectedHtml ) {
1000 $page = $this->createPage( __METHOD__
, $text, $model );
1002 $opt = $page->makeParserOptions( 'canonical' );
1003 $po = $page->getParserOutput( $opt );
1004 $text = $po->getText();
1006 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
1007 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
1009 $this->assertEquals( $expectedHtml, $text );
1015 * @covers WikiPage::getParserOutput
1017 public function testGetParserOutput_nonexisting() {
1018 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1020 $opt = new ParserOptions();
1021 $po = $page->getParserOutput( $opt );
1023 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
1027 * @covers WikiPage::getParserOutput
1029 public function testGetParserOutput_badrev() {
1030 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
1032 $opt = new ParserOptions();
1033 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
1035 // @todo would be neat to also test deleted revision
1037 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
1040 public static $sections =
1054 public function dataReplaceSection() {
1055 // NOTE: assume the Help namespace to contain wikitext
1057 [ 'Help:WikiPageTest_testReplaceSection',
1058 CONTENT_MODEL_WIKITEXT
,
1063 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
1065 [ 'Help:WikiPageTest_testReplaceSection',
1066 CONTENT_MODEL_WIKITEXT
,
1073 [ 'Help:WikiPageTest_testReplaceSection',
1074 CONTENT_MODEL_WIKITEXT
,
1077 "== TEST ==\nmore fun",
1079 trim( preg_replace( '/^== test ==.*== foo ==/sm',
1080 "== TEST ==\nmore fun\n\n== foo ==",
1083 [ 'Help:WikiPageTest_testReplaceSection',
1084 CONTENT_MODEL_WIKITEXT
,
1089 trim( self
::$sections )
1091 [ 'Help:WikiPageTest_testReplaceSection',
1092 CONTENT_MODEL_WIKITEXT
,
1097 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
1103 * @dataProvider dataReplaceSection
1104 * @covers WikiPage::replaceSectionContent
1106 public function testReplaceSectionContent( $title, $model, $text, $section,
1107 $with, $sectionTitle, $expected
1109 $page = $this->createPage( $title, $text, $model );
1111 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1112 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
1114 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1118 * @dataProvider dataReplaceSection
1119 * @covers WikiPage::replaceSectionAtRev
1121 public function testReplaceSectionAtRev( $title, $model, $text, $section,
1122 $with, $sectionTitle, $expected
1124 $page = $this->createPage( $title, $text, $model );
1125 $baseRevId = $page->getLatest();
1127 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1128 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1130 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1134 * @covers WikiPage::getOldestRevision
1136 public function testGetOldestRevision() {
1137 $page = $this->newPage( __METHOD__
);
1138 $page->doEditContent(
1139 new WikitextContent( 'one' ),
1143 $rev1 = $page->getRevision();
1145 $page = new WikiPage( $page->getTitle() );
1146 $page->doEditContent(
1147 new WikitextContent( 'two' ),
1152 $page = new WikiPage( $page->getTitle() );
1153 $page->doEditContent(
1154 new WikitextContent( 'three' ),
1160 $this->assertNotEquals(
1162 $page->getRevision()->getId(),
1163 '$page->getRevision()->getId()'
1167 $this->assertEquals(
1169 $page->getOldestRevision()->getId(),
1170 '$page->getOldestRevision()->getId()'
1175 * @covers WikiPage::doRollback
1176 * @covers WikiPage::commitRollback
1178 public function testDoRollback() {
1179 // FIXME: fails under postgres
1180 $this->markTestSkippedIfDbType( 'postgres' );
1182 $admin = $this->getTestSysop()->getUser();
1183 $user1 = $this->getTestUser()->getUser();
1184 // Use the confirmed group for user2 to make sure the user is different
1185 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1187 // make sure we can test autopatrolling
1188 $this->setMwGlobals( 'wgUseRCPatrol', true );
1190 // TODO: MCR: test rollback of multiple slots!
1191 $page = $this->newPage( __METHOD__
);
1195 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1196 "section one", EDIT_NEW
, false, $admin );
1199 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1200 "adding section two", 0, false, $user1 );
1202 $text .= "\n\nthree";
1203 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1204 "adding section three", 0, false, $user2 );
1206 /** @var Revision $rev1 */
1207 /** @var Revision $rev2 */
1208 /** @var Revision $rev3 */
1209 $rev1 = $status1->getValue()['revision'];
1210 $rev2 = $status2->getValue()['revision'];
1211 $rev3 = $status3->getValue()['revision'];
1214 * We are having issues with doRollback spuriously failing. Apparently
1215 * the last revision somehow goes missing or not committed under some
1216 * circumstances. So, make sure the revisions have the correct usernames.
1218 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1219 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1220 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1221 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1223 // Now, try the actual rollback
1224 $token = $admin->getEditToken( 'rollback' );
1225 $rollbackErrors = $page->doRollback(
1234 if ( $rollbackErrors ) {
1236 "Rollback failed:\n" .
1237 print_r( $rollbackErrors, true ) . ";\n" .
1238 print_r( $resultDetails, true )
1242 $page = new WikiPage( $page->getTitle() );
1243 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1244 "rollback did not revert to the correct revision" );
1245 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1247 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1248 $page->getRevision()->getRevisionRecord()
1251 $this->assertNotNull( $rc, 'RecentChanges entry' );
1252 $this->assertEquals(
1253 RecentChange
::PRC_AUTOPATROLLED
,
1254 $rc->getAttribute( 'rc_patrolled' ),
1258 // TODO: MCR: assert origin once we write slot data
1259 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( SlotRecord::MAIN );
1260 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1261 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1265 * @covers WikiPage::doRollback
1266 * @covers WikiPage::commitRollback
1268 public function testDoRollbackFailureSameContent() {
1269 $admin = $this->getTestSysop()->getUser();
1272 $page = $this->newPage( __METHOD__
);
1273 $page->doEditContent(
1274 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1280 $rev1 = $page->getRevision();
1282 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1284 $page = new WikiPage( $page->getTitle() );
1285 $page->doEditContent(
1286 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1287 "adding section two",
1293 # now, do a the rollback from the same user was doing the edit before
1294 $resultDetails = [];
1295 $token = $user1->getEditToken( 'rollback' );
1296 $errors = $page->doRollback(
1298 "testing revert same user",
1305 $this->assertEquals( [], $errors, "Rollback failed same user" );
1307 # now, try the rollback
1308 $resultDetails = [];
1309 $token = $admin->getEditToken( 'rollback' );
1310 $errors = $page->doRollback(
1319 $this->assertEquals(
1329 "Rollback not failed"
1332 $page = new WikiPage( $page->getTitle() );
1333 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1334 "rollback did not revert to the correct revision" );
1335 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1339 * Tests tagging for edits that do rollback action
1340 * @covers WikiPage::doRollback
1342 public function testDoRollbackTagging() {
1343 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1344 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1347 $admin = new User();
1348 $admin->setName( 'Administrator' );
1349 $admin->addToDatabase();
1351 $text = 'First line';
1352 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1353 $page->doEditContent(
1354 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1361 $secondUser = new User();
1362 $secondUser->setName( '92.65.217.32' );
1363 $text .= '\n\nSecond line';
1364 $page = new WikiPage( $page->getTitle() );
1365 $page->doEditContent(
1366 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1367 'Adding second line',
1373 // Now, try the rollback
1374 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1375 $token = $admin->getEditToken( 'rollback' );
1376 $errors = $page->doRollback(
1377 $secondUser->getName(),
1385 // If doRollback completed without errors
1386 if ( $errors === [] ) {
1387 $tags = $resultDetails[ 'tags' ];
1388 $this->assertContains( 'mw-rollback', $tags );
1392 public function provideGetAutoDeleteReason() {
1402 [ "first edit", null ],
1404 "/first edit.*only contributor/",
1410 [ "first edit", null ],
1411 [ "second edit", null ],
1413 "/second edit.*only contributor/",
1419 [ "first edit", "127.0.2.22" ],
1420 [ "second edit", "127.0.3.33" ],
1430 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1431 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1432 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1433 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1434 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1438 '/first edit:.*\.\.\."/',
1444 [ "first edit", "127.0.2.22" ],
1445 [ "", "127.0.3.33" ],
1447 "/before blanking.*first edit/",
1455 * @dataProvider provideGetAutoDeleteReason
1456 * @covers WikiPage::getAutoDeleteReason
1458 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1461 // NOTE: assume Help namespace to contain wikitext
1462 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1466 foreach ( $edits as $edit ) {
1469 if ( !empty( $edit[1] ) ) {
1470 $user->setName( $edit[1] );
1475 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1477 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1482 $reason = $page->getAutoDeleteReason( $hasHistory );
1484 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1485 $this->assertEquals( $expectedResult, $reason );
1487 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1488 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1491 $this->assertEquals( $expectedHistory, $hasHistory,
1492 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1494 $page->doDeleteArticle( "done" );
1497 public function providePreSaveTransform() {
1499 [ 'hello this is ~~~',
1500 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1502 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1503 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1509 * @covers WikiPage::factory
1511 public function testWikiPageFactory() {
1512 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1513 $page = WikiPage
::factory( $title );
1514 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1516 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1517 $page = WikiPage
::factory( $title );
1518 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1520 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1521 $page = WikiPage
::factory( $title );
1522 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1526 * @covers WikiPage::loadPageData
1527 * @covers WikiPage::wasLoadedFrom
1529 public function testLoadPageData() {
1530 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1531 $page = WikiPage
::factory( $title );
1533 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1534 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1535 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1536 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1538 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1539 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1540 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1541 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1542 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1544 $page->loadPageData( IDBAccessObject
::READ_LATEST
);
1545 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1546 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1547 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1548 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1550 $page->loadPageData( IDBAccessObject
::READ_LOCKING
);
1551 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1552 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1553 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1554 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1556 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
1557 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1558 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1559 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1560 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1564 * @dataProvider provideCommentMigrationOnDeletion
1566 * @param int $writeStage
1567 * @param int $readStage
1569 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1570 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1571 $this->overrideMwServices();
1573 $dbr = wfGetDB( DB_REPLICA
);
1575 $page = $this->createPage(
1578 CONTENT_MODEL_WIKITEXT
1580 $revid = $page->getLatest();
1581 if ( $writeStage > MIGRATION_OLD
) {
1582 $comment_id = $dbr->selectField(
1583 'revision_comment_temp',
1584 'revcomment_comment_id',
1585 [ 'revcomment_rev' => $revid ],
1590 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1591 $this->overrideMwServices();
1593 $page->doDeleteArticle( "testing deletion" );
1595 if ( $readStage > MIGRATION_OLD
) {
1596 // Didn't leave behind any 'revision_comment_temp' rows
1597 $n = $dbr->selectField(
1598 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1600 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1602 // Copied or upgraded the comment_id, as applicable
1603 $ar_comment_id = $dbr->selectField(
1606 [ 'ar_rev_id' => $revid ],
1609 if ( $writeStage > MIGRATION_OLD
) {
1610 $this->assertSame( $comment_id, $ar_comment_id );
1612 $this->assertNotEquals( 0, $ar_comment_id );
1616 // Copied rev_comment, if applicable
1617 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1618 $ar_comment = $dbr->selectField(
1621 [ 'ar_rev_id' => $revid ],
1624 $this->assertSame( 'testing', $ar_comment );
1628 public function provideCommentMigrationOnDeletion() {
1630 [ MIGRATION_OLD
, MIGRATION_OLD
],
1631 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1632 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1633 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1634 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1635 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1636 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1637 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1638 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1639 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1640 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1641 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1642 [ MIGRATION_NEW
, MIGRATION_NEW
],
1647 * @covers WikiPage::updateCategoryCounts
1649 public function testUpdateCategoryCounts() {
1650 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1652 // Add an initial category
1653 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1655 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1656 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1657 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1659 // Add a new category
1660 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1662 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1663 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1664 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1666 // Add and remove a category
1667 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1669 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1670 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1671 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1674 public function provideUpdateRedirectOn() {
1675 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1676 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1677 yield
[ 'SomeText', false, null, false, true, 0 ];
1678 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1682 * @dataProvider provideUpdateRedirectOn
1683 * @covers WikiPage::updateRedirectOn
1685 * @param string $initialText
1686 * @param bool $initialRedirectState
1687 * @param string|null $redirectTitle
1688 * @param bool|null $lastRevIsRedirect
1689 * @param bool $expectedSuccess
1690 * @param int $expectedRowCount
1692 public function testUpdateRedirectOn(
1694 $initialRedirectState,
1700 // FIXME: fails under sqlite and postgres
1701 $this->markTestSkippedIfDbType( 'sqlite' );
1702 $this->markTestSkippedIfDbType( 'postgres' );
1703 static $pageCounter = 0;
1706 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1707 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1709 $redirectTitle = is_string( $redirectTitle )
1710 ? Title
::newFromText( $redirectTitle )
1713 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1714 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1716 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1717 * Most of core checks the page table for redirect status, so we have to be ugly and
1718 * assert a select from the table here.
1720 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1723 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1724 $this->assertSelect(
1727 [ 'rd_from' => $pageId ],
1728 [ [ strval( $expected ) ] ]
1733 * @covers WikiPage::insertRedirectEntry
1735 public function testInsertRedirectEntry_insertsRedirectEntry() {
1736 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1737 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1739 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1740 $targetTitle->mInterwiki
= 'eninter';
1741 $page->insertRedirectEntry( $targetTitle, null );
1743 $this->assertSelect(
1745 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1746 [ 'rd_from' => $page->getId() ],
1748 strval( $page->getId() ),
1749 strval( $targetTitle->getNamespace() ),
1750 strval( $targetTitle->getDBkey() ),
1751 strval( $targetTitle->getFragment() ),
1752 strval( $targetTitle->getInterwiki() ),
1758 * @covers WikiPage::insertRedirectEntry
1760 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1761 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1762 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1764 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1765 $targetTitle->mInterwiki
= 'eninter';
1766 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1768 $this->assertSelect(
1770 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1771 [ 'rd_from' => $page->getId() ],
1773 strval( $page->getId() ),
1774 strval( $targetTitle->getNamespace() ),
1775 strval( $targetTitle->getDBkey() ),
1776 strval( $targetTitle->getFragment() ),
1777 strval( $targetTitle->getInterwiki() ),
1783 * @covers WikiPage::insertRedirectEntry
1785 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1786 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1787 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1789 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1790 $targetTitle->mInterwiki
= 'eninter';
1791 $page->insertRedirectEntry( $targetTitle, 215251 );
1793 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1796 private function getRow( array $overrides = [] ) {
1800 'page_is_redirect' => '1',
1801 'page_latest' => '99',
1802 'page_namespace' => '3',
1803 'page_title' => 'JaJaTitle',
1804 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1805 'page_touched' => '20120101020202',
1806 'page_links_updated' => '20140101020202',
1808 foreach ( $overrides as $key => $value ) {
1809 $row[$key] = $value;
1811 return (object)$row;
1814 public function provideNewFromRowSuccess() {
1815 yield
'basic row' => [
1817 function ( WikiPage
$wikiPage, self
$test ) {
1818 $test->assertSame( 44, $wikiPage->getId() );
1819 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1820 $test->assertTrue( $wikiPage->isRedirect() );
1821 $test->assertSame( 99, $wikiPage->getLatest() );
1822 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1823 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1826 'edit' => [ 'autoconfirmed', 'sysop' ],
1827 'move' => [ 'sysop' ],
1829 $wikiPage->getTitle()->getAllRestrictions()
1831 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1832 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1835 yield
'different timestamp formats' => [
1837 'page_touched' => '2012-01-01 02:02:02',
1838 'page_links_updated' => '2014-01-01 02:02:02',
1840 function ( WikiPage
$wikiPage, self
$test ) {
1841 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1842 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1845 yield
'no restrictions' => [
1847 'page_restrictions' => '',
1849 function ( WikiPage
$wikiPage, self
$test ) {
1855 $wikiPage->getTitle()->getAllRestrictions()
1859 yield
'not redirect' => [
1861 'page_is_redirect' => '0',
1863 function ( WikiPage
$wikiPage, self
$test ) {
1864 $test->assertFalse( $wikiPage->isRedirect() );
1870 * @covers WikiPage::newFromRow
1871 * @covers WikiPage::loadFromRow
1872 * @dataProvider provideNewFromRowSuccess
1874 * @param object $row
1875 * @param callable $assertions
1877 public function testNewFromRow( $row, $assertions ) {
1878 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1879 $assertions( $page, $this );
1882 public function provideTestNewFromId_returnsNullOnBadPageId() {
1888 * @covers WikiPage::newFromID
1889 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1891 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1892 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1896 * @covers WikiPage::newFromID
1898 public function testNewFromId_appearsToFetchCorrectRow() {
1899 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1900 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1901 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1902 $this->assertEquals(
1903 $createdPage->getContent()->getNativeData(),
1904 $fetchedPage->getContent()->getNativeData()
1909 * @covers WikiPage::newFromID
1911 public function testNewFromId_returnsNullOnNonExistingId() {
1912 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1915 public function provideTestInsertProtectNullRevision() {
1916 // phpcs:disable Generic.Files.LineLength
1919 [ 'edit' => 'sysop' ],
1920 [ 'edit' => '20200101040404' ],
1924 '(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)))'
1928 [ 'edit' => 'sysop', 'move' => 'something' ],
1929 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1933 '(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)))'
1939 * @dataProvider provideTestInsertProtectNullRevision
1940 * @covers WikiPage::insertProtectNullRevision
1941 * @covers WikiPage::protectDescription
1943 * @param string $revCommentMsg
1944 * @param array $limit
1945 * @param array $expiry
1946 * @param bool $cascade
1947 * @param string $reason
1948 * @param bool|null $user true if the test sysop should be used, or null
1949 * @param string $expectedComment
1951 public function testInsertProtectNullRevision(
1960 $this->setContentLang( 'qqx' );
1962 $page = $this->createPage( __METHOD__
, 'Goat' );
1964 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1966 $result = $page->insertProtectNullRevision(
1975 $this->assertTrue( $result instanceof Revision
);
1976 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1980 * @covers WikiPage::updateRevisionOn
1982 public function testUpdateRevisionOn_existingPage() {
1983 $user = $this->getTestSysop()->getUser();
1984 $page = $this->createPage( __METHOD__
, 'StartText' );
1986 $revision = new Revision(
1989 'page' => $page->getId(),
1990 'title' => $page->getTitle(),
1991 'comment' => __METHOD__
,
1992 'minor_edit' => true,
1993 'text' => __METHOD__
. '-text',
1994 'len' => strlen( __METHOD__
. '-text' ),
1995 'user' => $user->getId(),
1996 'user_text' => $user->getName(),
1997 'timestamp' => '20170707040404',
1998 'content_model' => CONTENT_MODEL_WIKITEXT
,
1999 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2003 $result = $page->updateRevisionOn( $this->db
, $revision );
2004 $this->assertTrue( $result );
2005 $this->assertSame( 9989, $page->getLatest() );
2006 $this->assertEquals( $revision, $page->getRevision() );
2010 * @covers WikiPage::updateRevisionOn
2012 public function testUpdateRevisionOn_NonExistingPage() {
2013 $user = $this->getTestSysop()->getUser();
2014 $page = $this->createPage( __METHOD__
, 'StartText' );
2015 $page->doDeleteArticle( 'reason' );
2017 $revision = new Revision(
2020 'page' => $page->getId(),
2021 'title' => $page->getTitle(),
2022 'comment' => __METHOD__
,
2023 'minor_edit' => true,
2024 'text' => __METHOD__
. '-text',
2025 'len' => strlen( __METHOD__
. '-text' ),
2026 'user' => $user->getId(),
2027 'user_text' => $user->getName(),
2028 'timestamp' => '20170707040404',
2029 'content_model' => CONTENT_MODEL_WIKITEXT
,
2030 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2034 $result = $page->updateRevisionOn( $this->db
, $revision );
2035 $this->assertFalse( $result );
2039 * @covers WikiPage::updateIfNewerOn
2041 public function testUpdateIfNewerOn_olderRevision() {
2042 $user = $this->getTestSysop()->getUser();
2043 $page = $this->createPage( __METHOD__
, 'StartText' );
2044 $initialRevision = $page->getRevision();
2046 $olderTimeStamp = wfTimestamp(
2048 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
2051 $olderRevison = new Revision(
2054 'page' => $page->getId(),
2055 'title' => $page->getTitle(),
2056 'comment' => __METHOD__
,
2057 'minor_edit' => true,
2058 'text' => __METHOD__
. '-text',
2059 'len' => strlen( __METHOD__
. '-text' ),
2060 'user' => $user->getId(),
2061 'user_text' => $user->getName(),
2062 'timestamp' => $olderTimeStamp,
2063 'content_model' => CONTENT_MODEL_WIKITEXT
,
2064 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2068 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
2069 $this->assertFalse( $result );
2073 * @covers WikiPage::updateIfNewerOn
2075 public function testUpdateIfNewerOn_newerRevision() {
2076 $user = $this->getTestSysop()->getUser();
2077 $page = $this->createPage( __METHOD__
, 'StartText' );
2078 $initialRevision = $page->getRevision();
2080 $newerTimeStamp = wfTimestamp(
2082 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
2085 $newerRevision = new Revision(
2088 'page' => $page->getId(),
2089 'title' => $page->getTitle(),
2090 'comment' => __METHOD__
,
2091 'minor_edit' => true,
2092 'text' => __METHOD__
. '-text',
2093 'len' => strlen( __METHOD__
. '-text' ),
2094 'user' => $user->getId(),
2095 'user_text' => $user->getName(),
2096 'timestamp' => $newerTimeStamp,
2097 'content_model' => CONTENT_MODEL_WIKITEXT
,
2098 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2101 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
2102 $this->assertTrue( $result );
2106 * @covers WikiPage::insertOn
2108 public function testInsertOn() {
2109 $title = Title
::newFromText( __METHOD__
);
2110 $page = new WikiPage( $title );
2112 $startTimeStamp = wfTimestampNow();
2113 $result = $page->insertOn( $this->db
);
2114 $endTimeStamp = wfTimestampNow();
2116 $this->assertInternalType( 'int', $result );
2117 $this->assertTrue( $result > 0 );
2119 $condition = [ 'page_id' => $result ];
2121 // Check the default fields have been filled
2122 $this->assertSelect(
2127 'page_restrictions',
2145 // Check the page_random field has been filled
2146 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2147 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2149 // Assert the touched timestamp in the DB is roughly when we inserted the page
2150 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2152 wfTimestamp( TS_UNIX
, $startTimeStamp )
2153 <= wfTimestamp( TS_UNIX
, $pageTouched )
2156 wfTimestamp( TS_UNIX
, $endTimeStamp )
2157 >= wfTimestamp( TS_UNIX
, $pageTouched )
2160 // Try inserting the same page again and checking the result is false (no change)
2161 $result = $page->insertOn( $this->db
);
2162 $this->assertFalse( $result );
2166 * @covers WikiPage::insertOn
2168 public function testInsertOn_idSpecified() {
2169 $title = Title
::newFromText( __METHOD__
);
2170 $page = new WikiPage( $title );
2173 $result = $page->insertOn( $this->db
, $id );
2175 $this->assertSame( $id, $result );
2177 $condition = [ 'page_id' => $result ];
2179 // Check there is actually a row in the db
2180 $this->assertSelect(
2188 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2189 // Note: Once the current dates passes the date in these tests they will fail.
2190 yield
'move something' => [
2192 [ 'move' => 'something' ],
2194 [ 'edit' => [], 'move' => [ 'something' ] ],
2197 yield
'move something, edit blank' => [
2199 [ 'move' => 'something', 'edit' => '' ],
2201 [ 'edit' => [], 'move' => [ 'something' ] ],
2204 yield
'edit sysop, with expiry' => [
2206 [ 'edit' => 'sysop' ],
2207 [ 'edit' => '21330101020202' ],
2208 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2209 [ 'edit' => '21330101020202' ],
2211 yield
'move and edit, move with expiry' => [
2213 [ 'move' => 'something', 'edit' => 'another' ],
2214 [ 'move' => '22220202010101' ],
2215 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2216 [ 'move' => '22220202010101' ],
2218 yield
'move and edit, edit with infinity expiry' => [
2220 [ 'move' => 'something', 'edit' => 'another' ],
2221 [ 'edit' => 'infinity' ],
2222 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2223 [ 'edit' => 'infinity' ],
2225 yield
'non existing, create something' => [
2227 [ 'create' => 'something' ],
2229 [ 'create' => [ 'something' ] ],
2232 yield
'non existing, create something with expiry' => [
2234 [ 'create' => 'something' ],
2235 [ 'create' => '23451212112233' ],
2236 [ 'create' => [ 'something' ] ],
2237 [ 'create' => '23451212112233' ],
2242 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2243 * @covers WikiPage::doUpdateRestrictions
2245 public function testDoUpdateRestrictions_setBasicRestrictions(
2249 array $expectedRestrictions,
2250 array $expectedRestrictionExpiries
2252 if ( $pageExists ) {
2253 $page = $this->createPage( __METHOD__
, 'ABC' );
2255 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2257 $user = $this->getTestSysop()->getUser();
2260 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2262 $logId = $status->getValue();
2263 $allRestrictions = $page->getTitle()->getAllRestrictions();
2265 $this->assertTrue( $status->isGood() );
2266 $this->assertInternalType( 'int', $logId );
2267 $this->assertSame( $expectedRestrictions, $allRestrictions );
2268 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2269 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2272 // Make sure the log entry looks good
2273 // log_params is not checked here
2274 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2275 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'log_comment' );
2276 $this->assertSelect(
2277 [ 'logging' ] +
$actorQuery['tables'] +
$commentQuery['tables'],
2279 'log_comment' => $commentQuery['fields']['log_comment_text'],
2280 'log_user' => $actorQuery['fields']['log_user'],
2281 'log_user_text' => $actorQuery['fields']['log_user_text'],
2285 [ 'log_id' => $logId ],
2288 (string)$user->getId(),
2290 (string)$page->getTitle()->getNamespace(),
2291 $page->getTitle()->getDBkey(),
2294 $actorQuery['joins'] +
$commentQuery['joins']
2299 * @covers WikiPage::doUpdateRestrictions
2301 public function testDoUpdateRestrictions_failsOnReadOnly() {
2302 $page = $this->createPage( __METHOD__
, 'ABC' );
2303 $user = $this->getTestSysop()->getUser();
2307 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2308 ->disableOriginalConstructor()
2309 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2311 $readOnly->expects( $this->once() )
2312 ->method( 'isReadOnly' )
2313 ->will( $this->returnValue( true ) );
2314 $readOnly->expects( $this->once() )
2315 ->method( 'getReason' )
2316 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2317 $this->setService( 'ReadOnlyMode', $readOnly );
2319 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2320 $this->assertFalse( $status->isOK() );
2321 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2325 * @covers WikiPage::doUpdateRestrictions
2327 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2328 $page = $this->createPage( __METHOD__
, 'ABC' );
2329 $user = $this->getTestSysop()->getUser();
2331 $limit = [ 'edit' => 'sysop' ];
2333 $status = $page->doUpdateRestrictions(
2342 // The first entry should have a logId as it did something
2343 $this->assertTrue( $status->isGood() );
2344 $this->assertInternalType( 'int', $status->getValue() );
2346 $status = $page->doUpdateRestrictions(
2355 // The second entry should not have a logId as nothing changed
2356 $this->assertTrue( $status->isGood() );
2357 $this->assertNull( $status->getValue() );
2361 * @covers WikiPage::doUpdateRestrictions
2363 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2364 $page = $this->createPage( __METHOD__
, 'ABC' );
2365 $user = $this->getTestSysop()->getUser();
2369 $status = $page->doUpdateRestrictions(
2370 [ 'edit' => 'sysop' ],
2377 $this->assertTrue( $status->isGood() );
2378 $this->assertInternalType( 'int', $status->getValue() );
2379 $this->assertSelect(
2381 [ 'log_type', 'log_action' ],
2382 [ 'log_id' => $status->getValue() ],
2383 [ [ 'protect', 'protect' ] ]
2386 // Modify the protection
2387 $status = $page->doUpdateRestrictions(
2388 [ 'edit' => 'somethingElse' ],
2395 $this->assertTrue( $status->isGood() );
2396 $this->assertInternalType( 'int', $status->getValue() );
2397 $this->assertSelect(
2399 [ 'log_type', 'log_action' ],
2400 [ 'log_id' => $status->getValue() ],
2401 [ [ 'protect', 'modify' ] ]
2404 // Remove the protection
2405 $status = $page->doUpdateRestrictions(
2413 $this->assertTrue( $status->isGood() );
2414 $this->assertInternalType( 'int', $status->getValue() );
2415 $this->assertSelect(
2417 [ 'log_type', 'log_action' ],
2418 [ 'log_id' => $status->getValue() ],
2419 [ [ 'protect', 'unprotect' ] ]
2424 * @covers WikiPage::newPageUpdater
2425 * @covers WikiPage::getDerivedDataUpdater
2427 public function testNewPageUpdater() {
2428 $user = $this->getTestUser()->getUser();
2429 $page = $this->newPage( __METHOD__
, __METHOD__
);
2431 /** @var Content $content */
2432 $content = $this->getMockBuilder( WikitextContent
::class )
2433 ->setConstructorArgs( [ 'Hello World' ] )
2434 ->setMethods( [ 'getParserOutput' ] )
2436 $content->expects( $this->once() )
2437 ->method( 'getParserOutput' )
2438 ->willReturn( new ParserOutput( 'HTML' ) );
2440 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2442 // provide context, so the cache can be kept in place
2443 $slotsUpdate = new revisionSlotsUpdate();
2444 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
2446 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2447 $updater->setContent( SlotRecord
::MAIN
, $content );
2448 $revision = $updater->saveRevision(
2449 CommentStoreComment
::newUnsavedComment( 'test' ),
2453 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2455 $this->assertSame( $revision->getId(), $page->getLatest() );
2457 // Parsed output must remain cached throughout.
2458 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2462 * @covers WikiPage::newPageUpdater
2463 * @covers WikiPage::getDerivedDataUpdater
2465 public function testGetDerivedDataUpdater() {
2466 $admin = $this->getTestSysop()->getUser();
2468 /** @var object $page */
2469 $page = $this->createPage( __METHOD__
, __METHOD__
);
2470 $page = TestingAccessWrapper
::newFromObject( $page );
2472 $revision = $page->getRevision()->getRevisionRecord();
2473 $user = $revision->getUser();
2475 $slotsUpdate = new RevisionSlotsUpdate();
2476 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, new WikitextContent( 'Hello World' ) );
2478 // get a virgin updater
2479 $updater1 = $page->getDerivedDataUpdater( $user );
2480 $this->assertFalse( $updater1->isUpdatePrepared() );
2482 $updater1->prepareUpdate( $revision );
2484 // Re-use updater with same revision or content, even if base changed
2485 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2487 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2488 [ SlotRecord
::MAIN
=> $revision->getContent( SlotRecord
::MAIN
) ]
2490 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2492 // Don't re-use for edit if base revision ID changed
2493 $this->assertNotSame(
2495 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2498 // Don't re-use with different user
2499 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2500 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2502 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2503 $updater2b->prepareContent( $user, $slotsUpdate, false );
2504 $this->assertNotSame( $updater2a, $updater2b );
2506 // Don't re-use with different content
2507 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2508 $updater3->prepareUpdate( $revision );
2509 $this->assertNotSame( $updater2b, $updater3 );
2511 // Don't re-use if no context given
2512 $updater4 = $page->getDerivedDataUpdater( $admin );
2513 $updater4->prepareUpdate( $revision );
2514 $this->assertNotSame( $updater3, $updater4 );
2516 // Don't re-use if AGAIN no context given
2517 $updater5 = $page->getDerivedDataUpdater( $admin );
2518 $this->assertNotSame( $updater4, $updater5 );
2520 // Don't re-use cached "virgin" unprepared updater
2521 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2522 $this->assertNotSame( $updater5, $updater6 );
2525 protected function assertPreparedEditEquals(
2526 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2528 // suppress differences caused by a clock tick between generating the two PreparedEdits
2529 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2530 $edit2 = clone $edit2;
2531 $edit2->timestamp
= $edit->timestamp
;
2533 $this->assertEquals( $edit, $edit2, $message );
2536 protected function assertPreparedEditNotEquals(
2537 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2539 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2540 $edit2 = clone $edit2;
2541 $edit2->timestamp
= $edit->timestamp
;
2543 $this->assertNotEquals( $edit, $edit2, $message );