ReadableStreamFunctionalTest.php 10.9 KB
Newer Older
1 2 3 4 5
<?php

namespace MongoDB\Tests\GridFS;

use MongoDB\BSON\Binary;
6
use MongoDB\Exception\InvalidArgumentException;
7
use MongoDB\GridFS\CollectionWrapper;
8
use MongoDB\GridFS\Exception\CorruptFileException;
9
use MongoDB\GridFS\ReadableStream;
Katherine Walker's avatar
Katherine Walker committed
10
use MongoDB\Tests\CommandObserver;
11
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
12
use function array_filter;
13 14 15 16 17 18

/**
 * Functional tests for the internal ReadableStream class.
 */
class ReadableStreamFunctionalTest extends FunctionalTestCase
{
19 20
    use SetUpTearDownTrait;

21
    /** @var CollectionWrapper */
22 23
    private $collectionWrapper;

24
    private function doSetUp()
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    {
        parent::setUp();

        $this->collectionWrapper = new CollectionWrapper($this->manager, $this->getDatabaseName(), 'fs');

        $this->filesCollection->insertMany([
            ['_id' => 'length-0', 'length' => 0, 'chunkSize' => 4],
            ['_id' => 'length-0-with-empty-chunk', 'length' => 0, 'chunkSize' => 4],
            ['_id' => 'length-2', 'length' => 2, 'chunkSize' => 4],
            ['_id' => 'length-8', 'length' => 8, 'chunkSize' => 4],
            ['_id' => 'length-10', 'length' => 10, 'chunkSize' => 4],
        ]);

        $this->chunksCollection->insertMany([
            ['_id' => 1, 'files_id' => 'length-0-with-empty-chunk', 'n' => 0, 'data' => new Binary('', Binary::TYPE_GENERIC)],
            ['_id' => 2, 'files_id' => 'length-2', 'n' => 0, 'data' => new Binary('ab', Binary::TYPE_GENERIC)],
            ['_id' => 3, 'files_id' => 'length-8', 'n' => 0, 'data' => new Binary('abcd', Binary::TYPE_GENERIC)],
            ['_id' => 4, 'files_id' => 'length-8', 'n' => 1, 'data' => new Binary('efgh', Binary::TYPE_GENERIC)],
            ['_id' => 5, 'files_id' => 'length-10', 'n' => 0, 'data' => new Binary('abcd', Binary::TYPE_GENERIC)],
            ['_id' => 6, 'files_id' => 'length-10', 'n' => 1, 'data' => new Binary('efgh', Binary::TYPE_GENERIC)],
            ['_id' => 7, 'files_id' => 'length-10', 'n' => 2, 'data' => new Binary('ij', Binary::TYPE_GENERIC)],
        ]);
    }

49
    public function testGetFile()
50
    {
51 52 53
        $fileDocument = (object) ['_id' => null, 'chunkSize' => 1, 'length' => 0];
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);
        $this->assertSame($fileDocument, $stream->getFile());
54 55 56 57 58 59 60
    }

    /**
     * @dataProvider provideInvalidConstructorFileDocuments
     */
    public function testConstructorFileDocumentChecks($file)
    {
61
        $this->expectException(CorruptFileException::class);
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
        new ReadableStream($this->collectionWrapper, $file);
    }

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

        foreach ($this->getInvalidIntegerValues() as $value) {
            $options[][] = (object) ['_id' => 1, 'chunkSize' => $value, 'length' => 0];
        }

        foreach ($this->getInvalidIntegerValues() as $value) {
            $options[][] = (object) ['_id' => 1, 'chunkSize' => 1, 'length' => $value];
        }

        $options[][] = (object) ['_id' => 1, 'chunkSize' => 0, 'length' => 0];
        $options[][] = (object) ['_id' => 1, 'chunkSize' => 1, 'length' => -1];
        $options[][] = (object) ['chunkSize' => 1, 'length' => 0];

        return $options;
    }

    /**
     * @dataProvider provideFileIdAndExpectedBytes
     */
87
    public function testReadBytes($fileId, $length, $expectedBytes)
88 89 90 91
    {
        $fileDocument = $this->collectionWrapper->findFileById($fileId);
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

92
        $this->assertSame($expectedBytes, $stream->readBytes($length));
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
    }

    public function provideFileIdAndExpectedBytes()
    {
        return [
            ['length-0', 0, ''],
            ['length-0', 2, ''],
            ['length-0-with-empty-chunk', 0, ''],
            ['length-0-with-empty-chunk', 2, ''],
            ['length-2', 0, ''],
            ['length-2', 2, 'ab'],
            ['length-2', 4, 'ab'],
            ['length-8', 0, ''],
            ['length-8', 2, 'ab'],
            ['length-8', 4, 'abcd'],
            ['length-8', 6, 'abcdef'],
            ['length-8', 8, 'abcdefgh'],
            ['length-8', 10, 'abcdefgh'],
            ['length-10', 0, ''],
            ['length-10', 2, 'ab'],
            ['length-10', 4, 'abcd'],
            ['length-10', 6, 'abcdef'],
            ['length-10', 8, 'abcdefgh'],
            ['length-10', 10, 'abcdefghij'],
            ['length-10', 12, 'abcdefghij'],
        ];
    }

121 122
    public function provideFilteredFileIdAndExpectedBytes()
    {
123 124 125
        return array_filter(
            $this->provideFileIdAndExpectedBytes(),
            function (array $args) {
126 127 128 129 130
                return $args[1] > 0;
            }
        );
    }

131
    /**
132
     * @dataProvider provideFilteredFileIdAndExpectedBytes
133
     */
134
    public function testReadBytesCalledMultipleTimes($fileId, $length, $expectedBytes)
135 136 137
    {
        $fileDocument = $this->collectionWrapper->findFileById($fileId);
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);
138
        for ($i = 0; $i < $length; $i++) {
139
            $expectedByte = $expectedBytes[$i] ?? '';
140
            $this->assertSame($expectedByte, $stream->readBytes(1));
141 142 143
        }
    }

144
    public function testReadBytesWithMissingChunk()
145 146 147 148 149 150
    {
        $this->chunksCollection->deleteOne(['files_id' => 'length-10', 'n' => 2]);

        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

151 152
        $this->expectException(CorruptFileException::class);
        $this->expectExceptionMessage('Chunk not found for index "2"');
153
        $stream->readBytes(10);
154 155
    }

156
    public function testReadBytesWithUnexpectedChunkIndex()
157 158 159 160 161 162
    {
        $this->chunksCollection->deleteOne(['files_id' => 'length-10', 'n' => 1]);

        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

163 164
        $this->expectException(CorruptFileException::class);
        $this->expectExceptionMessage('Expected chunk to have index "1" but found "2"');
165
        $stream->readBytes(10);
166 167
    }

168
    public function testReadBytesWithUnexpectedChunkSize()
169 170 171 172 173 174 175 176 177
    {
        $this->chunksCollection->updateOne(
            ['files_id' => 'length-10', 'n' => 2],
            ['$set' => ['data' => new Binary('i', Binary::TYPE_GENERIC)]]
        );

        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

178 179
        $this->expectException(CorruptFileException::class);
        $this->expectExceptionMessage('Expected chunk to have size "2" but found "1"');
180
        $stream->readBytes(10);
181 182
    }

183
    public function testReadBytesWithNegativeLength()
184 185 186 187
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-0');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

188
        $this->expectException(InvalidArgumentException::class);
189
        $stream->readBytes(-1);
190
    }
191

192 193 194 195 196 197 198 199 200
    public function testSeekBeforeReading()
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

        $stream->seek(8);
        $this->assertSame('ij', $stream->readBytes(2));
    }

201 202 203 204 205
    public function testSeekOutOfRange()
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

206 207
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('$offset must be >= 0 and <= 10; given: 11');
208 209
        $stream->seek(11);
    }
210

Katherine Walker's avatar
Katherine Walker committed
211 212 213 214
    /**
     * @dataProvider providePreviousChunkSeekOffsetAndBytes
     */
    public function testSeekPreviousChunk($offset, $length, $expectedBytes)
215 216 217 218
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

Katherine Walker's avatar
Katherine Walker committed
219 220 221 222 223
        // Read to initialize and advance the chunk iterator to the last chunk
        $this->assertSame('abcdefghij', $stream->readBytes(10));

        $commands = [];

224 225
        (new CommandObserver())->observe(
            function () use ($stream, $offset, $length, $expectedBytes) {
Katherine Walker's avatar
Katherine Walker committed
226 227 228
                $stream->seek($offset);
                $this->assertSame($expectedBytes, $stream->readBytes($length));
            },
229
            function (array $event) use (&$commands) {
230
                $commands[] = $event['started']->getCommandName();
Katherine Walker's avatar
Katherine Walker committed
231 232 233 234
            }
        );

        $this->assertSame(['find'], $commands);
235 236
    }

Katherine Walker's avatar
Katherine Walker committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250
    public function providePreviousChunkSeekOffsetAndBytes()
    {
        return [
            [0, 4, 'abcd'],
            [2, 4, 'cdef'],
            [4, 4, 'efgh'],
            [6, 4, 'ghij'],
        ];
    }

    /**
     * @dataProvider provideSameChunkSeekOffsetAndBytes
     */
    public function testSeekSameChunk($offset, $length, $expectedBytes)
251 252
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-10');
Katherine Walker's avatar
Katherine Walker committed
253 254 255 256
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

        // Read to initialize and advance the chunk iterator to the middle chunk
        $this->assertSame('abcdef', $stream->readBytes(6));
257

Katherine Walker's avatar
Katherine Walker committed
258
        $commands = [];
259

260 261
        (new CommandObserver())->observe(
            function () use ($stream, $offset, $length, $expectedBytes) {
Katherine Walker's avatar
Katherine Walker committed
262 263 264
                $stream->seek($offset);
                $this->assertSame($expectedBytes, $stream->readBytes($length));
            },
265
            function (array $event) use (&$commands) {
266
                $commands[] = $event['started']->getCommandName();
Katherine Walker's avatar
Katherine Walker committed
267 268
            }
        );
269

Katherine Walker's avatar
Katherine Walker committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        $this->assertSame([], $commands);
    }

    public function provideSameChunkSeekOffsetAndBytes()
    {
        return [
            [4, 4, 'efgh'],
            [6, 4, 'ghij'],
        ];
    }

    /**
     * @dataProvider provideSubsequentChunkSeekOffsetAndBytes
     */
    public function testSeekSubsequentChunk($offset, $length, $expectedBytes)
    {
        $fileDocument = $this->collectionWrapper->findFileById('length-10');
        $stream = new ReadableStream($this->collectionWrapper, $fileDocument);

        // Read to initialize the chunk iterator to the first chunk
        $this->assertSame('a', $stream->readBytes(1));

        $commands = [];

294 295
        (new CommandObserver())->observe(
            function () use ($stream, $offset, $length, $expectedBytes) {
Katherine Walker's avatar
Katherine Walker committed
296 297 298
                $stream->seek($offset);
                $this->assertSame($expectedBytes, $stream->readBytes($length));
            },
299
            function (array $event) use (&$commands) {
300
                $commands[] = $event['started']->getCommandName();
Katherine Walker's avatar
Katherine Walker committed
301 302 303 304 305 306 307 308 309 310 311 312 313
            }
        );

        $this->assertSame([], $commands);
    }

    public function provideSubsequentChunkSeekOffsetAndBytes()
    {
        return [
            [4, 4, 'efgh'],
            [6, 4, 'ghij'],
            [8, 2, 'ij'],
        ];
314
    }
315
}