Python mongomock.MongoClient() Examples
The following are 30
code examples of mongomock.MongoClient().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
mongomock
, or try the search function
.
Example #1
Source File: conftest.py From scout with BSD 3-Clause "New" or "Revised" License | 9 votes |
def real_pymongo_client(request): """Get a client to the mongo database""" LOG.info("Get a real pymongo client") start_time = datetime.datetime.now() mongo_client = pymongo.MongoClient() def teardown(): print("\n") LOG.info("Deleting database") mongo_client.drop_database(REAL_DATABASE) LOG.info("Database deleted") LOG.info("Time to run test:{}".format(datetime.datetime.now() - start_time)) request.addfinalizer(teardown) return mongo_client
Example #2
Source File: test_mongo.py From airflow with Apache License 2.0 | 7 votes |
def test_find_one(self): collection = mongomock.MongoClient().db.collection obj = {'test_find_one': 'test_value'} collection.insert(obj) result_obj = self.hook.find(collection, {}, find_one=True) result_obj = {result: result_obj[result] for result in result_obj} self.assertEqual(obj, result_obj)
Example #3
Source File: conftest.py From core with MIT License | 6 votes |
def app(): """Return api instance that uses mocked os.environ, ElasticSearch and MongoClient""" test_env = { 'SCITRAN_CORE_DRONE_SECRET': SCITRAN_CORE_DRONE_SECRET, 'TERM': 'xterm', # enable terminal features - useful for pdb sessions } env_patch = mock.patch.dict(os.environ, test_env, clear=True) env_patch.start() es_patch = mock.patch('elasticsearch.Elasticsearch') es_patch.start() mongo_patch = mock.patch('pymongo.MongoClient', new=mongomock.MongoClient) mongo_patch.start() # NOTE db and log_db is created at import time in api.config # reloading the module is needed to use the mocked MongoClient reload(api.config) yield api.web.start.app_factory() mongo_patch.stop() es_patch.stop() env_patch.stop()
Example #4
Source File: test_server_validation.py From optimade-python-tools with MIT License | 6 votes |
def test_mongo_backend_package_used(): import pymongo import mongomock from optimade.server.entry_collections import client force_mongo_env_var = os.environ.get("OPTIMADE_CI_FORCE_MONGO", None) if force_mongo_env_var is None: return if int(force_mongo_env_var) == 1: assert issubclass(client.__class__, pymongo.MongoClient) elif int(force_mongo_env_var) == 0: assert issubclass(client.__class__, mongomock.MongoClient) else: raise Exception( "The environment variable OPTIMADE_CI_FORCE_MONGO cannot be parsed as an int." )
Example #5
Source File: test_mongo.py From airflow with Apache License 2.0 | 6 votes |
def test_aggregate(self): collection = mongomock.MongoClient().db.collection objs = [ { 'test_id': '1', 'test_status': 'success' }, { 'test_id': '2', 'test_status': 'failure' }, { 'test_id': '3', 'test_status': 'success' } ] collection.insert(objs) aggregate_query = [ {"$match": {'test_status': 'success'}} ] results = self.hook.aggregate(collection, aggregate_query) self.assertEqual(len(list(results)), 2)
Example #6
Source File: test_connect.py From scout with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_connection(monkeypatch): def simple_mongo(): return mongomock.MongoClient() monkeypatch.setattr(scout.adapter.client, "get_connection", simple_mongo) client = scout.adapter.client.get_connection() assert isinstance(client, mongomock.MongoClient) # ##GIVEN a connection to a mongodatabase # print('du') # ##WHEN getting a mongo client # ##THEN assert that the port is default # print(client) # assert False # assert client.PORT == 27017 # def test_get_connection_uri(pymongo_client): # ##GIVEN a connection to a mongodatabase # uri = 'mongomock://' # client = get_connection(uri=uri) # ##WHEN getting a mongo client # ##THEN assert that the port is default # assert client.PORT == 27017
Example #7
Source File: conftest.py From scout with BSD 3-Clause "New" or "Revised" License | 6 votes |
def pymongo_client(request): """Get a client to the mongo database""" LOG.info("Get a mongomock client") start_time = datetime.datetime.now() mock_client = MongoClient() def teardown(): print("\n") LOG.info("Deleting database") mock_client.drop_database(DATABASE) LOG.info("Database deleted") LOG.info("Time to run test:{}".format(datetime.datetime.now() - start_time)) request.addfinalizer(teardown) return mock_client
Example #8
Source File: conftest.py From scout with BSD 3-Clause "New" or "Revised" License | 6 votes |
def user_obj(request, parsed_user): """Return a User object""" _user_obj = build_user(parsed_user) return _user_obj ############################################################# ##################### Adapter fixtures ##################### ############################################################# # We need to monkeypatch 'connect' function so the tests use a mongomock database # @pytest.fixture(autouse=True) # def no_connect(monkeypatch): # # from scout.adapter.client import get_connection # mongo = Mock(return_value=MongoClient()) # print('hej') # # monkeypatch.setattr('scout.adapter.client.get_connection', mongo)
Example #9
Source File: test_mongolog.py From baleen with MIT License | 5 votes |
def test_logging_to_mongo(self): """ Test the mongo log handler and logging to mongo """ assert ml.MongoClient is MockMongoClient handler = ml.MongoHandler(level=logging.DEBUG) self.assertIsInstance(handler.connection, MockMongoClient) # Ensure there is nothing in the database. self.assertEqual(handler.collection.count(), 0) # Create the logging instance. logger = logging.getLogger('test.mongo.logger.demo') logger.setLevel(logging.INFO) logger.addHandler(handler) # Log a message logger.info(tmsgf("This is a test of the mongo logger")) # Ensure there is now a log message self.assertEqual(handler.collection.count(), 1)
Example #10
Source File: test_feed.py From baleen with MIT License | 5 votes |
def setUp(self): """ Create the mongomock connection """ self.conn = connect(host='mongomock://localhost') assert isinstance(self.conn, MockMongoClient) # Clear out the database for feed in Feed.objects(): feed.delete() for post in Post.objects(): post.delete()
Example #11
Source File: test_models.py From baleen with MIT License | 5 votes |
def setUp(self): """ Create the mongomock connection """ self.conn = connect(host='mongomock://localhost') assert isinstance(self.conn, MockMongoClient) # Clear out the database for feed in Feed.objects(): feed.delete() for post in Post.objects(): post.delete()
Example #12
Source File: test_models.py From baleen with MIT License | 5 votes |
def tearDown(self): """ Drop the mongomock connection """ assert isinstance(self.conn, MockMongoClient) self.conn = None
Example #13
Source File: test_mongomock.py From umongo with MIT License | 5 votes |
def make_db(): return MongoClient()[TEST_DB]
Example #14
Source File: test_connect.py From scout with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_mock_client(): return MongoClient()
Example #15
Source File: conftest.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def __init__(self, _domain: Domain): from mongomock import MongoClient self.db = MongoClient().rasa self.collection = "conversations" super(MongoTrackerStore, self).__init__(_domain, None) # https://github.com/pytest-dev/pytest-asyncio/issues/68 # this event_loop is used by pytest-asyncio, and redefining it # is currently the only way of changing the scope of this fixture
Example #16
Source File: test_rsvpapp.py From rsvpapp with Apache License 2.0 | 5 votes |
def setup_method(self, method): rsvp.client = mongomock.MongoClient() rsvp.db = rsvp.client.mock_db_function self.client = rsvp.app.test_client()
Example #17
Source File: test_mappers.py From optimade-python-tools with MIT License | 5 votes |
def test_disallowed_aliases(self): class MyMapper(BaseResourceMapper): ALIASES = (("$and", "my_special_and"), ("not", "$not")) mapper = MyMapper() toy_collection = mongomock.MongoClient()["fake"]["fake"] with self.assertRaises(RuntimeError): MongoCollection(toy_collection, StructureResource, mapper)
Example #18
Source File: conftest.py From ceph-lcm with Apache License 2.0 | 5 votes |
def pymongo_connection(mongo_db_name): client = mongomock.MongoClient() with mock.patch("decapod_common.models.db.MongoDB", return_value=client): yield client
Example #19
Source File: test_feed.py From baleen with MIT License | 5 votes |
def tearDown(self): """ Drop the mongomock connection """ assert isinstance(self.conn, MockMongoClient) self.conn = None
Example #20
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_get_conn(self): self.assertEqual(self.hook.connection.port, 27017) self.assertIsInstance(self.conn, pymongo.MongoClient)
Example #21
Source File: test_plugin.py From iopipe-python with Apache License 2.0 | 5 votes |
def test_trace_plugin__auto_db__pymongo( mock_send_report, handler_with_trace_auto_db_pymongo, mock_context, monkeypatch ): monkeypatch.setattr( pymongo.collection, "Collection", mongomock.collection.Collection ) monkeypatch.setattr(pymongo, "MongoClient", mongomock.MongoClient) setattr(mongomock.database.Database, "address", ("localhost", 27017)) iopipe, handler = handler_with_trace_auto_db_pymongo assert len(iopipe.config["plugins"]) == 1 handler({}, mock_context) assert len(iopipe.report.performance_entries) == 0 db_traces = iopipe.report.db_trace_entries assert len(db_traces) == 3 for db_trace in db_traces: assert db_trace["dbType"] == "mongodb" assert db_trace["request"]["hostname"] == "localhost" assert db_trace["request"]["port"] == 27017 assert db_trace["request"]["db"] == "test" assert db_trace["request"]["table"] == "my_collection" assert db_traces[0]["request"]["command"] == "insert_one" assert db_traces[2]["request"]["command"] == "update"
Example #22
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_find_many(self): collection = mongomock.MongoClient().db.collection objs = [{'test_find_many_1': 'test_value'}, {'test_find_many_2': 'test_value'}] collection.insert(objs) result_objs = self.hook.find(collection, {}, find_one=False) self.assertGreater(len(list(result_objs)), 1)
Example #23
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_delete_many(self): collection = mongomock.MongoClient().db.collection obj1 = {'_id': '1', 'field': 'value'} obj2 = {'_id': '2', 'field': 'value'} collection.insert_many([obj1, obj2]) self.hook.delete_many(collection, {'field': 'value'}) self.assertEqual(0, collection.count())
Example #24
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_delete_one(self): collection = mongomock.MongoClient().db.collection obj = {'_id': '1'} collection.insert_one(obj) self.hook.delete_one(collection, {'_id': '1'}) self.assertEqual(0, collection.count())
Example #25
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_replace_many(self): collection = mongomock.MongoClient().db.collection obj1 = {'_id': '1', 'field': 'test_value_1'} obj2 = {'_id': '2', 'field': 'test_value_2'} collection.insert_many([obj1, obj2]) obj1['field'] = 'test_value_1_updated' obj2['field'] = 'test_value_2_updated' self.hook.replace_many(collection, [obj1, obj2]) result_obj = collection.find_one(filter='1') self.assertEqual('test_value_1_updated', result_obj['field']) result_obj = collection.find_one(filter='2') self.assertEqual('test_value_2_updated', result_obj['field'])
Example #26
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_replace_one_with_upsert(self): collection = mongomock.MongoClient().db.collection obj = {'_id': '1', 'field': 'test_value_1'} self.hook.replace_one(collection, obj, upsert=True) result_obj = collection.find_one(filter='1') self.assertEqual('test_value_1', result_obj['field'])
Example #27
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_replace_one_with_filter(self): collection = mongomock.MongoClient().db.collection obj1 = {'_id': '1', 'field': 'test_value_1'} obj2 = {'_id': '2', 'field': 'test_value_2'} collection.insert_many([obj1, obj2]) obj1['field'] = 'test_value_1_updated' self.hook.replace_one(collection, obj1, {'field': 'test_value_1'}) result_obj = collection.find_one(filter='1') self.assertEqual('test_value_1_updated', result_obj['field']) # Other document should stay intact result_obj = collection.find_one(filter='2') self.assertEqual('test_value_2', result_obj['field'])
Example #28
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_replace_one(self): collection = mongomock.MongoClient().db.collection obj1 = {'_id': '1', 'field': 'test_value_1'} obj2 = {'_id': '2', 'field': 'test_value_2'} collection.insert_many([obj1, obj2]) obj1['field'] = 'test_value_1_updated' self.hook.replace_one(collection, obj1) result_obj = collection.find_one(filter='1') self.assertEqual('test_value_1_updated', result_obj['field']) # Other document should stay intact result_obj = collection.find_one(filter='2') self.assertEqual('test_value_2', result_obj['field'])
Example #29
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_update_many_with_upsert(self): collection = mongomock.MongoClient().db.collection filter_doc = {'_id': '1', 'field': 0} update_doc = {'$inc': {'field': 123}} self.hook.update_many(collection, filter_doc, update_doc, upsert=True) result_obj = collection.find_one(filter='1') self.assertEqual(123, result_obj['field'])
Example #30
Source File: test_mongo.py From airflow with Apache License 2.0 | 5 votes |
def test_update_one_with_upsert(self): collection = mongomock.MongoClient().db.collection filter_doc = {'_id': '1', 'field': 0} update_doc = {'$inc': {'field': 123}} self.hook.update_one(collection, filter_doc, update_doc, upsert=True) result_obj = collection.find_one(filter='1') self.assertEqual(123, result_obj['field'])