ResultExpectation.php 11.8 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\SpecTests;

5
use LogicException;
6 7 8 9
use MongoDB\BulkWriteResult;
use MongoDB\DeleteResult;
use MongoDB\Driver\WriteResult;
use MongoDB\Exception\InvalidArgumentException;
10 11
use MongoDB\InsertManyResult;
use MongoDB\InsertOneResult;
12
use MongoDB\Tests\TestCase;
13
use MongoDB\UpdateResult;
14
use stdClass;
15 16 17 18
use function call_user_func;
use function is_array;
use function is_object;
use function property_exists;
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

/**
 * Spec test operation result expectation.
 */
final class ResultExpectation
{
    const ASSERT_NOTHING = 0;
    const ASSERT_BULKWRITE = 1;
    const ASSERT_DELETE = 2;
    const ASSERT_INSERTMANY = 3;
    const ASSERT_INSERTONE = 4;
    const ASSERT_UPDATE = 5;
    const ASSERT_SAME = 6;
    const ASSERT_SAME_DOCUMENT = 7;
    const ASSERT_SAME_DOCUMENTS = 8;
    const ASSERT_MATCHES_DOCUMENT = 9;
    const ASSERT_NULL = 10;
36
    const ASSERT_CALLABLE = 11;
37

38
    /** @var integer */
39
    private $assertionType = self::ASSERT_NOTHING;
40 41

    /** @var mixed */
42
    private $expectedValue;
43 44

    /** @var callable */
45
    private $assertionCallable;
46

47 48 49 50
    /**
     * @param integer $assertionType
     * @param mixed   $expectedValue
     */
51 52 53 54 55 56 57 58
    private function __construct($assertionType, $expectedValue)
    {
        switch ($assertionType) {
            case self::ASSERT_BULKWRITE:
            case self::ASSERT_DELETE:
            case self::ASSERT_INSERTMANY:
            case self::ASSERT_INSERTONE:
            case self::ASSERT_UPDATE:
59
                if (! is_object($expectedValue)) {
60 61 62 63 64
                    throw InvalidArgumentException::invalidType('$expectedValue', $expectedValue, 'object');
                }
                break;

            case self::ASSERT_SAME_DOCUMENTS:
65
                if (! self::isArrayOfObjects($expectedValue)) {
66 67 68 69 70 71 72 73 74
                    throw InvalidArgumentException::invalidType('$expectedValue', $expectedValue, 'object[]');
                }
                break;
        }

        $this->assertionType = $assertionType;
        $this->expectedValue = $expectedValue;
    }

75 76
    public static function fromChangeStreams(stdClass $result, callable $assertionCallable)
    {
77
        if (! property_exists($result, 'success')) {
78 79 80 81 82 83 84 85 86 87
            return new self(self::ASSERT_NOTHING, null);
        }

        $o = new self(self::ASSERT_CALLABLE, $result->success);

        $o->assertionCallable = $assertionCallable;

        return $o;
    }

88 89
    public static function fromCrud(stdClass $operation, $defaultAssertionType)
    {
90
        if (property_exists($operation, 'result') && ! self::isErrorResult($operation->result)) {
91 92 93 94 95 96 97 98 99 100
            $assertionType = $operation->result === null ? self::ASSERT_NULL : $defaultAssertionType;
            $expectedValue = $operation->result;
        } else {
            $assertionType = self::ASSERT_NOTHING;
            $expectedValue = null;
        }

        return new self($assertionType, $expectedValue);
    }

101 102 103 104 105 106 107 108 109 110 111 112 113
    public static function fromRetryableReads(stdClass $operation, $defaultAssertionType)
    {
        if (property_exists($operation, 'result') && ! self::isErrorResult($operation->result)) {
            $assertionType = $operation->result === null ? self::ASSERT_NULL : $defaultAssertionType;
            $expectedValue = $operation->result;
        } else {
            $assertionType = self::ASSERT_NOTHING;
            $expectedValue = null;
        }

        return new self($assertionType, $expectedValue);
    }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    public static function fromRetryableWrites(stdClass $outcome, $defaultAssertionType)
    {
        if (property_exists($outcome, 'result')) {
            $assertionType = $outcome->result === null ? self::ASSERT_NULL : $defaultAssertionType;
            $expectedValue = $outcome->result;
        } else {
            $assertionType = self::ASSERT_NOTHING;
            $expectedValue = null;
        }

        return new self($assertionType, $expectedValue);
    }

    public static function fromTransactions(stdClass $operation, $defaultAssertionType)
    {
129
        if (property_exists($operation, 'result') && ! self::isErrorResult($operation->result)) {
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
            $assertionType = $operation->result === null ? self::ASSERT_NULL : $defaultAssertionType;
            $expectedValue = $operation->result;
        } else {
            $assertionType = self::ASSERT_NOTHING;
            $expectedValue = null;
        }

        return new self($assertionType, $expectedValue);
    }

    /**
     * Assert that the result expectation matches the actual outcome.
     *
     * @param TestCase $test   Test instance for performing assertions
     * @param mixed    $result Result (if any) from the actual outcome
     * @throws LogicException if the assertion type is unsupported
     */
    public function assert(TestCase $test, $actual)
    {
        $expected = $this->expectedValue;

        switch ($this->assertionType) {
            case self::ASSERT_BULKWRITE:
                /* If the bulk write was successful, the actual value should be
                 * a BulkWriteResult; otherwise, expect a WriteResult extracted
                 * from the BulkWriteException. */
                $test->assertThat($actual, $test->logicalOr(
                    $test->isInstanceOf(BulkWriteResult::class),
                    $test->isInstanceOf(WriteResult::class)
                ));

161
                if (! $actual->isAcknowledged()) {
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
                    break;
                }

                if (isset($expected->deletedCount)) {
                    $test->assertSame($expected->deletedCount, $actual->getDeletedCount());
                }

                if (isset($expected->insertedCount)) {
                    $test->assertSame($expected->insertedCount, $actual->getInsertedCount());
                }

                // insertedIds are not available after BulkWriteException (see: PHPLIB-428)
                if (isset($expected->insertedIds) && $actual instanceof BulkWriteResult) {
                    $test->assertSameDocument($expected->insertedIds, $actual->getInsertedIds());
                }

                if (isset($expected->matchedCount)) {
                    $test->assertSame($expected->matchedCount, $actual->getMatchedCount());
                }

                if (isset($expected->modifiedCount)) {
                    $test->assertSame($expected->modifiedCount, $actual->getModifiedCount());
                }

                if (isset($expected->upsertedCount)) {
                    $test->assertSame($expected->upsertedCount, $actual->getUpsertedCount());
                }

                if (isset($expected->upsertedIds)) {
                    $test->assertSameDocument($expected->upsertedIds, $actual->getUpsertedIds());
                }
                break;

195 196 197 198
            case self::ASSERT_CALLABLE:
                call_user_func($this->assertionCallable, $expected, $actual);
                break;

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
            case self::ASSERT_DELETE:
                $test->assertInstanceOf(DeleteResult::class, $actual);

                if (isset($expected->deletedCount)) {
                    $test->assertSame($expected->deletedCount, $actual->getDeletedCount());
                }
                break;

            case self::ASSERT_INSERTMANY:
                /* If the bulk insert was successful, the actual value should be
                 * a InsertManyResult; otherwise, expect a WriteResult extracted
                 * from the BulkWriteException. */
                $test->assertThat($actual, $test->logicalOr(
                    $test->isInstanceOf(InsertManyResult::class),
                    $test->isInstanceOf(WriteResult::class)
                ));

                if (isset($expected->insertedCount)) {
                    $test->assertSame($expected->insertedCount, $actual->getInsertedCount());
                }

                // insertedIds are not available after BulkWriteException (see: PHPLIB-428)
                if (isset($expected->insertedIds) && $actual instanceof BulkWriteResult) {
                    $test->assertSameDocument($expected->insertedIds, $actual->getInsertedIds());
                }
                break;

            case self::ASSERT_INSERTONE:
                $test->assertThat($actual, $test->logicalOr(
                    $test->isInstanceOf(InsertOneResult::class),
                    $test->isInstanceOf(WriteResult::class)
                ));

                if (isset($expected->insertedCount)) {
                    $test->assertSame($expected->insertedCount, $actual->getInsertedCount());
                }

                if (property_exists($expected, 'insertedId')) {
                    $test->assertSameDocument(
                        ['insertedId' => $expected->insertedId],
                        ['insertedId' => $actual->getInsertedId()]
                    );
                }
                break;

            case self::ASSERT_MATCHES_DOCUMENT:
245
                $test->assertIsObject($expected);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                $test->assertThat($actual, $test->logicalOr(
                    $test->isType('array'),
                    $test->isType('object')
                ));
                $test->assertMatchesDocument($expected, $actual);
                break;

            case self::ASSERT_NOTHING:
                break;

            case self::ASSERT_NULL:
                $test->assertNull($actual);
                break;

            case self::ASSERT_SAME:
                $test->assertSame($expected, $actual);
                break;

            case self::ASSERT_SAME_DOCUMENT:
265
                $test->assertIsObject($expected);
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
                $test->assertThat($actual, $test->logicalOr(
                    $test->isType('array'),
                    $test->isType('object')
                ));
                $test->assertSameDocument($expected, $actual);
                break;

            case self::ASSERT_SAME_DOCUMENTS:
                $test->assertSameDocuments($expected, $actual);
                break;

            case self::ASSERT_UPDATE:
                $test->assertInstanceOf(UpdateResult::class, $actual);

                if (isset($expected->matchedCount)) {
                    $test->assertSame($expected->matchedCount, $actual->getMatchedCount());
                }

                if (isset($expected->modifiedCount)) {
                    $test->assertSame($expected->modifiedCount, $actual->getModifiedCount());
                }

                if (isset($expected->upsertedCount)) {
                    $test->assertSame($expected->upsertedCount, $actual->getUpsertedCount());
                }

                if (property_exists($expected, 'upsertedId')) {
                    $test->assertSameDocument(
                        ['upsertedId' => $expected->upsertedId],
                        ['upsertedId' => $actual->getUpsertedId()]
                    );
                }
                break;

            default:
                throw new LogicException('Unsupported assertion type: ' . $this->assertionType);
        }
    }

    public function isExpected()
    {
        return $this->assertionType !== self::ASSERT_NOTHING;
    }

    private static function isArrayOfObjects($array)
    {
312
        if (! is_array($array)) {
313 314 315 316
            return false;
        }

        foreach ($array as $object) {
317
            if (! is_object($object)) {
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                return false;
            }
        }

        return true;
    }

    /**
     * Determines whether the result is actually an error expectation.
     *
     * @see https://github.com/mongodb/specifications/blob/master/source/transactions/tests/README.rst#test-format
     * @param mixed $result
     * @return boolean
     */
    private static function isErrorResult($result)
    {
334
        if (! is_object($result)) {
335 336 337 338 339 340 341 342 343 344 345 346 347 348
            return false;
        }

        $keys = ['errorContains', 'errorCodeName', 'errorLabelsContain', 'errorLabelsOmit'];

        foreach ($keys as $key) {
            if (isset($result->{$key})) {
                return true;
            }
        }

        return false;
    }
}