CollectionFunctionalTest.php 8.8 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\Collection;

5
use MongoDB\BSON\Javascript;
6
use MongoDB\Collection;
7
use MongoDB\Driver\BulkWrite;
8
use MongoDB\Driver\ReadConcern;
9 10
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
11
use MongoDB\Exception\InvalidArgumentException;
12
use MongoDB\Operation\MapReduce;
13 14
use MongoDB\Tests\CommandObserver;
use stdClass;
15

16 17 18 19 20
/**
 * Functional tests for the Collection class.
 */
class CollectionFunctionalTest extends FunctionalTestCase
{
21
    /**
22
     * @dataProvider provideInvalidDatabaseAndCollectionNames
23
     */
24
    public function testConstructorDatabaseNameArgument($databaseName)
25
    {
26
        $this->expectException(InvalidArgumentException::class);
27
        // TODO: Move to unit test once ManagerInterface can be mocked (PHPC-378)
28
        new Collection($this->manager, $databaseName, $this->getCollectionName());
29 30
    }

31 32 33 34 35
    /**
     * @dataProvider provideInvalidDatabaseAndCollectionNames
     */
    public function testConstructorCollectionNameArgument($collectionName)
    {
36
        $this->expectException(InvalidArgumentException::class);
37 38 39 40 41
        // TODO: Move to unit test once ManagerInterface can be mocked (PHPC-378)
        new Collection($this->manager, $this->getDatabaseName(), $collectionName);
    }

    public function provideInvalidDatabaseAndCollectionNames()
42
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
43 44 45 46
        return [
            [null],
            [''],
        ];
47 48
    }

49 50 51 52 53
    /**
     * @dataProvider provideInvalidConstructorOptions
     */
    public function testConstructorOptionTypeChecks(array $options)
    {
54
        $this->expectException(InvalidArgumentException::class);
55
        new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $options);
56 57 58 59 60 61
    }

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

62 63 64 65
        foreach ($this->getInvalidReadConcernValues() as $value) {
            $options[][] = ['readConcern' => $value];
        }

66 67 68 69
        foreach ($this->getInvalidReadPreferenceValues() as $value) {
            $options[][] = ['readPreference' => $value];
        }

70 71 72 73
        foreach ($this->getInvalidArrayValues() as $value) {
            $options[][] = ['typeMap' => $value];
        }

74 75 76 77 78 79 80
        foreach ($this->getInvalidWriteConcernValues() as $value) {
            $options[][] = ['writeConcern' => $value];
        }

        return $options;
    }

81 82 83 84 85
    public function testGetManager()
    {
        $this->assertSame($this->manager, $this->collection->getManager());
    }

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    public function testToString()
    {
        $this->assertEquals($this->getNamespace(), (string) $this->collection);
    }

    public function getGetCollectionName()
    {
        $this->assertEquals($this->getCollectionName(), $this->collection->getCollectionName());
    }

    public function getGetDatabaseName()
    {
        $this->assertEquals($this->getDatabaseName(), $this->collection->getDatabaseName());
    }

    public function testGetNamespace()
    {
        $this->assertEquals($this->getNamespace(), $this->collection->getNamespace());
    }

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
    public function testCreateIndexSplitsCommandOptions()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

        (new CommandObserver)->observe(
            function() {
                $this->collection->createIndex(
                    ['x' => 1],
                    [
                        'maxTimeMS' => 1000,
                        'session' => $this->manager->startSession(),
                        'sparse' => true,
                        'unique' => true,
                        'writeConcern' => new WriteConcern(1),
                    ]
                );
            },
            function(stdClass $command) {
                $this->assertObjectHasAttribute('lsid', $command);
                $this->assertObjectHasAttribute('maxTimeMS', $command);
                $this->assertObjectHasAttribute('writeConcern', $command);
                $this->assertObjectHasAttribute('sparse', $command->indexes[0]);
                $this->assertObjectHasAttribute('unique', $command->indexes[0]);
            }
        );
    }

135 136
    public function testDrop()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
137
        $writeResult = $this->collection->insertOne(['x' => 1]);
138 139 140 141 142 143
        $this->assertEquals(1, $writeResult->getInsertedCount());

        $commandResult = $this->collection->drop();
        $this->assertCommandSucceeded($commandResult);
        $this->assertCollectionCount($this->getNamespace(), 0);
    }
144

145 146 147 148 149
    /**
     * @todo Move this to a unit test once Manager can be mocked
     */
    public function testDropIndexShouldNotAllowWildcardCharacter()
    {
150
        $this->expectException(InvalidArgumentException::class);
151 152 153
        $this->collection->dropIndex('*');
    }

154 155 156 157
    public function testFindOne()
    {
        $this->createFixtures(5);

Jeremy Mikola's avatar
Jeremy Mikola committed
158 159
        $filter = ['_id' => ['$lt' => 5]];
        $options = [
160
            'skip' => 1,
Jeremy Mikola's avatar
Jeremy Mikola committed
161 162
            'sort' => ['x' => -1],
        ];
163

164
        $expected = ['_id' => 3, 'x' => 33];
165

166
        $this->assertSameDocument($expected, $this->collection->findOne($filter, $options));
167 168
    }

169
    public function testWithOptionsInheritsOptions()
170 171
    {
        $collectionOptions = [
172
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
173
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
174
            'typeMap' => ['root' => 'array'],
175 176 177
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

178
        $collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $collectionOptions);
179 180 181
        $clone = $collection->withOptions();
        $debug = $clone->__debugInfo();

182 183 184
        $this->assertSame($this->manager, $debug['manager']);
        $this->assertSame($this->getDatabaseName(), $debug['databaseName']);
        $this->assertSame($this->getCollectionName(), $debug['collectionName']);
185 186
        $this->assertInstanceOf('MongoDB\Driver\ReadConcern', $debug['readConcern']);
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
187 188
        $this->assertInstanceOf('MongoDB\Driver\ReadPreference', $debug['readPreference']);
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
189 190
        $this->assertInternalType('array', $debug['typeMap']);
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
191 192 193 194
        $this->assertInstanceOf('MongoDB\Driver\WriteConcern', $debug['writeConcern']);
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

195
    public function testWithOptionsPassesOptions()
196 197
    {
        $collectionOptions = [
198
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
199
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
200
            'typeMap' => ['root' => 'array'],
201 202 203 204 205 206
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

        $clone = $this->collection->withOptions($collectionOptions);
        $debug = $clone->__debugInfo();

207 208
        $this->assertInstanceOf('MongoDB\Driver\ReadConcern', $debug['readConcern']);
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
209 210
        $this->assertInstanceOf('MongoDB\Driver\ReadPreference', $debug['readPreference']);
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
211 212
        $this->assertInternalType('array', $debug['typeMap']);
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
213 214 215 216
        $this->assertInstanceOf('MongoDB\Driver\WriteConcern', $debug['writeConcern']);
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    public function testMapReduce()
    {
        $this->createFixtures(3);

        $map = new Javascript('function() { emit(1, this.x); }');
        $reduce = new Javascript('function(key, values) { return Array.sum(values); }');
        $out = ['inline' => 1];

        $result = $this->collection->mapReduce($map, $reduce, $out);

        $this->assertInstanceOf('MongoDB\MapReduceResult', $result);
        $expected = [
            [ '_id' => 1.0, 'value' => 66.0 ],
        ];

        $this->assertSameDocuments($expected, $result);

        $this->assertGreaterThanOrEqual(0, $result->getExecutionTimeMS());
        $this->assertNotEmpty($result->getCounts());
    }

238 239 240 241 242 243 244
    /**
     * Create data fixtures.
     *
     * @param integer $n
     */
    private function createFixtures($n)
    {
245
        $bulkWrite = new BulkWrite(['ordered' => true]);
246 247

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
248
            $bulkWrite->insert([
249 250
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
251
            ]);
252 253 254 255 256 257
        }

        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);

        $this->assertEquals($n, $result->getInsertedCount());
    }
258
}