Debian Codegraph @

tests/phpunit/unit/includes/libs/filebackend/FileBackendTest.php

raw symbols SCIP
1 <?php
2
3 declare( strict_types = 1 );
4
5 namespace Wikimedia\Tests\FileBackend;
6
7 use Closure;
8 use InvalidArgumentException;
9 use LockManager;
10 use MediaWiki\FileBackend\FSFile\TempFSFileFactory;
11 use MediaWikiUnitTestCase;
12 use PHPUnit\Framework\MockObject\MockObject;
13 use Psr\Log\NullLogger;
14 use ScopedLock;
15 use StatusValue;
16 use Wikimedia\FileBackend\FileBackend;
17 use Wikimedia\ScopedCallback;
18 use Wikimedia\TestingAccessWrapper;
19
20 /**
21 * @covers \Wikimedia\FileBackend\FileBackend
22 */
23 class FileBackendTest extends MediaWikiUnitTestCase {
24 /**
25 * createMock() stubs out all methods, which isn't desirable for testing an abstract base class,
26 * since we often want to test that the base class calls certain methods that the derived class
27 * is meant to override. getMockBuilder() can be set to override only certain methods, but then
28 * you have to manually specify all abstract methods or else it doesn't work.
29 * getMockForAbstractClass() automatically fills in stubs for the abstract methods, but by
30 * default doesn't allow overriding any other methods. So we have to write our own.
31 *
32 * @param string|array ...$args Zero or more of the following:
33 * - A nonempty associative array, interpreted as $config to be passed to the constructor. The
34 * 'name' and 'domainId' will be given default values if not present.
35 * - A nonempty indexed array or a string, interpreted as a list of methods to override.
36 * - An empty array, which is ignored.
37 * @return FileBackend|MockObject A mock with no methods overridden except those specified in
38 * $methodsToMock, and all abstract methods.
39 */
40 private function newMockFileBackend( ...$args ): FileBackend {
41 $methodsToMock = [];
42 $config = [];
43 foreach ( $args as $arg ) {
44 if ( is_string( $arg ) ) {
45 $methodsToMock = [ $arg ];
46 } elseif ( is_array( $arg ) ) {
47 if ( isset( $arg[0] ) ) {
48 $methodsToMock = $arg;
49 } elseif ( $arg ) {
50 $config = $arg;
51 }
52 } else {
53 throw new InvalidArgumentException(
54 'Arguments must be strings or nonempty arrays' );
55 }
56 }
57
58 $config += [ 'name' => 'test_name' ];
59 if ( !array_key_exists( 'wikiId', $config ) ) {
60 $config += [ 'domainId' => '' ];
61 }
62
63 return $this->getMockBuilder( FileBackend::class )
64 ->setConstructorArgs( [ $config ] )
65 ->onlyMethods( $methodsToMock )
66 ->getMockForAbstractClass();
67 }
68
69 /**
70 * @dataProvider provideConstruct_validName
71 */
72 public function testConstruct_validName( $name ): void {
73 $this->newMockFileBackend( [ 'name' => $name ] );
74
75 // No exception
76 $this->assertTrue( true );
77 }
78
79 public static function provideConstruct_validName(): array {
80 return [
81 'simple' => [ 'foobar' ],
82 'dash and underscore' => [ 'foo_bar-baz' ],
83 'capital and numbers' => [ 'Duck-Car313' ],
84 '255 chars' => [ str_repeat( 'a', 255 ) ],
85 ];
86 }
87
88 /**
89 * @dataProvider provideConstruct_invalidName
90 * @param mixed $name
91 */
92 public function testConstruct_invalidName( $name ): void {
93 $this->expectException( InvalidArgumentException::class );
94 $this->expectExceptionMessage( "Backend name '$name' is invalid." );
95
96 $this->newMockFileBackend( [ 'name' => $name, 'domainId' => false ] );
97 }
98
99 public static function provideConstruct_invalidName(): array {
100 return [
101 'Empty string' => [ '' ],
102 'Illegal slash' => [ 'foo/bar' ],
103 'Illegal space' => [ 'foo bar' ],
104 'Illegal percent' => [ 'foo%20bar' ],
105 '256 chars' => [ str_repeat( 'a', 256 ) ],
106 'Bang' => [ '!' ],
107 'With space' => [ 'a b' ],
108 'False' => [ false ],
109 'Null' => [ null ],
110 'Positive float' => [ 13.402 ],
111 'Negative float' => [ -13.402 ],
112 'True' => [ true ],
113 'Positive integer' => [ 7 ],
114 'Zero integer' => [ 0 ],
115 'Zero float' => [ 0.0 ],
116 'Negative integer' => [ -7 ],
117 ];
118 }
119
120 public function testConstruct_noName(): void {
121 $this->expectException( InvalidArgumentException::class );
122 $this->expectExceptionMessage( 'Backend name not specified' );
123
124 $this->getMockBuilder( FileBackend::class )
125 ->setConstructorArgs( [ [] ] )
126 ->getMock();
127 }
128
129 /**
130 * @dataProvider provideConstruct_validDomainId
131 */
132 public function testConstruct_validDomainId( string $domainId ): void {
133 $this->newMockFileBackend( [ 'domainId' => $domainId ] );
134
135 // No exception
136 $this->assertTrue( true );
137 }
138
139 /**
140 * @dataProvider provideConstruct_validDomainId
141 */
142 public function testConstruct_validWikiId( string $wikiId ): void {
143 $this->newMockFileBackend( [ 'wikiId' => $wikiId ] );
144
145 // No exception
146 $this->assertTrue( true );
147 }
148
149 public static function provideConstruct_validDomainId(): array {
150 return [
151 'Empty string' => [ '' ],
152 '1000 chars' => [ str_repeat( 'a', 1000 ) ],
153 'Null character' => [ "\0" ],
154 'Invalid UTF-8' => [ "\xff" ],
155 ];
156 }
157
158 /**
159 * @dataProvider provideConstruct_invalidDomainId
160 */
161 public function testConstruct_invalidDomainId( $domainId ): void {
162 $this->expectException( InvalidArgumentException::class );
163 $this->expectExceptionMessage( "Backend domain ID not provided for 'test_name'." );
164
165 $this->newMockFileBackend( [ 'domainId' => $domainId ] );
166 }
167
168 public static function provideConstruct_invalidDomainId(): array {
169 return [
170 // We don't include null because that will fall back to wikiId
171 'False' => [ false ],
172 'True' => [ true ],
173 'Integer' => [ 7 ],
174 'Function' => [ static function () {
175 } ],
176 'Float' => [ -13.402 ],
177 'Object' => [ (object)[] ],
178 'Array' => [ [] ],
179 ];
180 }
181
182 /**
183 * @dataProvider provideConstruct_invalidWikiId
184 */
185 public function testConstruct_invalidWikiId( $wikiId ): void {
186 $this->expectException( InvalidArgumentException::class );
187 $this->expectExceptionMessage( "Backend domain ID not provided for 'test_name'." );
188
189 $this->newMockFileBackend( [ 'wikiId' => $wikiId ] );
190 }
191
192 public static function provideConstruct_invalidWikiId(): array {
193 return [
194 'Null' => [ null ],
195 ] + self::provideConstruct_invalidDomainId();
196 }
197
198 public function testConstruct_noDomainId(): void {
199 $this->expectException( InvalidArgumentException::class );
200 $this->expectExceptionMessage( "Backend domain ID not provided for 'test_name'" );
201
202 $this->getMockBuilder( FileBackend::class )
203 ->setConstructorArgs( [ [ 'name' => 'test_name' ] ] )
204 ->getMock();
205 }
206
207 /**
208 * @dataProvider provideConstruct_properties
209 * @param string $property
210 * @param mixed $expected
211 * @param array $config Can also include the key 'inexact' to tell us to not check equality
212 * strictly.
213 */
214 public function testConstruct_properties(
215 string $property, $expected, array $config = []
216 ): void {
217 $backend = $this->newMockFileBackend( $config );
218
219 if ( $expected instanceof Closure ) {
220 $expected = $expected( $backend );
221 }
222
223 $assertMethod = isset( $config['inexact'] ) ? 'assertEquals' : 'assertSame';
224 unset( $config['inexact'] );
225
226 // We need to test this for the sake of subclasses that actually use the property. There
227 // doesn't seem to be any better way to do it. It shouldn't be tested in the subclasses,
228 // because we're testing the behavior of this class' constructor. We could make our own
229 // subclass, but we'd have to stub 26 abstract methods.
230 $this->$assertMethod( $expected,
231 TestingAccessWrapper::newFromObject( $backend )->$property );
232 }
233
234 public static function provideConstruct_properties(): array {
235 $tmpFileFactory = new TempFSFileFactory( 'some_unique_path' );
236
237 return [
238 'parallelize default value' => [ 'parallelize', 'off' ],
239 'parallelize null' => [ 'parallelize', 'off', [ 'parallelize' => null ] ],
240 'parallelize cast to string' => [ 'parallelize', '1', [ 'parallelize' => true ] ],
241 'parallelize case-preserving' =>
242 [ 'parallelize', 'iMpLiCiT', [ 'parallelize' => 'iMpLiCiT' ] ],
243
244 'concurrency default value' => [ 'concurrency', 50 ],
245 'concurrency null' => [ 'concurrency', 50, [ 'concurrency' => null ] ],
246 'concurrency cast to int' => [ 'concurrency', 51, [ 'concurrency' => '51x' ] ],
247
248 'obResetFunc default value' =>
249 [ 'obResetFunc', [ FileBackend::class, 'resetOutputBufferTheDefaultWay' ] ],
250 'obResetFunc null' => [
251 'obResetFunc',
252 [ FileBackend::class, 'resetOutputBufferTheDefaultWay' ],
253 [ 'obResetFunc' => null ]
254 ],
255 'obResetFunc set' => [
256 'obResetFunc',
257 'wfSomeImaginaryFunction',
258 [ 'obResetFunc' => 'wfSomeImaginaryFunction' ]
259 ],
260
261 'headerFunc default value' => [ 'headerFunc', 'header' ],
262 'headerFunc set' => [ 'headerFunc', 'myHeaderFunc', [ 'headerFunc' => 'myHeaderFunc' ] ],
263
264 'profiler default value' => [ 'profiler', null ],
265 'profiler not callable' => [ 'profiler', null, [ 'profiler' => '!' ] ],
266
267 'logger default value' => [ 'logger', new NullLogger, [ 'inexact' => true ] ],
268 'logger set' => [ 'logger', 'abcd', [ 'logger' => 'abcd' ] ],
269
270 'statusWrapper default value' => [ 'statusWrapper', null ],
271
272 'tmpFileFactory default value' =>
273 [ 'tmpFileFactory', new TempFSFileFactory, [ 'inexact' => true ] ],
274 'tmpDirectory null' => [ 'tmpFileFactory', new TempFSFileFactory,
275 [ 'tmpDirectory' => null, 'inexact' => true ] ],
276 'tmpDirectory set' => [ 'tmpFileFactory', new TempFSFileFactory( 'dir' ),
277 [ 'tmpDirectory' => 'dir', 'inexact' => true ] ],
278 'tmpFileFactory null' => [ 'tmpFileFactory', new TempFSFileFactory,
279 [ 'tmpFileFactory' => null, 'inexact' => true ] ],
280 'tmpFileFactory set' => [ 'tmpFileFactory', $tmpFileFactory,
281 [ 'tmpFileFactory' => $tmpFileFactory ] ],
282 'tmpDirectory and tmpFileFactory set' => [
283 'tmpFileFactory',
284 new TempFSFileFactory( 'dir' ),
285 [ 'tmpDirectory' => 'dir', 'tmpFileFactory' => $tmpFileFactory, 'inexact' => true ],
286 ],
287 'tmpDirectory null and tmpFileFactory set' => [ 'tmpFileFactory', $tmpFileFactory,
288 [ 'tmpDirectory' => null, 'tmpFileFactory' => $tmpFileFactory ] ],
289 ];
290 }
291
292 public function testSetLogger(): void {
293 $backend = $this->newMockFileBackend();
294 $logger = new NullLogger;
295 // See comment in testConstruct_properties about use of TestingAccessWrapper.
296 $this->assertNotSame( $logger, TestingAccessWrapper::newFromObject( $backend )->logger );
297 $backend->setLogger( $logger );
298 $this->assertSame( $logger, TestingAccessWrapper::newFromObject( $backend )->logger );
299 }
300
301 public function testGetName(): void {
302 $backend = $this->newMockFileBackend();
303 $this->assertSame( 'test_name', $backend->getName() );
304 }
305
306 /**
307 * @dataProvider provideGetDomainId
308 */
309 public function testGetDomainId( array $config ): void {
310 $backend = $this->newMockFileBackend( $config );
311 $this->assertSame( 'test_domain', $backend->getDomainId() );
312 }
313
314 /**
315 * @dataProvider provideGetDomainId
316 */
317 public function testGetWikiId( array $config ): void {
318 $backend = $this->newMockFileBackend( $config );
319 $this->assertSame( 'test_domain', $backend->getWikiId() );
320 }
321
322 public static function provideGetDomainId(): array {
323 return [
324 'Only domainId' => [ [ 'domainId' => 'test_domain' ] ],
325 'Only wikiId' => [ [ 'wikiId' => 'test_domain' ] ],
326 'null domainId' => [ [ 'domainId' => null, 'wikiId' => 'test_domain' ] ],
327 'wikiId is ignored if domainId is present' =>
328 [ [ 'domainId' => 'test_domain', 'wikiId' => 'other_domain' ] ],
329 ];
330 }
331
332 public function testIsReadOnly_default(): void {
333 $backend = $this->newMockFileBackend();
334 $this->assertFalse( $backend->isReadOnly() );
335 $this->assertFalse( $backend->getReadOnlyReason() );
336 }
337
338 public function testIsReadOnly(): void {
339 $backend = $this->newMockFileBackend( [ 'readOnly' => '.' ] );
340 $this->assertTrue( $backend->isReadOnly() );
341 $this->assertSame( '.', $backend->getReadOnlyReason() );
342 }
343
344 public function testGetFeatures(): void {
345 $backend = $this->newMockFileBackend();
346 $this->assertSame( FileBackend::ATTR_UNICODE_PATHS, $backend->getFeatures() );
347 }
348
349 /**
350 * @dataProvider provideHasFeatures
351 */
352 public function testHasFeatures(
353 bool $expected, int $actualFeatures, int $testedFeatures
354 ): void {
355 $backend = $this->createMock( FileBackend::class );
356 $backend->method( 'getFeatures' )->willReturn( $actualFeatures );
357
358 $this->assertSame( $expected, $backend->hasFeatures( $testedFeatures ) );
359 }
360
361 public static function provideHasFeatures(): array {
362 return [
363 'Nothing has nothing' => [ true, 0, 0 ],
364 "Nothing doesn't have something" => [ false, 0, 1 ],
365 'Something has nothing' => [ true, 1, 0 ],
366 'Something has itself' => [ true, 1, 1 ],
367 "Something doesn't have something else" => [ false, 0b01, 0b10 ],
368 "Something doesn't have itself and something else" => [ false, 0b01, 0b11 ],
369 'Two things have the first one' => [ true, 0b11, 0b01 ],
370 'Two things have the second one' => [ true, 0b11, 0b10 ],
371 'Two things have both' => [ true, 0b11, 0b11 ],
372 "Two things don't have a third" => [ false, 0b11, 0b100 ],
373 ];
374 }
375
376 /**
377 * @dataProvider provideReadOnly
378 */
379 public function testReadOnly( string $method ): void {
380 $backend = $this->newMockFileBackend( [ 'readOnly' => '.' ] );
381 $status = $backend->$method( [] );
382 $this->assertStatusError( 'backend-fail-readonly', $status );
383 }
384
385 public static function provideReadOnly(): array {
386 return [
387 'doOperations' => [ 'doOperations', 'doOperationsInternal', [ [ [] ] ] ],
388 'doOperation' => [ 'doOperation', 'doOperationsInternal', [ [ 'op' => '' ] ] ],
389 'doQuickOperations' => [ 'doQuickOperations', 'doQuickOperationsInternal', [ [ [] ] ] ],
390 'doQuickOperation' => [
391 'doQuickOperation',
392 'doQuickOperationsInternal',
393 [ [ 'op' => '' ] ]
394 ],
395 'prepare' => [ 'prepare', 'doPrepare' ],
396 'secure' => [ 'secure', 'doSecure' ],
397 'publish' => [ 'publish', 'doPublish' ],
398 'clean' => [ 'clean', 'doClean' ],
399 ];
400 }
401
402 /**
403 * @dataProvider provideReadOnly
404 * @param string $method Method to call
405 * @param string $internalMethod Internal method the call will be forwarded to
406 * @param array $args To be passed to $method before a final argument of
407 * [ 'bypassReadOnly' => true ]
408 */
409 public function testDoOperations_bypassReadOnly(
410 string $method, string $internalMethod, array $args = []
411 ): void {
412 $backend = $this->newMockFileBackend( [ 'readOnly' => '.' ], $internalMethod );
413 $backend->expects( $this->once() )->method( $internalMethod )
414 ->willReturn( StatusValue::newGood( 'myvalue' ) );
415
416 $status = $backend->$method( ...array_merge( $args, [ [ 'bypassReadOnly' => true ] ] ) );
417
418 $this->assertStatusGood( $status );
419 $this->assertStatusValue( 'myvalue', $status );
420 }
421
422 /**
423 * @dataProvider provideDoMultipleOperations
424 */
425 public function testDoOperations_noOp( string $method ): void {
426 $backend = $this->newMockFileBackend(
427 [ 'doOperationsInternal', 'doQuickOperationsInternal' ] );
428 $backend->expects( $this->never() )->method( 'doOperationsInternal' );
429 $backend->expects( $this->never() )->method( 'doQuickOperationsInternal' );
430
431 $status = $backend->$method( [] );
432 $this->assertStatusGood( $status );
433 }
434
435 public static function provideDoMultipleOperations(): array {
436 return [
437 'doOperations' => [ 'doOperations' ],
438 'doQuickOperations' => [ 'doQuickOperations' ],
439 ];
440 }
441
442 /**
443 * @dataProvider provideDoOperations
444 * @param string $method 'doOperation' or 'doOperations'
445 */
446 public function testDoOperations_nonLockingNoForce( string $method ): void {
447 $backend = $this->newMockFileBackend( [ 'doOperationsInternal' ] );
448 $backend->expects( $this->once() )->method( 'doOperationsInternal' )
449 ->with( [ [] ], [] );
450 $backend->$method( $method === 'doOperation' ? [] : [ [] ], [ 'nonLocking' => true ] );
451 }
452
453 public static function provideDoOperations(): array {
454 return [
455 'doOperations' => [ 'doOperations' ],
456 'doOperation' => [ 'doOperation' ],
457 ];
458 }
459
460 /**
461 * @dataProvider provideDoOperations
462 * @param string $method 'doOperation' or 'doOperations'
463 */
464 public function testDoOperations_nonLockingForce( string $method ): void {
465 $backend = $this->newMockFileBackend( [ 'doOperationsInternal' ] );
466 $backend->expects( $this->once() )->method( 'doOperationsInternal' )
467 ->with( [ [] ], [ 'nonLocking' => true, 'force' => true ] );
468 $backend->$method(
469 $method === 'doOperation' ? [] : [ [] ],
470 [ 'nonLocking' => true, 'force' => true ]
471 );
472 }
473
474 // XXX Can't test newScopedIgnoreUserAbort() because it's a no-op in CLI
475
476 /**
477 * @dataProvider provideAction
478 * @param string $prefix '' or 'quick'
479 * @param string $action
480 */
481 public function testAction( string $prefix, string $action ): void {
482 $backend = $this->newMockFileBackend( 'do' . ucfirst( $prefix ) . 'OperationsInternal' );
483 $expectedOp = [ 'op' => $action, 'foo' => 'bar' ];
484 if ( $prefix === 'quick' ) {
485 $expectedOp['overwrite'] = true;
486 }
487 $backend->expects( $this->once() )
488 ->method( 'do' . ucfirst( $prefix ) . 'OperationsInternal' )
489 ->with( [ $expectedOp ], [ 'baz' => 'quuz' ] )
490 ->willReturn( StatusValue::newGood( 'myvalue' ) );
491
492 $method = $prefix ? $prefix . ucfirst( $action ) : $action;
493 $status = $backend->$method( [ 'op' => 'ignored', 'foo' => 'bar' ], [ 'baz' => 'quuz' ] );
494
495 $this->assertStatusOK( $status );
496 $this->assertStatusValue( 'myvalue', $status );
497 }
498
499 public static function provideAction(): array {
500 $ret = [];
501 foreach ( [ '', 'quick' ] as $prefix ) {
502 foreach ( [ 'create', 'store', 'copy', 'move', 'delete', 'describe' ] as $action ) {
503 $key = $prefix ? $prefix . ucfirst( $action ) : $action;
504 $ret[$key] = [ $prefix, $action ];
505 }
506 }
507 return $ret;
508 }
509
510 /**
511 * @dataProvider provideForwardToDo
512 */
513 public function testForwardToDo( string $method ): void {
514 $backend = $this->newMockFileBackend( 'do' . ucfirst( $method ) );
515 $backend->expects( $this->once() )->method( 'do' . ucfirst( $method ) )
516 ->with( [ 'foo' => 'bar' ] )
517 ->willReturn( StatusValue::newGood( 'myvalue' ) );
518
519 $status = $backend->$method( [ 'foo' => 'bar' ] );
520
521 $this->assertStatusGood( $status );
522 $this->assertStatusValue( 'myvalue', $status );
523 }
524
525 public static function provideForwardToDo(): array {
526 return [
527 'prepare' => [ 'prepare' ],
528 'secure' => [ 'secure' ],
529 'publish' => [ 'publish' ],
530 'clean' => [ 'clean' ],
531 ];
532 }
533
534 /**
535 * @dataProvider provideForwardToMulti
536 */
537 public function testForwardToMulti( string $method ): void {
538 $backend = $this->newMockFileBackend( "{$method}Multi" );
539 $backend->expects( $this->once() )->method( "{$method}Multi" )
540 ->with( [ 'srcs' => [ 'mysrc' ], 'foo' => 'bar', 'src' => 'mysrc' ] )
541 ->willReturn( [ 'mysrc' => 'mycontents' ] );
542
543 $result = $backend->$method( [ 'srcs' => 'ignored', 'foo' => 'bar', 'src' => 'mysrc' ] );
544
545 $this->assertSame( 'mycontents', $result );
546 }
547
548 public static function provideForwardToMulti(): array {
549 return [
550 'getFileContents' => [ 'getFileContents' ],
551 'getLocalReference' => [ 'getLocalReference' ],
552 'getLocalCopy' => [ 'getLocalCopy' ],
553 ];
554 }
555
556 /**
557 * @dataProvider provideForwardFromTop
558 */
559 public function testForwardFromTop( string $methodSuffix ): void {
560 $backend = $this->newMockFileBackend( "get$methodSuffix" );
561 $backend->expects( $this->once() )->method( "get$methodSuffix" )
562 ->with( [ 'topOnly' => true, 'foo' => 'bar' ] )
563 ->willReturn( [ 'something' ] );
564
565 $method = "getTop$methodSuffix";
566 $result = $backend->$method( [ 'topOnly' => 'ignored', 'foo' => 'bar' ] );
567
568 $this->assertSame( [ 'something' ], $result );
569 }
570
571 public static function provideForwardFromTop(): array {
572 return [
573 'getTopDirectoryList' => [ 'DirectoryList' ],
574 'getTopFileList' => [ 'FileList' ],
575 ];
576 }
577
578 /**
579 * @dataProvider provideLockUnlockFiles
580 * @param string $method
581 * @param int|null $timeout Only relevant for lockFiles
582 */
583 public function testLockUnlockFiles( string $method, ?int $timeout = null ): void {
584 $args = [ [ 'mwstore://a/b/', 'mwstore://c/d//e' ], LockManager::LOCK_SH ];
585
586 $mockLm = $this->getMockBuilder( LockManager::class )
587 ->disableOriginalConstructor()
588 ->onlyMethods( [ 'do' . ucfirst( $method ) . 'ByType', 'doLock', 'doUnlock' ] )
589 ->getMock();
590 // XXX PHPUnit can't override final methods (T231419)
591 //$mockLm->expects( $this->once() )->method( $method )
592 // ->with( ...array_merge( $args, [ $timeout ?? 0 ] ) )
593 // ->willReturn( StatusValue::newGood( 'myvalue' ) );
594 //$mockLm->expects( $this->never() )->method( $this->anythingBut( $method ) );
595 $mockLm->expects( $this->once() )->method( 'do' . ucfirst( $method ) . 'ByType' )
596 ->with( [ LockManager::LOCK_SH => [ 'mwstore://a/b', 'mwstore://c/d/e' ] ] )
597 ->willReturn( StatusValue::newGood( 'myvalue' ) );
598
599 $backend = $this->newMockFileBackend( [ 'lockManager' => $mockLm ] );
600 $backendMethod = "{$method}Files";
601
602 $status = $backend->$backendMethod( ...array_merge( $args, (array)$timeout ) );
603
604 $this->assertStatusGood( $status );
605 $this->assertStatusValue( 'myvalue', $status );
606 }
607
608 public static function provideLockUnlockFiles(): array {
609 return [
610 [ 'lock' ],
611 [ 'lock', 731 ],
612 [ 'unlock' ],
613 ];
614 }
615
616 /**
617 * @dataProvider provideGetScopedFileLocks
618 * @param array $paths
619 * @param int|string $type
620 * @param array $expectedPathsByType Expected to be passed to the LockManager
621 * @param StatusValue $lockStatus Returned from doLockByType()
622 * @param StatusValue|null $unlockStatus Returned from doUnlockByType() (if locking succeeded)
623 */
624 public function testGetScopedFileLocks(
625 array $paths, $type, array $expectedPathsByType, StatusValue $lockStatus,
626 ?StatusValue $unlockStatus = null
627 ): void {
628 $mockLm = $this->getMockBuilder( LockManager::class )
629 ->disableOriginalConstructor()
630 ->onlyMethods( [ 'doLockByType', 'doUnlockByType', 'doLock', 'doUnlock' ] )
631 ->getMock();
632 $mockLm->expects( $this->once() )->method( 'doLockByType' )
633 ->with( $expectedPathsByType )
634 ->willReturn( $lockStatus );
635 $mockLm->expects( $this->exactly( $unlockStatus ? 1 : 0 ) )->method( 'doUnlockByType' )
636 ->with( $expectedPathsByType )
637 ->willReturn( $unlockStatus );
638
639 $backend = $this->newMockFileBackend( [ 'lockManager' => $mockLm ] );
640
641 $status = StatusValue::newGood( 'myvalue' );
642 $scopedLock = $backend->getScopedFileLocks( $paths, $type, $status );
643
644 $this->assertStatusValue( 'myvalue', $status );
645 $this->assertSame( $lockStatus->isOK(), $status->isOK() );
646 $this->assertStatusMessagesExactly( $lockStatus, $status );
647
648 if ( !$lockStatus->isOK() ) {
649 $this->assertNull( $scopedLock );
650 return;
651 }
652
653 $this->assertInstanceOf( ScopedLock::class, $scopedLock );
654 unset( $scopedLock );
655
656 $this->assertStatusValue( 'myvalue', $status );
657 $this->assertSame( $lockStatus->isOK(), $status->isOK() );
658 $this->assertStatusMessagesExactly( $lockStatus->merge( $unlockStatus ), $status );
659 }
660
661 public static function provideGetScopedFileLocks(): array {
662 return [
663 'Simple successful shared lock' => [
664 [ 'mwstore://a/b/' ], LockManager::LOCK_SH,
665 [ LockManager::LOCK_SH => [ 'mwstore://a/b' ] ],
666 StatusValue::newGood( 'value2' ), StatusValue::newGood( 'value3' ),
667 ],
668 'Mixed lock' => [
669 [ LockManager::LOCK_SH => [ 'mwstore://a/b/' ],
670 LockManager::LOCK_EX => [ 'mwstore://c/d//e' ] ], 'mixed',
671 [ LockManager::LOCK_SH => [ 'mwstore://a/b' ],
672 LockManager::LOCK_EX => [ 'mwstore://c/d/e' ] ],
673 StatusValue::newGood(), StatusValue::newGood(),
674 ],
675 'Mixed with only shared locks' => [
676 [ LockManager::LOCK_SH => [ 'mwstore://a/b/', 'mwstore://c/d//e' ] ], 'mixed',
677 [ LockManager::LOCK_SH => [ 'mwstore://a/b', 'mwstore://c/d/e' ] ],
678 StatusValue::newGood(), StatusValue::newGood(),
679 ],
680 'Locking error' => [
681 [ 'mwstore://a/b/' ], LockManager::LOCK_EX,
682 [ LockManager::LOCK_EX => [ 'mwstore://a/b' ] ],
683 StatusValue::newFatal( 'XXX' ),
684 ],
685 'Unlocking error' => [
686 [ 'mwstore://a/b/', 'mwstore://c/d//e' ], LockManager::LOCK_EX,
687 [ LockManager::LOCK_EX => [ 'mwstore://a/b', 'mwstore://c/d/e' ] ],
688 StatusValue::newGood(), StatusValue::newFatal( 'XXXX' ),
689 ],
690 ];
691 }
692
693 /**
694 * @dataProvider provideConstruct_validName
695 * @param mixed $name
696 */
697 public function testGetRootStoragePath( $name ): void {
698 $backend = $this->newMockFileBackend( [ 'name' => $name ] );
699 $this->assertSame( "mwstore://$name", $backend->getRootStoragePath() );
700 }
701
702 /**
703 * @dataProvider provideConstruct_validName
704 */
705 public function testGetContainerStoragePath( $name ): void {
706 $backend = $this->newMockFileBackend( [ 'name' => $name ] );
707 $this->assertSame( "mwstore://$name/mycontainer",
708 $backend->getContainerStoragePath( 'mycontainer' ) );
709 }
710
711 /**
712 * @dataProvider provideIsStoragePath
713 */
714 public function testIsStoragePath( string $path, bool $expected ): void {
715 $this->assertSame( $expected, FileBackend::isStoragePath( $path ) );
716 }
717
718 public static function provideIsStoragePath(): array {
719 $paths = [
720 'mwstore://' => true,
721 'mwstore://backend' => true,
722 'mwstore://backend/container' => true,
723 'mwstore://backend/container/' => true,
724 'mwstore://backend/container/path' => true,
725 'mwstore://backend//container/' => true,
726 'mwstore://backend//container//' => true,
727 'mwstore://backend//container//path' => true,
728 'mwstore:///' => true,
729 'mwstore:/' => false,
730 'mwstore:' => false,
731 ];
732 $ret = [];
733 foreach ( $paths as $path => $expected ) {
734 $ret[$path] = [ $path, $expected ];
735 }
736 return $ret;
737 }
738
739 /**
740 * @dataProvider provideSplitStoragePath
741 */
742 public function testSplitStoragePath( string $path, array $expected ): void {
743 $this->assertSame( $expected, FileBackend::splitStoragePath( $path ) );
744 }
745
746 public static function provideSplitStoragePath(): array {
747 $paths = [
748 'mwstore://backend/container' => [ 'backend', 'container', '' ],
749 'mwstore://backend/container/' => [ 'backend', 'container', '' ],
750 'mwstore://backend/container/path' => [ 'backend', 'container', 'path' ],
751 'mwstore://backend/container//path' => [ 'backend', 'container', '/path' ],
752 'mwstore://backend//container/path' => [ null, null, null ],
753 'mwstore://backend//container' => [ null, null, null ],
754 'mwstore://backend//container//path' => [ null, null, null ],
755 'mwstore://' => [ null, null, null ],
756 'mwstore://backend' => [ null, null, null ],
757 'mwstore:///' => [ null, null, null ],
758 'mwstore:/' => [ null, null, null ],
759 'mwstore:' => [ null, null, null ],
760 ];
761 $ret = [];
762 foreach ( $paths as $path => $expected ) {
763 $ret[$path] = [ $path, $expected ];
764 }
765 return $ret;
766 }
767
768 /**
769 * @dataProvider provideNormalizeStoragePath
770 * @param string $path
771 * @param string|null $expected
772 */
773 public function testNormalizeStoragePath( string $path, ?string $expected ): void {
774 $this->assertSame( $expected, FileBackend::normalizeStoragePath( $path ) );
775 }
776
777 public static function provideNormalizeStoragePath(): array {
778 $paths = [
779 'mwstore://backend/container' => 'mwstore://backend/container',
780 'mwstore://backend/container/' => 'mwstore://backend/container',
781 'mwstore://backend/container/path' => 'mwstore://backend/container/path',
782 'mwstore://backend/container//path' => 'mwstore://backend/container/path',
783 'mwstore://backend/container///path' => 'mwstore://backend/container/path',
784 'mwstore://backend/container///path//to///obj' =>
785 'mwstore://backend/container/path/to/obj',
786 'mwstore://' => null,
787 'mwstore://backend' => null,
788 'mwstore://backend//container' => null,
789 'mwstore://backend//container/path' => null,
790 'mwstore://backend//container//path' => null,
791 'mwstore:///' => null,
792 'mwstore:/' => null,
793 'mwstore:' => null,
794 ];
795 $ret = [];
796 foreach ( $paths as $path => $expected ) {
797 $ret[$path] = [ $path, $expected ];
798 }
799 return $ret;
800 }
801
802 /**
803 * @dataProvider provideParentStoragePath
804 * @param string $path
805 * @param string|null $expected
806 */
807 public function testParentStoragePath( string $path, ?string $expected ): void {
808 $this->assertSame( $expected, FileBackend::parentStoragePath( $path ) );
809 }
810
811 public static function provideParentStoragePath(): array {
812 $paths = [
813 'mwstore://backend/container/path/to/obj' => 'mwstore://backend/container/path/to',
814 'mwstore://backend/container/path/to' => 'mwstore://backend/container/path',
815 'mwstore://backend/container/path' => 'mwstore://backend/container',
816 'mwstore://backend/container' => null,
817 'mwstore://backend/container/path/to/obj/' => 'mwstore://backend/container/path/to',
818 'mwstore://backend/container/path/to/' => 'mwstore://backend/container/path',
819 'mwstore://backend/container/path/' => 'mwstore://backend/container',
820 'mwstore://backend/container/' => null,
821 ];
822 $ret = [];
823 foreach ( $paths as $path => $expected ) {
824 $ret[$path] = [ $path, $expected ];
825 }
826 return $ret;
827 }
828
829 /**
830 * @dataProvider provideExtensionFromPath
831 */
832 public function testExtensionFromPath( array $args, string $expected ): void {
833 $this->assertSame( $expected, FileBackend::extensionFromPath( ...$args ) );
834 }
835
836 public static function provideExtensionFromPath(): array {
837 $paths = [
838 'mwstore://backend/container/path.Txt' => 'Txt',
839 'mwstore://backend/container/path.svg.pNG' => 'pNG',
840 'mwstore://backend/container/path' => '',
841 'mwstore://backend/container/path.' => '',
842 ];
843 $ret = [];
844 foreach ( $paths as $path => $expected ) {
845 $ret[$path] = [ [ $path ], strtolower( $expected ) ];
846 $ret["$path (lowercase)"] = [ [ $path, 'lowercase' ], strtolower( $expected ) ];
847 $ret["$path (uppercase)"] = [ [ $path, 'uppercase' ], strtoupper( $expected ) ];
848 $ret["$path (rawcase)"] = [ [ $path, 'rawcase' ], $expected ];
849 }
850 return $ret;
851 }
852
853 /**
854 * @dataProvider provideIsPathTraversalFree
855 */
856 public function testIsPathTraversalFree( string $path, bool $expected ): void {
857 $this->assertSame( $expected, FileBackend::isPathTraversalFree( $path ) );
858 }
859
860 public static function provideIsPathTraversalFree(): array {
861 $traversalFree = [
862 'a\\b',
863 'a//b',
864 '/a',
865 '\\a//b/',
866 ];
867
868 $hasTraversal = [];
869
870 $strippedPrefixes = [ '', '/', '//', '///', '\\', '\\\\', '\\\\\\' ];
871 $unstrippedPrefixes = [ '.', 'a', 'a/', '/a', ' ', "\0" ];
872 $suffixes = [ '', '.', 'a', '/', '/a', ' ', "\0" ];
873
874 foreach ( [ '.', '..' ] as $basePath ) {
875 foreach ( $strippedPrefixes as $prefix ) {
876 foreach ( $suffixes as $suffix ) {
877 if ( $suffix === '' ) {
878 $hasTraversal[] = "$prefix$basePath";
879 } else {
880 $traversalFree[] = "$prefix$basePath$suffix";
881 }
882 }
883 }
884 foreach ( $unstrippedPrefixes as $prefix ) {
885 foreach ( $suffixes as $suffix ) {
886 $traversalFree[] = "$prefix$basePath$suffix";
887 }
888 }
889 }
890
891 foreach ( [ './', '.\\', '../', '..\\' ] as $basePath ) {
892 foreach ( $strippedPrefixes as $prefix ) {
893 foreach ( $suffixes as $suffix ) {
894 $hasTraversal[] = "$prefix$basePath$suffix";
895 }
896 }
897 foreach ( $unstrippedPrefixes as $prefix ) {
898 foreach ( $suffixes as $suffix ) {
899 $traversalFree[] = "$prefix$basePath$suffix";
900 }
901 }
902 }
903
904 foreach (
905 [ '/./', '\\./', '/.\\', '\\.\\', '/../', '\\../', '/..\\', '\\..\\' ] as $basePath
906 ) {
907 foreach ( array_merge( $strippedPrefixes, $unstrippedPrefixes ) as $prefix ) {
908 foreach ( $suffixes as $suffix ) {
909 $hasTraversal[] = "$prefix$basePath$suffix";
910 }
911 }
912 }
913
914 // Some things might be traversal-free vis-a-vis one base path but a traversal for another
915 $traversalFree = array_diff( $traversalFree, $hasTraversal );
916
917 $ret = [];
918 foreach ( $traversalFree as $path ) {
919 $ret[$path] = [ $path, true ];
920 }
921 foreach ( $hasTraversal as $path ) {
922 $ret[$path] = [ $path, false ];
923 }
924 return $ret;
925 }
926
927 /**
928 * @dataProvider provideMakeContentDisposition
929 */
930 public function testMakeContentDisposition( array $args, string $expected ): void {
931 $this->assertSame( $expected, FileBackend::makeContentDisposition( ...$args ) );
932 }
933
934 public static function provideMakeContentDisposition(): array {
935 $tests = [
936 [ [ 'inline' ], 'inline' ],
937 [ [ 'inLINE' ], 'inline' ],
938 [ [ 'inLINE', '' ], 'inline' ],
939 [ [ 'attachment' ], 'attachment' ],
940 [ [ 'atTACHment' ], 'attachment' ],
941 [ [ 'atTACHment', '' ], 'attachment' ],
942
943 [ [ 'inline', 'filename.txt' ], "inline;filename*=UTF-8''filename.txt" ],
944 [ [ 'attachment', 'filename.txt' ], "attachment;filename*=UTF-8''filename.txt" ],
945
946 [ [ 'inline', 'path/filename!!!' ], "inline;filename*=UTF-8''filename%21%21%21" ],
947 ];
948 $ret = [];
949 foreach ( $tests as [ $args, $expected ] ) {
950 $ret[implode( ', ', $args )] = [ $args, $expected ];
951 }
952 return $ret;
953 }
954
955 /**
956 * @dataProvider provideMakeContentDisposition_invalid
957 */
958 public function testMakeContentDisposition_invalid( string ...$args ): void {
959 $this->expectException( InvalidArgumentException::class );
960 $this->expectExceptionMessage( "Invalid Content-Disposition type '{$args[0]}'." );
961
962 FileBackend::makeContentDisposition( ...$args );
963 }
964
965 public static function provideMakeContentDisposition_invalid(): array {
966 return [
967 [ 'foo' ],
968 [ 'foo', '' ],
969 [ 'foo', 'bar' ],
970 [ ' inline' ],
971 [ 'inline ' ],
972 ];
973 }
974
975 /**
976 * @dataProvider provideDoOperations
977 * @param string $method 'doOperation' or 'doOperations'
978 */
979 public function testResolveFSFileObjects( string $method ): void {
980 $tmpFile = ( new TempFSFileFactory )->newTempFSFile( 'a' );
981
982 $backend = $this->newMockFileBackend( 'doOperationsInternal' );
983 $backend->expects( $this->once() )->method( 'doOperationsInternal' )
984 ->with( [ [ 'src' => $tmpFile->getPath(), 'srcRef' => $tmpFile ] ] )
985 ->willReturn( StatusValue::newGood() );
986
987 $op = [ 'src' => $tmpFile ];
988 if ( $method === 'doOperations' ) {
989 $op = [ $op ];
990 }
991 $status = $backend->$method( $op );
992
993 $this->assertStatusGood( $status );
994 }
995
996 /**
997 * @dataProvider provideDoOperations
998 * @param string $method 'doOperation' or 'doOperations'
999 */
1000 public function testResolveFSFileObjects_preservesTempFiles( string $method ): void {
1001 $tmpFile = ( new TempFSFileFactory )->newTempFSFile( 'a' );
1002 $path = $tmpFile->getPath();
1003
1004 $backend = $this->newMockFileBackend();
1005
1006 $op = [ 'src' => $tmpFile ];
1007 if ( $method === 'doOperations' ) {
1008 $op = [ $op ];
1009 }
1010 $status = $backend->$method( $op );
1011
1012 $this->assertTrue( is_file( $path ) );
1013 }
1014
1015 public function testWrapStatus(): void {
1016 $expectedSv = StatusValue::newGood( 'myvalue' );
1017 $backend = $this->newMockFileBackend( [ 'statusWrapper' =>
1018 function ( StatusValue $sv ) use ( $expectedSv ): StatusValue {
1019 $this->assertEquals( StatusValue::newGood(), $sv );
1020 return $expectedSv;
1021 }
1022 ] );
1023 $this->assertSame( $expectedSv, $backend->doOperations( [] ) );
1024 }
1025
1026 public function testScopedProfileSection(): void {
1027 $scopedCallback = new ScopedCallback( static function () {
1028 } );
1029 $backend = $this->newMockFileBackend( [ 'profiler' =>
1030 function ( string $section ) use ( $scopedCallback ): ScopedCallback {
1031 $this->assertSame( 'mysection', $section );
1032 return $scopedCallback;
1033 }
1034 ] );
1035 // See comment in testConstruct_properties about use of TestingAccessWrapper.
1036 $this->assertSame( $scopedCallback,
1037 TestingAccessWrapper::newFromObject( $backend )->scopedProfileSection( 'mysection' ) );
1038 }
1039 }