You are here

public function ToolsTest::testFind in MongoDB 8.2

@covers ::find

File

modules/mongodb/tests/src/Kernel/ToolsTest.php, line 43

Class

ToolsTest
Class CommandsTest.

Namespace

Drupal\Tests\mongodb\Kernel

Code

public function testFind() {

  /** @var \Drupal\mongodb\DatabaseFactory $database */
  $dbFactory = $this->container
    ->get(MongoDb::SERVICE_DB_FACTORY);

  /** @var \MongoDB\Database $database */
  $database = $dbFactory
    ->get(MongoDb::DB_DEFAULT);
  $collectionName = $this
    ->randomMachineName();
  $collection = $database
    ->selectCollection($collectionName);
  $collection
    ->drop();
  $documents = [
    [
      "foo" => "bar",
    ],
    [
      "foo" => "baz",
    ],
  ];
  $docCount = count($documents);
  $collection
    ->insertMany($documents);

  // Just a sanity check.
  $this
    ->assertEquals($docCount, $collection
    ->countDocuments());
  $tools = $this->container
    ->get(MongoDb::SERVICE_TOOLS);
  $expectations = [
    [
      [],
      2,
    ],
    [
      [
        "foo" => "baz",
      ],
      1,
    ],
    [
      [
        "foo" => "qux",
      ],
      0,
    ],
  ];
  foreach ($expectations as $expectation) {

    // Current coding standards don't support foreach (foo as list()).
    list($selector, $count) = $expectation;
    $selectorString = json_encode($selector);
    $actual = $tools
      ->find(MongoDb::DB_DEFAULT, $collectionName, $selectorString);
    $this
      ->assertIsArray($actual);
    $this
      ->assertEquals($count, count($actual));
  }
}