Debian Codegraph @

tests/phpunit/unit/includes/filebackend/FileBackendGroupTestTrait.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\FileBackend\FileBackendGroup;
4 use MediaWiki\FileBackend\FSFile\TempFSFileFactory;
5 use MediaWiki\FileBackend\LockManager\LockManagerGroupFactory;
6 use MediaWiki\Logger\LoggerFactory;
7 use MediaWiki\MainConfigNames;
8 use MediaWiki\Output\StreamFile;
9 use MediaWiki\Status\Status;
10 use Wikimedia\FileBackend\FSFileBackend;
11 use Wikimedia\Mime\MimeAnalyzer;
12 use Wikimedia\ObjectCache\BagOStuff;
13 use Wikimedia\ObjectCache\HashBagOStuff;
14 use Wikimedia\ObjectCache\WANObjectCache;
15 use Wikimedia\TestingAccessWrapper;
16
17 /**
18 * Code shared by the FileBackendGroup integration and unit tests. They need merely provide a
19 * suitable newObj() method and everything else works magically.
20 */
21 trait FileBackendGroupTestTrait {
22 /**
23 * @param array $options Dictionary to use as a source for ServiceOptions before defaults, plus
24 * the following options are available to override other arguments:
25 * * 'readOnlyMode'
26 * * 'lmgFactory'
27 * * 'mimeAnalyzer'
28 * * 'tmpFileFactory'
29 * @return FileBackendGroup
30 */
31 abstract protected function newObj( array $options = [] ): FileBackendGroup;
32
33 /**
34 * @param string $domain Expected argument that LockManagerGroupFactory::getLockManagerGroup
35 * will receive
36 * @return LockManagerGroupFactory
37 */
38 abstract protected function getLockManagerGroupFactory( $domain ): LockManagerGroupFactory;
39
40 /**
41 * @return string As from WikiMap::getCurrentWikiId()
42 */
43 abstract protected static function getWikiID();
44
45 /**
46 * null indicates that we don't have the actual object reference, but it should be an empty
47 * HashBagOStuff.
48 *
49 * @var BagOStuff|null
50 */
51 private $srvCache;
52
53 /** @var WANObjectCache */
54 private $wanCache;
55
56 /** @var LockManagerGroupFactory */
57 private $lmgFactory;
58
59 /** @var TempFSFileFactory */
60 private $tmpFileFactory;
61
62 private static function getDefaultLocalFileRepo() {
63 return [
64 'class' => LocalRepo::class,
65 'name' => 'local',
66 'directory' => 'upload-dir',
67 'thumbDir' => 'thumb/',
68 'transcodedDir' => 'transcoded/',
69 'fileMode' => 0664,
70 'scriptDirUrl' => 'script-path/',
71 'url' => 'upload-path/',
72 'hashLevels' => 2,
73 'thumbScriptUrl' => false,
74 'transformVia404' => false,
75 'deletedDir' => 'deleted/',
76 'deletedHashLevels' => 3,
77 'backend' => 'local-backend',
78 ];
79 }
80
81 private static function getDefaultOptions() {
82 return [
83 MainConfigNames::DirectoryMode => 0775,
84 MainConfigNames::FileBackends => [],
85 MainConfigNames::ForeignFileRepos => [],
86 MainConfigNames::LocalFileRepo => self::getDefaultLocalFileRepo(),
87 'fallbackWikiId' => self::getWikiID(),
88 ];
89 }
90
91 /**
92 * @covers ::__construct
93 */
94 public function testConstructor_overrideImplicitBackend() {
95 $obj = $this->newObj( [ MainConfigNames::FileBackends =>
96 [ [ 'name' => 'local-backend', 'class' => '', 'lockManager' => 'fsLockManager' ] ]
97 ] );
98 $this->assertSame( '', $obj->config( 'local-backend' )['class'] );
99 }
100
101 /**
102 * @covers ::__construct
103 */
104 public function testConstructor_backendObject() {
105 // 'backend' being an object makes that repo from configuration ignored
106 // XXX This is not documented in MainConfigSchema, does it do anything useful?
107 $obj = $this->newObj( [ MainConfigNames::ForeignFileRepos => [ [ 'backend' => (object)[] ] ] ] );
108 $this->assertSame( FSFileBackend::class, $obj->config( 'local-backend' )['class'] );
109 }
110
111 /**
112 * @dataProvider provideRegister_domainId
113 * @param string $key Key to check in return value of config()
114 * @param string|callable $expected Expected value of config()[$key], or callable returning it
115 * @param array $extraBackendsOptions To add to the FileBackends entry passed to newObj()
116 * @param array $otherExtraOptions To add to the array passed to newObj() (e.g., services)
117 * @covers ::register
118 */
119 public function testRegister(
120 $key, $expected, array $extraBackendsOptions = [], array $otherExtraOptions = []
121 ) {
122 if ( $expected instanceof Closure ) {
123 // Lame hack to get around providers being called too early
124 $expected = $expected();
125 }
126 if ( $key === 'domainId' ) {
127 // This will change the expected LMG name too
128 $otherExtraOptions['lmgFactory'] = $this->getLockManagerGroupFactory( $expected );
129 }
130 $obj = $this->newObj( $otherExtraOptions + [
131 MainConfigNames::FileBackends => [
132 $extraBackendsOptions + [
133 'name' => 'myname', 'class' => '', 'lockManager' => 'fsLockManager'
134 ]
135 ],
136 ] );
137 $this->assertSame( $expected, $obj->config( 'myname' )[$key] );
138 }
139
140 public static function provideRegister_domainId() {
141 return [
142 'domainId with neither wikiId nor domainId set' => [
143 'domainId',
144 static function () {
145 return self::getWikiID();
146 },
147 ],
148 'domainId with wikiId set but no domainId' =>
149 [ 'domainId', 'id0', [ 'wikiId' => 'id0' ] ],
150 'domainId with wikiId and domainId set' =>
151 [ 'domainId', 'dom1', [ 'wikiId' => 'id0', 'domainId' => 'dom1' ] ],
152 'readOnly without readOnly set' => [ 'readOnly', false ],
153 'readOnly with readOnly set to string' =>
154 [ 'readOnly', 'cuz', [ 'readOnly' => 'cuz' ] ],
155 'readOnly without readOnly set but with string in passed object' => [
156 'readOnly',
157 'cuz',
158 [],
159 [ 'readOnlyMode' => 'cuz' ],
160 ],
161 'readOnly with readOnly set to false but string in passed object' => [
162 'readOnly',
163 false,
164 [ 'readOnly' => false ],
165 [ 'readOnlyMode' => 'cuz' ],
166 ],
167 ];
168 }
169
170 /**
171 * @dataProvider provideRegister_exception
172 * @param array $fileBackends Value of FileBackends to pass to constructor
173 * @param string $class Expected exception class
174 * @param string $msg Expected exception message
175 * @covers ::__construct
176 * @covers ::register
177 */
178 public function testRegister_exception( $fileBackends, $class, $msg ) {
179 $this->expectException( $class );
180 $this->expectExceptionMessage( $msg );
181 $this->newObj( [ MainConfigNames::FileBackends => $fileBackends ] );
182 }
183
184 public static function provideRegister_exception() {
185 return [
186 'Nameless' => [
187 [ [] ], InvalidArgumentException::class, "Cannot register a backend with no name."
188 ],
189 'Duplicate' => [
190 [ [ 'name' => 'dupe', 'class' => '' ], [ 'name' => 'dupe' ] ],
191 LogicException::class,
192 "Backend with name 'dupe' already registered.",
193 ],
194 'Classless' => [
195 [ [ 'name' => 'classless' ] ],
196 InvalidArgumentException::class,
197 "Backend with name 'classless' has no class.",
198 ],
199 ];
200 }
201
202 /**
203 * @covers ::__construct
204 * @covers ::config
205 * @covers ::get
206 */
207 public function testGet() {
208 $backend = $this->newObj()->get( 'local-backend' );
209 $this->assertTrue( $backend instanceof FSFileBackend );
210 }
211
212 /**
213 * @covers ::get
214 */
215 public function testGetUnrecognized() {
216 $this->expectException( InvalidArgumentException::class );
217 $this->expectExceptionMessage( "No backend defined with the name 'unrecognized'." );
218 $this->newObj()->get( 'unrecognized' );
219 }
220
221 /**
222 * @covers ::__construct
223 * @covers ::config
224 */
225 public function testConfig() {
226 $obj = $this->newObj();
227 $config = $obj->config( 'local-backend' );
228
229 // XXX How to actually test that a profiler is loaded?
230 $this->assertNull( $config['profiler']( 'x' ) );
231 // Equality comparison doesn't work for closures, so just set to null
232 $config['profiler'] = null;
233
234 $this->assertEquals( [
235 'mimeCallback' => [ $obj, 'guessMimeInternal' ],
236 'obResetFunc' => 'wfResetOutputBuffers',
237 'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
238 'tmpFileFactory' => $this->tmpFileFactory,
239 'statusWrapper' => [ Status::class, 'wrap' ],
240 'wanCache' => $this->wanCache,
241 // If $this->srvCache is null, we don't know what it should be, so just fill in the
242 // actual value. Equality to a new HashBagOStuff doesn't work because of the token.
243 'srvCache' => $this->srvCache ?? $config['srvCache'],
244 'logger' => LoggerFactory::getInstance( 'FileOperation' ),
245 // This was set to null above in $config, it's not really null
246 'profiler' => null,
247 'name' => 'local-backend',
248 'containerPaths' => [
249 'local-public' => 'upload-dir',
250 'local-thumb' => 'thumb/',
251 'local-transcoded' => 'transcoded/',
252 'local-deleted' => 'deleted/',
253 'local-temp' => 'upload-dir/temp',
254 ],
255 'fileMode' => 0664,
256 'directoryMode' => 0775,
257 'domainId' => self::getWikiID(),
258 'readOnly' => false,
259 'class' => FSFileBackend::class,
260 'lockManager' =>
261 $this->lmgFactory->getLockManagerGroup( self::getWikiID() )->get( 'fsLockManager' ),
262 ], $config );
263
264 // For config values that are objects, check object identity.
265 $this->assertSame( [ $obj, 'guessMimeInternal' ], $config['mimeCallback'] );
266 $this->assertSame( $this->tmpFileFactory, $config['tmpFileFactory'] );
267 $this->assertSame( $this->wanCache, $config['wanCache'] );
268 if ( $this->srvCache === null ) {
269 $this->assertInstanceOf( HashBagOStuff::class, $config['srvCache'] );
270 $this->assertSame(
271 [], TestingAccessWrapper::newFromObject( $config['srvCache'] )->bag );
272 } else {
273 $this->assertSame( $this->srvCache, $config['srvCache'] );
274 }
275 }
276
277 /**
278 * @dataProvider provideConfig_default
279 * @param string $expected Expected default value
280 * @param string $inputName Name to set to null in LocalFileRepo setting
281 * @param string|array $key Key to check in array returned by config(), or array [ 'key1',
282 * 'key2' ] for nested key
283 * @covers ::__construct
284 * @covers ::config
285 */
286 public function testConfig_defaultNull( $expected, $inputName, $key ) {
287 $config = self::getDefaultLocalFileRepo();
288 $config[$inputName] = null;
289
290 $result = $this->newObj( [ MainConfigNames::LocalFileRepo => $config ] )->config( 'local-backend' );
291
292 $actual = is_string( $key ) ? $result[$key] : $result[$key[0]][$key[1]];
293
294 $this->assertSame( $expected, $actual );
295 }
296
297 /**
298 * @dataProvider provideConfig_default
299 * @param string $expected Expected default value
300 * @param string $inputName Name to unset in LocalFileRepo setting
301 * @param string|array $key Key to check in array returned by config(), or array [ 'key1',
302 * 'key2' ] for nested key
303 * @covers ::__construct
304 * @covers ::config
305 */
306 public function testConfig_defaultUnset( $expected, $inputName, $key ) {
307 $config = self::getDefaultLocalFileRepo();
308 unset( $config[$inputName] );
309
310 $result = $this->newObj( [ MainConfigNames::LocalFileRepo => $config ] )->config( 'local-backend' );
311
312 $actual = is_string( $key ) ? $result[$key] : $result[$key[0]][$key[1]];
313
314 $this->assertSame( $expected, $actual );
315 }
316
317 public static function provideConfig_default() {
318 return [
319 'deletedDir' => [ false, 'deletedDir', [ 'containerPaths', 'local-deleted' ] ],
320 'thumbDir' => [ 'upload-dir/thumb', 'thumbDir', [ 'containerPaths', 'local-thumb' ] ],
321 'transcodedDir' => [
322 'upload-dir/transcoded', 'transcodedDir', [ 'containerPaths', 'local-transcoded' ]
323 ],
324 'fileMode' => [ 0644, 'fileMode', 'fileMode' ],
325 ];
326 }
327
328 /**
329 * @covers ::config
330 */
331 public function testConfigUnrecognized() {
332 $this->expectException( InvalidArgumentException::class );
333 $this->expectExceptionMessage( "No backend defined with the name 'unrecognized'." );
334 $this->newObj()->config( 'unrecognized' );
335 }
336
337 /**
338 * @dataProvider provideBackendFromPath
339 * @covers ::backendFromPath
340 * @param string|null $expected Name of backend that will be returned from 'get', or null
341 * @param string $storagePath
342 */
343 public function testBackendFromPath( $expected, $storagePath ) {
344 $obj = $this->newObj( [ MainConfigNames::FileBackends => [
345 [ 'name' => '', 'class' => stdClass::class, 'lockManager' => 'fsLockManager' ],
346 [ 'name' => 'a', 'class' => stdClass::class, 'lockManager' => 'fsLockManager' ],
347 [ 'name' => 'b', 'class' => stdClass::class, 'lockManager' => 'fsLockManager' ],
348 ] ] );
349 $this->assertSame(
350 $expected === null ? null : $obj->get( $expected ),
351 $obj->backendFromPath( $storagePath )
352 );
353 }
354
355 public static function provideBackendFromPath() {
356 return [
357 'Empty string' => [ null, '' ],
358 'mwstore://' => [ null, 'mwstore://' ],
359 'mwstore://a' => [ null, 'mwstore://a' ],
360 'mwstore:///' => [ null, 'mwstore:///' ],
361 'mwstore://a/' => [ null, 'mwstore://a/' ],
362 'mwstore://a//' => [ null, 'mwstore://a//' ],
363 'mwstore://a/b' => [ 'a', 'mwstore://a/b' ],
364 'mwstore://a/b/' => [ 'a', 'mwstore://a/b/' ],
365 'mwstore://a/b////' => [ 'a', 'mwstore://a/b////' ],
366 'mwstore://a/b/c' => [ 'a', 'mwstore://a/b/c' ],
367 'mwstore://a/b/c/d' => [ 'a', 'mwstore://a/b/c/d' ],
368 'mwstore://b/b' => [ 'b', 'mwstore://b/b' ],
369 'mwstore://c/b' => [ null, 'mwstore://c/b' ],
370 ];
371 }
372
373 /**
374 * @dataProvider provideGuessMimeInternal
375 * @covers ::guessMimeInternal
376 * @param string $storagePath
377 * @param string|null $content
378 * @param string|null $fsPath
379 * @param string|null $expectedExtensionType Expected return of
380 * MimeAnalyzer::getMimeTypeFromExtensionOrNull
381 * @param string|null $expectedGuessedMimeType Expected return value of
382 * MimeAnalyzer::guessMimeType (null if expected not to be called)
383 */
384 public function testGuessMimeInternal(
385 $storagePath,
386 $content,
387 $fsPath,
388 $expectedExtensionType,
389 $expectedGuessedMimeType
390 ) {
391 $mimeAnalyzer = $this->createNoOpMock( MimeAnalyzer::class,
392 [ 'getMimeTypeFromExtensionOrNull', 'guessMimeType' ] );
393 $mimeAnalyzer->expects( $this->once() )->method( 'getMimeTypeFromExtensionOrNull' )
394 ->willReturn( $expectedExtensionType );
395 $tmpFileFactory = $this->createNoOpMock( TempFSFileFactory::class, [ 'newTempFSFile' ] );
396
397 if ( !$expectedExtensionType && $fsPath ) {
398 $tmpFileFactory->expects( $this->never() )->method( 'newTempFSFile' );
399 $mimeAnalyzer->expects( $this->once() )->method( 'guessMimeType' )
400 ->with( $fsPath, false )->willReturn( $expectedGuessedMimeType );
401 } elseif ( !$expectedExtensionType && $content !== null && $content !== '' ) {
402 // XXX What should we do about the file creation here? Really we should mock
403 // file_put_contents() somehow. It's not very nice to ignore the value of
404 // $wgTmpDirectory.
405 $tmpFile = ( new TempFSFileFactory() )->newTempFSFile( 'mime_', '' );
406
407 $tmpFileFactory->expects( $this->once() )->method( 'newTempFSFile' )
408 ->with( 'mime_', '' )->willReturn( $tmpFile );
409 $mimeAnalyzer->expects( $this->once() )->method( 'guessMimeType' )
410 ->with( $tmpFile->getPath(), false )->willReturn( $expectedGuessedMimeType );
411 } else {
412 $tmpFileFactory->expects( $this->never() )->method( 'newTempFSFile' );
413 $mimeAnalyzer->expects( $this->never() )->method( 'guessMimeType' );
414 }
415
416 $obj = $this->newObj( [
417 'mimeAnalyzer' => $mimeAnalyzer,
418 'tmpFileFactory' => $tmpFileFactory,
419 ] );
420
421 $this->assertSame( $expectedExtensionType ?? $expectedGuessedMimeType ?? 'unknown/unknown',
422 $obj->guessMimeInternal( $storagePath, $content, $fsPath ) );
423 }
424
425 public static function provideGuessMimeInternal() {
426 return [
427 'With extension' =>
428 [ 'foo.txt', null, null, 'text/plain', null ],
429 'No extension' =>
430 [ 'foo', null, null, null, null ],
431 'Empty content, with extension' =>
432 [ 'foo.txt', '', null, 'text/plain', null ],
433 'Empty content, no extension' =>
434 [ 'foo', '', null, null, null ],
435 'Non-empty content, with extension' =>
436 [ 'foo.txt', '<b>foo</b>', null, 'text/plain', null ],
437 'Non-empty content, no extension' =>
438 [ 'foo', '<b>foo</b>', null, null, 'text/html' ],
439 'Empty path, with extension' =>
440 [ 'foo.txt', null, '', 'text/plain', null ],
441 'Empty path, no extension' =>
442 [ 'foo', null, '', null, null ],
443 'Non-empty path, with extension' =>
444 [ 'foo.txt', null, '/bogus/path', 'text/plain', null ],
445 'Non-empty path, no extension' =>
446 [ 'foo', null, '/bogus/path', null, 'text/html' ],
447 'Empty path and content, with extension' =>
448 [ 'foo.txt', '', '', 'text/plain', null ],
449 'Empty path and content, no extension' =>
450 [ 'foo', '', '', null, null ],
451 'Non-empty path and content, with extension' =>
452 [ 'foo.txt', '<b>foo</b>', '/bogus/path', 'text/plain', null ],
453 'Non-empty path and content, no extension' =>
454 [ 'foo', '<b>foo</b>', '/bogus/path', null, 'image/jpeg' ],
455 ];
456 }
457 }