Passed
Push — 8.x-2.x ( 28cdbd...dac389 )
by Frédéric G.
01:03 queued 11s
created

MongoDbTest::testLibraryVersion()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 27
rs 9.488
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Drupal\Tests\mongodb\Kernel;
6
7
use Drupal\mongodb\MongoDb;
8
use MongoDB\Collection;
9
10
/**
11
 * Class CommandsTest.
12
 *
13
 * @coversDefaultClass \Drupal\mongodb\MongoDb
14
 *
15
 * @group MongoDB
16
 */
17
class MongoDbTest extends MongoDbTestBase {
18
19
  /**
20
   * @covers ::libraryApiVersion
21
   */
22
  public function testLibraryVersion() {
23
    $actual = MongoDb::libraryApiVersion();
24
    $this->assertRegExp('/[\d]\.[\d]+\.[\d]+/', $actual,
25
      'API version matches expected format.');
26
    list(, $minor,) = sscanf($actual, "%d.%d.%d");
27
    $hasWatch = method_exists(Collection::class, 'watch');
28
    $hasCountDocuments = method_exists(Collection::class, 'countDocuments');
29
    switch ($minor) {
30
      case 2:
31
        $this->assertFalse($hasWatch);
32
        $this->assertFalse($hasCountDocuments);
33
        break;
34
35
      case 3:
36
        $this->assertTrue($hasWatch);
37
        $this->assertFalse($hasCountDocuments);
38
        break;
39
40
      case 4:
41
        $this->assertTrue($hasWatch);
42
        $this->assertTrue($hasCountDocuments);
43
        break;
44
45
      default:
46
        $this->fail("Unexpected API version: $actual");
47
    }
48
  }
49
50
  /**
51
   * @covers ::countCollection
52
   */
53
  public function testCountCollection() {
54
    /** @var \Drupal\mongodb\DatabaseFactory $dbFactory */
55
    $dbFactory = $this->container->get(MongoDb::SERVICE_DB_FACTORY);
56
    $database = $dbFactory->get(MongoDb::DB_DEFAULT);
57
    $collectionName = $this->getDatabasePrefix() . $this->randomMachineName();
58
    $collection = $database->selectCollection($collectionName);
59
    $collection->drop();
60
61
    $expected = mt_rand(0, 100);
62
    $docs = [];
63
    for ($i = 0; $i < $expected; $i++) {
64
      $docs[] = [
65
        "index" => $i,
66
      ];
67
    }
68
    $collection->insertMany($docs);
69
    $actual = MongoDb::countCollection($collection);
70
    $this->assertEquals($expected, $actual,
71
      "countCollection finds the correct number of documents");
72
  }
73
74
}
75