3 use MediaWiki\MediaWikiServices
;
4 use MediaWiki\Storage\RevisionSlotsUpdate
;
5 use Wikimedia\TestingAccessWrapper
;
10 abstract class WikiPageDbTestBase
extends MediaWikiLangTestCase
{
12 private $pagesToDelete;
14 public function __construct( $name = null, array $data = [], $dataName = '' ) {
15 parent
::__construct( $name, $data, $dataName );
17 $this->tablesUsed
= array_merge(
40 protected function addCoreDBData() {
41 // Blank out. This would fail with a modified schema, and we don't need it.
47 abstract protected function getMcrMigrationStage();
52 abstract protected function getMcrTablesToReset();
54 protected function setUp() {
57 $this->tablesUsed +
= $this->getMcrTablesToReset();
59 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
61 'wgMultiContentRevisionSchemaMigrationStage',
62 $this->getMcrMigrationStage()
64 $this->pagesToDelete
= [];
66 $this->overrideMwServices();
69 protected function tearDown() {
70 foreach ( $this->pagesToDelete
as $p ) {
71 /* @var $p WikiPage */
75 $p->doDeleteArticle( "testing done." );
77 } catch ( MWException
$ex ) {
84 abstract protected function getContentHandlerUseDB();
87 * @param Title|string $title
88 * @param string|null $model
91 private function newPage( $title, $model = null ) {
92 if ( is_string( $title ) ) {
93 $ns = $this->getDefaultWikitextNS();
94 $title = Title
::newFromText( $title, $ns );
97 $p = new WikiPage( $title );
99 $this->pagesToDelete
[] = $p;
105 * @param string|Title|WikiPage $page
106 * @param string $text
111 protected function createPage( $page, $text, $model = null, $user = null ) {
112 if ( is_string( $page ) ||
$page instanceof Title
) {
113 $page = $this->newPage( $page, $model );
116 $content = ContentHandler
::makeContent( $text, $page->getTitle(), $model );
117 $page->doEditContent( $content, "testing", EDIT_NEW
, false, $user );
123 * @covers WikiPage::prepareContentForEdit
125 public function testPrepareContentForEdit() {
126 $user = $this->getTestUser()->getUser();
127 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
129 $page = $this->createPage( __METHOD__
, __METHOD__
, null, $user );
130 $title = $page->getTitle();
132 $content = ContentHandler
::makeContent(
133 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
134 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
136 CONTENT_MODEL_WIKITEXT
138 $content2 = ContentHandler
::makeContent(
139 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
140 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
142 CONTENT_MODEL_WIKITEXT
145 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
147 $this->assertInstanceOf(
148 ParserOptions
::class,
152 $this->assertContains( '</a>', $edit->output
->getText(), "output" );
153 $this->assertContains(
154 'consetetur sadipscing elitr',
155 $edit->output
->getText(),
159 $this->assertTrue( $content->equals( $edit->newContent
), "newContent field" );
160 $this->assertTrue( $content->equals( $edit->pstContent
), "pstContent field" );
161 $this->assertSame( $edit->output
, $edit->output
, "output field" );
162 $this->assertSame( $edit->popts
, $edit->popts
, "popts field" );
163 $this->assertSame( null, $edit->revid
, "revid field" );
165 // Re-using the prepared info if possible
166 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
167 $this->assertEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
168 $this->assertSame( $edit->pstContent
, $sameEdit->pstContent
, 're-use output' );
169 $this->assertSame( $edit->output
, $sameEdit->output
, 're-use output' );
171 // Not re-using the same PreparedEdit if not possible
172 $rev = $page->getRevision();
173 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
174 $this->assertNotEquals( $edit, $edit2 );
175 $this->assertContains( 'At vero eos', $edit2->pstContent
->serialize(), "content" );
177 // Check pre-safe transform
178 $this->assertContains( '[[gubergren]]', $edit2->pstContent
->serialize() );
179 $this->assertNotContains( '~~~~', $edit2->pstContent
->serialize() );
181 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
182 $this->assertNotEquals( $edit2, $edit3 );
184 // TODO: test with passing revision, then same without revision.
188 * @covers WikiPage::doEditUpdates
190 public function testDoEditUpdates() {
191 $user = $this->getTestUser()->getUser();
193 // NOTE: if site stats get out of whack and drop below 0,
194 // that causes a DB error during tear-down. So bump the
195 // numbers high enough to not drop below 0.
196 $siteStatsUpdate = SiteStatsUpdate
::factory(
197 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
199 $siteStatsUpdate->doUpdate();
201 $page = $this->createPage( __METHOD__
, __METHOD__
);
203 $revision = new Revision(
206 'page' => $page->getId(),
207 'title' => $page->getTitle(),
208 'comment' => __METHOD__
,
209 'minor_edit' => true,
210 'text' => __METHOD__
. ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
211 'user' => $user->getId(),
212 'user_text' => $user->getName(),
213 'timestamp' => '20170707040404',
214 'content_model' => CONTENT_MODEL_WIKITEXT
,
215 'content_format' => CONTENT_FORMAT_WIKITEXT
,
219 $page->doEditUpdates( $revision, $user );
221 // TODO: test various options; needs temporary hooks
223 $dbr = wfGetDB( DB_REPLICA
);
224 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
225 $n = $res->numRows();
228 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
232 * @covers WikiPage::doEditContent
233 * @covers WikiPage::prepareContentForEdit
235 public function testDoEditContent() {
236 $this->setMwGlobals( 'wgPageCreationLog', true );
238 $page = $this->newPage( __METHOD__
);
239 $title = $page->getTitle();
241 $user1 = $this->getTestUser()->getUser();
242 // Use the confirmed group for user2 to make sure the user is different
243 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
245 $content = ContentHandler
::makeContent(
246 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
247 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
249 CONTENT_MODEL_WIKITEXT
252 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW
, false, $user1 );
254 $this->assertTrue( $status->isOK(), 'OK' );
255 $this->assertTrue( $status->value
['new'], 'new' );
256 $this->assertNotNull( $status->value
['revision'], 'revision' );
257 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
258 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
259 $this->assertTrue( $status->value
['revision']->getContent()->equals( $content ), 'equals' );
261 $rev = $page->getRevision();
262 $this->assertNotNull( $rev->getRecentChange() );
263 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
265 $id = $page->getId();
267 // Test page creation logging
270 [ 'log_type', 'log_action' ],
271 [ 'log_page' => $id ],
272 [ [ 'create', 'create' ] ]
275 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
276 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
277 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
278 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
280 # ------------------------
281 $dbr = wfGetDB( DB_REPLICA
);
282 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
283 $n = $res->numRows();
286 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
288 # ------------------------
289 $page = new WikiPage( $title );
291 $retrieved = $page->getContent();
292 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
294 # ------------------------
295 $page = new WikiPage( $title );
297 // try null edit, with a different user
298 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE
, false, $user2 );
299 $this->assertTrue( $status->isOK(), 'OK' );
300 $this->assertFalse( $status->value
['new'], 'new' );
301 $this->assertNull( $status->value
['revision'], 'revision' );
302 $this->assertNotNull( $page->getRevision() );
303 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
305 # ------------------------
306 $content = ContentHandler
::makeContent(
307 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
308 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
310 CONTENT_MODEL_WIKITEXT
313 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE
);
314 $this->assertTrue( $status->isOK(), 'OK' );
315 $this->assertFalse( $status->value
['new'], 'new' );
316 $this->assertNotNull( $status->value
['revision'], 'revision' );
317 $this->assertSame( $status->value
['revision']->getId(), $page->getRevision()->getId() );
318 $this->assertSame( $status->value
['revision']->getSha1(), $page->getRevision()->getSha1() );
320 $status->value
['revision']->getContent()->equals( $content ),
321 'not equals (PST must substitute signature)'
324 $rev = $page->getRevision();
325 $this->assertNotNull( $rev->getRecentChange() );
326 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
328 # ------------------------
329 $page = new WikiPage( $title );
331 $retrieved = $page->getContent();
332 $newText = $retrieved->serialize();
333 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
334 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
336 # ------------------------
337 $dbr = wfGetDB( DB_REPLICA
);
338 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
339 $n = $res->numRows();
342 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
346 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
347 * TODO: Revision deletion
349 * @covers WikiPage::doDeleteArticle
350 * @covers WikiPage::doDeleteArticleReal
352 public function testDoDeleteArticle() {
353 $page = $this->createPage(
355 "[[original text]] foo",
356 CONTENT_MODEL_WIKITEXT
358 $id = $page->getId();
360 $page->doDeleteArticle( "testing deletion" );
363 $page->getTitle()->getArticleID() > 0,
364 "Title object should now have page id 0"
366 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
369 "WikiPage::exists should return false after page was deleted"
373 "WikiPage::getContent should return null after page was deleted"
376 $t = Title
::newFromText( $page->getTitle()->getPrefixedText() );
379 "Title::exists should return false after page was deleted"
383 JobQueueGroup
::destroySingletons();
385 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
388 # ------------------------
389 $dbr = wfGetDB( DB_REPLICA
);
390 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
391 $n = $res->numRows();
394 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
398 * @covers WikiPage::doDeleteArticleReal
400 public function testDoDeleteArticleReal_user0() {
401 $page = $this->createPage(
403 "[[original text]] foo",
404 CONTENT_MODEL_WIKITEXT
406 $id = $page->getId();
409 $status = $page->doDeleteArticleReal(
410 /* reason */ "testing user 0 deletion",
411 /* suppress */ false,
414 /* errorStack */ $errorStack,
417 $logId = $status->getValue();
418 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
420 [ 'logging' ] +
$actorQuery['tables'], /* table */
425 'log_user' => $actorQuery['fields']['log_user'],
426 'log_user_text' => $actorQuery['fields']['log_user_text'],
430 [ 'log_id' => $logId ],
434 'testing user 0 deletion',
437 (string)$page->getTitle()->getNamespace(),
438 $page->getTitle()->getDBkey(),
446 * @covers WikiPage::doDeleteArticleReal
448 public function testDoDeleteArticleReal_userSysop() {
449 $page = $this->createPage(
451 "[[original text]] foo",
452 CONTENT_MODEL_WIKITEXT
454 $id = $page->getId();
456 $user = $this->getTestSysop()->getUser();
458 $status = $page->doDeleteArticleReal(
459 /* reason */ "testing sysop deletion",
460 /* suppress */ false,
463 /* errorStack */ $errorStack,
466 $logId = $status->getValue();
467 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
469 [ 'logging' ] +
$actorQuery['tables'], /* table */
474 'log_user' => $actorQuery['fields']['log_user'],
475 'log_user_text' => $actorQuery['fields']['log_user_text'],
479 [ 'log_id' => $logId ],
483 'testing sysop deletion',
484 (string)$user->getId(),
486 (string)$page->getTitle()->getNamespace(),
487 $page->getTitle()->getDBkey(),
495 * TODO: Test more stuff about suppression.
497 * @covers WikiPage::doDeleteArticleReal
499 public function testDoDeleteArticleReal_suppress() {
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 deletion",
514 /* errorStack */ $errorStack,
517 $logId = $status->getValue();
518 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
520 [ 'logging' ] +
$actorQuery['tables'], /* table */
525 'log_user' => $actorQuery['fields']['log_user'],
526 'log_user_text' => $actorQuery['fields']['log_user_text'],
530 [ 'log_id' => $logId ],
535 (string)$user->getId(),
537 (string)$page->getTitle()->getNamespace(),
538 $page->getTitle()->getDBkey(),
545 $page->getContent( Revision
::FOR_PUBLIC
),
546 "WikiPage::getContent should return null after the page was suppressed for general users"
550 $page->getContent( Revision
::FOR_THIS_USER
, null ),
551 "WikiPage::getContent should return null after the page was suppressed for user zero"
555 $page->getContent( Revision
::FOR_THIS_USER
, $user ),
556 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
561 * @covers WikiPage::doDeleteUpdates
563 public function testDoDeleteUpdates() {
564 $page = $this->createPage(
566 "[[original text]] foo",
567 CONTENT_MODEL_WIKITEXT
569 $id = $page->getId();
571 // Similar to MovePage logic
572 wfGetDB( DB_MASTER
)->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
573 $page->doDeleteUpdates( $id );
576 JobQueueGroup
::destroySingletons();
578 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
581 # ------------------------
582 $dbr = wfGetDB( DB_REPLICA
);
583 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
584 $n = $res->numRows();
587 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
591 * @covers WikiPage::getRevision
593 public function testGetRevision() {
594 $page = $this->newPage( __METHOD__
);
596 $rev = $page->getRevision();
597 $this->assertNull( $rev );
600 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
602 $rev = $page->getRevision();
604 $this->assertEquals( $page->getLatest(), $rev->getId() );
605 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
609 * @covers WikiPage::getContent
611 public function testGetContent() {
612 $page = $this->newPage( __METHOD__
);
614 $content = $page->getContent();
615 $this->assertNull( $content );
618 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
620 $content = $page->getContent();
621 $this->assertEquals( "some text", $content->getNativeData() );
625 * @covers WikiPage::exists
627 public function testExists() {
628 $page = $this->newPage( __METHOD__
);
629 $this->assertFalse( $page->exists() );
632 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
633 $this->assertTrue( $page->exists() );
635 $page = new WikiPage( $page->getTitle() );
636 $this->assertTrue( $page->exists() );
639 $page->doDeleteArticle( "done testing" );
640 $this->assertFalse( $page->exists() );
642 $page = new WikiPage( $page->getTitle() );
643 $this->assertFalse( $page->exists() );
646 public function provideHasViewableContent() {
648 [ 'WikiPageTest_testHasViewableContent', false, true ],
649 [ 'Special:WikiPageTest_testHasViewableContent', false ],
650 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
651 [ 'Special:Userlogin', true ],
652 [ 'MediaWiki:help', true ],
657 * @dataProvider provideHasViewableContent
658 * @covers WikiPage::hasViewableContent
660 public function testHasViewableContent( $title, $viewable, $create = false ) {
661 $page = $this->newPage( $title );
662 $this->assertEquals( $viewable, $page->hasViewableContent() );
665 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT
);
666 $this->assertTrue( $page->hasViewableContent() );
668 $page = new WikiPage( $page->getTitle() );
669 $this->assertTrue( $page->hasViewableContent() );
673 public function provideGetRedirectTarget() {
675 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT
, "hello world", null ],
677 'WikiPageTest_testGetRedirectTarget_2',
678 CONTENT_MODEL_WIKITEXT
,
679 "#REDIRECT [[hello world]]",
686 * @dataProvider provideGetRedirectTarget
687 * @covers WikiPage::getRedirectTarget
689 public function testGetRedirectTarget( $title, $model, $text, $target ) {
690 $this->setMwGlobals( [
691 'wgCapitalLinks' => true,
694 $page = $this->createPage( $title, $text, $model );
696 # sanity check, because this test seems to fail for no reason for some people.
697 $c = $page->getContent();
698 $this->assertEquals( WikitextContent
::class, get_class( $c ) );
700 # now, test the actual redirect
701 $t = $page->getRedirectTarget();
702 $this->assertEquals( $target, is_null( $t ) ?
null : $t->getPrefixedText() );
706 * @dataProvider provideGetRedirectTarget
707 * @covers WikiPage::isRedirect
709 public function testIsRedirect( $title, $model, $text, $target ) {
710 $page = $this->createPage( $title, $text, $model );
711 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
714 public function provideIsCountable() {
718 [ 'WikiPageTest_testIsCountable',
719 CONTENT_MODEL_WIKITEXT
,
724 [ 'WikiPageTest_testIsCountable',
725 CONTENT_MODEL_WIKITEXT
,
732 [ 'WikiPageTest_testIsCountable',
733 CONTENT_MODEL_WIKITEXT
,
738 [ 'WikiPageTest_testIsCountable',
739 CONTENT_MODEL_WIKITEXT
,
746 [ 'WikiPageTest_testIsCountable',
747 CONTENT_MODEL_WIKITEXT
,
752 [ 'WikiPageTest_testIsCountable',
753 CONTENT_MODEL_WIKITEXT
,
759 // not a content namespace
760 [ 'Talk:WikiPageTest_testIsCountable',
761 CONTENT_MODEL_WIKITEXT
,
766 [ 'Talk:WikiPageTest_testIsCountable',
767 CONTENT_MODEL_WIKITEXT
,
773 // not a content namespace, different model
774 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
780 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
790 * @dataProvider provideIsCountable
791 * @covers WikiPage::isCountable
793 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
794 global $wgContentHandlerUseDB;
796 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
798 $title = Title
::newFromText( $title );
800 if ( !$wgContentHandlerUseDB
802 && ContentHandler
::getDefaultModelFor( $title ) != $model
804 $this->markTestSkipped( "Can not use non-default content model $model for "
805 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
808 $page = $this->createPage( $title, $text, $model );
810 $editInfo = $page->prepareContentForEdit( $page->getContent() );
812 $v = $page->isCountable();
813 $w = $page->isCountable( $editInfo );
818 "isCountable( null ) returned unexpected value " . var_export( $v, true )
819 . " instead of " . var_export( $expected, true )
820 . " in mode `$mode` for text \"$text\""
826 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
827 . " instead of " . var_export( $expected, true )
828 . " in mode `$mode` for text \"$text\""
832 public function provideGetParserOutput() {
835 CONTENT_MODEL_WIKITEXT
,
837 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
844 * @dataProvider provideGetParserOutput
845 * @covers WikiPage::getParserOutput
847 public function testGetParserOutput( $model, $text, $expectedHtml ) {
848 $page = $this->createPage( __METHOD__
, $text, $model );
850 $opt = $page->makeParserOptions( 'canonical' );
851 $po = $page->getParserOutput( $opt );
852 $text = $po->getText();
854 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
855 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
857 $this->assertEquals( $expectedHtml, $text );
863 * @covers WikiPage::getParserOutput
865 public function testGetParserOutput_nonexisting() {
866 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
868 $opt = new ParserOptions();
869 $po = $page->getParserOutput( $opt );
871 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
875 * @covers WikiPage::getParserOutput
877 public function testGetParserOutput_badrev() {
878 $page = $this->createPage( __METHOD__
, 'dummy', CONTENT_MODEL_WIKITEXT
);
880 $opt = new ParserOptions();
881 $po = $page->getParserOutput( $opt, $page->getLatest() +
1234 );
883 // @todo would be neat to also test deleted revision
885 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
888 public static $sections =
902 public function dataReplaceSection() {
903 // NOTE: assume the Help namespace to contain wikitext
905 [ 'Help:WikiPageTest_testReplaceSection',
906 CONTENT_MODEL_WIKITEXT
,
911 trim( preg_replace( '/^Intro/sm', 'No more', self
::$sections ) )
913 [ 'Help:WikiPageTest_testReplaceSection',
914 CONTENT_MODEL_WIKITEXT
,
921 [ 'Help:WikiPageTest_testReplaceSection',
922 CONTENT_MODEL_WIKITEXT
,
925 "== TEST ==\nmore fun",
927 trim( preg_replace( '/^== test ==.*== foo ==/sm',
928 "== TEST ==\nmore fun\n\n== foo ==",
931 [ 'Help:WikiPageTest_testReplaceSection',
932 CONTENT_MODEL_WIKITEXT
,
937 trim( self
::$sections )
939 [ 'Help:WikiPageTest_testReplaceSection',
940 CONTENT_MODEL_WIKITEXT
,
945 trim( self
::$sections ) . "\n\n== New ==\n\nNo more"
951 * @dataProvider dataReplaceSection
952 * @covers WikiPage::replaceSectionContent
954 public function testReplaceSectionContent( $title, $model, $text, $section,
955 $with, $sectionTitle, $expected
957 $page = $this->createPage( $title, $text, $model );
959 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
960 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
962 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
966 * @dataProvider dataReplaceSection
967 * @covers WikiPage::replaceSectionAtRev
969 public function testReplaceSectionAtRev( $title, $model, $text, $section,
970 $with, $sectionTitle, $expected
972 $page = $this->createPage( $title, $text, $model );
973 $baseRevId = $page->getLatest();
975 $content = ContentHandler
::makeContent( $with, $page->getTitle(), $page->getContentModel() );
976 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
978 $this->assertEquals( $expected, is_null( $c ) ?
null : trim( $c->getNativeData() ) );
982 * @covers WikiPage::getOldestRevision
984 public function testGetOldestRevision() {
985 $page = $this->newPage( __METHOD__
);
986 $page->doEditContent(
987 new WikitextContent( 'one' ),
991 $rev1 = $page->getRevision();
993 $page = new WikiPage( $page->getTitle() );
994 $page->doEditContent(
995 new WikitextContent( 'two' ),
1000 $page = new WikiPage( $page->getTitle() );
1001 $page->doEditContent(
1002 new WikitextContent( 'three' ),
1008 $this->assertNotEquals(
1010 $page->getRevision()->getId(),
1011 '$page->getRevision()->getId()'
1015 $this->assertEquals(
1017 $page->getOldestRevision()->getId(),
1018 '$page->getOldestRevision()->getId()'
1023 * @covers WikiPage::doRollback
1024 * @covers WikiPage::commitRollback
1026 public function testDoRollback() {
1027 $admin = $this->getTestSysop()->getUser();
1028 $user1 = $this->getTestUser()->getUser();
1029 // Use the confirmed group for user2 to make sure the user is different
1030 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1032 // make sure we can test autopatrolling
1033 $this->setMwGlobals( 'wgUseRCPatrol', true );
1035 // TODO: MCR: test rollback of multiple slots!
1036 $page = $this->newPage( __METHOD__
);
1040 $status1 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1041 "section one", EDIT_NEW
, false, $admin );
1044 $status2 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1045 "adding section two", 0, false, $user1 );
1047 $text .= "\n\nthree";
1048 $status3 = $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ),
1049 "adding section three", 0, false, $user2 );
1051 /** @var Revision $rev1 */
1052 /** @var Revision $rev2 */
1053 /** @var Revision $rev3 */
1054 $rev1 = $status1->getValue()['revision'];
1055 $rev2 = $status2->getValue()['revision'];
1056 $rev3 = $status3->getValue()['revision'];
1059 * We are having issues with doRollback spuriously failing. Apparently
1060 * the last revision somehow goes missing or not committed under some
1061 * circumstances. So, make sure the revisions have the correct usernames.
1063 $this->assertEquals( 3, Revision
::countByPageId( wfGetDB( DB_REPLICA
), $page->getId() ) );
1064 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1065 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1066 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1068 // Now, try the actual rollback
1069 $token = $admin->getEditToken( 'rollback' );
1070 $rollbackErrors = $page->doRollback(
1079 if ( $rollbackErrors ) {
1081 "Rollback failed:\n" .
1082 print_r( $rollbackErrors, true ) . ";\n" .
1083 print_r( $resultDetails, true )
1087 $page = new WikiPage( $page->getTitle() );
1088 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1089 "rollback did not revert to the correct revision" );
1090 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1092 $rc = MediaWikiServices
::getInstance()->getRevisionStore()->getRecentChange(
1093 $page->getRevision()->getRevisionRecord()
1096 $this->assertNotNull( $rc, 'RecentChanges entry' );
1097 $this->assertEquals(
1098 RecentChange
::PRC_AUTOPATROLLED
,
1099 $rc->getAttribute( 'rc_patrolled' ),
1103 // TODO: MCR: assert origin once we write slot data
1104 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
1105 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1106 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1110 * @covers WikiPage::doRollback
1111 * @covers WikiPage::commitRollback
1113 public function testDoRollbackFailureSameContent() {
1114 $admin = $this->getTestSysop()->getUser();
1117 $page = $this->newPage( __METHOD__
);
1118 $page->doEditContent(
1119 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1125 $rev1 = $page->getRevision();
1127 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1129 $page = new WikiPage( $page->getTitle() );
1130 $page->doEditContent(
1131 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1132 "adding section two",
1138 # now, do a the rollback from the same user was doing the edit before
1139 $resultDetails = [];
1140 $token = $user1->getEditToken( 'rollback' );
1141 $errors = $page->doRollback(
1143 "testing revert same user",
1150 $this->assertEquals( [], $errors, "Rollback failed same user" );
1152 # now, try the rollback
1153 $resultDetails = [];
1154 $token = $admin->getEditToken( 'rollback' );
1155 $errors = $page->doRollback(
1164 $this->assertEquals(
1174 "Rollback not failed"
1177 $page = new WikiPage( $page->getTitle() );
1178 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1179 "rollback did not revert to the correct revision" );
1180 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1184 * Tests tagging for edits that do rollback action
1185 * @covers WikiPage::doRollback
1187 public function testDoRollbackTagging() {
1188 if ( !in_array( 'mw-rollback', ChangeTags
::getSoftwareTags() ) ) {
1189 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1192 $admin = new User();
1193 $admin->setName( 'Administrator' );
1194 $admin->addToDatabase();
1196 $text = 'First line';
1197 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1198 $page->doEditContent(
1199 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1206 $secondUser = new User();
1207 $secondUser->setName( '92.65.217.32' );
1208 $text .= '\n\nSecond line';
1209 $page = new WikiPage( $page->getTitle() );
1210 $page->doEditContent(
1211 ContentHandler
::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT
),
1212 'Adding second line',
1218 // Now, try the rollback
1219 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1220 $token = $admin->getEditToken( 'rollback' );
1221 $errors = $page->doRollback(
1222 $secondUser->getName(),
1230 // If doRollback completed without errors
1231 if ( $errors === [] ) {
1232 $tags = $resultDetails[ 'tags' ];
1233 $this->assertContains( 'mw-rollback', $tags );
1237 public function provideGetAutoDeleteReason() {
1247 [ "first edit", null ],
1249 "/first edit.*only contributor/",
1255 [ "first edit", null ],
1256 [ "second edit", null ],
1258 "/second edit.*only contributor/",
1264 [ "first edit", "127.0.2.22" ],
1265 [ "second edit", "127.0.3.33" ],
1275 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1276 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1277 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1278 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1279 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1283 '/first edit:.*\.\.\."/',
1289 [ "first edit", "127.0.2.22" ],
1290 [ "", "127.0.3.33" ],
1292 "/before blanking.*first edit/",
1300 * @dataProvider provideGetAutoDeleteReason
1301 * @covers WikiPage::getAutoDeleteReason
1303 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1306 // NOTE: assume Help namespace to contain wikitext
1307 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1311 foreach ( $edits as $edit ) {
1314 if ( !empty( $edit[1] ) ) {
1315 $user->setName( $edit[1] );
1320 $content = ContentHandler
::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1322 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW
: 0, false, $user );
1327 $reason = $page->getAutoDeleteReason( $hasHistory );
1329 if ( is_bool( $expectedResult ) ||
is_null( $expectedResult ) ) {
1330 $this->assertEquals( $expectedResult, $reason );
1332 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1333 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1336 $this->assertEquals( $expectedHistory, $hasHistory,
1337 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1339 $page->doDeleteArticle( "done" );
1342 public function providePreSaveTransform() {
1344 [ 'hello this is ~~~',
1345 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1347 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1348 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1354 * @covers WikiPage::factory
1356 public function testWikiPageFactory() {
1357 $title = Title
::makeTitle( NS_FILE
, 'Someimage.png' );
1358 $page = WikiPage
::factory( $title );
1359 $this->assertEquals( WikiFilePage
::class, get_class( $page ) );
1361 $title = Title
::makeTitle( NS_CATEGORY
, 'SomeCategory' );
1362 $page = WikiPage
::factory( $title );
1363 $this->assertEquals( WikiCategoryPage
::class, get_class( $page ) );
1365 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1366 $page = WikiPage
::factory( $title );
1367 $this->assertEquals( WikiPage
::class, get_class( $page ) );
1371 * @covers WikiPage::loadPageData
1372 * @covers WikiPage::wasLoadedFrom
1374 public function testLoadPageData() {
1375 $title = Title
::makeTitle( NS_MAIN
, 'SomePage' );
1376 $page = WikiPage
::factory( $title );
1378 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1379 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1380 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1381 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1383 $page->loadPageData( IDBAccessObject
::READ_NORMAL
);
1384 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1385 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1386 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1387 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1389 $page->loadPageData( IDBAccessObject
::READ_LATEST
);
1390 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1391 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1392 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1393 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1395 $page->loadPageData( IDBAccessObject
::READ_LOCKING
);
1396 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1397 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1398 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1399 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1401 $page->loadPageData( IDBAccessObject
::READ_EXCLUSIVE
);
1402 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_NORMAL
) );
1403 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LATEST
) );
1404 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_LOCKING
) );
1405 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject
::READ_EXCLUSIVE
) );
1409 * @dataProvider provideCommentMigrationOnDeletion
1411 * @param int $writeStage
1412 * @param int $readStage
1414 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1415 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1416 $this->overrideMwServices();
1418 $dbr = wfGetDB( DB_REPLICA
);
1420 $page = $this->createPage(
1423 CONTENT_MODEL_WIKITEXT
1425 $revid = $page->getLatest();
1426 if ( $writeStage > MIGRATION_OLD
) {
1427 $comment_id = $dbr->selectField(
1428 'revision_comment_temp',
1429 'revcomment_comment_id',
1430 [ 'revcomment_rev' => $revid ],
1435 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1436 $this->overrideMwServices();
1438 $page->doDeleteArticle( "testing deletion" );
1440 if ( $readStage > MIGRATION_OLD
) {
1441 // Didn't leave behind any 'revision_comment_temp' rows
1442 $n = $dbr->selectField(
1443 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1445 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1447 // Copied or upgraded the comment_id, as applicable
1448 $ar_comment_id = $dbr->selectField(
1451 [ 'ar_rev_id' => $revid ],
1454 if ( $writeStage > MIGRATION_OLD
) {
1455 $this->assertSame( $comment_id, $ar_comment_id );
1457 $this->assertNotEquals( 0, $ar_comment_id );
1461 // Copied rev_comment, if applicable
1462 if ( $readStage <= MIGRATION_WRITE_BOTH
&& $writeStage <= MIGRATION_WRITE_BOTH
) {
1463 $ar_comment = $dbr->selectField(
1466 [ 'ar_rev_id' => $revid ],
1469 $this->assertSame( 'testing', $ar_comment );
1473 public function provideCommentMigrationOnDeletion() {
1475 [ MIGRATION_OLD
, MIGRATION_OLD
],
1476 [ MIGRATION_OLD
, MIGRATION_WRITE_BOTH
],
1477 [ MIGRATION_OLD
, MIGRATION_WRITE_NEW
],
1478 [ MIGRATION_WRITE_BOTH
, MIGRATION_OLD
],
1479 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_BOTH
],
1480 [ MIGRATION_WRITE_BOTH
, MIGRATION_WRITE_NEW
],
1481 [ MIGRATION_WRITE_BOTH
, MIGRATION_NEW
],
1482 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_BOTH
],
1483 [ MIGRATION_WRITE_NEW
, MIGRATION_WRITE_NEW
],
1484 [ MIGRATION_WRITE_NEW
, MIGRATION_NEW
],
1485 [ MIGRATION_NEW
, MIGRATION_WRITE_BOTH
],
1486 [ MIGRATION_NEW
, MIGRATION_WRITE_NEW
],
1487 [ MIGRATION_NEW
, MIGRATION_NEW
],
1492 * @covers WikiPage::updateCategoryCounts
1494 public function testUpdateCategoryCounts() {
1495 $page = new WikiPage( Title
::newFromText( __METHOD__
) );
1497 // Add an initial category
1498 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1500 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1501 $this->assertEquals( 0, Category
::newFromName( 'B' )->getPageCount() );
1502 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1504 // Add a new category
1505 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1507 $this->assertEquals( 1, Category
::newFromName( 'A' )->getPageCount() );
1508 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1509 $this->assertEquals( 0, Category
::newFromName( 'C' )->getPageCount() );
1511 // Add and remove a category
1512 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1514 $this->assertEquals( 0, Category
::newFromName( 'A' )->getPageCount() );
1515 $this->assertEquals( 1, Category
::newFromName( 'B' )->getPageCount() );
1516 $this->assertEquals( 1, Category
::newFromName( 'C' )->getPageCount() );
1519 public function provideUpdateRedirectOn() {
1520 yield
[ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1521 yield
[ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1522 yield
[ 'SomeText', false, null, false, true, 0 ];
1523 yield
[ 'SomeText', false, 'Foo', false, false, 1 ];
1527 * @dataProvider provideUpdateRedirectOn
1528 * @covers WikiPage::updateRedirectOn
1530 * @param string $initialText
1531 * @param bool $initialRedirectState
1532 * @param string|null $redirectTitle
1533 * @param bool|null $lastRevIsRedirect
1534 * @param bool $expectedSuccess
1535 * @param int $expectedRowCount
1537 public function testUpdateRedirectOn(
1539 $initialRedirectState,
1545 static $pageCounter = 0;
1548 $page = $this->createPage( Title
::newFromText( __METHOD__
. $pageCounter ), $initialText );
1549 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1551 $redirectTitle = is_string( $redirectTitle )
1552 ? Title
::newFromText( $redirectTitle )
1555 $success = $page->updateRedirectOn( $this->db
, $redirectTitle, $lastRevIsRedirect );
1556 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1558 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1559 * Most of core checks the page table for redirect status, so we have to be ugly and
1560 * assert a select from the table here.
1562 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1565 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1566 $this->assertSelect(
1569 [ 'rd_from' => $pageId ],
1570 [ [ strval( $expected ) ] ]
1575 * @covers WikiPage::insertRedirectEntry
1577 public function testInsertRedirectEntry_insertsRedirectEntry() {
1578 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1579 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1581 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1582 $targetTitle->mInterwiki
= 'eninter';
1583 $page->insertRedirectEntry( $targetTitle, null );
1585 $this->assertSelect(
1587 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1588 [ 'rd_from' => $page->getId() ],
1590 strval( $page->getId() ),
1591 strval( $targetTitle->getNamespace() ),
1592 strval( $targetTitle->getDBkey() ),
1593 strval( $targetTitle->getFragment() ),
1594 strval( $targetTitle->getInterwiki() ),
1600 * @covers WikiPage::insertRedirectEntry
1602 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1603 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1604 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1606 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1607 $targetTitle->mInterwiki
= 'eninter';
1608 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1610 $this->assertSelect(
1612 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1613 [ 'rd_from' => $page->getId() ],
1615 strval( $page->getId() ),
1616 strval( $targetTitle->getNamespace() ),
1617 strval( $targetTitle->getDBkey() ),
1618 strval( $targetTitle->getFragment() ),
1619 strval( $targetTitle->getInterwiki() ),
1625 * @covers WikiPage::insertRedirectEntry
1627 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1628 $page = $this->createPage( Title
::newFromText( __METHOD__
), 'A' );
1629 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1631 $targetTitle = Title
::newFromText( 'SomeTarget#Frag' );
1632 $targetTitle->mInterwiki
= 'eninter';
1633 $page->insertRedirectEntry( $targetTitle, 215251 );
1635 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1638 private function getRow( array $overrides = [] ) {
1642 'page_is_redirect' => '1',
1643 'page_latest' => '99',
1644 'page_namespace' => '3',
1645 'page_title' => 'JaJaTitle',
1646 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1647 'page_touched' => '20120101020202',
1648 'page_links_updated' => '20140101020202',
1650 foreach ( $overrides as $key => $value ) {
1651 $row[$key] = $value;
1653 return (object)$row;
1656 public function provideNewFromRowSuccess() {
1657 yield
'basic row' => [
1659 function ( WikiPage
$wikiPage, self
$test ) {
1660 $test->assertSame( 44, $wikiPage->getId() );
1661 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1662 $test->assertTrue( $wikiPage->isRedirect() );
1663 $test->assertSame( 99, $wikiPage->getLatest() );
1664 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1665 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1668 'edit' => [ 'autoconfirmed', 'sysop' ],
1669 'move' => [ 'sysop' ],
1671 $wikiPage->getTitle()->getAllRestrictions()
1673 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1674 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1677 yield
'different timestamp formats' => [
1679 'page_touched' => '2012-01-01 02:02:02',
1680 'page_links_updated' => '2014-01-01 02:02:02',
1682 function ( WikiPage
$wikiPage, self
$test ) {
1683 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1684 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1687 yield
'no restrictions' => [
1689 'page_restrictions' => '',
1691 function ( WikiPage
$wikiPage, self
$test ) {
1697 $wikiPage->getTitle()->getAllRestrictions()
1701 yield
'not redirect' => [
1703 'page_is_redirect' => '0',
1705 function ( WikiPage
$wikiPage, self
$test ) {
1706 $test->assertFalse( $wikiPage->isRedirect() );
1712 * @covers WikiPage::newFromRow
1713 * @covers WikiPage::loadFromRow
1714 * @dataProvider provideNewFromRowSuccess
1716 * @param object $row
1717 * @param callable $assertions
1719 public function testNewFromRow( $row, $assertions ) {
1720 $page = WikiPage
::newFromRow( $row, 'fromdb' );
1721 $assertions( $page, $this );
1724 public function provideTestNewFromId_returnsNullOnBadPageId() {
1730 * @covers WikiPage::newFromID
1731 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1733 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1734 $this->assertNull( WikiPage
::newFromID( $pageId ) );
1738 * @covers WikiPage::newFromID
1740 public function testNewFromId_appearsToFetchCorrectRow() {
1741 $createdPage = $this->createPage( __METHOD__
, 'Xsfaij09' );
1742 $fetchedPage = WikiPage
::newFromID( $createdPage->getId() );
1743 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1744 $this->assertEquals(
1745 $createdPage->getContent()->getNativeData(),
1746 $fetchedPage->getContent()->getNativeData()
1751 * @covers WikiPage::newFromID
1753 public function testNewFromId_returnsNullOnNonExistingId() {
1754 $this->assertNull( WikiPage
::newFromID( 2147483647 ) );
1757 public function provideTestInsertProtectNullRevision() {
1758 // phpcs:disable Generic.Files.LineLength
1761 [ 'edit' => 'sysop' ],
1762 [ 'edit' => '20200101040404' ],
1766 '(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)))'
1770 [ 'edit' => 'sysop', 'move' => 'something' ],
1771 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1775 '(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)))'
1781 * @dataProvider provideTestInsertProtectNullRevision
1782 * @covers WikiPage::insertProtectNullRevision
1783 * @covers WikiPage::protectDescription
1785 * @param string $revCommentMsg
1786 * @param array $limit
1787 * @param array $expiry
1788 * @param bool $cascade
1789 * @param string $reason
1790 * @param bool|null $user true if the test sysop should be used, or null
1791 * @param string $expectedComment
1793 public function testInsertProtectNullRevision(
1802 $this->setContentLang( 'qqx' );
1804 $page = $this->createPage( __METHOD__
, 'Goat' );
1806 $user = $user === null ?
$user : $this->getTestSysop()->getUser();
1808 $result = $page->insertProtectNullRevision(
1817 $this->assertTrue( $result instanceof Revision
);
1818 $this->assertSame( $expectedComment, $result->getComment( Revision
::RAW
) );
1822 * @covers WikiPage::updateRevisionOn
1824 public function testUpdateRevisionOn_existingPage() {
1825 $user = $this->getTestSysop()->getUser();
1826 $page = $this->createPage( __METHOD__
, 'StartText' );
1828 $revision = new Revision(
1831 'page' => $page->getId(),
1832 'title' => $page->getTitle(),
1833 'comment' => __METHOD__
,
1834 'minor_edit' => true,
1835 'text' => __METHOD__
. '-text',
1836 'len' => strlen( __METHOD__
. '-text' ),
1837 'user' => $user->getId(),
1838 'user_text' => $user->getName(),
1839 'timestamp' => '20170707040404',
1840 'content_model' => CONTENT_MODEL_WIKITEXT
,
1841 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1845 $result = $page->updateRevisionOn( $this->db
, $revision );
1846 $this->assertTrue( $result );
1847 $this->assertSame( 9989, $page->getLatest() );
1848 $this->assertEquals( $revision, $page->getRevision() );
1852 * @covers WikiPage::updateRevisionOn
1854 public function testUpdateRevisionOn_NonExistingPage() {
1855 $user = $this->getTestSysop()->getUser();
1856 $page = $this->createPage( __METHOD__
, 'StartText' );
1857 $page->doDeleteArticle( 'reason' );
1859 $revision = new Revision(
1862 'page' => $page->getId(),
1863 'title' => $page->getTitle(),
1864 'comment' => __METHOD__
,
1865 'minor_edit' => true,
1866 'text' => __METHOD__
. '-text',
1867 'len' => strlen( __METHOD__
. '-text' ),
1868 'user' => $user->getId(),
1869 'user_text' => $user->getName(),
1870 'timestamp' => '20170707040404',
1871 'content_model' => CONTENT_MODEL_WIKITEXT
,
1872 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1876 $result = $page->updateRevisionOn( $this->db
, $revision );
1877 $this->assertFalse( $result );
1881 * @covers WikiPage::updateIfNewerOn
1883 public function testUpdateIfNewerOn_olderRevision() {
1884 $user = $this->getTestSysop()->getUser();
1885 $page = $this->createPage( __METHOD__
, 'StartText' );
1886 $initialRevision = $page->getRevision();
1888 $olderTimeStamp = wfTimestamp(
1890 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) - 1
1893 $olderRevison = new Revision(
1896 'page' => $page->getId(),
1897 'title' => $page->getTitle(),
1898 'comment' => __METHOD__
,
1899 'minor_edit' => true,
1900 'text' => __METHOD__
. '-text',
1901 'len' => strlen( __METHOD__
. '-text' ),
1902 'user' => $user->getId(),
1903 'user_text' => $user->getName(),
1904 'timestamp' => $olderTimeStamp,
1905 'content_model' => CONTENT_MODEL_WIKITEXT
,
1906 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1910 $result = $page->updateIfNewerOn( $this->db
, $olderRevison );
1911 $this->assertFalse( $result );
1915 * @covers WikiPage::updateIfNewerOn
1917 public function testUpdateIfNewerOn_newerRevision() {
1918 $user = $this->getTestSysop()->getUser();
1919 $page = $this->createPage( __METHOD__
, 'StartText' );
1920 $initialRevision = $page->getRevision();
1922 $newerTimeStamp = wfTimestamp(
1924 wfTimestamp( TS_UNIX
, $initialRevision->getTimestamp() ) +
1
1927 $newerRevision = new Revision(
1930 'page' => $page->getId(),
1931 'title' => $page->getTitle(),
1932 'comment' => __METHOD__
,
1933 'minor_edit' => true,
1934 'text' => __METHOD__
. '-text',
1935 'len' => strlen( __METHOD__
. '-text' ),
1936 'user' => $user->getId(),
1937 'user_text' => $user->getName(),
1938 'timestamp' => $newerTimeStamp,
1939 'content_model' => CONTENT_MODEL_WIKITEXT
,
1940 'content_format' => CONTENT_FORMAT_WIKITEXT
,
1943 $result = $page->updateIfNewerOn( $this->db
, $newerRevision );
1944 $this->assertTrue( $result );
1948 * @covers WikiPage::insertOn
1950 public function testInsertOn() {
1951 $title = Title
::newFromText( __METHOD__
);
1952 $page = new WikiPage( $title );
1954 $startTimeStamp = wfTimestampNow();
1955 $result = $page->insertOn( $this->db
);
1956 $endTimeStamp = wfTimestampNow();
1958 $this->assertInternalType( 'int', $result );
1959 $this->assertTrue( $result > 0 );
1961 $condition = [ 'page_id' => $result ];
1963 // Check the default fields have been filled
1964 $this->assertSelect(
1969 'page_restrictions',
1987 // Check the page_random field has been filled
1988 $pageRandom = $this->db
->selectField( 'page', 'page_random', $condition );
1989 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
1991 // Assert the touched timestamp in the DB is roughly when we inserted the page
1992 $pageTouched = $this->db
->selectField( 'page', 'page_touched', $condition );
1994 wfTimestamp( TS_UNIX
, $startTimeStamp )
1995 <= wfTimestamp( TS_UNIX
, $pageTouched )
1998 wfTimestamp( TS_UNIX
, $endTimeStamp )
1999 >= wfTimestamp( TS_UNIX
, $pageTouched )
2002 // Try inserting the same page again and checking the result is false (no change)
2003 $result = $page->insertOn( $this->db
);
2004 $this->assertFalse( $result );
2008 * @covers WikiPage::insertOn
2010 public function testInsertOn_idSpecified() {
2011 $title = Title
::newFromText( __METHOD__
);
2012 $page = new WikiPage( $title );
2015 $result = $page->insertOn( $this->db
, $id );
2017 $this->assertSame( $id, $result );
2019 $condition = [ 'page_id' => $result ];
2021 // Check there is actually a row in the db
2022 $this->assertSelect(
2030 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2031 // Note: Once the current dates passes the date in these tests they will fail.
2032 yield
'move something' => [
2034 [ 'move' => 'something' ],
2036 [ 'edit' => [], 'move' => [ 'something' ] ],
2039 yield
'move something, edit blank' => [
2041 [ 'move' => 'something', 'edit' => '' ],
2043 [ 'edit' => [], 'move' => [ 'something' ] ],
2046 yield
'edit sysop, with expiry' => [
2048 [ 'edit' => 'sysop' ],
2049 [ 'edit' => '21330101020202' ],
2050 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2051 [ 'edit' => '21330101020202' ],
2053 yield
'move and edit, move with expiry' => [
2055 [ 'move' => 'something', 'edit' => 'another' ],
2056 [ 'move' => '22220202010101' ],
2057 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2058 [ 'move' => '22220202010101' ],
2060 yield
'move and edit, edit with infinity expiry' => [
2062 [ 'move' => 'something', 'edit' => 'another' ],
2063 [ 'edit' => 'infinity' ],
2064 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2065 [ 'edit' => 'infinity' ],
2067 yield
'non existing, create something' => [
2069 [ 'create' => 'something' ],
2071 [ 'create' => [ 'something' ] ],
2074 yield
'non existing, create something with expiry' => [
2076 [ 'create' => 'something' ],
2077 [ 'create' => '23451212112233' ],
2078 [ 'create' => [ 'something' ] ],
2079 [ 'create' => '23451212112233' ],
2084 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2085 * @covers WikiPage::doUpdateRestrictions
2087 public function testDoUpdateRestrictions_setBasicRestrictions(
2091 array $expectedRestrictions,
2092 array $expectedRestrictionExpiries
2094 if ( $pageExists ) {
2095 $page = $this->createPage( __METHOD__
, 'ABC' );
2097 $page = new WikiPage( Title
::newFromText( __METHOD__
. '-nonexist' ) );
2099 $user = $this->getTestSysop()->getUser();
2102 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2104 $logId = $status->getValue();
2105 $allRestrictions = $page->getTitle()->getAllRestrictions();
2107 $this->assertTrue( $status->isGood() );
2108 $this->assertInternalType( 'int', $logId );
2109 $this->assertSame( $expectedRestrictions, $allRestrictions );
2110 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2111 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2114 // Make sure the log entry looks good
2115 // log_params is not checked here
2116 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
2117 $this->assertSelect(
2118 [ 'logging' ] +
$actorQuery['tables'],
2121 'log_user' => $actorQuery['fields']['log_user'],
2122 'log_user_text' => $actorQuery['fields']['log_user_text'],
2126 [ 'log_id' => $logId ],
2129 (string)$user->getId(),
2131 (string)$page->getTitle()->getNamespace(),
2132 $page->getTitle()->getDBkey(),
2135 $actorQuery['joins']
2140 * @covers WikiPage::doUpdateRestrictions
2142 public function testDoUpdateRestrictions_failsOnReadOnly() {
2143 $page = $this->createPage( __METHOD__
, 'ABC' );
2144 $user = $this->getTestSysop()->getUser();
2148 $readOnly = $this->getMockBuilder( ReadOnlyMode
::class )
2149 ->disableOriginalConstructor()
2150 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2152 $readOnly->expects( $this->once() )
2153 ->method( 'isReadOnly' )
2154 ->will( $this->returnValue( true ) );
2155 $readOnly->expects( $this->once() )
2156 ->method( 'getReason' )
2157 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2158 $this->setService( 'ReadOnlyMode', $readOnly );
2160 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2161 $this->assertFalse( $status->isOK() );
2162 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2166 * @covers WikiPage::doUpdateRestrictions
2168 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2169 $page = $this->createPage( __METHOD__
, 'ABC' );
2170 $user = $this->getTestSysop()->getUser();
2172 $limit = [ 'edit' => 'sysop' ];
2174 $status = $page->doUpdateRestrictions(
2183 // The first entry should have a logId as it did something
2184 $this->assertTrue( $status->isGood() );
2185 $this->assertInternalType( 'int', $status->getValue() );
2187 $status = $page->doUpdateRestrictions(
2196 // The second entry should not have a logId as nothing changed
2197 $this->assertTrue( $status->isGood() );
2198 $this->assertNull( $status->getValue() );
2202 * @covers WikiPage::doUpdateRestrictions
2204 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2205 $page = $this->createPage( __METHOD__
, 'ABC' );
2206 $user = $this->getTestSysop()->getUser();
2210 $status = $page->doUpdateRestrictions(
2211 [ 'edit' => 'sysop' ],
2218 $this->assertTrue( $status->isGood() );
2219 $this->assertInternalType( 'int', $status->getValue() );
2220 $this->assertSelect(
2222 [ 'log_type', 'log_action' ],
2223 [ 'log_id' => $status->getValue() ],
2224 [ [ 'protect', 'protect' ] ]
2227 // Modify the protection
2228 $status = $page->doUpdateRestrictions(
2229 [ 'edit' => 'somethingElse' ],
2236 $this->assertTrue( $status->isGood() );
2237 $this->assertInternalType( 'int', $status->getValue() );
2238 $this->assertSelect(
2240 [ 'log_type', 'log_action' ],
2241 [ 'log_id' => $status->getValue() ],
2242 [ [ 'protect', 'modify' ] ]
2245 // Remove the protection
2246 $status = $page->doUpdateRestrictions(
2254 $this->assertTrue( $status->isGood() );
2255 $this->assertInternalType( 'int', $status->getValue() );
2256 $this->assertSelect(
2258 [ 'log_type', 'log_action' ],
2259 [ 'log_id' => $status->getValue() ],
2260 [ [ 'protect', 'unprotect' ] ]
2265 * @covers WikiPage::newPageUpdater
2266 * @covers WikiPage::getDerivedDataUpdater
2268 public function testNewPageUpdater() {
2269 $user = $this->getTestUser()->getUser();
2270 $page = $this->newPage( __METHOD__
, __METHOD__
);
2272 /** @var Content $content */
2273 $content = $this->getMockBuilder( WikitextContent
::class )
2274 ->setConstructorArgs( [ 'Hello World' ] )
2275 ->setMethods( [ 'getParserOutput' ] )
2277 $content->expects( $this->once() )
2278 ->method( 'getParserOutput' )
2279 ->willReturn( new ParserOutput( 'HTML' ) );
2281 $updater = $page->newPageUpdater( $user );
2282 $updater->setContent( 'main', $content );
2283 $revision = $updater->saveRevision(
2284 CommentStoreComment
::newUnsavedComment( 'test' ),
2288 $this->assertSame( $revision->getId(), $page->getLatest() );
2292 * @covers WikiPage::newPageUpdater
2293 * @covers WikiPage::getDerivedDataUpdater
2295 public function testGetDerivedDataUpdater() {
2296 $admin = $this->getTestSysop()->getUser();
2298 /** @var object $page */
2299 $page = $this->createPage( __METHOD__
, __METHOD__
);
2300 $page = TestingAccessWrapper
::newFromObject( $page );
2302 $revision = $page->getRevision()->getRevisionRecord();
2303 $user = $revision->getUser();
2305 $slotsUpdate = new RevisionSlotsUpdate();
2306 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2308 // get a virgin updater
2309 $updater1 = $page->getDerivedDataUpdater( $user );
2310 $this->assertFalse( $updater1->isUpdatePrepared() );
2312 $updater1->prepareUpdate( $revision );
2314 // Re-use updater with same revision or content
2315 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2317 $slotsUpdate = RevisionSlotsUpdate
::newFromContent(
2318 [ 'main' => $revision->getContent( 'main' ) ]
2320 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2322 // Don't re-use with different user
2323 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2324 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2326 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2327 $updater2b->prepareContent( $user, $slotsUpdate, false );
2328 $this->assertNotSame( $updater2a, $updater2b );
2330 // Don't re-use with different content
2331 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2332 $updater3->prepareUpdate( $revision );
2333 $this->assertNotSame( $updater2b, $updater3 );
2335 // Don't re-use if no context given
2336 $updater4 = $page->getDerivedDataUpdater( $admin );
2337 $updater4->prepareUpdate( $revision );
2338 $this->assertNotSame( $updater3, $updater4 );
2340 // Don't re-use if AGAIN no context given
2341 $updater5 = $page->getDerivedDataUpdater( $admin );
2342 $this->assertNotSame( $updater4, $updater5 );
2344 // Don't re-use cached "virgin" unprepared updater
2345 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2346 $this->assertNotSame( $updater5, $updater6 );