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' );
467 [ 'logging' ] +
$actorQuery['tables'], /* table */
472 'log_user' => $actorQuery['fields']['log_user'],
473 'log_user_text' => $actorQuery['fields']['log_user_text'],
477 [ 'log_id' => $logId ],
481 'testing user 0 deletion',
484 (string)$page->getTitle()->getNamespace(),
485 $page->getTitle()->getDBkey(),
493 * @covers WikiPage::doDeleteArticleReal
495 public function testDoDeleteArticleReal_userSysop() {
496 $page = $this->createPage(
498 "[[original text]] foo",
499 CONTENT_MODEL_WIKITEXT
501 $id = $page->getId();
503 $user = $this->getTestSysop()->getUser();
505 $status = $page->doDeleteArticleReal(
506 /* reason */ "testing sysop deletion",
507 /* suppress */ false,
510 /* errorStack */ $errorStack,
513 $logId = $status->getValue();
514 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
516 [ 'logging' ] +
$actorQuery['tables'], /* table */
521 'log_user' => $actorQuery['fields']['log_user'],
522 'log_user_text' => $actorQuery['fields']['log_user_text'],
526 [ 'log_id' => $logId ],
530 'testing sysop deletion',
531 (string)$user->getId(),
533 (string)$page->getTitle()->getNamespace(),
534 $page->getTitle()->getDBkey(),
542 * TODO: Test more stuff about suppression.
544 * @covers WikiPage::doDeleteArticleReal
546 public function testDoDeleteArticleReal_suppress() {
547 $page = $this->createPage(
549 "[[original text]] foo",
550 CONTENT_MODEL_WIKITEXT
552 $id = $page->getId();
554 $user = $this->getTestSysop()->getUser();
556 $status = $page->doDeleteArticleReal(
557 /* reason */ "testing deletion",
561 /* errorStack */ $errorStack,
564 $logId = $status->getValue();
565 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
567 [ 'logging' ] +
$actorQuery['tables'], /* table */
572 'log_user' => $actorQuery['fields']['log_user'],
573 'log_user_text' => $actorQuery['fields']['log_user_text'],
577 [ 'log_id' => $logId ],
582 (string)$user->getId(),
584 (string)$page->getTitle()->getNamespace(),
585 $page->getTitle()->getDBkey(),
592 $page->getContent( Revision
::FOR_PUBLIC
),
593 "WikiPage::getContent should return null after the page was suppressed for general users"
597 $page->getContent( Revision
::FOR_THIS_USER
, null ),
598 "WikiPage::getContent should return null after the page was suppressed for user zero"
602 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
603 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
608 * @covers WikiPage::doDeleteUpdates
610 public function testDoDeleteUpdates() {
611 $user = $this->getTestUser()->getUser();
612 $page = $this->createPage(
614 "[[original text]] foo",
615 CONTENT_MODEL_WIKITEXT
617 $id = $page->getId();
618 $page->loadPageData(); // make sure the current revision is cached.
620 // Similar to MovePage logic
621 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
622 $page->doDeleteUpdates( $page->getId(), $page->getContent(), $page->getRevision(), $user );
625 JobQueueGroup
::destroySingletons();
627 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
630 # ------------------------
631 $dbr = wfGetDB( DB_REPLICA
);
632 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
633 $n = $res->numRows();
636 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
640 * @param string $name
642 * @return ContentHandler
644 protected function defineMockContentModelForUpdateTesting( $name ) {
645 /** @var ContentHandler|MockObject $handler */
646 $handler = $this->getMockBuilder( TextContentHandler
::class )
647 ->setConstructorArgs( [ $name ] )
649 [ 'getSecondaryDataUpdates', 'getDeletionUpdates', 'unserializeContent' ]
653 $dataUpdate = new MWCallableUpdate( 'time' );
654 $dataUpdate->_name
= "$name data update";
656 $deletionUpdate = new MWCallableUpdate( 'time' );
657 $deletionUpdate->_name
= "$name deletion update";
659 $handler->method( 'getSecondaryDataUpdates' )->willReturn( [ $dataUpdate ] );
660 $handler->method( 'getDeletionUpdates' )->willReturn( [ $deletionUpdate ] );
661 $handler->method( 'unserializeContent' )->willReturnCallback(
662 function ( $text ) use ( $handler ) {
663 return $this->createMockContent( $handler, $text );
667 $this->mergeMwGlobalArrayValue(
668 'wgContentHandlers', [
669 $name => function () use ( $handler ){
679 * @param ContentHandler $handler
680 * @param string $text
684 protected function createMockContent( ContentHandler
$handler, $text ) {
685 /** @var Content|MockObject $content */
686 $content = $this->getMockBuilder( TextContent
::class )
687 ->setConstructorArgs( [ $text ] )
688 ->setMethods( [ 'getModel', 'getContentHandler' ] )
691 $content->method( 'getModel' )->willReturn( $handler->getModelID() );
692 $content->method( 'getContentHandler' )->willReturn( $handler );
697 public function testGetDeletionUpdates() {
698 $m1 = $this->defineMockContentModelForUpdateTesting( 'M1' );
700 $mainContent1 = $this->createMockContent( $m1, 'main 1' );
702 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
703 $page = $this->createPage(
705 [ 'main' => $mainContent1 ]
708 $dataUpdates = $page->getDeletionUpdates( $page->getRevisionRecord() );
709 $this->assertNotEmpty( $dataUpdates );
711 $updateNames = array_map( function ( $du ) {
712 return isset( $du->_name
) ?
$du->_name
: get_class( $du );
715 $this->assertContains( LinksDeletionUpdate
::class, $updateNames );
716 $this->assertContains( 'M1 deletion update', $updateNames );
720 * @covers WikiPage::getRevision
722 public function testGetRevision() {
723 $page = $this->newPage( __METHOD__
);
725 $rev = $page->getRevision();
726 $this->assertNull( $rev );
729 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
731 $rev = $page->getRevision();
733 $this->assertEquals( $page->getLatest(), $rev->getId() );
734 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
738 * @covers WikiPage::getContent
740 public function testGetContent() {
741 $page = $this->newPage( __METHOD__
);
743 $content = $page->getContent();
744 $this->assertNull( $content );
747 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
749 $content = $page->getContent();
750 $this->assertEquals( "some text", $content->getNativeData() );
754 * @covers WikiPage::exists
756 public function testExists() {
757 $page = $this->newPage( __METHOD__
);
758 $this->assertFalse( $page->exists() );
761 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
762 $this->assertTrue( $page->exists() );
764 $page = new WikiPage( $page->getTitle() );
765 $this->assertTrue( $page->exists() );
768 $page->doDeleteArticle( "done testing" );
769 $this->assertFalse( $page->exists() );
771 $page = new WikiPage( $page->getTitle() );
772 $this->assertFalse( $page->exists() );
775 public function provideHasViewableContent() {
777 [ 'WikiPageTest_testHasViewableContent', false, true ],
778 [ 'Special:WikiPageTest_testHasViewableContent', false ],
779 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
780 [ 'Special:Userlogin', true ],
781 [ 'MediaWiki:help', true ],
786 * @dataProvider provideHasViewableContent
787 * @covers WikiPage::hasViewableContent
789 public function testHasViewableContent( $title, $viewable, $create = false ) {
790 $page = $this->newPage( $title );
791 $this->assertEquals( $viewable, $page->hasViewableContent() );
794 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
795 $this->assertTrue( $page->hasViewableContent() );
797 $page = new WikiPage( $page->getTitle() );
798 $this->assertTrue( $page->hasViewableContent() );
802 public function provideGetRedirectTarget() {
804 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
806 'WikiPageTest_testGetRedirectTarget_2',
807 CONTENT_MODEL_WIKITEXT
,
808 "#REDIRECT [[hello world]]",
811 // The below added to protect against Media namespace
812 // redirects which throw a fatal: (T203942)
814 'WikiPageTest_testGetRedirectTarget_3',
815 CONTENT_MODEL_WIKITEXT
,
816 "#REDIRECT [[Media:hello_world]]",
819 // Test fragments longer than 255 bytes (T207876)
821 'WikiPageTest_testGetRedirectTarget_4',
822 CONTENT_MODEL_WIKITEXT
,
823 // phpcs:ignore Generic.Files.LineLength
824 '#REDIRECT [[Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴]]',
825 // phpcs:ignore Generic.Files.LineLength
826 'Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴...'
832 * @dataProvider provideGetRedirectTarget
833 * @covers WikiPage::getRedirectTarget
835 public function testGetRedirectTarget( $title, $model, $text, $target ) {
836 $this->setMwGlobals( [
837 'wgCapitalLinks' => true,
840 $page = $this->createPage( $title, $text, $model );
842 # sanity check, because this test seems to fail for no reason for some people.
843 $c = $page->getContent();
844 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
846 # now, test the actual redirect
847 $t = $page->getRedirectTarget();
848 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getFullText() );
852 * @dataProvider provideGetRedirectTarget
853 * @covers WikiPage::isRedirect
855 public function testIsRedirect( $title, $model, $text, $target ) {
856 $page = $this->createPage( $title, $text, $model );
857 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
860 public function provideIsCountable() {
864 [ 'WikiPageTest_testIsCountable',
865 CONTENT_MODEL_WIKITEXT
,
870 [ 'WikiPageTest_testIsCountable',
871 CONTENT_MODEL_WIKITEXT
,
878 [ 'WikiPageTest_testIsCountable',
879 CONTENT_MODEL_WIKITEXT
,
884 [ 'WikiPageTest_testIsCountable',
885 CONTENT_MODEL_WIKITEXT
,
892 [ 'WikiPageTest_testIsCountable',
893 CONTENT_MODEL_WIKITEXT
,
898 [ 'WikiPageTest_testIsCountable',
899 CONTENT_MODEL_WIKITEXT
,
905 // not a content namespace
906 [ 'Talk:WikiPageTest_testIsCountable',
907 CONTENT_MODEL_WIKITEXT
,
912 [ 'Talk:WikiPageTest_testIsCountable',
913 CONTENT_MODEL_WIKITEXT
,
919 // not a content namespace, different model
920 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
926 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
936 * @dataProvider provideIsCountable
937 * @covers WikiPage::isCountable
939 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
940 global $wgContentHandlerUseDB;
942 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
944 $title = Title
::newFromText( $title );
946 if ( !$wgContentHandlerUseDB
948 && ContentHandler
::getDefaultModelFor( $title ) != $model
950 $this->markTestSkipped( "Can not use non-default content model $model for "
951 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
954 $page = $this->createPage( $title, $text, $model );
956 $editInfo = $page->prepareContentForEdit( $page->getContent() );
958 $v = $page->isCountable();
959 $w = $page->isCountable( $editInfo );
964 "isCountable( null ) returned unexpected value " . var_export( $v, true )
965 . " instead of " . var_export( $expected, true )
966 . " in mode `$mode` for text \"$text\""
972 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
973 . " instead of " . var_export( $expected, true )
974 . " in mode `$mode` for text \"$text\""
978 public function provideGetParserOutput() {
981 CONTENT_MODEL_WIKITEXT
,
983 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
990 * @dataProvider provideGetParserOutput
991 * @covers WikiPage::getParserOutput
993 public function testGetParserOutput( $model, $text, $expectedHtml ) {
994 $page = $this->createPage( __METHOD__
, $text, $model );
996 $opt = $page->makeParserOptions( 'canonical' );
997 $po = $page->getParserOutput( $opt );
998 $text = $po->getText();
1000 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
1001 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
1003 $this->assertEquals( $expectedHtml, $text );
1009 * @covers WikiPage::getParserOutput
1011 public function testGetParserOutput_nonexisting() {
1012 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1014 $opt = new ParserOptions();
1015 $po = $page->getParserOutput( $opt );
1017 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
1021 * @covers WikiPage::getParserOutput
1023 public function testGetParserOutput_badrev() {
1024 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
1026 $opt = new ParserOptions();
1027 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
1029 // @todo would be neat to also test deleted revision
1031 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
1034 public static $sections =
1048 public function dataReplaceSection() {
1049 // NOTE: assume the Help namespace to contain wikitext
1051 [ 'Help:WikiPageTest_testReplaceSection',
1052 CONTENT_MODEL_WIKITEXT
,
1057 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
1059 [ 'Help:WikiPageTest_testReplaceSection',
1060 CONTENT_MODEL_WIKITEXT
,
1067 [ 'Help:WikiPageTest_testReplaceSection',
1068 CONTENT_MODEL_WIKITEXT
,
1071 "== TEST ==\nmore fun",
1073 trim( preg_replace( '/^== test ==.*== foo ==/sm',
1074 "== TEST ==\nmore fun\n\n== foo ==",
1077 [ 'Help:WikiPageTest_testReplaceSection',
1078 CONTENT_MODEL_WIKITEXT
,
1083 trim( self
::$sections )
1085 [ 'Help:WikiPageTest_testReplaceSection',
1086 CONTENT_MODEL_WIKITEXT
,
1091 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
1097 * @dataProvider dataReplaceSection
1098 * @covers WikiPage::replaceSectionContent
1100 public function testReplaceSectionContent( $title, $model, $text, $section,
1101 $with, $sectionTitle, $expected
1103 $page = $this->createPage( $title, $text, $model );
1105 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1106 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
1108 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1112 * @dataProvider dataReplaceSection
1113 * @covers WikiPage::replaceSectionAtRev
1115 public function testReplaceSectionAtRev( $title, $model, $text, $section,
1116 $with, $sectionTitle, $expected
1118 $page = $this->createPage( $title, $text, $model );
1119 $baseRevId = $page->getLatest();
1121 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1122 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1124 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
1128 * @covers WikiPage::getOldestRevision
1130 public function testGetOldestRevision() {
1131 $page = $this->newPage( __METHOD__
);
1132 $page->doEditContent(
1133 new WikitextContent( 'one' ),
1137 $rev1 = $page->getRevision();
1139 $page = new WikiPage( $page->getTitle() );
1140 $page->doEditContent(
1141 new WikitextContent( 'two' ),
1146 $page = new WikiPage( $page->getTitle() );
1147 $page->doEditContent(
1148 new WikitextContent( 'three' ),
1154 $this->assertNotEquals(
1156 $page->getRevision()->getId(),
1157 '$page->getRevision()->getId()'
1161 $this->assertEquals(
1163 $page->getOldestRevision()->getId(),
1164 '$page->getOldestRevision()->getId()'
1169 * @covers WikiPage::doRollback
1170 * @covers WikiPage::commitRollback
1172 public function testDoRollback() {
1173 // FIXME: fails under postgres
1174 $this->markTestSkippedIfDbType( 'postgres' );
1176 $admin = $this->getTestSysop()->getUser();
1177 $user1 = $this->getTestUser()->getUser();
1178 // Use the confirmed group for user2 to make sure the user is different
1179 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1181 // make sure we can test autopatrolling
1182 $this->setMwGlobals( 'wgUseRCPatrol', true );
1184 // TODO: MCR: test rollback of multiple slots!
1185 $page = $this->newPage( __METHOD__
);
1189 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1190 "section one", EDIT_NEW
, false, $admin );
1193 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1194 "adding section two", 0, false, $user1 );
1196 $text .= "\n\nthree";
1197 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1198 "adding section three", 0, false, $user2 );
1200 /** @var Revision $rev1 */
1201 /** @var Revision $rev2 */
1202 /** @var Revision $rev3 */
1203 $rev1 = $status1->getValue()['revision'];
1204 $rev2 = $status2->getValue()['revision'];
1205 $rev3 = $status3->getValue()['revision'];
1208 * We are having issues with doRollback spuriously failing. Apparently
1209 * the last revision somehow goes missing or not committed under some
1210 * circumstances. So, make sure the revisions have the correct usernames.
1212 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1213 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1214 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1215 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1217 // Now, try the actual rollback
1218 $token = $admin->getEditToken( 'rollback' );
1219 $rollbackErrors = $page->doRollback(
1228 if ( $rollbackErrors ) {
1230 "Rollback failed:\n" .
1231 print_r( $rollbackErrors, true ) . ";\n" .
1232 print_r( $resultDetails, true )
1236 $page = new WikiPage( $page->getTitle() );
1237 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1238 "rollback did not revert to the correct revision" );
1239 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1241 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1242 $page->getRevision()->getRevisionRecord()
1245 $this->assertNotNull( $rc, 'RecentChanges entry' );
1246 $this->assertEquals(
1247 RecentChange
::PRC_AUTOPATROLLED
,
1248 $rc->getAttribute( 'rc_patrolled' ),
1252 // TODO: MCR: assert origin once we write slot data
1253 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( SlotRecord::MAIN );
1254 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1255 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1259 * @covers WikiPage::doRollback
1260 * @covers WikiPage::commitRollback
1262 public function testDoRollbackFailureSameContent() {
1263 $admin = $this->getTestSysop()->getUser();
1266 $page = $this->newPage( __METHOD__
);
1267 $page->doEditContent(
1268 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1274 $rev1 = $page->getRevision();
1276 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1278 $page = new WikiPage( $page->getTitle() );
1279 $page->doEditContent(
1280 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1281 "adding section two",
1287 # now, do a the rollback from the same user was doing the edit before
1288 $resultDetails = [];
1289 $token = $user1->getEditToken( 'rollback' );
1290 $errors = $page->doRollback(
1292 "testing revert same user",
1299 $this->assertEquals( [], $errors, "Rollback failed same user" );
1301 # now, try the rollback
1302 $resultDetails = [];
1303 $token = $admin->getEditToken( 'rollback' );
1304 $errors = $page->doRollback(
1313 $this->assertEquals(
1323 "Rollback not failed"
1326 $page = new WikiPage( $page->getTitle() );
1327 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1328 "rollback did not revert to the correct revision" );
1329 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1333 * Tests tagging for edits that do rollback action
1334 * @covers WikiPage::doRollback
1336 public function testDoRollbackTagging() {
1337 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1338 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1341 $admin = new User();
1342 $admin->setName( 'Administrator' );
1343 $admin->addToDatabase();
1345 $text = 'First line';
1346 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1347 $page->doEditContent(
1348 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1355 $secondUser = new User();
1356 $secondUser->setName( '92.65.217.32' );
1357 $text .= '\n\nSecond line';
1358 $page = new WikiPage( $page->getTitle() );
1359 $page->doEditContent(
1360 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1361 'Adding second line',
1367 // Now, try the rollback
1368 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1369 $token = $admin->getEditToken( 'rollback' );
1370 $errors = $page->doRollback(
1371 $secondUser->getName(),
1379 // If doRollback completed without errors
1380 if ( $errors === [] ) {
1381 $tags = $resultDetails[ 'tags' ];
1382 $this->assertContains( 'mw-rollback', $tags );
1386 public function provideGetAutoDeleteReason() {
1396 [ "first edit", null ],
1398 "/first edit.*only contributor/",
1404 [ "first edit", null ],
1405 [ "second edit", null ],
1407 "/second edit.*only contributor/",
1413 [ "first edit", "127.0.2.22" ],
1414 [ "second edit", "127.0.3.33" ],
1424 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1425 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1426 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1427 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1428 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1432 '/first edit:.*\.\.\."/',
1438 [ "first edit", "127.0.2.22" ],
1439 [ "", "127.0.3.33" ],
1441 "/before blanking.*first edit/",
1449 * @dataProvider provideGetAutoDeleteReason
1450 * @covers WikiPage::getAutoDeleteReason
1452 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1455 // NOTE: assume Help namespace to contain wikitext
1456 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1460 foreach ( $edits as $edit ) {
1463 if ( !empty( $edit[1] ) ) {
1464 $user->setName( $edit[1] );
1469 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1471 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1476 $reason = $page->getAutoDeleteReason( $hasHistory );
1478 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1479 $this->assertEquals( $expectedResult, $reason );
1481 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1482 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1485 $this->assertEquals( $expectedHistory, $hasHistory,
1486 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1488 $page->doDeleteArticle( "done" );
1491 public function providePreSaveTransform() {
1493 [ 'hello this is ~~~',
1494 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1496 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1497 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1503 * @covers WikiPage::factory
1505 public function testWikiPageFactory() {
1506 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1507 $page = WikiPage
::factory( $title );
1508 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1510 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1511 $page = WikiPage
::factory( $title );
1512 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1514 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1515 $page = WikiPage
::factory( $title );
1516 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1520 * @covers WikiPage::loadPageData
1521 * @covers WikiPage::wasLoadedFrom
1523 public function testLoadPageData() {
1524 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1525 $page = WikiPage
::factory( $title );
1527 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1528 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1529 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1530 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1532 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1533 $this->assertTrue( $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_LATEST
);
1539 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1540 $this->assertTrue( $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_LOCKING
);
1545 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1546 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1547 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1548 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1550 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
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->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1558 * @dataProvider provideCommentMigrationOnDeletion
1560 * @param int $writeStage
1561 * @param int $readStage
1563 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1564 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1565 $this->overrideMwServices();
1567 $dbr = wfGetDB( DB_REPLICA
);
1569 $page = $this->createPage(
1572 CONTENT_MODEL_WIKITEXT
1574 $revid = $page->getLatest();
1575 if ( $writeStage > MIGRATION_OLD
) {
1576 $comment_id = $dbr->selectField(
1577 'revision_comment_temp',
1578 'revcomment_comment_id',
1579 [ 'revcomment_rev' => $revid ],
1584 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1585 $this->overrideMwServices();
1587 $page->doDeleteArticle( "testing deletion" );
1589 if ( $readStage > MIGRATION_OLD
) {
1590 // Didn't leave behind any 'revision_comment_temp' rows
1591 $n = $dbr->selectField(
1592 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1594 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1596 // Copied or upgraded the comment_id, as applicable
1597 $ar_comment_id = $dbr->selectField(
1600 [ 'ar_rev_id' => $revid ],
1603 if ( $writeStage > MIGRATION_OLD
) {
1604 $this->assertSame( $comment_id, $ar_comment_id );
1606 $this->assertNotEquals( 0, $ar_comment_id );
1610 // Copied rev_comment, if applicable
1611 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1612 $ar_comment = $dbr->selectField(
1615 [ 'ar_rev_id' => $revid ],
1618 $this->assertSame( 'testing', $ar_comment );
1622 public function provideCommentMigrationOnDeletion() {
1624 [ MIGRATION_OLD
, MIGRATION_OLD
],
1625 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1626 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1627 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1628 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1629 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1630 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1631 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1632 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1633 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1634 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1635 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1636 [ MIGRATION_NEW
, MIGRATION_NEW
],
1641 * @covers WikiPage::updateCategoryCounts
1643 public function testUpdateCategoryCounts() {
1644 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1646 // Add an initial category
1647 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1649 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1650 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1651 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1653 // Add a new category
1654 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1656 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1657 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1658 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1660 // Add and remove a category
1661 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1663 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1664 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1665 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1668 public function provideUpdateRedirectOn() {
1669 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1670 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1671 yield
[ 'SomeText', false, null, false, true, 0 ];
1672 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1676 * @dataProvider provideUpdateRedirectOn
1677 * @covers WikiPage::updateRedirectOn
1679 * @param string $initialText
1680 * @param bool $initialRedirectState
1681 * @param string|null $redirectTitle
1682 * @param bool|null $lastRevIsRedirect
1683 * @param bool $expectedSuccess
1684 * @param int $expectedRowCount
1686 public function testUpdateRedirectOn(
1688 $initialRedirectState,
1694 // FIXME: fails under sqlite and postgres
1695 $this->markTestSkippedIfDbType( 'sqlite' );
1696 $this->markTestSkippedIfDbType( 'postgres' );
1697 static $pageCounter = 0;
1700 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1701 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1703 $redirectTitle = is_string( $redirectTitle )
1704 ? Title
::newFromText( $redirectTitle )
1707 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1708 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1710 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1711 * Most of core checks the page table for redirect status, so we have to be ugly and
1712 * assert a select from the table here.
1714 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1717 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1718 $this->assertSelect(
1721 [ 'rd_from' => $pageId ],
1722 [ [ strval( $expected ) ] ]
1727 * @covers WikiPage::insertRedirectEntry
1729 public function testInsertRedirectEntry_insertsRedirectEntry() {
1730 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1731 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1733 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1734 $targetTitle->mInterwiki
= 'eninter';
1735 $page->insertRedirectEntry( $targetTitle, null );
1737 $this->assertSelect(
1739 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1740 [ 'rd_from' => $page->getId() ],
1742 strval( $page->getId() ),
1743 strval( $targetTitle->getNamespace() ),
1744 strval( $targetTitle->getDBkey() ),
1745 strval( $targetTitle->getFragment() ),
1746 strval( $targetTitle->getInterwiki() ),
1752 * @covers WikiPage::insertRedirectEntry
1754 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1755 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1756 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1758 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1759 $targetTitle->mInterwiki
= 'eninter';
1760 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1762 $this->assertSelect(
1764 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1765 [ 'rd_from' => $page->getId() ],
1767 strval( $page->getId() ),
1768 strval( $targetTitle->getNamespace() ),
1769 strval( $targetTitle->getDBkey() ),
1770 strval( $targetTitle->getFragment() ),
1771 strval( $targetTitle->getInterwiki() ),
1777 * @covers WikiPage::insertRedirectEntry
1779 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1780 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1781 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1783 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1784 $targetTitle->mInterwiki
= 'eninter';
1785 $page->insertRedirectEntry( $targetTitle, 215251 );
1787 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1790 private function getRow( array $overrides = [] ) {
1794 'page_is_redirect' => '1',
1795 'page_latest' => '99',
1796 'page_namespace' => '3',
1797 'page_title' => 'JaJaTitle',
1798 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1799 'page_touched' => '20120101020202',
1800 'page_links_updated' => '20140101020202',
1802 foreach ( $overrides as $key => $value ) {
1803 $row[$key] = $value;
1805 return (object)$row;
1808 public function provideNewFromRowSuccess() {
1809 yield
'basic row' => [
1811 function ( WikiPage
$wikiPage, self
$test ) {
1812 $test->assertSame( 44, $wikiPage->getId() );
1813 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1814 $test->assertTrue( $wikiPage->isRedirect() );
1815 $test->assertSame( 99, $wikiPage->getLatest() );
1816 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1817 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1820 'edit' => [ 'autoconfirmed', 'sysop' ],
1821 'move' => [ 'sysop' ],
1823 $wikiPage->getTitle()->getAllRestrictions()
1825 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1826 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1829 yield
'different timestamp formats' => [
1831 'page_touched' => '2012-01-01 02:02:02',
1832 'page_links_updated' => '2014-01-01 02:02:02',
1834 function ( WikiPage
$wikiPage, self
$test ) {
1835 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1836 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1839 yield
'no restrictions' => [
1841 'page_restrictions' => '',
1843 function ( WikiPage
$wikiPage, self
$test ) {
1849 $wikiPage->getTitle()->getAllRestrictions()
1853 yield
'not redirect' => [
1855 'page_is_redirect' => '0',
1857 function ( WikiPage
$wikiPage, self
$test ) {
1858 $test->assertFalse( $wikiPage->isRedirect() );
1864 * @covers WikiPage::newFromRow
1865 * @covers WikiPage::loadFromRow
1866 * @dataProvider provideNewFromRowSuccess
1868 * @param object $row
1869 * @param callable $assertions
1871 public function testNewFromRow( $row, $assertions ) {
1872 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1873 $assertions( $page, $this );
1876 public function provideTestNewFromId_returnsNullOnBadPageId() {
1882 * @covers WikiPage::newFromID
1883 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1885 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1886 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1890 * @covers WikiPage::newFromID
1892 public function testNewFromId_appearsToFetchCorrectRow() {
1893 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1894 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1895 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1896 $this->assertEquals(
1897 $createdPage->getContent()->getNativeData(),
1898 $fetchedPage->getContent()->getNativeData()
1903 * @covers WikiPage::newFromID
1905 public function testNewFromId_returnsNullOnNonExistingId() {
1906 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1909 public function provideTestInsertProtectNullRevision() {
1910 // phpcs:disable Generic.Files.LineLength
1913 [ 'edit' => 'sysop' ],
1914 [ 'edit' => '20200101040404' ],
1918 '(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)))'
1922 [ 'edit' => 'sysop', 'move' => 'something' ],
1923 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1927 '(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)))'
1933 * @dataProvider provideTestInsertProtectNullRevision
1934 * @covers WikiPage::insertProtectNullRevision
1935 * @covers WikiPage::protectDescription
1937 * @param string $revCommentMsg
1938 * @param array $limit
1939 * @param array $expiry
1940 * @param bool $cascade
1941 * @param string $reason
1942 * @param bool|null $user true if the test sysop should be used, or null
1943 * @param string $expectedComment
1945 public function testInsertProtectNullRevision(
1954 $this->setContentLang( 'qqx' );
1956 $page = $this->createPage( __METHOD__
, 'Goat' );
1958 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1960 $result = $page->insertProtectNullRevision(
1969 $this->assertTrue( $result instanceof Revision
);
1970 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1974 * @covers WikiPage::updateRevisionOn
1976 public function testUpdateRevisionOn_existingPage() {
1977 $user = $this->getTestSysop()->getUser();
1978 $page = $this->createPage( __METHOD__
, 'StartText' );
1980 $revision = new Revision(
1983 'page' => $page->getId(),
1984 'title' => $page->getTitle(),
1985 'comment' => __METHOD__
,
1986 'minor_edit' => true,
1987 'text' => __METHOD__
. '-text',
1988 'len' => strlen( __METHOD__
. '-text' ),
1989 'user' => $user->getId(),
1990 'user_text' => $user->getName(),
1991 'timestamp' => '20170707040404',
1992 'content_model' => CONTENT_MODEL_WIKITEXT
,
1993 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1997 $result = $page->updateRevisionOn( $this->db
, $revision );
1998 $this->assertTrue( $result );
1999 $this->assertSame( 9989, $page->getLatest() );
2000 $this->assertEquals( $revision, $page->getRevision() );
2004 * @covers WikiPage::updateRevisionOn
2006 public function testUpdateRevisionOn_NonExistingPage() {
2007 $user = $this->getTestSysop()->getUser();
2008 $page = $this->createPage( __METHOD__
, 'StartText' );
2009 $page->doDeleteArticle( 'reason' );
2011 $revision = new Revision(
2014 'page' => $page->getId(),
2015 'title' => $page->getTitle(),
2016 'comment' => __METHOD__
,
2017 'minor_edit' => true,
2018 'text' => __METHOD__
. '-text',
2019 'len' => strlen( __METHOD__
. '-text' ),
2020 'user' => $user->getId(),
2021 'user_text' => $user->getName(),
2022 'timestamp' => '20170707040404',
2023 'content_model' => CONTENT_MODEL_WIKITEXT
,
2024 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2028 $result = $page->updateRevisionOn( $this->db
, $revision );
2029 $this->assertFalse( $result );
2033 * @covers WikiPage::updateIfNewerOn
2035 public function testUpdateIfNewerOn_olderRevision() {
2036 $user = $this->getTestSysop()->getUser();
2037 $page = $this->createPage( __METHOD__
, 'StartText' );
2038 $initialRevision = $page->getRevision();
2040 $olderTimeStamp = wfTimestamp(
2042 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
2045 $olderRevison = new Revision(
2048 'page' => $page->getId(),
2049 'title' => $page->getTitle(),
2050 'comment' => __METHOD__
,
2051 'minor_edit' => true,
2052 'text' => __METHOD__
. '-text',
2053 'len' => strlen( __METHOD__
. '-text' ),
2054 'user' => $user->getId(),
2055 'user_text' => $user->getName(),
2056 'timestamp' => $olderTimeStamp,
2057 'content_model' => CONTENT_MODEL_WIKITEXT
,
2058 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2062 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
2063 $this->assertFalse( $result );
2067 * @covers WikiPage::updateIfNewerOn
2069 public function testUpdateIfNewerOn_newerRevision() {
2070 $user = $this->getTestSysop()->getUser();
2071 $page = $this->createPage( __METHOD__
, 'StartText' );
2072 $initialRevision = $page->getRevision();
2074 $newerTimeStamp = wfTimestamp(
2076 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
2079 $newerRevision = new Revision(
2082 'page' => $page->getId(),
2083 'title' => $page->getTitle(),
2084 'comment' => __METHOD__
,
2085 'minor_edit' => true,
2086 'text' => __METHOD__
. '-text',
2087 'len' => strlen( __METHOD__
. '-text' ),
2088 'user' => $user->getId(),
2089 'user_text' => $user->getName(),
2090 'timestamp' => $newerTimeStamp,
2091 'content_model' => CONTENT_MODEL_WIKITEXT
,
2092 'content_format' => CONTENT_FORMAT_WIKITEXT
,
2095 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
2096 $this->assertTrue( $result );
2100 * @covers WikiPage::insertOn
2102 public function testInsertOn() {
2103 $title = Title
::newFromText( __METHOD__
);
2104 $page = new WikiPage( $title );
2106 $startTimeStamp = wfTimestampNow();
2107 $result = $page->insertOn( $this->db
);
2108 $endTimeStamp = wfTimestampNow();
2110 $this->assertInternalType( 'int', $result );
2111 $this->assertTrue( $result > 0 );
2113 $condition = [ 'page_id' => $result ];
2115 // Check the default fields have been filled
2116 $this->assertSelect(
2121 'page_restrictions',
2139 // Check the page_random field has been filled
2140 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
2141 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2143 // Assert the touched timestamp in the DB is roughly when we inserted the page
2144 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
2146 wfTimestamp( TS_UNIX
, $startTimeStamp )
2147 <= wfTimestamp( TS_UNIX
, $pageTouched )
2150 wfTimestamp( TS_UNIX
, $endTimeStamp )
2151 >= wfTimestamp( TS_UNIX
, $pageTouched )
2154 // Try inserting the same page again and checking the result is false (no change)
2155 $result = $page->insertOn( $this->db
);
2156 $this->assertFalse( $result );
2160 * @covers WikiPage::insertOn
2162 public function testInsertOn_idSpecified() {
2163 $title = Title
::newFromText( __METHOD__
);
2164 $page = new WikiPage( $title );
2167 $result = $page->insertOn( $this->db
, $id );
2169 $this->assertSame( $id, $result );
2171 $condition = [ 'page_id' => $result ];
2173 // Check there is actually a row in the db
2174 $this->assertSelect(
2182 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2183 // Note: Once the current dates passes the date in these tests they will fail.
2184 yield
'move something' => [
2186 [ 'move' => 'something' ],
2188 [ 'edit' => [], 'move' => [ 'something' ] ],
2191 yield
'move something, edit blank' => [
2193 [ 'move' => 'something', 'edit' => '' ],
2195 [ 'edit' => [], 'move' => [ 'something' ] ],
2198 yield
'edit sysop, with expiry' => [
2200 [ 'edit' => 'sysop' ],
2201 [ 'edit' => '21330101020202' ],
2202 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2203 [ 'edit' => '21330101020202' ],
2205 yield
'move and edit, move with expiry' => [
2207 [ 'move' => 'something', 'edit' => 'another' ],
2208 [ 'move' => '22220202010101' ],
2209 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2210 [ 'move' => '22220202010101' ],
2212 yield
'move and edit, edit with infinity expiry' => [
2214 [ 'move' => 'something', 'edit' => 'another' ],
2215 [ 'edit' => 'infinity' ],
2216 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2217 [ 'edit' => 'infinity' ],
2219 yield
'non existing, create something' => [
2221 [ 'create' => 'something' ],
2223 [ 'create' => [ 'something' ] ],
2226 yield
'non existing, create something with expiry' => [
2228 [ 'create' => 'something' ],
2229 [ 'create' => '23451212112233' ],
2230 [ 'create' => [ 'something' ] ],
2231 [ 'create' => '23451212112233' ],
2236 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2237 * @covers WikiPage::doUpdateRestrictions
2239 public function testDoUpdateRestrictions_setBasicRestrictions(
2243 array $expectedRestrictions,
2244 array $expectedRestrictionExpiries
2246 if ( $pageExists ) {
2247 $page = $this->createPage( __METHOD__
, 'ABC' );
2249 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2251 $user = $this->getTestSysop()->getUser();
2254 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2256 $logId = $status->getValue();
2257 $allRestrictions = $page->getTitle()->getAllRestrictions();
2259 $this->assertTrue( $status->isGood() );
2260 $this->assertInternalType( 'int', $logId );
2261 $this->assertSame( $expectedRestrictions, $allRestrictions );
2262 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2263 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2266 // Make sure the log entry looks good
2267 // log_params is not checked here
2268 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2269 $this->assertSelect(
2270 [ 'logging' ] +
$actorQuery['tables'],
2273 'log_user' => $actorQuery['fields']['log_user'],
2274 'log_user_text' => $actorQuery['fields']['log_user_text'],
2278 [ 'log_id' => $logId ],
2281 (string)$user->getId(),
2283 (string)$page->getTitle()->getNamespace(),
2284 $page->getTitle()->getDBkey(),
2287 $actorQuery['joins']
2292 * @covers WikiPage::doUpdateRestrictions
2294 public function testDoUpdateRestrictions_failsOnReadOnly() {
2295 $page = $this->createPage( __METHOD__
, 'ABC' );
2296 $user = $this->getTestSysop()->getUser();
2300 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2301 ->disableOriginalConstructor()
2302 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2304 $readOnly->expects( $this->once() )
2305 ->method( 'isReadOnly' )
2306 ->will( $this->returnValue( true ) );
2307 $readOnly->expects( $this->once() )
2308 ->method( 'getReason' )
2309 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2310 $this->setService( 'ReadOnlyMode', $readOnly );
2312 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2313 $this->assertFalse( $status->isOK() );
2314 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2318 * @covers WikiPage::doUpdateRestrictions
2320 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2321 $page = $this->createPage( __METHOD__
, 'ABC' );
2322 $user = $this->getTestSysop()->getUser();
2324 $limit = [ 'edit' => 'sysop' ];
2326 $status = $page->doUpdateRestrictions(
2335 // The first entry should have a logId as it did something
2336 $this->assertTrue( $status->isGood() );
2337 $this->assertInternalType( 'int', $status->getValue() );
2339 $status = $page->doUpdateRestrictions(
2348 // The second entry should not have a logId as nothing changed
2349 $this->assertTrue( $status->isGood() );
2350 $this->assertNull( $status->getValue() );
2354 * @covers WikiPage::doUpdateRestrictions
2356 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2357 $page = $this->createPage( __METHOD__
, 'ABC' );
2358 $user = $this->getTestSysop()->getUser();
2362 $status = $page->doUpdateRestrictions(
2363 [ 'edit' => 'sysop' ],
2370 $this->assertTrue( $status->isGood() );
2371 $this->assertInternalType( 'int', $status->getValue() );
2372 $this->assertSelect(
2374 [ 'log_type', 'log_action' ],
2375 [ 'log_id' => $status->getValue() ],
2376 [ [ 'protect', 'protect' ] ]
2379 // Modify the protection
2380 $status = $page->doUpdateRestrictions(
2381 [ 'edit' => 'somethingElse' ],
2388 $this->assertTrue( $status->isGood() );
2389 $this->assertInternalType( 'int', $status->getValue() );
2390 $this->assertSelect(
2392 [ 'log_type', 'log_action' ],
2393 [ 'log_id' => $status->getValue() ],
2394 [ [ 'protect', 'modify' ] ]
2397 // Remove the protection
2398 $status = $page->doUpdateRestrictions(
2406 $this->assertTrue( $status->isGood() );
2407 $this->assertInternalType( 'int', $status->getValue() );
2408 $this->assertSelect(
2410 [ 'log_type', 'log_action' ],
2411 [ 'log_id' => $status->getValue() ],
2412 [ [ 'protect', 'unprotect' ] ]
2417 * @covers WikiPage::newPageUpdater
2418 * @covers WikiPage::getDerivedDataUpdater
2420 public function testNewPageUpdater() {
2421 $user = $this->getTestUser()->getUser();
2422 $page = $this->newPage( __METHOD__
, __METHOD__
);
2424 /** @var Content $content */
2425 $content = $this->getMockBuilder( WikitextContent
::class )
2426 ->setConstructorArgs( [ 'Hello World' ] )
2427 ->setMethods( [ 'getParserOutput' ] )
2429 $content->expects( $this->once() )
2430 ->method( 'getParserOutput' )
2431 ->willReturn( new ParserOutput( 'HTML' ) );
2433 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2435 // provide context, so the cache can be kept in place
2436 $slotsUpdate = new revisionSlotsUpdate();
2437 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, $content );
2439 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2440 $updater->setContent( SlotRecord
::MAIN
, $content );
2441 $revision = $updater->saveRevision(
2442 CommentStoreComment
::newUnsavedComment( 'test' ),
2446 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2448 $this->assertSame( $revision->getId(), $page->getLatest() );
2450 // Parsed output must remain cached throughout.
2451 $this->assertSame( $preparedEditBefore->output
, $preparedEditAfter->output
);
2455 * @covers WikiPage::newPageUpdater
2456 * @covers WikiPage::getDerivedDataUpdater
2458 public function testGetDerivedDataUpdater() {
2459 $admin = $this->getTestSysop()->getUser();
2461 /** @var object $page */
2462 $page = $this->createPage( __METHOD__
, __METHOD__
);
2463 $page = TestingAccessWrapper
::newFromObject( $page );
2465 $revision = $page->getRevision()->getRevisionRecord();
2466 $user = $revision->getUser();
2468 $slotsUpdate = new RevisionSlotsUpdate();
2469 $slotsUpdate->modifyContent( SlotRecord
::MAIN
, new WikitextContent( 'Hello World' ) );
2471 // get a virgin updater
2472 $updater1 = $page->getDerivedDataUpdater( $user );
2473 $this->assertFalse( $updater1->isUpdatePrepared() );
2475 $updater1->prepareUpdate( $revision );
2477 // Re-use updater with same revision or content, even if base changed
2478 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2480 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2481 [ SlotRecord
::MAIN
=> $revision->getContent( SlotRecord
::MAIN
) ]
2483 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2485 // Don't re-use for edit if base revision ID changed
2486 $this->assertNotSame(
2488 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2491 // Don't re-use with different user
2492 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2493 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2495 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2496 $updater2b->prepareContent( $user, $slotsUpdate, false );
2497 $this->assertNotSame( $updater2a, $updater2b );
2499 // Don't re-use with different content
2500 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2501 $updater3->prepareUpdate( $revision );
2502 $this->assertNotSame( $updater2b, $updater3 );
2504 // Don't re-use if no context given
2505 $updater4 = $page->getDerivedDataUpdater( $admin );
2506 $updater4->prepareUpdate( $revision );
2507 $this->assertNotSame( $updater3, $updater4 );
2509 // Don't re-use if AGAIN no context given
2510 $updater5 = $page->getDerivedDataUpdater( $admin );
2511 $this->assertNotSame( $updater4, $updater5 );
2513 // Don't re-use cached "virgin" unprepared updater
2514 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2515 $this->assertNotSame( $updater5, $updater6 );
2518 protected function assertPreparedEditEquals(
2519 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2521 // suppress differences caused by a clock tick between generating the two PreparedEdits
2522 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2523 $edit2 = clone $edit2;
2524 $edit2->timestamp
= $edit->timestamp
;
2526 $this->assertEquals( $edit, $edit2, $message );
2529 protected function assertPreparedEditNotEquals(
2530 PreparedEdit
$edit, PreparedEdit
$edit2, $message = ''
2532 if ( abs( $edit->timestamp
- $edit2->timestamp
) < 3 ) {
2533 $edit2 = clone $edit2;
2534 $edit2->timestamp
= $edit->timestamp
;
2536 $this->assertNotEquals( $edit, $edit2, $message );