| 1 |
import pymongo |
| 2 |
import pytest |
| 3 |
from clear import ClearTests |
| 4 |
from common import CommonTests |
| 5 |
from has import HasTests |
| 6 |
from serializer import SerializerTests |
| 7 |
|
| 8 |
from cachelib.mongodb import MongoDbCache |
| 9 |
|
| 10 |
|
| 11 |
@pytest.fixture(autouse=True, params=[MongoDbCache]) |
| 12 |
def cache_factory(request, key_prefix): |
| 13 |
client = pymongo.MongoClient() |
| 14 |
|
| 15 |
def _factory(self, *args, **kwargs): |
| 16 |
kwargs["client"] = client |
| 17 |
kwargs["db"] = "test-db" |
| 18 |
kwargs["collection"] = "test-collection" |
| 19 |
kwargs.setdefault("key_prefix", key_prefix) |
| 20 |
|
| 21 |
rc = request.param(*args, **kwargs) |
| 22 |
index_info = rc.client.index_information() |
| 23 |
all_keys = { |
| 24 |
subkey[0] for value in index_info.values() for subkey in value["key"] |
| 25 |
} |
| 26 |
assert "id" in all_keys, "Failed to create index on 'id' field" |
| 27 |
rc.clear() |
| 28 |
return rc |
| 29 |
|
| 30 |
if request.cls: |
| 31 |
request.cls.cache_factory = _factory |
| 32 |
|
| 33 |
yield |
| 34 |
|
| 35 |
client.close() |
| 36 |
|
| 37 |
|
| 38 |
@pytest.mark.network |
| 39 |
class TestMongoDbCache(CommonTests, ClearTests, HasTests, SerializerTests): |
| 40 |
pass |
| 41 |
|
| 42 |
|
| 43 |
class TestMongoDbCacheCheckConnection: |
| 44 |
# nothing listens on port 1; short timeouts keep the ping failure fast |
| 45 |
def test_unreachable_server_raises_when_enabled(self): |
| 46 |
client = pymongo.MongoClient( |
| 47 |
"mongodb://127.0.0.1:1/", |
| 48 |
serverSelectionTimeoutMS=100, |
| 49 |
connectTimeoutMS=100, |
| 50 |
) |
| 51 |
try: |
| 52 |
with pytest.raises(RuntimeError, match="could not connect to MongoDB"): |
| 53 |
MongoDbCache(client=client, check_connection=True) |
| 54 |
finally: |
| 55 |
client.close() |
| 56 |
|
| 57 |
|
| 58 |
@pytest.mark.network |
| 59 |
class TestMongoDbCacheCheckConnectionLive: |
| 60 |
def test_reachable_server_constructs_and_works(self): |
| 61 |
client = pymongo.MongoClient() |
| 62 |
try: |
| 63 |
cache = MongoDbCache( |
| 64 |
client=client, |
| 65 |
db="test-db", |
| 66 |
collection="test-collection", |
| 67 |
check_connection=True, |
| 68 |
) |
| 69 |
assert cache.set("check-connection-key", "value") |
| 70 |
assert cache.get("check-connection-key") == "value" |
| 71 |
finally: |
| 72 |
client.close() |