DropCollectionFunctionalTest.php 1.97 KB
Newer Older
1 2 3 4 5 6
<?php

namespace MongoDB\Tests\Operation;

use MongoDB\Driver\Server;
use MongoDB\Operation\DropCollection;
7
use MongoDB\Operation\InsertOne;
8 9 10 11 12 13
use MongoDB\Operation\ListCollections;

class DropCollectionFunctionalTest extends FunctionalTestCase
{
    public function testDropExistingCollection()
    {
14 15 16 17
        $server = $this->getPrimaryServer();

        $insertOne = new InsertOne($this->getDatabaseName(), $this->getCollectionName(), ['x' => 1]);
        $writeResult = $insertOne->execute($server);
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 62 63
        $this->assertEquals(1, $writeResult->getInsertedCount());

        $operation = new DropCollection($this->getDatabaseName(), $this->getCollectionName());
        $operation->execute($server);

        $this->assertCollectionDoesNotExist($server, $this->getDatabaseName(), $this->getCollectionName());
    }

    /**
     * @depends testDropExistingCollection
     */
    public function testDropNonexistentCollection()
    {
        $server = $this->getPrimaryServer();

        $this->assertCollectionDoesNotExist($server, $this->getDatabaseName(), $this->getCollectionName());

        $operation = new DropCollection($this->getDatabaseName(), $this->getCollectionName());
        $operation->execute($server);
    }

    /**
     * Asserts that a collection with the given name does not exist on the
     * server.
     *
     * @param Server $server
     * @param string $databaseName
     * @param string $collectionName
     */
    private function assertCollectionDoesNotExist(Server $server, $databaseName, $collectionName)
    {
        $operation = new ListCollections($databaseName);
        $collections = $operation->execute($server);

        $foundCollection = null;

        foreach ($collections as $collection) {
            if ($collection->getName() === $collectionName) {
                $foundCollection = $collection;
                break;
            }
        }

        $this->assertNull($foundCollection, sprintf('Collection %s exists on the server', $collectionName));
    }
}