SpecFunctionalTest.php 11.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

namespace MongoDB\Tests\GridFS;

use MongoDB\Collection;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Operation\BulkWrite;
use DateTime;
11
use Exception;
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
use IteratorIterator;
use LogicException;
use MultipleIterator;

/**
 * GridFS spec functional tests.
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/gridfs/tests
 */
class SpecFunctionalTest extends FunctionalTestCase
{
    private $expectedChunksCollection;
    private $expectedFilesCollection;

    public function setUp()
    {
        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->setName(str_replace(' ', '_', $test['description']));
        $this->initializeData($initialData);

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

        try {
            $result = $this->executeAct($test['act']);
53
        } catch (Exception $e) {
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            $result = $e;
        }

        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) {
                $testArgs[] = [$json['data'], $test];
            }
        }

        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)
    {
        $mi = new MultipleIterator;
        $mi->attachIterator(new IteratorIterator($expectedCollection->find()));
        $mi->attachIterator(new IteratorIterator($actualCollection->find()));

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

            array_walk($expectedDocument, function(&$value) use ($actualResult) {
                if ($value === '*result') {
                    $value = $actualResult;
                }
            });

            array_walk($expectedDocument, function(&$value, $key) use ($actualDocument) {
                if ( ! is_string($value)) {
                    return;
                }

                if ( ! strncmp($value, '*actual_', 8)) {
                    $value = $actualDocument[$key];
                }
            });

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

    /**
     * Convert encoded types in the array and return the modified array.
     *
     * Nested arrays with "$oid" and "$date" keys will be converted to ObjectID
     * 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.
         */
        array_walk($data, function(&$value) use ($createBinary) {
            if ( ! is_array($value)) {
                return;
            }

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

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

                return;
            }

            if (isset($value['$date'])) {
                // TODO: This is necessary until PHPC-536 is implemented
                $milliseconds = floor((new DateTime($value['$date']))->format('U.u') * 1000);
                $value = new UTCDateTime($milliseconds);
                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'],
                    isset($act['arguments']['options']) ? $act['arguments']['options'] : []
                ));

            case 'upload':
                return $this->bucket->uploadFromStream(
                    $act['arguments']['filename'],
                    $this->createStream($act['arguments']['source']),
                    isset($act['arguments']['options']) ? $act['arguments']['options'] : []
                );

            default:
                throw new LogicException('Unsupported act: ' . $act['operation']);
        }
    }

    /**
     * Executes an "assert" block.
     *
     * @param array $assert
     * @param mixed $actualResult
     * @return mixed
     * @throws FileNotFoundException
     * @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);
        }

        if ( ! isset($assert['data'])) {
            return;
        }

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

        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
     * @param array $data
     * @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)
    {
        foreach ($dataModification as $type => $collectionName) {
            break;
        }

        if ( ! in_array($collectionName, ['fs.files', 'fs.chunks', 'expected.files', 'expected.chunks'])) {
            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':
                return 'MongoDB\GridFS\Exception\FileNotFoundException';

            case 'ChunkIsMissing':
            case 'ChunkIsWrongSize':
336 337 338 339
                /* Although ReadableStream throws a CorruptFileException, the
                 * stream wrapper will convert it to a PHP error of type
                 * E_USER_WARNING. */
                return 'PHPUnit_Framework_Error_Warning';
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365

            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);

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

        if ( ! empty($data['chunks'])) {
            $this->chunksCollection->insertMany($data['chunks']);
            $this->expectedChunksCollection->insertMany($data['chunks']);
        }
    }
}