Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to start DB as single-member replica set #280

Open
languitar opened this issue Mar 25, 2021 · 0 comments
Open

Option to start DB as single-member replica set #280

languitar opened this issue Mar 25, 2021 · 0 comments

Comments

@languitar
Copy link
Contributor

languitar commented Mar 25, 2021

Some MongoDB features such as change streams do not work with standalone instances. In that case a replica set is required. It would be nice if there was an option to start a database as a single-member replica set for being able to use change streams, transactions etc. also in tests.

Here is workaround that I am currently using in most affected projects. As this is required more often, it would be nice if this was part of the pytest-plugin itself:

@pytest.fixture(scope="session")
def mongo_repl_proc(mongo_proc):
    client = pymongo.MongoClient(f"mongodb://{mongo_proc.host}:{mongo_proc.port}")
    client.admin.command("replSetInitiate")
    time.sleep(1)
    return mongo_proc


@pytest.fixture
def mongo(mongo_repl_proc):  # noqa: CCR001
    """
    Provide an empty mongodb client.

    This is a modification of the fixture from pytest-mongo to support replica
    sets. These require returning a client that specifically knows about them.
    """
    client = pymongo.MongoClient(
        f"mongodb://{mongo_repl_proc.host}:{mongo_repl_proc.port}",
        replicaset="rep0",
        tz_aware=True,
        # Ensures that write operations in tests are always visible to subsequent reads
        # without using explicit sessions.
        journal=True,
    )

    # wait for nodes
    while not client.nodes:
        time.sleep(0.1)

    yield client

    # clean the database
    for db_name in client.list_database_names():
        if db_name == "config":
            continue
        database = client[db_name]
        for collection_name in database.list_collection_names():
            collection = database[collection_name]
            # Do not delete any of Mongo system collections
            if (
                collection.name.startswith("system.")
                or collection.name.startswith("oplog.")
                or collection.name.startswith("replset.")
            ):
                continue
            collection.drop()

An in pytest.ini:

mongo_params = --replSet rep0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants