Giter VIP home page Giter VIP logo

clearcodehq / pytest-mongo Goto Github PK

View Code? Open in Web Editor NEW
20.0 9.0 5.0 895 KB

This is a pytest plugin, that enables you to test your code that relies on a running MongoDB database. It allows you to specify fixtures for MongoDB process and client.

Home Page: https://pypi.python.org/pypi/pytest-mongo/

License: GNU Lesser General Public License v3.0

Python 100.00%
python pytest-plugin mongodb hacktoberfest

pytest-mongo's Introduction

https://raw.githubusercontent.com/ClearcodeHQ/pytest-mongo/master/logo.png

pytest-mongo

Latest PyPI version Wheel Status Supported Python Versions License

What is this?

This is a pytest plugin, that enables you to test your code that relies on a running MongoDB database. It allows you to specify fixtures for MongoDB process and client.

How to use

Plugin contains two fixtures

  • mongodb - it's a client fixture that has functional scope, and which cleans MongoDB at the end of each test.
  • mongo_proc - session scoped fixture, that starts MongoDB instance at the first use and stops at the end of the tests.
  • mongo_noproc - a no process fixture, that's connecting to already running mongodb instance. For example on dockerized test environments, or CI providing mongodb services

Simply include one of these fixtures into your tests fixture list.

You can also create additional MongoDB client and process fixtures if you'd need to:

from pytest_mongo import factories

mongo_my_proc = factories.mongo_proc(
    port=None, logsdir='/tmp')
mongo_my = factories.mongodb('mongo_my_proc')

Note

Each MongoDB process fixture can be configured in a different way than the others through the fixture factory arguments.

Connecting to already existing mongodb database

Some projects are using already running MongoDB servers (ie on docker instances). In order to connect to them, one would be using the mongo_noproc fixture.

mongo_external = factories.mongodb('mongo_noproc')

By default the mongo_noproc fixture would connect to MongoDB instance using 27017 port. Standard configuration options apply to it.

These are the configuration options that are working on all levels with the mongo_noproc fixture:

Configuration

You can define your settings in three ways, it's fixture factory argument, command line option and pytest.ini configuration option. You can pick which you prefer, but remember that these settings are handled in the following order:

  • Fixture factory argument
  • Command line option
  • Configuration option in your pytest.ini file
Configuration options
MongoDB server option Fixture factory argument Command line option pytest.ini option Noop process fixture Default
Path to mongodb exec executable --mongo-exec mongo_exec no /usr/bin/mongod
MongoDB host host --mongo-host mongo_host 127.0.0.1 127.0.0.1
MongoDB port port --mongo-port port 27017 random
Path to store logs logsdir --mongo-logsdir mongo_logsdir no $TMPDIR
Additional parameters params --mongo-params mongo_params no ย 
MongoDB client's time zone awarness tz_aware --mongo-tz-aware mongo_tz_aware no False

Example usage:

  • pass it as an argument in your own fixture

    mongo_proc = factories.mongo_proc(port=8888)
  • use --mongo-port command line option when you run your tests

    py.test tests --mongo-port=8888
  • specify your directory as mongo_port in your pytest.ini file.

    To do so, put a line like the following under the [pytest] section of your pytest.ini:

    [pytest]
    mongo_port = 8888

Package resources

pytest-mongo's People

Contributors

damianskrzypczak avatar dependabot-preview[bot] avatar dependabot[bot] avatar fizyk avatar github-actions[bot] avatar languitar avatar merger-application[bot] avatar requires avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytest-mongo's Issues

Allow defining port (and maybe other configuration) at runtime

Hi there,

I have a use case where I will only know the port to a running instance of mongo at runtime (and I'm able to get that via a session-scoped fixture). I would like to be able to tell pytest-mongo to use such a port. By looking at the documentation, it seems that there isn't a supported way of passing the port (or other configuration) to pytest-mongo at runtime. That would really be useful.

A way I can think of providing such a feature is to allow users to override a fixture that will give the configuration necessary. For example:

@pyest.fixture(scope='session')
def pytest_mongo_conf(my, own, required, fixtures, here):
    ... # Get host and port from other fixtures
    # Options defined in the returned dictionary would override their previous (or default) values
    return {
        'host': host,
        'port': port,
    }

Latest mirakuru release breaks pytest-mongo 2.7 support

What action do you want to perform

It would be great to keep the current version of pytest-mongo still working for 2.7 releases - at least until EOY.

The fix is simple - currently in setup.py there is no version attached to mirakuru - fixing that at 1.1.0 would keep all this working.

What are the results

What are the expected results

Option to start DB as single-member replica set

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

migrate dependency management to pipenv

use Pipfile to manage development dependencies for pytest-postgresql. Change repo structure if needed. (again - see pytest-redis/pytest-mysql for changes that were required)

Mongodb noprocess factory

I maintain few postgresql and mongodb related applications and due to a testing requirement change I switched all my postgresql tests to utilize either postgresql_proc or postgresql_noproc depending on a cli parameter. I just found out pytest-mongo does not have a noproc factory.

I think, pytest-mongo features should be on par and in sync with pytest-postgresql.

remove path.py dependency

Path.py has a really nice api, however it's use can safely be replace by stdlib limiting the number of dependencies pytest-mongo has

Failure to import python 3.5.4 on Windows

What action do you want to perform

Import and use package using Python 3.5.4 running on Windows.

What are the results

>>> from pytest_mongo import factories                                                                                                                                                           Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Jackson Clarke\AppData\Local\Programs\Python\Python35\lib\site-packages\pytest_mongo\factories.py", line 25, in <module>
    from mirakuru import TCPExecutor
  File "C:\Users\Jackson Clarke\AppData\Local\Programs\Python\Python35\lib\site-packages\mirakuru\__init__.py", line 24, in <module>
    from mirakuru.output import OutputExecutor
  File "C:\Users\Jackson Clarke\AppData\Local\Programs\Python\Python35\lib\site-packages\mirakuru\output.py", line 30, in <module>
    class OutputExecutor(SimpleExecutor):
  File "C:\Users\Jackson Clarke\AppData\Local\Programs\Python\Python35\lib\site-packages\mirakuru\output.py", line 107, in OutputExecutor
    def _wait_for_output(self, *polls: Tuple[select.poll, IO[Any]]) -> bool:
AttributeError: module 'select' has no attribute 'poll'

What are the expected results

Successful import. Not sure if Python 3.5 is the problem (is it supported?), or Windows. May be similar to github.com/ClearcodeHQ/mirakuru/pull/333.

Option to make the returned MongoClient tz_aware

MongoClient instances can optionally be timezone aware by providing the tz_aware parameter at construction time. It would be nice at least this parameter could be set such that the mongodb fixture returns clients with this (or other options) enabled. In my case, my application that I am testing requires timezone-aware clients and thus I cannot use the fixture right now.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.