SpecFunctionalTest.php 12.5 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\GridFS;

5 6 7
use DateTime;
use IteratorIterator;
use LogicException;
8 9 10
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\UTCDateTime;
11
use MongoDB\Collection;
12
use MongoDB\GridFS\Exception\FileNotFoundException;
13 14
use MongoDB\Operation\BulkWrite;
use MultipleIterator;
15
use PHPUnit\Framework\Error\Warning;
16
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
17
use Throwable;
18 19 20 21 22 23 24 25 26 27 28 29 30
use function array_walk;
use function array_walk_recursive;
use function file_get_contents;
use function glob;
use function hex2bin;
use function in_array;
use function is_array;
use function is_string;
use function json_decode;
use function str_replace;
use function stream_get_contents;
use function strncmp;
use function var_export;
31 32 33 34 35 36 37 38

/**
 * GridFS spec functional tests.
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/gridfs/tests
 */
class SpecFunctionalTest extends FunctionalTestCase
{
39 40
    use SetUpTearDownTrait;

41
    /** @var Collection */
42
    private $expectedChunksCollection;
43 44

    /** @var Collection */
45 46
    private $expectedFilesCollection;

47
    private function doSetUp()
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
    {
        parent::setUp();

        $this->expectedFilesCollection = new Collection($this->manager, $this->getDatabaseName(), 'expected.files');
        $this->expectedFilesCollection->drop();

        $this->expectedChunksCollection = new Collection($this->manager, $this->getDatabaseName(), 'expected.chunks');
        $this->expectedChunksCollection->drop();
    }

    /**
     * @dataProvider provideSpecificationTests
     */
    public function testSpecification(array $initialData, array $test)
    {
        $this->initializeData($initialData);

        if (isset($test['arrange'])) {
            foreach ($test['arrange']['data'] as $dataModification) {
                $this->executeDataModification($dataModification);
            }
        }

        try {
            $result = $this->executeAct($test['act']);
73
        } catch (Throwable $e) {
74 75 76
            $result = $e;
        }

77 78 79 80 81 82 83 84 85
        /* Per the GridFS spec: "Drivers MAY attempt to delete any orphaned
         * chunks with files_id equal to id before raising the error." The spec
         * tests do not expect orphaned chunks to be removed, so we manually
         * remove those chunks from the expected collection. */
        if ($test['act']['operation'] === 'delete' && $result instanceof FileNotFoundException) {
            $filesId = $this->convertTypes($test['act'])['arguments']['id'];
            $this->expectedChunksCollection->deleteMany(['files_id' => $filesId]);
        }

86 87 88 89 90 91 92 93 94 95 96 97 98
        if (isset($test['assert'])) {
            $this->executeAssert($test['assert'], $result);
        }
    }

    public function provideSpecificationTests()
    {
        $testArgs = [];

        foreach (glob(__DIR__ . '/spec-tests/*.json') as $filename) {
            $json = json_decode(file_get_contents($filename), true);

            foreach ($json['tests'] as $test) {
99 100
                $name = str_replace(' ', '_', $test['description']);
                $testArgs[$name] = [$json['data'], $test];
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            }
        }

        return $testArgs;
    }

    /**
     * Assert that the collections contain equivalent documents.
     *
     * This method will resolve references within the expected collection's
     * documents before comparing documents. Occurrences of "*result" in the
     * expected collection's documents will be replaced with the actual result.
     * Occurrences of "*actual" in the expected collection's documents will be
     * replaced with the corresponding value in the actual collection's document
     * being compared.
     *
     * @param Collection $expectedCollection
     * @param Collection $actualCollection
     * @param mixed      $actualResult
     */
    private function assertEquivalentCollections($expectedCollection, $actualCollection, $actualResult)
    {
123
        $mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
124 125 126 127 128 129
        $mi->attachIterator(new IteratorIterator($expectedCollection->find()));
        $mi->attachIterator(new IteratorIterator($actualCollection->find()));

        foreach ($mi as $documents) {
            list($expectedDocument, $actualDocument) = $documents;

130
            foreach ($expectedDocument as $key => $value) {
131
                if (! is_string($value)) {
132
                    continue;
133 134
                }

135 136
                if ($value === '*result') {
                    $expectedDocument[$key] = $actualResult;
137 138
                }

139
                if (! strncmp($value, '*actual_', 8)) {
140
                    $expectedDocument[$key] = $actualDocument[$key];
141
                }
142
            }
143 144 145 146 147 148 149 150

            $this->assertSameDocument($expectedDocument, $actualDocument);
        }
    }

    /**
     * Convert encoded types in the array and return the modified array.
     *
151
     * Nested arrays with "$oid" and "$date" keys will be converted to ObjectId
152 153 154 155 156 157 158 159 160 161 162 163
     * and UTCDateTime instances, respectively. Nested arrays with "$hex" keys
     * will be converted to a string or Binary object.
     *
     * @param param   $data
     * @param boolean $createBinary If true, convert "$hex" values to a Binary
     * @return array
     */
    private function convertTypes(array $data, $createBinary = true)
    {
        /* array_walk_recursive() only visits leaf nodes within the array, so we
         * need to manually recurse.
         */
164 165
        array_walk($data, function (&$value) use ($createBinary) {
            if (! is_array($value)) {
166 167 168 169 170
                return;
            }

            if (isset($value['$oid'])) {
                $value = new ObjectId($value['$oid']);
171

172 173 174 175 176 177 178 179 180 181 182 183
                return;
            }

            if (isset($value['$hex'])) {
                $value = $createBinary
                    ? new Binary(hex2bin($value['$hex']), Binary::TYPE_GENERIC)
                    : hex2bin($value['$hex']);

                return;
            }

            if (isset($value['$date'])) {
184
                $value = new UTCDateTime(new DateTime($value['$date']));
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
                return;
            }

            $value = $this->convertTypes($value, $createBinary);
        });

        return $data;
    }

    /**
     * Executes an "act" block.
     *
     * @param array $act
     * @return mixed
     * @throws LogicException if the operation is unsupported
     */
    private function executeAct(array $act)
    {
        $act = $this->convertTypes($act, false);

        switch ($act['operation']) {
            case 'delete':
                return $this->bucket->delete($act['arguments']['id']);
            case 'download':
                return stream_get_contents($this->bucket->openDownloadStream($act['arguments']['id']));
            case 'download_by_name':
                return stream_get_contents($this->bucket->openDownloadStreamByName(
                    $act['arguments']['filename'],
214
                    $act['arguments']['options'] ?? []
215 216 217 218 219
                ));
            case 'upload':
                return $this->bucket->uploadFromStream(
                    $act['arguments']['filename'],
                    $this->createStream($act['arguments']['source']),
220
                    $act['arguments']['options'] ?? []
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
                );
            default:
                throw new LogicException('Unsupported act: ' . $act['operation']);
        }
    }

    /**
     * Executes an "assert" block.
     *
     * @param array $assert
     * @param mixed $actualResult
     * @return mixed
     * @throws LogicException if the operation is unsupported
     */
    private function executeAssert(array $assert, $actualResult)
    {
        if (isset($assert['error'])) {
            $this->assertInstanceOf($this->getExceptionClassForError($assert['error']), $actualResult);
        }

        if (isset($assert['result'])) {
            $this->executeAssertResult($assert['result'], $actualResult);
        }

245
        if (! isset($assert['data'])) {
246 247 248 249 250 251
            return;
        }

        /* Since "*actual" may be used for an expected document's "_id", append
         * a unique value to avoid duplicate key exceptions.
         */
252
        array_walk_recursive($assert['data'], function (&$value) {
253
            if ($value === '*actual') {
254
                $value .= '_' . new ObjectId();
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
            }
        });

        foreach ($assert['data'] as $dataModification) {
            $this->executeDataModification($dataModification);
        }

        $this->assertEquivalentCollections($this->expectedFilesCollection, $this->filesCollection, $actualResult);
        $this->assertEquivalentCollections($this->expectedChunksCollection, $this->chunksCollection, $actualResult);
    }

    /**
     * Executes the "result" section of an "assert" block.
     *
     * @param mixed $expectedResult
     * @param mixed $actualResult
     * @throws LogicException if the result assertion is unsupported
     */
    private function executeAssertResult($expectedResult, $actualResult)
    {
        if ($expectedResult === 'void') {
            return $this->assertNull($actualResult);
        }

        if ($expectedResult === '&result') {
            // Do nothing; assertEquivalentCollections() will handle this
            return;
        }

        if (isset($expectedResult['$hex'])) {
            return $this->assertSame(hex2bin($expectedResult['$hex']), $actualResult);
        }

        throw new LogicException('Unsupported result assertion: ' . var_export($expectedResult, true));
    }

    /**
     * Executes a data modification from an "arrange" or "assert" block.
     *
     * @param array $dataModification
     * @return mixed
     * @throws LogicException if the operation or collection is unsupported
     */
    private function executeDataModification(array $dataModification)
    {
300 301 302 303
        if (empty($dataModification)) {
            throw new LogicException('Command for data modification is empty');
        }

304 305 306 307
        foreach ($dataModification as $type => $collectionName) {
            break;
        }

308
        if (! in_array($collectionName, ['fs.files', 'fs.chunks', 'expected.files', 'expected.chunks'])) {
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
            throw new LogicException('Unsupported collection: ' . $collectionName);
        }

        $dataModification = $this->convertTypes($dataModification);
        $operations = [];

        switch ($type) {
            case 'delete':
                foreach ($dataModification['deletes'] as $delete) {
                    $operations[] = [ ($delete['limit'] === 1 ? 'deleteOne' : 'deleteMany') => [ $delete['q'] ] ];
                }

                break;

            case 'insert':
                foreach ($dataModification['documents'] as $document) {
                    $operations[] = [ 'insertOne' => [ $document ] ];
                }

                break;

            case 'update':
                foreach ($dataModification['updates'] as $update) {
                    $operations[] = [ 'updateOne' => [ $update['q'], $update['u'] ] ];
                }

                break;

            default:
                throw new LogicException('Unsupported arrangement: ' . $type);
        }

        $bulk = new BulkWrite($this->getDatabaseName(), $collectionName, $operations);

        return $bulk->execute($this->getPrimaryServer());
    }

    /**
     * Returns the exception class for the "error" section of an "assert" block.
     *
     * @param string $error
     * @return string
     * @throws LogicException if the error is unsupported
     */
    private function getExceptionClassForError($error)
    {
        switch ($error) {
            case 'FileNotFound':
            case 'RevisionNotFound':
358
                return FileNotFoundException::class;
359 360
            case 'ChunkIsMissing':
            case 'ChunkIsWrongSize':
361 362 363
                /* Although ReadableStream throws a CorruptFileException, the
                 * stream wrapper will convert it to a PHP error of type
                 * E_USER_WARNING. */
364
                return Warning::class;
365 366 367 368 369 370 371 372 373 374 375 376 377 378
            default:
                throw new LogicException('Unsupported error: ' . $error);
        }
    }

    /**
     * Initializes data in the files and chunks collections.
     *
     * @param array $data
     */
    private function initializeData(array $data)
    {
        $data = $this->convertTypes($data);

379
        if (! empty($data['files'])) {
380 381 382 383
            $this->filesCollection->insertMany($data['files']);
            $this->expectedFilesCollection->insertMany($data['files']);
        }

384
        if (! empty($data['chunks'])) {
385 386 387 388 389
            $this->chunksCollection->insertMany($data['chunks']);
            $this->expectedChunksCollection->insertMany($data['chunks']);
        }
    }
}