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