BucketFunctionalTest.php 26.2 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\GridFS;

5
use MongoDB\BSON\Binary;
6
use MongoDB\Collection;
7
use MongoDB\Driver\ReadConcern;
8 9
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
10
use MongoDB\Exception\InvalidArgumentException;
11
use MongoDB\GridFS\Bucket;
12
use MongoDB\GridFS\Exception\FileNotFoundException;
13
use MongoDB\Model\BSONDocument;
14 15 16
use MongoDB\Model\IndexInfo;
use MongoDB\Operation\ListCollections;
use MongoDB\Operation\ListIndexes;
17
use PHPUnit\Framework\Error\Warning;
18 19 20 21 22 23 24 25 26 27 28 29 30 31
use function array_merge;
use function call_user_func;
use function current;
use function fclose;
use function fread;
use function fwrite;
use function hash_init;
use function is_callable;
use function min;
use function sprintf;
use function str_repeat;
use function stream_get_contents;
use function strlen;
use function substr;
32 33 34 35 36 37

/**
 * Functional tests for the Bucket class.
 */
class BucketFunctionalTest extends FunctionalTestCase
{
38 39 40
    /**
     * @doesNotPerformAssertions
     */
41 42 43 44 45
    public function testValidConstructorOptions()
    {
        new Bucket($this->manager, $this->getDatabaseName(), [
            'bucketName' => 'test',
            'chunkSizeBytes' => 8192,
46
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
47 48 49 50
            'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY, 1000),
        ]);
    }
51 52 53 54 55 56

    /**
     * @dataProvider provideInvalidConstructorOptions
     */
    public function testConstructorOptionTypeChecks(array $options)
    {
57
        $this->expectException(InvalidArgumentException::class);
58
        new Bucket($this->manager, $this->getDatabaseName(), $options);
59 60 61 62 63 64
    }

    public function provideInvalidConstructorOptions()
    {
        $options = [];

65
        foreach ($this->getInvalidStringValues(true) as $value) {
66 67 68
            $options[][] = ['bucketName' => $value];
        }

69
        foreach ($this->getInvalidIntegerValues(true) as $value) {
70 71
            $options[][] = ['chunkSizeBytes' => $value];
        }
72

73
        foreach ($this->getInvalidBooleanValues(true) as $value) {
74 75 76
            $options[][] = ['disableMD5' => $value];
        }

77 78 79 80
        foreach ($this->getInvalidReadConcernValues() as $value) {
            $options[][] = ['readConcern' => $value];
        }

81 82 83 84
        foreach ($this->getInvalidReadPreferenceValues() as $value) {
            $options[][] = ['readPreference' => $value];
        }

85 86 87 88
        foreach ($this->getInvalidArrayValues() as $value) {
            $options[][] = ['typeMap' => $value];
        }

89 90 91 92 93 94 95
        foreach ($this->getInvalidWriteConcernValues() as $value) {
            $options[][] = ['writeConcern' => $value];
        }

        return $options;
    }

96 97
    public function testConstructorShouldRequireChunkSizeBytesOptionToBePositive()
    {
98 99
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Expected "chunkSizeBytes" option to be >= 1, 0 given');
100 101 102
        new Bucket($this->manager, $this->getDatabaseName(), ['chunkSizeBytes' => 0]);
    }

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
    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testDelete($input, $expectedChunks)
    {
        $id = $this->bucket->uploadFromStream('filename', $this->createStream($input));

        $this->assertCollectionCount($this->filesCollection, 1);
        $this->assertCollectionCount($this->chunksCollection, $expectedChunks);

        $this->bucket->delete($id);

        $this->assertCollectionCount($this->filesCollection, 0);
        $this->assertCollectionCount($this->chunksCollection, 0);
    }

    public function provideInputDataAndExpectedChunks()
    {
        return [
            ['', 0],
            ['foobar', 1],
            [str_repeat('a', 261120), 1],
            [str_repeat('a', 261121), 2],
            [str_repeat('a', 522240), 2],
            [str_repeat('a', 522241), 3],
            [str_repeat('foobar', 43520), 1],
            [str_repeat('foobar', 43521), 2],
            [str_repeat('foobar', 87040), 2],
            [str_repeat('foobar', 87041), 3],
        ];
    }

    public function testDeleteShouldRequireFileToExist()
    {
137
        $this->expectException(FileNotFoundException::class);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        $this->bucket->delete('nonexistent-id');
    }

    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testDeleteStillRemovesChunksIfFileDoesNotExist($input, $expectedChunks)
    {
        $id = $this->bucket->uploadFromStream('filename', $this->createStream($input));

        $this->assertCollectionCount($this->filesCollection, 1);
        $this->assertCollectionCount($this->chunksCollection, $expectedChunks);

        $this->filesCollection->deleteOne(['_id' => $id]);

        try {
            $this->bucket->delete($id);
            $this->fail('FileNotFoundException was not thrown');
156 157
        } catch (FileNotFoundException $e) {
        }
158 159 160 161 162 163 164 165 166 167

        $this->assertCollectionCount($this->chunksCollection, 0);
    }

    public function testDownloadingFileWithMissingChunk()
    {
        $id = $this->bucket->uploadFromStream("filename", $this->createStream("foobar"));

        $this->chunksCollection->deleteOne(['files_id' => $id, 'n' => 0]);

168
        $this->expectException(Warning::class);
169 170 171 172 173 174 175 176 177 178 179 180
        stream_get_contents($this->bucket->openDownloadStream($id));
    }

    public function testDownloadingFileWithUnexpectedChunkIndex()
    {
        $id = $this->bucket->uploadFromStream("filename", $this->createStream("foobar"));

        $this->chunksCollection->updateOne(
            ['files_id' => $id, 'n' => 0],
            ['$set' => ['n' => 1]]
        );

181
        $this->expectException(Warning::class);
182 183 184 185 186 187 188 189 190 191 192 193
        stream_get_contents($this->bucket->openDownloadStream($id));
    }

    public function testDownloadingFileWithUnexpectedChunkSize()
    {
        $id = $this->bucket->uploadFromStream("filename", $this->createStream("foobar"));

        $this->chunksCollection->updateOne(
            ['files_id' => $id, 'n' => 0],
            ['$set' => ['data' => new Binary('fooba', Binary::TYPE_GENERIC)]]
        );

194
        $this->expectException(Warning::class);
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        stream_get_contents($this->bucket->openDownloadStream($id));
    }

    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testDownloadToStream($input)
    {
        $id = $this->bucket->uploadFromStream('filename', $this->createStream($input));
        $destination = $this->createStream();
        $this->bucket->downloadToStream($id, $destination);

        $this->assertStreamContents($input, $destination);
    }

210 211 212 213 214
    /**
     * @dataProvider provideInvalidStreamValues
     */
    public function testDownloadToStreamShouldRequireDestinationStream($destination)
    {
215
        $this->expectException(InvalidArgumentException::class);
216 217 218 219 220
        $this->bucket->downloadToStream('id', $destination);
    }

    public function provideInvalidStreamValues()
    {
221
        return $this->wrapValuesForDataProvider($this->getInvalidStreamValues());
222 223
    }

224 225
    public function testDownloadToStreamShouldRequireFileToExist()
    {
226
        $this->expectException(FileNotFoundException::class);
227 228 229
        $this->bucket->downloadToStream('nonexistent-id', $this->createStream());
    }

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
    public function testDownloadToStreamByName()
    {
        $this->bucket->uploadFromStream('filename', $this->createStream('foo'));
        $this->bucket->uploadFromStream('filename', $this->createStream('bar'));
        $this->bucket->uploadFromStream('filename', $this->createStream('baz'));

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination);
        $this->assertStreamContents('baz', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => -3]);
        $this->assertStreamContents('foo', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => -2]);
        $this->assertStreamContents('bar', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => -1]);
        $this->assertStreamContents('baz', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => 0]);
        $this->assertStreamContents('foo', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => 1]);
        $this->assertStreamContents('bar', $destination);

        $destination = $this->createStream();
        $this->bucket->downloadToStreamByName('filename', $destination, ['revision' => 2]);
        $this->assertStreamContents('baz', $destination);
    }

    /**
     * @dataProvider provideInvalidStreamValues
     */
    public function testDownloadToStreamByNameShouldRequireDestinationStream($destination)
    {
270
        $this->expectException(InvalidArgumentException::class);
271 272 273 274 275 276 277 278 279 280 281 282
        $this->bucket->downloadToStreamByName('filename', $destination);
    }

    /**
     * @dataProvider provideNonexistentFilenameAndRevision
     */
    public function testDownloadToStreamByNameShouldRequireFilenameAndRevisionToExist($filename, $revision)
    {
        $this->bucket->uploadFromStream('filename', $this->createStream('foo'));
        $this->bucket->uploadFromStream('filename', $this->createStream('bar'));

        $destination = $this->createStream();
283
        $this->expectException(FileNotFoundException::class);
284 285 286 287 288 289 290 291 292 293 294 295 296
        $this->bucket->downloadToStreamByName($filename, $destination, ['revision' => $revision]);
    }

    public function provideNonexistentFilenameAndRevision()
    {
        return [
            ['filename', 2],
            ['filename', -3],
            ['nonexistent-filename', 0],
            ['nonexistent-filename', -1],
        ];
    }

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
    public function testDrop()
    {
        $this->bucket->uploadFromStream('filename', $this->createStream('foobar'));

        $this->assertCollectionCount($this->filesCollection, 1);
        $this->assertCollectionCount($this->chunksCollection, 1);

        $this->bucket->drop();

        $this->assertCollectionDoesNotExist($this->filesCollection->getCollectionName());
        $this->assertCollectionDoesNotExist($this->chunksCollection->getCollectionName());
    }

    public function testFind()
    {
        $this->bucket->uploadFromStream('a', $this->createStream('foo'));
        $this->bucket->uploadFromStream('b', $this->createStream('foobar'));
        $this->bucket->uploadFromStream('c', $this->createStream('foobarbaz'));

        $cursor = $this->bucket->find(
            ['length' => ['$lte' => 6]],
            [
                'projection' => [
                    'filename' => 1,
                    'length' => 1,
                    '_id' => 0,
                ],
                'sort' => ['length' => -1],
            ]
        );

        $expected = [
            ['filename' => 'b', 'length' => 6],
            ['filename' => 'a', 'length' => 3],
        ];

        $this->assertSameDocuments($expected, $cursor);
    }

336 337 338 339 340 341 342
    public function testFindUsesTypeMap()
    {
        $this->bucket->uploadFromStream('a', $this->createStream('foo'));

        $cursor = $this->bucket->find();
        $fileDocument = current($cursor->toArray());

343
        $this->assertInstanceOf(BSONDocument::class, $fileDocument);
344 345
    }

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    public function testFindOne()
    {
        $this->bucket->uploadFromStream('a', $this->createStream('foo'));
        $this->bucket->uploadFromStream('b', $this->createStream('foobar'));
        $this->bucket->uploadFromStream('c', $this->createStream('foobarbaz'));

        $fileDocument = $this->bucket->findOne(
            ['length' => ['$lte' => 6]],
            [
                'projection' => [
                    'filename' => 1,
                    'length' => 1,
                    '_id' => 0,
                ],
                'sort' => ['length' => -1],
            ]
        );

364
        $this->assertInstanceOf(BSONDocument::class, $fileDocument);
365 366 367
        $this->assertSameDocument(['filename' => 'b', 'length' => 6], $fileDocument);
    }

368 369 370 371 372 373 374 375 376 377 378 379
    public function testGetBucketNameWithCustomValue()
    {
        $bucket = new Bucket($this->manager, $this->getDatabaseName(), ['bucketName' => 'custom_fs']);

        $this->assertEquals('custom_fs', $bucket->getBucketName());
    }

    public function testGetBucketNameWithDefaultValue()
    {
        $this->assertEquals('fs', $this->bucket->getBucketName());
    }

380 381 382 383
    public function testGetChunksCollection()
    {
        $chunksCollection = $this->bucket->getChunksCollection();

384
        $this->assertInstanceOf(Collection::class, $chunksCollection);
385 386 387
        $this->assertEquals('fs.chunks', $chunksCollection->getCollectionName());
    }

388 389 390 391 392 393 394 395 396 397 398 399
    public function testGetChunkSizeBytesWithCustomValue()
    {
        $bucket = new Bucket($this->manager, $this->getDatabaseName(), ['chunkSizeBytes' => 8192]);

        $this->assertEquals(8192, $bucket->getChunkSizeBytes());
    }

    public function testGetChunkSizeBytesWithDefaultValue()
    {
        $this->assertEquals(261120, $this->bucket->getChunkSizeBytes());
    }

400 401 402 403 404
    public function testGetDatabaseName()
    {
        $this->assertEquals($this->getDatabaseName(), $this->bucket->getDatabaseName());
    }

405 406 407 408 409 410 411
    public function testGetFileDocumentForStreamUsesTypeMap()
    {
        $metadata = ['foo' => 'bar'];
        $stream = $this->bucket->openUploadStream('filename', ['_id' => 1, 'metadata' => $metadata]);

        $fileDocument = $this->bucket->getFileDocumentForStream($stream);

412 413
        $this->assertInstanceOf(BSONDocument::class, $fileDocument);
        $this->assertInstanceOf(BSONDocument::class, $fileDocument['metadata']);
414 415 416
        $this->assertSame(['foo' => 'bar'], $fileDocument['metadata']->getArrayCopy());
    }

417 418 419 420 421 422 423 424
    public function testGetFileDocumentForStreamWithReadableStream()
    {
        $metadata = ['foo' => 'bar'];
        $id = $this->bucket->uploadFromStream('filename', $this->createStream('foobar'), ['metadata' => $metadata]);
        $stream = $this->bucket->openDownloadStream($id);

        $fileDocument = $this->bucket->getFileDocumentForStream($stream);

425
        $this->assertSameObjectId($id, $fileDocument->_id);
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        $this->assertSame('filename', $fileDocument->filename);
        $this->assertSame(6, $fileDocument->length);
        $this->assertSameDocument($metadata, $fileDocument->metadata);
    }

    public function testGetFileDocumentForStreamWithWritableStream()
    {
        $metadata = ['foo' => 'bar'];
        $stream = $this->bucket->openUploadStream('filename', ['_id' => 1, 'metadata' => $metadata]);

        $fileDocument = $this->bucket->getFileDocumentForStream($stream);

        $this->assertEquals(1, $fileDocument->_id);
        $this->assertSame('filename', $fileDocument->filename);
        $this->assertSameDocument($metadata, $fileDocument->metadata);
    }

    /**
444
     * @dataProvider provideInvalidGridFSStreamValues
445
     */
446
    public function testGetFileDocumentForStreamShouldRequireGridFSStreamResource($stream)
447
    {
448
        $this->expectException(InvalidArgumentException::class);
449 450 451
        $this->bucket->getFileDocumentForStream($stream);
    }

452 453 454 455 456
    public function provideInvalidGridFSStreamValues()
    {
        return $this->wrapValuesForDataProvider(array_merge($this->getInvalidStreamValues(), [$this->createStream()]));
    }

457 458 459 460 461 462
    public function testGetFileIdForStreamUsesTypeMap()
    {
        $stream = $this->bucket->openUploadStream('filename', ['_id' => ['x' => 1]]);

        $id = $this->bucket->getFileIdForStream($stream);

463
        $this->assertInstanceOf(BSONDocument::class, $id);
464 465 466
        $this->assertSame(['x' => 1], $id->getArrayCopy());
    }

467
    public function testGetFileIdForStreamWithReadableStream()
468
    {
469 470
        $id = $this->bucket->uploadFromStream('filename', $this->createStream('foobar'));
        $stream = $this->bucket->openDownloadStream($id);
471

472
        $this->assertSameObjectId($id, $this->bucket->getFileIdForStream($stream));
473 474 475 476 477 478 479 480 481 482
    }

    public function testGetFileIdForStreamWithWritableStream()
    {
        $stream = $this->bucket->openUploadStream('filename', ['_id' => 1]);

        $this->assertEquals(1, $this->bucket->getFileIdForStream($stream));
    }

    /**
483
     * @dataProvider provideInvalidGridFSStreamValues
484
     */
485
    public function testGetFileIdForStreamShouldRequireGridFSStreamResource($stream)
486
    {
487
        $this->expectException(InvalidArgumentException::class);
488
        $this->bucket->getFileIdForStream($stream);
489
    }
490

491 492 493 494
    public function testGetFilesCollection()
    {
        $filesCollection = $this->bucket->getFilesCollection();

495
        $this->assertInstanceOf(Collection::class, $filesCollection);
496 497 498
        $this->assertEquals('fs.files', $filesCollection->getCollectionName());
    }

499 500 501 502
    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testOpenDownloadStream($input)
503
    {
504 505 506
        $id = $this->bucket->uploadFromStream('filename', $this->createStream($input));

        $this->assertStreamContents($input, $this->bucket->openDownloadStream($id));
507 508
    }

509 510 511 512
    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testOpenDownloadStreamAndMultipleReadOperations($input)
513
    {
514 515 516
        $id = $this->bucket->uploadFromStream('filename', $this->createStream($input));
        $stream = $this->bucket->openDownloadStream($id);
        $buffer = '';
517

518 519 520 521
        while (strlen($buffer) < strlen($input)) {
            $expectedReadLength = min(4096, strlen($input) - strlen($buffer));
            $buffer .= $read = fread($stream, 4096);

522
            $this->assertIsString($read);
523 524 525 526 527
            $this->assertEquals($expectedReadLength, strlen($read));
        }

        $this->assertTrue(fclose($stream));
        $this->assertEquals($input, $buffer);
528
    }
529 530

    public function testOpenDownloadStreamShouldRequireFileToExist()
531
    {
532
        $this->expectException(FileNotFoundException::class);
533 534
        $this->bucket->openDownloadStream('nonexistent-id');
    }
535

536 537
    public function testOpenDownloadStreamByNameShouldRequireFilenameToExist()
    {
538
        $this->expectException(FileNotFoundException::class);
539
        $this->bucket->openDownloadStream('nonexistent-filename');
540
    }
541 542

    public function testOpenDownloadStreamByName()
543
    {
544 545 546
        $this->bucket->uploadFromStream('filename', $this->createStream('foo'));
        $this->bucket->uploadFromStream('filename', $this->createStream('bar'));
        $this->bucket->uploadFromStream('filename', $this->createStream('baz'));
547

548 549 550 551 552 553 554
        $this->assertStreamContents('baz', $this->bucket->openDownloadStreamByName('filename'));
        $this->assertStreamContents('foo', $this->bucket->openDownloadStreamByName('filename', ['revision' => -3]));
        $this->assertStreamContents('bar', $this->bucket->openDownloadStreamByName('filename', ['revision' => -2]));
        $this->assertStreamContents('baz', $this->bucket->openDownloadStreamByName('filename', ['revision' => -1]));
        $this->assertStreamContents('foo', $this->bucket->openDownloadStreamByName('filename', ['revision' => 0]));
        $this->assertStreamContents('bar', $this->bucket->openDownloadStreamByName('filename', ['revision' => 1]));
        $this->assertStreamContents('baz', $this->bucket->openDownloadStreamByName('filename', ['revision' => 2]));
555
    }
556 557 558 559 560

    /**
     * @dataProvider provideNonexistentFilenameAndRevision
     */
    public function testOpenDownloadStreamByNameShouldRequireFilenameAndRevisionToExist($filename, $revision)
561
    {
562 563
        $this->bucket->uploadFromStream('filename', $this->createStream('foo'));
        $this->bucket->uploadFromStream('filename', $this->createStream('bar'));
564

565
        $this->expectException(FileNotFoundException::class);
566 567
        $this->bucket->openDownloadStream($filename, ['revision' => $revision]);
    }
568

569
    public function testOpenUploadStream()
570
    {
571
        $stream = $this->bucket->openUploadStream('filename');
572

573 574
        fwrite($stream, 'foobar');
        fclose($stream);
575

576 577
        $this->assertStreamContents('foobar', $this->bucket->openDownloadStreamByName('filename'));
    }
578

579 580 581 582 583 584 585 586 587 588 589 590 591 592
    /**
     * @dataProvider provideInputDataAndExpectedChunks
     */
    public function testOpenUploadStreamAndMultipleWriteOperations($input)
    {
        $stream = $this->bucket->openUploadStream('filename');
        $offset = 0;

        while ($offset < strlen($input)) {
            $expectedWriteLength = min(4096, strlen($input) - $offset);
            $writeLength = fwrite($stream, substr($input, $offset, 4096));
            $offset += $writeLength;

            $this->assertEquals($expectedWriteLength, $writeLength);
593
        }
594 595 596

        $this->assertTrue(fclose($stream));
        $this->assertStreamContents($input, $this->bucket->openDownloadStreamByName('filename'));
597
    }
598 599

    public function testRename()
600
    {
601 602 603 604 605 606 607 608 609 610
        $id = $this->bucket->uploadFromStream('a', $this->createStream('foo'));
        $this->bucket->rename($id, 'b');

        $fileDocument = $this->filesCollection->findOne(
            ['_id' => $id],
            ['projection' => ['filename' => 1, '_id' => 0]]
        );

        $this->assertSameDocument(['filename' => 'b'], $fileDocument);
        $this->assertStreamContents('foo', $this->bucket->openDownloadStreamByName('b'));
611
    }
612 613

    public function testRenameShouldNotRequireFileToBeModified()
Will Banfield's avatar
Will Banfield committed
614
    {
615 616
        $id = $this->bucket->uploadFromStream('a', $this->createStream('foo'));
        $this->bucket->rename($id, 'a');
617

618 619 620 621 622 623 624
        $fileDocument = $this->filesCollection->findOne(
            ['_id' => $id],
            ['projection' => ['filename' => 1, '_id' => 0]]
        );

        $this->assertSameDocument(['filename' => 'a'], $fileDocument);
        $this->assertStreamContents('foo', $this->bucket->openDownloadStreamByName('a'));
Will Banfield's avatar
Will Banfield committed
625
    }
626 627

    public function testRenameShouldRequireFileToExist()
628
    {
629
        $this->expectException(FileNotFoundException::class);
630 631
        $this->bucket->rename('nonexistent-id', 'b');
    }
632

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    public function testUploadFromStream()
    {
        $options = [
            '_id' => 'custom-id',
            'chunkSizeBytes' => 2,
            'metadata' => ['foo' => 'bar'],
        ];

        $id = $this->bucket->uploadFromStream('filename', $this->createStream('foobar'), $options);

        $this->assertCollectionCount($this->filesCollection, 1);
        $this->assertCollectionCount($this->chunksCollection, 3);
        $this->assertSame('custom-id', $id);

        $fileDocument = $this->filesCollection->findOne(['_id' => $id]);

        $this->assertSameDocument(['foo' => 'bar'], $fileDocument['metadata']);
650
    }
651

652 653 654 655 656
    /**
     * @dataProvider provideInvalidStreamValues
     */
    public function testUploadFromStreamShouldRequireSourceStream($source)
    {
657
        $this->expectException(InvalidArgumentException::class);
658 659 660
        $this->bucket->uploadFromStream('filename', $source);
    }

661
    public function testUploadingAnEmptyFile()
662
    {
663 664 665
        $id = $this->bucket->uploadFromStream('filename', $this->createStream(''));
        $destination = $this->createStream();
        $this->bucket->downloadToStream($id, $destination);
666

667 668 669
        $this->assertStreamContents('', $destination);
        $this->assertCollectionCount($this->filesCollection, 1);
        $this->assertCollectionCount($this->chunksCollection, 0);
670

671 672 673 674 675 676 677 678 679 680
        $fileDocument = $this->filesCollection->findOne(
            ['_id' => $id],
            [
                'projection' => [
                    'length' => 1,
                    'md5' => 1,
                    '_id' => 0,
                ],
            ]
        );
681

682 683 684 685 686 687
        $expected = [
            'length' => 0,
            'md5' => 'd41d8cd98f00b204e9800998ecf8427e',
        ];

        $this->assertSameDocument($expected, $fileDocument);
688
    }
689 690

    public function testUploadingFirstFileCreatesIndexes()
691
    {
692 693 694
        $this->bucket->uploadFromStream('filename', $this->createStream('foo'));

        $this->assertIndexExists($this->filesCollection->getCollectionName(), 'filename_1_uploadDate_1');
695
        $this->assertIndexExists($this->chunksCollection->getCollectionName(), 'files_id_1_n_1', function (IndexInfo $info) {
696 697
            $this->assertTrue($info->isUnique());
        });
698
    }
699

700
    /**
701 702 703 704
     * Asserts that a collection with the given name does not exist on the
     * server.
     *
     * @param string $collectionName
705
     */
706 707 708 709 710 711 712 713 714 715 716 717
    private function assertCollectionDoesNotExist($collectionName)
    {
        $operation = new ListCollections($this->getDatabaseName());
        $collections = $operation->execute($this->getPrimaryServer());

        $foundCollection = null;

        foreach ($collections as $collection) {
            if ($collection->getName() === $collectionName) {
                $foundCollection = $collection;
                break;
            }
718
        }
719 720

        $this->assertNull($foundCollection, sprintf('Collection %s exists', $collectionName));
721
    }
722 723 724 725 726 727 728 729 730 731 732 733 734 735

    /**
     * Asserts that an index with the given name exists for the collection.
     *
     * An optional $callback may be provided, which should take an IndexInfo
     * argument as its first and only parameter. If an IndexInfo matching the
     * given name is found, it will be passed to the callback, which may perform
     * additional assertions.
     *
     * @param string   $collectionName
     * @param string   $indexName
     * @param callable $callback
     */
    private function assertIndexExists($collectionName, $indexName, $callback = null)
736
    {
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        if ($callback !== null && ! is_callable($callback)) {
            throw new InvalidArgumentException('$callback is not a callable');
        }

        $operation = new ListIndexes($this->getDatabaseName(), $collectionName);
        $indexes = $operation->execute($this->getPrimaryServer());

        $foundIndex = null;

        foreach ($indexes as $index) {
            if ($index->getName() === $indexName) {
                $foundIndex = $index;
                break;
            }
        }

        $this->assertNotNull($foundIndex, sprintf('Index %s does not exist', $indexName));

        if ($callback !== null) {
            call_user_func($callback, $foundIndex);
        }
758
    }
759 760 761 762 763 764 765 766 767 768

    /**
     * Return a list of invalid stream values.
     *
     * @return array
     */
    private function getInvalidStreamValues()
    {
        return [null, 123, 'foo', [], hash_init('md5')];
    }
769
}