Passed
Pull Request — master (#251)
by Gabriel
10:21
created

ExtMongoDBCacheTest   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 5
dl 0
loc 56
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Doctrine\Tests\Common\Cache;
4
5
use Doctrine\Common\Cache\Cache;
6
use Doctrine\Common\Cache\CacheProvider;
7
use Doctrine\Common\Cache\MongoDBCache;
8
use MongoDB\Client;
9
use MongoDB\Collection;
10
use MongoDB\Driver\Exception\Exception;
11
use function sleep;
12
13
/**
14
 * @requires extension mongodb
15
 */
16
class ExtMongoDBCacheTest extends CacheTest
17
{
18
    /** @var Collection */
19
    private $collection;
20
21
    protected function setUp() : void
22
    {
23
        try {
24
            $mongo = new Client();
25
            $mongo->listDatabases();
26
        } catch (Exception $e) {
27
            $this->markTestSkipped('Cannot connect to MongoDB because of: ' . $e);
28
        }
29
30
        $this->collection = $mongo->selectCollection('doctrine_common_cache', 'test');
31
    }
32
33
    protected function tearDown() : void
34
    {
35
        if (! ($this->collection instanceof Collection)) {
36
            return;
37
        }
38
39
        $this->collection->drop();
40
    }
41
42
    public function testGetStats() : void
43
    {
44
        $cache = $this->_getCacheDriver();
45
        // Run a query to create the collection
46
        $this->collection->find([]);
47
        $stats = $cache->getStats();
48
49
        self::assertNull($stats[Cache::STATS_HITS]);
50
        self::assertNull($stats[Cache::STATS_MISSES]);
51
        self::assertGreaterThan(0, $stats[Cache::STATS_UPTIME]);
52
        self::assertEquals(0, $stats[Cache::STATS_MEMORY_USAGE]);
53
        self::assertNull($stats[Cache::STATS_MEMORY_AVAILABLE]);
54
    }
55
56
    public function testLifetime() : void
57
    {
58
        $cache = $this->_getCacheDriver();
59
        $cache->save('expire', 'value', 1);
60
        self::assertCount(1, $this->collection->listIndexes());
61
        self::assertTrue($cache->contains('expire'), 'Data should not be expired yet');
62
        sleep(2);
63
        self::assertFalse($cache->contains('expire'), 'Data should be expired');
64
        self::assertCount(2, $this->collection->listIndexes());
65
    }
66
67
    protected function _getCacheDriver() : CacheProvider
68
    {
69
        return new MongoDBCache($this->collection);
70
    }
71
}
72