Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created February 13, 2016 19:05
Show Gist options
  • Save jaraco/0b9e482f5c0a1300dc9a to your computer and use it in GitHub Desktop.
Save jaraco/0b9e482f5c0a1300dc9a to your computer and use it in GitHub Desktop.
Demonstration of pytest-runner to invoke a script with dependencies loaded.
"""
This script demonstrates how pytest-runner facilitates
the simple execution of complex tasks with their
dependencies.
Save this file and invoke it
under Python (i.e. ``python test-mongodb-records.py``).
It creates a MongoDB instance, and then runs some
assertions against it.
MongoDB must be installed to a typical location or
available on PATH.
As it uses jaraco.mongodb, set MONGODB_HOME to
specify the MongoDB version to use for the ephemeral
instance.
Running this script will download the necessary
requirements to ./.eggs.
"""
setup_params = dict(
setup_requires=[
'pytest_runner',
],
tests_require=[
'pytest',
'jaraco.mongodb>=3.10',
],
)
if __name__ == '__main__':
import sys
# note that sys.argv[0] is the script name
opts = ' '.join(sys.argv)
sys.argv[1:] = ['pytest', '--addopts=' + opts]
__import__('setuptools').setup(**setup_params)
raise SystemExit(0)
import random
import itertools
import pytest
from jaraco.mongodb.testing import assert_covered
@pytest.fixture
def docs_in_db(mongodb_instance):
"""
Install 100 records with random numbers
"""
conn = mongodb_instance.get_connection()
coll = conn.test_db.test_coll
coll.drop()
coll.create_index('number')
n_records = 100
for n in itertools.islice(itertools.count(), n_records):
doc = dict(
number=random.randint(0, 2**32-1),
value='some value',
)
conn.test_db.test_coll.insert(doc)
return coll
def test_records(docs_in_db, mongodb_instance):
"Test 100 records are present and query is covered"
# load all the numbers to ensure the index is in RAM
_hint = 'number_1'
_filter = {'number': {'$gt': 0}}
_projection = {'number': True, '_id': False}
cur = docs_in_db.find(filter=_filter, projection=_projection).hint(_hint)
assert_covered(cur)
# consume the cursor for good measure
docs = list(cur)
assert len(docs) == 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment