MediaWiki  1.32.0
ApiStashEditTest.php
Go to the documentation of this file.
1 <?php
2 
3 use Wikimedia\TestingAccessWrapper;
4 
12  public function setUp() {
13  parent::setUp();
14 
15  // We need caching here, but note that the cache gets cleared in between tests, so it
16  // doesn't work with @depends
17  $this->setMwGlobals( 'wgMainCacheType', 'hash' );
18  }
19 
28  protected function doStash(
29  array $params = [], User $user = null, $expectedResult = 'stashed'
30  ) {
31  $params = array_merge( [
32  'action' => 'stashedit',
33  'title' => __CLASS__,
34  'contentmodel' => 'wikitext',
35  'contentformat' => 'text/x-wiki',
36  'baserevid' => 0,
37  ], $params );
38  if ( !array_key_exists( 'text', $params ) &&
39  !array_key_exists( 'stashedtexthash', $params )
40  ) {
41  $params['text'] = 'Content';
42  }
43  foreach ( $params as $key => $val ) {
44  if ( $val === null ) {
45  unset( $params[$key] );
46  }
47  }
48 
49  if ( isset( $params['text'] ) ) {
50  $expectedText = $params['text'];
51  } elseif ( isset( $params['stashedtexthash'] ) ) {
52  $expectedText = $this->getStashedText( $params['stashedtexthash'] );
53  }
54  if ( isset( $expectedText ) ) {
55  $expectedText = rtrim( str_replace( "\r\n", "\n", $expectedText ) );
56  $expectedHash = sha1( $expectedText );
57  $origText = $this->getStashedText( $expectedHash );
58  }
59 
60  $res = $this->doApiRequestWithToken( $params, null, $user );
61 
62  $this->assertSame( $expectedResult, $res[0]['stashedit']['status'] );
63  $this->assertCount( $expectedResult === 'stashed' ? 2 : 1, $res[0]['stashedit'] );
64 
65  if ( $expectedResult === 'stashed' ) {
66  $hash = $res[0]['stashedit']['texthash'];
67 
68  $this->assertSame( $expectedText, $this->getStashedText( $hash ) );
69 
70  $this->assertSame( $expectedHash, $hash );
71 
72  if ( isset( $params['stashedtexthash'] ) ) {
73  $this->assertSame( $params['stashedtexthash'], $expectedHash, 'Sanity' );
74  }
75  } else {
76  $this->assertSame( $origText, $this->getStashedText( $expectedHash ) );
77  }
78 
79  $this->assertArrayNotHasKey( 'warnings', $res[0] );
80 
81  return $res;
82  }
83 
90  protected function getStashedText( $hash ) {
92  $key = $cache->makeKey( 'stashedit', 'text', $hash );
93  return $cache->get( $key );
94  }
95 
104  protected function getStashKey( $title = __CLASS__, $text = 'Content', User $user = null ) {
105  $titleObj = Title::newFromText( $title );
106  $content = new WikitextContent( $text );
107  if ( !$user ) {
108  $user = $this->getTestSysop()->getUser();
109  }
110  $wrapper = TestingAccessWrapper::newFromClass( ApiStashEdit::class );
111  return $wrapper->getStashKey( $titleObj, $wrapper->getContentHash( $content ), $user );
112  }
113 
114  public function testBasicEdit() {
115  $this->doStash();
116  }
117 
118  public function testBot() {
119  // @todo This restriction seems arbitrary, is there any good reason to keep it?
120  $this->setExpectedApiException( 'apierror-botsnotsupported' );
121 
122  $this->doStash( [], $this->getTestUser( [ 'bot' ] )->getUser() );
123  }
124 
125  public function testUnrecognizedFormat() {
127  [ 'apierror-badformat-generic', 'application/json', 'wikitext' ] );
128 
129  $this->doStash( [ 'contentformat' => 'application/json' ] );
130  }
131 
133  $this->setExpectedApiException( [
134  'apierror-missingparam-one-of',
135  Message::listParam( [ '<var>stashedtexthash</var>', '<var>text</var>' ] ),
136  2
137  ] );
138  $this->doStash( [ 'text' => null ] );
139  }
140 
141  public function testStashedTextHash() {
142  $res = $this->doStash();
143 
144  $this->doStash( [ 'stashedtexthash' => $res[0]['stashedit']['texthash'] ] );
145  }
146 
147  public function testMalformedStashedTextHash() {
148  $this->setExpectedApiException( 'apierror-stashedit-missingtext' );
149  $this->doStash( [ 'stashedtexthash' => 'abc' ] );
150  }
151 
152  public function testMissingStashedTextHash() {
153  $this->setExpectedApiException( 'apierror-stashedit-missingtext' );
154  $this->doStash( [ 'stashedtexthash' => str_repeat( '0', 40 ) ] );
155  }
156 
157  public function testHashNormalization() {
158  $res1 = $this->doStash( [ 'text' => "a\r\nb\rc\nd \t\n\r" ] );
159  $res2 = $this->doStash( [ 'text' => "a\nb\rc\nd" ] );
160 
161  $this->assertSame( $res1[0]['stashedit']['texthash'], $res2[0]['stashedit']['texthash'] );
162  $this->assertSame( "a\nb\rc\nd",
163  $this->getStashedText( $res1[0]['stashedit']['texthash'] ) );
164  }
165 
166  public function testNonexistentBaseRevId() {
167  $this->setExpectedApiException( [ 'apierror-nosuchrevid', pow( 2, 31 ) - 1 ] );
168 
169  $name = ucfirst( __FUNCTION__ );
170  $this->editPage( $name, '' );
171  $this->doStash( [ 'title' => $name, 'baserevid' => pow( 2, 31 ) - 1 ] );
172  }
173 
174  public function testPageWithNoRevisions() {
175  $name = ucfirst( __FUNCTION__ );
176  $rev = $this->editPage( $name, '' )->value['revision'];
177 
178  $this->setExpectedApiException( [ 'apierror-missingrev-pageid', $rev->getPage() ] );
179 
180  // Corrupt the database. @todo Does the API really need to fail gracefully for this case?
181  $dbw = wfGetDB( DB_MASTER );
182  $dbw->update(
183  'page',
184  [ 'page_latest' => 0 ],
185  [ 'page_id' => $rev->getPage() ],
186  __METHOD__
187  );
188 
189  $this->doStash( [ 'title' => $name, 'baserevid' => $rev->getId() ] );
190  }
191 
192  public function testExistingPage() {
193  $name = ucfirst( __FUNCTION__ );
194  $rev = $this->editPage( $name, '' )->value['revision'];
195 
196  $this->doStash( [ 'title' => $name, 'baserevid' => $rev->getId() ] );
197  }
198 
199  public function testInterveningEdit() {
200  $name = ucfirst( __FUNCTION__ );
201  $oldRev = $this->editPage( $name, "A\n\nB" )->value['revision'];
202  $this->editPage( $name, "A\n\nC" );
203 
204  $this->doStash( [
205  'title' => $name,
206  'baserevid' => $oldRev->getId(),
207  'text' => "D\n\nB",
208  ] );
209  }
210 
211  public function testEditConflict() {
212  $name = ucfirst( __FUNCTION__ );
213  $oldRev = $this->editPage( $name, 'A' )->value['revision'];
214  $this->editPage( $name, 'B' );
215 
216  $this->doStash( [
217  'title' => $name,
218  'baserevid' => $oldRev->getId(),
219  'text' => 'C',
220  ], null, 'editconflict' );
221  }
222 
223  public function testDeletedRevision() {
224  $name = ucfirst( __FUNCTION__ );
225  $oldRev = $this->editPage( $name, 'A' )->value['revision'];
226  $this->editPage( $name, 'B' );
227 
228  $this->setExpectedApiException( [ 'apierror-missingcontent-pageid', $oldRev->getPage() ] );
229 
230  $this->revisionDelete( $oldRev );
231 
232  $this->doStash( [
233  'title' => $name,
234  'baserevid' => $oldRev->getId(),
235  'text' => 'C',
236  ] );
237  }
238 
239  public function testDeletedRevisionSection() {
240  $name = ucfirst( __FUNCTION__ );
241  $oldRev = $this->editPage( $name, 'A' )->value['revision'];
242  $this->editPage( $name, 'B' );
243 
244  $this->setExpectedApiException( 'apierror-sectionreplacefailed' );
245 
246  $this->revisionDelete( $oldRev );
247 
248  $this->doStash( [
249  'title' => $name,
250  'baserevid' => $oldRev->getId(),
251  'text' => 'C',
252  'section' => '1',
253  ] );
254  }
255 
256  public function testPingLimiter() {
257  $this->mergeMwGlobalArrayValue( 'wgRateLimits',
258  [ 'stashedit' => [ '&can-bypass' => false, 'user' => [ 1, 60 ] ] ] );
259 
260  $this->doStash( [ 'text' => 'A' ] );
261 
262  $this->doStash( [ 'text' => 'B' ], null, 'ratelimited' );
263  }
264 
273  protected function doCheckCache( User $user, $text = 'Content' ) {
275  Title::newFromText( __CLASS__ ),
276  new WikitextContent( $text ),
277  $user
278  );
279  }
280 
281  public function testCheckCache() {
282  $user = $this->getMutableTestUser()->getUser();
283 
284  $this->doStash( [], $user );
285 
286  $this->assertInstanceOf( stdClass::class, $this->doCheckCache( $user ) );
287 
288  // Another user doesn't see the cache
289  $this->assertFalse(
290  $this->doCheckCache( $this->getTestUser()->getUser() ),
291  'Cache is user-specific'
292  );
293 
294  // Nor does the original one if they become a bot
295  $user->addGroup( 'bot' );
296  $this->assertFalse(
297  $this->doCheckCache( $user ),
298  "We assume bots don't have cache entries"
299  );
300 
301  // But other groups are okay
302  $user->removeGroup( 'bot' );
303  $user->addGroup( 'sysop' );
304  $this->assertInstanceOf( stdClass::class, $this->doCheckCache( $user ) );
305  }
306 
307  public function testCheckCacheAnon() {
308  $user = new User();
309 
310  $this->doStash( [], $user );
311 
312  $this->assertInstanceOf( stdClass::class, $this->docheckCache( $user ) );
313  }
314 
322  protected function doStashOld(
323  User $user, $text = 'Content', $howOld = ApiStashEdit::PRESUME_FRESH_TTL_SEC
324  ) {
325  $this->doStash( [ 'text' => $text ], $user );
326 
327  // Monkey with the cache to make the edit look old. @todo Is there a less fragile way to
328  // fake the time?
329  $key = $this->getStashKey( __CLASS__, $text, $user );
330 
332 
333  $editInfo = $cache->get( $key );
334  $editInfo->output->setCacheTime( wfTimestamp( TS_MW,
335  wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() ) - $howOld - 1 ) );
336 
337  $cache->set( $key, $editInfo );
338  }
339 
340  public function testCheckCacheOldNoEdits() {
341  $user = $this->getTestSysop()->getUser();
342 
343  $this->doStashOld( $user );
344 
345  // Should still be good, because no intervening edits
346  $this->assertInstanceOf( stdClass::class, $this->doCheckCache( $user ) );
347  }
348 
349  public function testCheckCacheOldNoEditsAnon() {
350  // Specify a made-up IP address to make sure no edits are lying around
351  $user = User::newFromName( '192.0.2.77', false );
352 
353  $this->doStashOld( $user );
354 
355  // Should still be good, because no intervening edits
356  $this->assertInstanceOf( stdClass::class, $this->doCheckCache( $user ) );
357  }
358 
359  public function testCheckCacheInterveningEdits() {
360  $user = $this->getTestSysop()->getUser();
361 
362  $this->doStashOld( $user );
363 
364  // Now let's also increment our editcount
365  $this->editPage( ucfirst( __FUNCTION__ ), '' );
366 
367  $this->assertFalse( $this->doCheckCache( $user ),
368  "Cache should be invalidated when it's old and the user has an intervening edit" );
369  }
370 
376  public function testSignatureTtl( $text, $ttl ) {
377  $this->doStash( [ 'text' => $text ] );
378 
380  $key = $this->getStashKey( __CLASS__, $text );
381 
382  $wrapper = TestingAccessWrapper::newFromObject( $cache );
383 
384  $this->assertEquals( $ttl, $wrapper->bag[$key][HashBagOStuff::KEY_EXP] - time(), '', 1 );
385  }
386 
387  public function signatureProvider() {
388  return [
389  '~~~' => [ '~~~', ApiStashEdit::MAX_SIGNATURE_TTL ],
390  '~~~~' => [ '~~~~', ApiStashEdit::MAX_SIGNATURE_TTL ],
391  '~~~~~' => [ '~~~~~', ApiStashEdit::MAX_SIGNATURE_TTL ],
392  ];
393  }
394 
395  public function testIsInternal() {
396  $res = $this->doApiRequest( [
397  'action' => 'paraminfo',
398  'modules' => 'stashedit',
399  ] );
400 
401  $this->assertCount( 1, $res[0]['paraminfo']['modules'] );
402  $this->assertSame( true, $res[0]['paraminfo']['modules'][0]['internal'] );
403  }
404 
405  public function testBusy() {
406  // @todo This doesn't work because both lock acquisitions are in the same MySQL session, so
407  // they don't conflict. How do I open a different session?
408  $this->markTestSkipped();
409 
410  $key = $this->getStashKey();
411  $this->db->lock( $key, __METHOD__, 0 );
412  try {
413  $this->doStash( [], null, 'busy' );
414  } finally {
415  $this->db->unlock( $key, __METHOD__ );
416  }
417  }
418 }
HashBagOStuff\KEY_EXP
const KEY_EXP
Definition: HashBagOStuff.php:38
ApiStashEditTest\testCheckCacheInterveningEdits
testCheckCacheInterveningEdits()
Definition: ApiStashEditTest.php:359
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:244
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:365
ApiStashEditTest\testCheckCacheOldNoEdits
testCheckCacheOldNoEdits()
Definition: ApiStashEditTest.php:340
MediaWikiTestCase\mergeMwGlobalArrayValue
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Definition: MediaWikiTestCase.php:901
ApiStashEditTest\testCheckCacheOldNoEditsAnon
testCheckCacheOldNoEditsAnon()
Definition: ApiStashEditTest.php:349
MediaWikiTestCase\getTestUser
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
Definition: MediaWikiTestCase.php:179
ApiStashEdit\PRESUME_FRESH_TTL_SEC
const PRESUME_FRESH_TTL_SEC
Definition: ApiStashEdit.php:45
ApiStashEditTest\testStashedTextHash
testStashedTextHash()
Definition: ApiStashEditTest.php:141
ApiStashEditTest\doStash
doStash(array $params=[], User $user=null, $expectedResult='stashed')
Make a stashedit API call with suitable default parameters.
Definition: ApiStashEditTest.php:28
ApiStashEditTest\testExistingPage
testExistingPage()
Definition: ApiStashEditTest.php:192
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1954
ApiStashEditTest\testBusy
testBusy()
Definition: ApiStashEditTest.php:405
ApiStashEditTest\getStashKey
getStashKey( $title=__CLASS__, $text='Content', User $user=null)
Return a key that can be passed to the cache to obtain a PreparedEdit object.
Definition: ApiStashEditTest.php:104
ApiStashEditTest\setUp
setUp()
Definition: ApiStashEditTest.php:12
$params
$params
Definition: styleTest.css.php:44
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:592
$res
$res
Definition: database.txt:21
User
User
Definition: All_system_messages.txt:425
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ApiStashEditTest\testBot
testBot()
Definition: ApiStashEditTest.php:118
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:63
ApiStashEditTest\getStashedText
getStashedText( $hash)
Return the text stashed for $hash.
Definition: ApiStashEditTest.php:90
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:706
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
ApiTestCase\doApiRequestWithToken
doApiRequestWithToken(array $params, array $session=null, User $user=null, $tokenType='auto')
Convenience function to access the token parameter of doApiRequest() more succinctly.
Definition: ApiTestCase.php:133
ApiStashEditTest\testIsInternal
testIsInternal()
Definition: ApiStashEditTest.php:395
DB_MASTER
const DB_MASTER
Definition: defines.php:26
WikitextContent
Content object for wiki text pages.
Definition: WikitextContent.php:35
ApiStashEditTest\testPageWithNoRevisions
testPageWithNoRevisions()
Definition: ApiStashEditTest.php:174
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ApiStashEditTest\testDeletedRevisionSection
testDeletedRevisionSection()
Definition: ApiStashEditTest.php:239
ApiStashEditTest\testMalformedStashedTextHash
testMalformedStashedTextHash()
Definition: ApiStashEditTest.php:147
MediaWikiTestCase\editPage
editPage( $pageName, $text, $summary='', $defaultNs=NS_MAIN)
Edits or creates a page/revision.
Definition: MediaWikiTestCase.php:2333
ApiTestCase
Definition: ApiTestCase.php:5
MediaWikiTestCase\revisionDelete
revisionDelete( $rev, array $value=[Revision::DELETED_TEXT=> 1], $comment='')
Revision-deletes a revision.
Definition: MediaWikiTestCase.php:2353
ApiStashEditTest\testBasicEdit
testBasicEdit()
Definition: ApiStashEditTest.php:114
MediaWikiTestCase\getMutableTestUser
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
Definition: MediaWikiTestCase.php:191
ApiStashEditTest\doStashOld
doStashOld(User $user, $text='Content', $howOld=ApiStashEdit::PRESUME_FRESH_TTL_SEC)
Stash an edit some time in the past, for testing expiry and freshness logic.
Definition: ApiStashEditTest.php:322
ApiStashEditTest\testInterveningEdit
testInterveningEdit()
Definition: ApiStashEditTest.php:199
MediaWikiTestCase\getTestSysop
static getTestSysop()
Convenience method for getting an immutable admin test user.
Definition: MediaWikiTestCase.php:203
ApiStashEditTest\signatureProvider
signatureProvider()
Definition: ApiStashEditTest.php:387
ApiStashEditTest\testHashNormalization
testHashNormalization()
Definition: ApiStashEditTest.php:157
ApiStashEditTest\testNonexistentBaseRevId
testNonexistentBaseRevId()
Definition: ApiStashEditTest.php:166
$cache
$cache
Definition: mcc.php:33
ApiTestCase\setExpectedApiException
setExpectedApiException( $msg, $code=null, array $data=null, $httpCode=0)
Expect an ApiUsageException to be thrown with the given parameters, which are the same as ApiUsageExc...
Definition: ApiTestCase.php:217
ApiStashEditTest\testPingLimiter
testPingLimiter()
Definition: ApiStashEditTest.php:256
ApiStashEditTest\testCheckCache
testCheckCache()
Definition: ApiStashEditTest.php:281
ApiStashEdit\MAX_SIGNATURE_TTL
const MAX_SIGNATURE_TTL
Definition: ApiStashEdit.php:47
$rev
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1808
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
ApiStashEditTest\testEditConflict
testEditConflict()
Definition: ApiStashEditTest.php:211
ApiStashEditTest\testMissingTextAndStashedTextHash
testMissingTextAndStashedTextHash()
Definition: ApiStashEditTest.php:132
ApiStashEditTest\testDeletedRevision
testDeletedRevision()
Definition: ApiStashEditTest.php:223
$content
$content
Definition: pageupdater.txt:72
ApiStashEditTest\testUnrecognizedFormat
testUnrecognizedFormat()
Definition: ApiStashEditTest.php:125
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
ApiStashEditTest\testMissingStashedTextHash
testMissingStashedTextHash()
Definition: ApiStashEditTest.php:152
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:47
ApiStashEditTest\doCheckCache
doCheckCache(User $user, $text='Content')
Shortcut for calling ApiStashEdit::checkCache() without having to create Titles and Contents in every...
Definition: ApiStashEditTest.php:273
ApiStashEdit\checkCache
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
Definition: ApiStashEdit.php:265
ApiStashEditTest\testCheckCacheAnon
testCheckCacheAnon()
Definition: ApiStashEditTest.php:307
ApiStashEditTest\testSignatureTtl
testSignatureTtl( $text, $ttl)
signatureProvider
Definition: ApiStashEditTest.php:376
ApiStashEditTest
ApiStashEdit API medium Database.
Definition: ApiStashEditTest.php:11