Skip to content

Commit

Permalink
Add support for using an extant MongoDB instance for mongodb_instance…
Browse files Browse the repository at this point in the history
… fixture. Fixes #22.
  • Loading branch information
jaraco committed Apr 30, 2021
1 parent 7d980d6 commit e5839f8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
8 changes: 8 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
v11.1.0
=======

#22: The pytest fixture now honors ``--mongodb-uri`` or
the environment variable ``MONGODB_URL`` to run tests
against an existing instance of MongoDB rather than starting
up a new one.

v11.0.1
=======

Expand Down
19 changes: 18 additions & 1 deletion jaraco/mongodb/fixtures.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# coding: future-fstrings

import shlex
import os

import pytest

Expand All @@ -17,14 +18,30 @@ def pytest_addoption(parser):
'--mongod-args',
help="Arbitrary arguments to mongod",
)
parser.addoption(
'--mongodb-uri',
help="URI to an extant MongoDB instance (supersedes ephemeral)",
)


@pytest.yield_fixture(scope='session')
def mongodb_instance(request):
if 'pymongo' not in globals():
pytest.skip("pymongo not available")

params_raw = request.config.getoption('mongod_args') or ''
yield from _extant_instance(request.config)
yield from _ephemeral_instance(request.config)


def _extant_instance(config):
uri = config.getoption('mongodb_uri') or os.environ.get('MONGODB_URL')
if not uri:
return
yield service.ExtantInstance(uri)


def _ephemeral_instance(config):
params_raw = config.getoption('mongod_args') or ''
params = shlex.split(params_raw)
try:
instance = service.MongoDBInstance()
Expand Down
12 changes: 12 additions & 0 deletions jaraco/mongodb/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,18 @@ def stop(self):
del self.data_dir


class ExtantInstance:
def __init__(self, uri):
self.uri = uri

def get_connection(self):
pymongo = importlib.import_module('pymongo')
return pymongo.MongoClient(self.uri)

def get_uri(self):
return self.uri


class MongoDBReplicaSet(MongoDBFinder, services.Service):
replica_set_name = 'test'

Expand Down

0 comments on commit e5839f8

Please sign in to comment.