3 use MediaWiki\MediaWikiServices
;
4 use MediaWiki\Storage\PageEditStash
;
5 use Wikimedia\TestingAccessWrapper
;
6 use Psr\Log\NullLogger
;
10 * @covers \MediaWiki\Storage\PageEditStash
15 class ApiStashEditTest
extends ApiTestCase
{
16 public function setUp() {
18 $this->setService( 'PageEditStash', new PageEditStash(
19 new HashBagOStuff( [] ),
20 MediaWikiServices
::getInstance()->getDBLoadBalancer(),
22 new NullStatsdDataFactory(),
23 PageEditStash
::INITIATOR_USER
25 // Clear rate-limiting cache between tests
26 $this->setMwGlobals( 'wgMainCacheType', 'hash' );
29 public function tearDown() {
34 * Make a stashedit API call with suitable default parameters
36 * @param array $params Query parameters for API request. All are optional and will have
37 * sensible defaults filled in. To make a parameter actually not passed, set to null.
38 * @param User $user User to do the request
39 * @param string $expectedResult 'stashed', 'editconflict'
42 protected function doStash(
43 array $params = [], User
$user = null, $expectedResult = 'stashed'
45 $params = array_merge( [
46 'action' => 'stashedit',
48 'contentmodel' => 'wikitext',
49 'contentformat' => 'text/x-wiki',
52 if ( !array_key_exists( 'text', $params ) &&
53 !array_key_exists( 'stashedtexthash', $params )
55 $params['text'] = 'Content';
57 foreach ( $params as $key => $val ) {
58 if ( $val === null ) {
59 unset( $params[$key] );
63 if ( isset( $params['text'] ) ) {
64 $expectedText = $params['text'];
65 } elseif ( isset( $params['stashedtexthash'] ) ) {
66 $expectedText = $this->getStashedText( $params['stashedtexthash'] );
68 if ( isset( $expectedText ) ) {
69 $expectedText = rtrim( str_replace( "\r\n", "\n", $expectedText ) );
70 $expectedHash = sha1( $expectedText );
71 $origText = $this->getStashedText( $expectedHash );
74 $res = $this->doApiRequestWithToken( $params, null, $user );
76 $this->assertSame( $expectedResult, $res[0]['stashedit']['status'] );
77 $this->assertCount( $expectedResult === 'stashed' ?
2 : 1, $res[0]['stashedit'] );
79 if ( $expectedResult === 'stashed' ) {
80 $hash = $res[0]['stashedit']['texthash'];
82 $this->assertSame( $expectedText, $this->getStashedText( $hash ) );
84 $this->assertSame( $expectedHash, $hash );
86 if ( isset( $params['stashedtexthash'] ) ) {
87 $this->assertSame( $params['stashedtexthash'], $expectedHash, 'Sanity' );
90 $this->assertSame( $origText, $this->getStashedText( $expectedHash ) );
93 $this->assertArrayNotHasKey( 'warnings', $res[0] );
99 * Return the text stashed for $hash.
101 * @param string $hash
104 protected function getStashedText( $hash ) {
105 return MediaWikiServices
::getInstance()->getPageEditStash()->fetchInputText( $hash );
109 * Return a key that can be passed to the cache to obtain a stashed edit object.
111 * @param string $title Title of page
112 * @param string Content $text Content of edit
113 * @param User $user User who made edit
116 protected function getStashKey( $title = __CLASS__
, $text = 'Content', User
$user = null ) {
117 $titleObj = Title
::newFromText( $title );
118 $content = new WikitextContent( $text );
120 $user = $this->getTestSysop()->getUser();
122 $editStash = TestingAccessWrapper
::newFromObject(
123 MediaWikiServices
::getInstance()->getPageEditStash() );
125 return $editStash->getStashKey( $titleObj, $editStash->getContentHash( $content ), $user );
128 public function testBasicEdit() {
132 public function testBot() {
133 // @todo This restriction seems arbitrary, is there any good reason to keep it?
134 $this->setExpectedApiException( 'apierror-botsnotsupported' );
136 $this->doStash( [], $this->getTestUser( [ 'bot' ] )->getUser() );
139 public function testUnrecognizedFormat() {
140 $this->setExpectedApiException(
141 [ 'apierror-badformat-generic', 'application/json', 'wikitext' ] );
143 $this->doStash( [ 'contentformat' => 'application/json' ] );
146 public function testMissingTextAndStashedTextHash() {
147 $this->setExpectedApiException( [
148 'apierror-missingparam-one-of',
149 Message
::listParam( [ '<var>stashedtexthash</var>', '<var>text</var>' ] ),
152 $this->doStash( [ 'text' => null ] );
155 public function testStashedTextHash() {
156 $res = $this->doStash();
158 $this->doStash( [ 'stashedtexthash' => $res[0]['stashedit']['texthash'] ] );
161 public function testMalformedStashedTextHash() {
162 $this->setExpectedApiException( 'apierror-stashedit-missingtext' );
163 $this->doStash( [ 'stashedtexthash' => 'abc' ] );
166 public function testMissingStashedTextHash() {
167 $this->setExpectedApiException( 'apierror-stashedit-missingtext' );
168 $this->doStash( [ 'stashedtexthash' => str_repeat( '0', 40 ) ] );
171 public function testHashNormalization() {
172 $res1 = $this->doStash( [ 'text' => "a\r\nb\rc\nd \t\n\r" ] );
173 $res2 = $this->doStash( [ 'text' => "a\nb\rc\nd" ] );
175 $this->assertSame( $res1[0]['stashedit']['texthash'], $res2[0]['stashedit']['texthash'] );
176 $this->assertSame( "a\nb\rc\nd",
177 $this->getStashedText( $res1[0]['stashedit']['texthash'] ) );
180 public function testNonexistentBaseRevId() {
181 $this->setExpectedApiException( [ 'apierror-nosuchrevid', pow( 2, 31 ) - 1 ] );
183 $name = ucfirst( __FUNCTION__
);
184 $this->editPage( $name, '' );
185 $this->doStash( [ 'title' => $name, 'baserevid' => pow( 2, 31 ) - 1 ] );
188 public function testPageWithNoRevisions() {
189 $name = ucfirst( __FUNCTION__
);
190 $rev = $this->editPage( $name, '' )->value
['revision'];
192 $this->setExpectedApiException( [ 'apierror-missingrev-pageid', $rev->getPage() ] );
194 // Corrupt the database. @todo Does the API really need to fail gracefully for this case?
195 $dbw = wfGetDB( DB_MASTER
);
198 [ 'page_latest' => 0 ],
199 [ 'page_id' => $rev->getPage() ],
203 $this->doStash( [ 'title' => $name, 'baserevid' => $rev->getId() ] );
206 public function testExistingPage() {
207 $name = ucfirst( __FUNCTION__
);
208 $rev = $this->editPage( $name, '' )->value
['revision'];
210 $this->doStash( [ 'title' => $name, 'baserevid' => $rev->getId() ] );
213 public function testInterveningEdit() {
214 $name = ucfirst( __FUNCTION__
);
215 $oldRev = $this->editPage( $name, "A\n\nB" )->value
['revision'];
216 $this->editPage( $name, "A\n\nC" );
220 'baserevid' => $oldRev->getId(),
225 public function testEditConflict() {
226 $name = ucfirst( __FUNCTION__
);
227 $oldRev = $this->editPage( $name, 'A' )->value
['revision'];
228 $this->editPage( $name, 'B' );
232 'baserevid' => $oldRev->getId(),
234 ], null, 'editconflict' );
237 public function testDeletedRevision() {
238 $name = ucfirst( __FUNCTION__
);
239 $oldRev = $this->editPage( $name, 'A' )->value
['revision'];
240 $this->editPage( $name, 'B' );
242 $this->setExpectedApiException( [ 'apierror-missingcontent-pageid', $oldRev->getPage() ] );
244 $this->revisionDelete( $oldRev );
248 'baserevid' => $oldRev->getId(),
253 public function testDeletedRevisionSection() {
254 $name = ucfirst( __FUNCTION__
);
255 $oldRev = $this->editPage( $name, 'A' )->value
['revision'];
256 $this->editPage( $name, 'B' );
258 $this->setExpectedApiException( 'apierror-sectionreplacefailed' );
260 $this->revisionDelete( $oldRev );
264 'baserevid' => $oldRev->getId(),
270 public function testPingLimiter() {
271 $this->mergeMwGlobalArrayValue( 'wgRateLimits',
272 [ 'stashedit' => [ '&can-bypass' => false, 'user' => [ 1, 60 ] ] ] );
274 $this->doStash( [ 'text' => 'A' ] );
276 $this->doStash( [ 'text' => 'B' ], null, 'ratelimited' );
280 * Shortcut for calling PageStashEdit::checkCache() without
281 * having to create Titles and Contents in every test.
284 * @param string $text The text of the article
285 * @return stdClass|bool Return value of PageStashEdit::checkCache(), false if not in cache
287 protected function doCheckCache( User
$user, $text = 'Content' ) {
288 return MediaWikiServices
::getInstance()->getPageEditStash()->checkCache(
289 Title
::newFromText( __CLASS__
),
290 new WikitextContent( $text ),
295 public function testCheckCache() {
296 $user = $this->getMutableTestUser()->getUser();
298 $this->doStash( [], $user );
300 $this->assertInstanceOf( stdClass
::class, $this->doCheckCache( $user ) );
302 // Another user doesn't see the cache
304 $this->doCheckCache( $this->getTestUser()->getUser() ),
305 'Cache is user-specific'
308 // Nor does the original one if they become a bot
309 $user->addGroup( 'bot' );
311 $this->doCheckCache( $user ),
312 "We assume bots don't have cache entries"
315 // But other groups are okay
316 $user->removeGroup( 'bot' );
317 $user->addGroup( 'sysop' );
318 $this->assertInstanceOf( stdClass
::class, $this->doCheckCache( $user ) );
321 public function testCheckCacheAnon() {
322 $user = User
::newFromName( '174.5.4.6', false );
324 $this->doStash( [], $user );
326 $this->assertInstanceOf( stdClass
::class, $this->doCheckCache( $user ) );
330 * Stash an edit some time in the past, for testing expiry and freshness logic.
332 * @param User $user Who's doing the editing
333 * @param string $text What text should be cached
334 * @param int $howOld How many seconds is "old" (we actually set it one second before this)
336 protected function doStashOld(
337 User
$user, $text = 'Content', $howOld = PageEditStash
::PRESUME_FRESH_TTL_SEC
339 $this->doStash( [ 'text' => $text ], $user );
341 // Monkey with the cache to make the edit look old. @todo Is there a less fragile way to
343 $key = $this->getStashKey( __CLASS__
, $text, $user );
345 $editStash = TestingAccessWrapper
::newFromObject(
346 MediaWikiServices
::getInstance()->getPageEditStash() );
347 $cache = $editStash->cache
;
349 $editInfo = $cache->get( $key );
350 $editInfo->output
->setCacheTime( wfTimestamp( TS_MW
,
351 wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() ) - $howOld - 1 ) );
353 $cache->set( $key, $editInfo );
356 public function testCheckCacheOldNoEdits() {
357 $user = $this->getTestSysop()->getUser();
359 $this->doStashOld( $user );
361 // Should still be good, because no intervening edits
362 $this->assertInstanceOf( stdClass
::class, $this->doCheckCache( $user ) );
365 public function testCheckCacheOldNoEditsAnon() {
366 // Specify a made-up IP address to make sure no edits are lying around
367 $user = User
::newFromName( '172.0.2.77', false );
369 $this->doStashOld( $user );
371 // Should still be good, because no intervening edits
372 $this->assertInstanceOf( stdClass
::class, $this->doCheckCache( $user ) );
375 public function testCheckCacheInterveningEdits() {
376 $user = $this->getTestSysop()->getUser();
378 $this->doStashOld( $user );
380 // Now let's also increment our editcount
381 $this->editPage( ucfirst( __FUNCTION__
), '' );
383 $user->clearInstanceCache();
384 $this->assertFalse( $this->doCheckCache( $user ),
385 "Cache should be invalidated when it's old and the user has an intervening edit" );
389 * @dataProvider signatureProvider
390 * @param string $text Which signature to test (~~~, ~~~~, or ~~~~~)
391 * @param int $ttl Expected TTL in seconds
393 public function testSignatureTtl( $text, $ttl ) {
394 $this->doStash( [ 'text' => $text ] );
396 $editStash = TestingAccessWrapper
::newFromObject(
397 MediaWikiServices
::getInstance()->getPageEditStash() );
398 $cache = $editStash->cache
;
399 $key = $this->getStashKey( __CLASS__
, $text );
401 $wrapper = TestingAccessWrapper
::newFromObject( $cache );
403 $this->assertEquals( $ttl, $wrapper->bag
[$key][HashBagOStuff
::KEY_EXP
] - time(), '', 1 );
406 public function signatureProvider() {
408 '~~~' => [ '~~~', PageEditStash
::MAX_SIGNATURE_TTL
],
409 '~~~~' => [ '~~~~', PageEditStash
::MAX_SIGNATURE_TTL
],
410 '~~~~~' => [ '~~~~~', PageEditStash
::MAX_SIGNATURE_TTL
],
414 public function testIsInternal() {
415 $res = $this->doApiRequest( [
416 'action' => 'paraminfo',
417 'modules' => 'stashedit',
420 $this->assertCount( 1, $res[0]['paraminfo']['modules'] );
421 $this->assertSame( true, $res[0]['paraminfo']['modules'][0]['internal'] );
424 public function testBusy() {
425 // @todo This doesn't work because both lock acquisitions are in the same MySQL session, so
426 // they don't conflict. How do I open a different session?
427 $this->markTestSkipped();
429 $key = $this->getStashKey();
430 $this->db
->lock( $key, __METHOD__
, 0 );
432 $this->doStash( [], null, 'busy' );
434 $this->db
->unlock( $key, __METHOD__
);