TransactionsSpecTest.php 10.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 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 53 54 55 56 57 58 59 60 61
<?php

namespace MongoDB\Tests\SpecTests;

use MongoDB\BSON\Int64;
use MongoDB\BSON\Timestamp;
use MongoDB\Driver\Command;
use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Server;
use MongoDB\Driver\WriteConcern;
use MongoDB\Driver\Exception\ServerException;
use stdClass;

/**
 * Transactions spec tests.
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/transactions
 */
class TransactionsSpecTest extends FunctionalTestCase
{
    const INTERRUPTED = 11601;

    /* In addition to the useMultipleMongoses tests, these should all pass
     * before the driver can be considered compatible with MongoDB 4.2. */
    private static $incompleteTests = [
        'error-labels: add unknown commit label to MaxTimeMSExpired' => 'PHPC-1382',
        'error-labels: add unknown commit label to writeConcernError MaxTimeMSExpired' => 'PHPC-1382',
        'read-concern: only first countDocuments includes readConcern' => 'PHPLIB-417',
        'read-concern: countDocuments ignores collection readConcern' => 'PHPLIB-417',
        'read-pref: default readPreference' => 'PHPLIB does not properly inherit readPreference for transactions',
        'read-pref: primary readPreference' => 'PHPLIB does not properly inherit readPreference for transactions',
        'run-command: run command with secondary read preference in client option and primary read preference in transaction options' => 'PHPLIB does not properly inherit readPreference for transactions',
        'transaction-options: transaction options inherited from defaultTransactionOptions' => 'PHPC-1382',
        'transaction-options: startTransaction options override defaults' => 'PHPC-1382',
        'transaction-options: defaultTransactionOptions override client options' => 'PHPC-1382',
        'transaction-options: transaction options inherited from client' => 'PHPLIB does not properly inherit readConcern for transactions',
        'transaction-options: readConcern local in defaultTransactionOptions' => 'PHPLIB does not properly inherit readConcern for transactions',
        'transaction-options: readConcern snapshot in startTransaction options' => 'PHPLIB does not properly inherit readConcern for transactions',
    ];

    public static function setUpBeforeClass()
    {
        parent::setUpBeforeClass();

        static::killAllSessions();
    }

    public function tearDown()
    {
        if ($this->hasFailed()) {
            static::killAllSessions();
        }

        parent::tearDown();
    }

    /**
     * Assert that the expected and actual command documents match.
     *
62
     * Note: this method may modify the $expected object.
63
     *
64 65
     * @param stdClass $expected Expected command document
     * @param stdClass $actual   Actual command document
66
     */
67
    public static function assertCommandMatches(stdClass $expected, stdClass $actual)
68
    {
69 70 71 72 73
        if (isset($expected->getMore) && $expected->getMore === 42) {
            static::assertObjectHasAttribute('getMore', $actual);
            static::assertThat($actual->getMore, static::logicalOr(
                static::isInstanceOf(Int64::class),
                static::isType('integer')
74
            ));
75
            unset($expected->getMore);
76 77
        }

78 79 80 81
        if (isset($expected->recoveryToken) && $expected->recoveryToken === 42) {
            static::assertObjectHasAttribute('recoveryToken', $actual);
            static::assertInternalType('object', $actual->recoveryToken);
            unset($expected->recoveryToken);
82 83
        }

84 85 86 87 88 89
        if (isset($expected->readConcern->afterClusterTime) && $expected->readConcern->afterClusterTime === 42) {
            static::assertObjectHasAttribute('readConcern', $actual);
            static::assertInternalType('object', $actual->readConcern);
            static::assertObjectHasAttribute('afterClusterTime', $actual->readConcern);
            static::assertInstanceOf(Timestamp::class, $actual->readConcern->afterClusterTime);
            unset($expected->readConcern->afterClusterTime);
90 91 92

            /* If "afterClusterTime" was the only assertion for "readConcern",
             * unset the field to avoid expecting an empty document later. */
93 94
            if (get_object_vars($expected->readConcern) === []) {
                unset($expected->readConcern);
95 96 97 98 99
            }
        }

        /* TODO: Determine if forcing a new libmongoc client in Context is
         * preferable to skipping the txnNumber assertion. */
100
        //unset($expected['txnNumber']);
101

102
        foreach ($expected as $key => $value) {
103
            if ($value === null) {
104 105
                static::assertObjectNotHasAttribute($key, $actual);
                unset($expected->{$key});
106 107 108
            }
        }

109 110 111
        static::assertDocumentsMatch($expected, $actual);
    }

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
    /**
     * Execute an individual test case from the specification.
     *
     * @dataProvider provideTests
     * @param string    $name           Test name
     * @param stdClass  $test           Individual "tests[]" document
     * @param array     $runOn          Top-level "runOn" array with server requirements
     * @param array     $data           Top-level "data" array to initialize collection
     * @param string    $databaseName   Name of database under test
     * @param string    $collectionName Name of collection under test
     */
    public function testTransactions($name, stdClass $test, array $runOn = null, array $data, $databaseName = null, $collectionName = null)
    {
        $this->setName($name);

        if (isset(self::$incompleteTests[$name])) {
            $this->markTestIncomplete(self::$incompleteTests[$name]);
        }

        // TODO: Revise this once a test environment with multiple mongos nodes is available (see: PHPLIB-430)
        if (isset($test->useMultipleMongoses) && $test->useMultipleMongoses && $this->isShardedCluster()) {
            $this->markTestIncomplete('"useMultipleMongoses" is not supported');
        }

        if (isset($runOn)) {
            $this->checkServerRequirements($runOn);
        }

        if (isset($test->skipReason)) {
            $this->markTestSkipped($test->skipReason);
        }

        $databaseName = isset($databaseName) ? $databaseName : $this->getDatabaseName();
        $collectionName = isset($collectionName) ? $collectionName : $this->getCollectionName();

        $context = Context::fromTransactions($test, $databaseName, $collectionName);
        $this->setContext($context);

        $this->dropTestAndOutcomeCollections();
        $this->createTestCollection();
        $this->insertDataFixtures($data);
        $this->preventStaleDbVersionError($test->operations);

        if (isset($test->failPoint)) {
            $this->configureFailPoint($test->failPoint);
        }

        if (isset($test->expectations)) {
            $commandExpectations = CommandExpectations::fromTransactions($test->expectations);
            $commandExpectations->startMonitoring();
        }

        foreach ($test->operations as $operation) {
            Operation::fromTransactions($operation)->assert($this, $context);
        }

        $context->session0->endSession();
        $context->session1->endSession();

        if (isset($commandExpectations)) {
            $commandExpectations->stopMonitoring();
            $commandExpectations->assert($this, $context);
        }

        if (isset($test->outcome->collection->data)) {
            $this->assertOutcomeCollectionData($test->outcome->collection->data);
        }
    }

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

        foreach (glob(__DIR__ . '/transactions/*.json') as $filename) {
            $json = $this->decodeJson(file_get_contents($filename));
            $group = basename($filename, '.json');
            $runOn = isset($json->runOn) ? $json->runOn : null;
            $data = isset($json->data) ? $json->data : [];
            $databaseName = isset($json->database_name) ? $json->database_name : null;
            $collectionName = isset($json->collection_name) ? $json->collection_name : null;

            foreach ($json->tests as $test) {
                $name = $group . ': ' . $test->description;
                $testArgs[] = [$name, $test, $runOn, $data, $databaseName, $collectionName];
            }
        }

        return $testArgs;
    }

    /**
     * Create the collection, since it cannot be created within a transaction.
     */
    protected function createTestCollection()
    {
        $context = $this->getContext();

        $database = $context->getDatabase();
        $database->createCollection($context->collectionName, $context->defaultWriteOptions);
    }

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
    /**
     * Kill all sessions on the cluster.
     *
     * This will clean up any open transactions that may remain from a
     * previously failed test. For sharded clusters, this command will be run
     * on all mongos nodes.
     */
    private static function killAllSessions()
    {
        $manager = new Manager(static::getUri());
        $primary = $manager->selectServer(new ReadPreference('primary'));

        $servers = ($primary->getType() === Server::TYPE_MONGOS)
            ? $manager->getServers()
            : [$primary];

        foreach ($servers as $server) {
            try {
                // Skip servers that do not support sessions
                if (!isset($server->getInfo()['logicalSessionTimeoutMinutes'])) {
                    continue;
                }
                $server->executeCommand('admin', new Command(['killAllSessions' => []]));
            } catch (ServerException $e) {
                // Interrupted error is safe to ignore (see: SERVER-38335)
                if ($e->getCode() != self::INTERRUPTED) {
                    throw $e;
                }
            }
        }
    }

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    /**
     * Work around potential error executing distinct on sharded clusters.
     *
     * @param array $operations
     * @see https://github.com/mongodb/specifications/tree/master/source/transactions/tests#why-do-tests-that-run-distinct-sometimes-fail-with-staledbversionts.
     */
    private function preventStaleDbVersionError(array $operations)
    {
        if (!$this->isShardedCluster()) {
            return;
        }

        foreach ($operations as $operation) {
            if ($operation->name === 'distinct') {
                $this->getContext()->getCollection()->distinct('foo');
                return;
            }
        }
    }
}