def setUp(self): self.mongoconnection = mongomock.Connection() self.ws_arbiter_url = "http://localhost:7760" app_hooks = [hooks.DBHook(self.mongoconnection, self.ws_arbiter_url)] policy_path = os.path.dirname(os.path.realpath(__file__)) opts = [ cfg.StrOpt('config_dir', default=policy_path), cfg.StrOpt('config_file', default='policy.json'), cfg.StrOpt('project', default='surveil'), ] cfg.CONF.register_opts(opts) self.app = pecan.testing.load_test_app({ 'app': { 'root': 'surveil.api.controllers.root.RootController', 'modules': ['surveil.api'], 'debug': False, 'hooks': app_hooks } })
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), "kernel-ci") self.base_path = tempfile.gettempdir() self.boot_report = dict( version="1.1", board="board", lab_name="lab_name", kernel="kernel", job="job", defconfig="defconfig", arch="arm", boot_log="boot-board-name.log", boot_result="PASS", boot_result_description="passed", boot_time=28.07, boot_warnings=0, dtb="dtb/board-name.dtb", dtb_addr="0x81f00000", initrd_addr="0x81f00001", kernel_image="zImage", loadaddr="0x80200000", endian="little", uimage="uimage", uimage_addr="xip", mach="soc", bootloader="bootloader", bootloader_version="1.2.3", chainloader="chainloader", filesystem="nfs", boot_job_id="1234", boot_job_url="http://boot-executor.example.net", git_branch="branch", build_environment="build_environment")
def setUp(self): def get_db(): return self.db self.app = flaskr.app.test_client() self.db = mongomock.Connection().db flaskr.get_db = get_db
def setUp(self): self.database = mongomock.Connection().db self.parser_client = ParserClient('readability secret parser key') response = Response(dict()) response.content = dict(content='<p>article</p>') self.parser_client.get_article_content = MagicMock( return_value=response)
def setUp(self): self.db = mongomock.Connection().map_reduce_test self.data = [{"x": 1, "tags": ["dog", "cat"]}, {"x": 2, "tags": ["cat"]}, {"x": 3, "tags": ["mouse", "cat", "dog"]}, {"x": 4, "tags": []}] for item in self.data: self.db.things.insert(item) self.map_func = Code(""" function() { this.tags.forEach(function(z) { emit(z, 1); }); }""") self.reduce_func = Code(""" function(key, values) { var total = 0; for(var i = 0; i<values.length; i++) { total += values[i]; } return total; }""") self.expected_results = [{'_id': 'mouse', 'value': 1}, {'_id': 'dog', 'value': 2}, {'_id': 'cat', 'value': 3}]
def setUp(self): super(TestLabCommon, self).setUp() logging.disable(logging.CRITICAL) self.database = mongomock.Connection()["kernel-ci"] self.doc_id = "".join( [random.choice(string.digits) for x in xrange(24)]) self.valid_keys = ["contact", "token", "address", "name", "private"]
def setUp(self): app.app.config['TESTING'] = True # Mock the database self.db = mongomock.Connection() app.connect_db = mock.Mock(return_value=self.db) self.app = app.app.test_client()
def setUp(self): def create_collection_test(collection_name, **kwargs): return self.db[collection_name] self.connection = mongomock.Connection() self.db = mongomock.Database(self.connection, 'mq') self.db.create_collection = create_collection_test self.factory = mtq.create_connection(db=self.db)
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), "kernel-ci") patcher = mock.patch("utils.db.get_db_connection") mock_db = patcher.start() mock_db.return_value = self.db self.addCleanup(patcher.stop)
def tmongo_update(): collection = mongomock.Connection().db.collection objects = [dict(age=1), dict(age=2)] for obj in objects: obj['_id'] = collection.insert(obj) for obj in objects: stored_obj = collection.find_one({'_id': obj['_id']}) stored_obj['age'] -= 1 assert stored_obj == obj # by comparing all fields we make sure only votes changed
def get_mock(coll_names=db_dumps.keys()): """ Returns a pointer to a mock mongodb Database object, with the given collections loaded. """ db = mm.Connection().db for coll_name in coll_names: if coll_name not in db_dumps: raise RuntimeError('Collection {} not currently mocked up. Supported mock collections: {}'.format(coll_name, db_dumps.keys())) else: dumpfn = db_dumps[coll_name] db[coll_name].restore(dumpfn) return db
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), "kernel-ci") patcher = mock.patch("utils.db.get_db_connection") mock_db = patcher.start() mock_db.return_value = self.db self.addCleanup(patcher.stop) self.baseline = { "job": "job", "kernel": "kernel", "arch": "arch", "defconfig_full": "defconfig_full", "board": "board", "lab_name": "lab" } self.baseline_return = { "job": "job", "kernel": "kernel", "arch": "arch", "defconfig": "defconfig", "defconfig_full": "defconfig_full", "board": "board", "lab_name": "lab", "status": "PASS" } self.compare_to = [{ "job": "job", "kernel": "kernel", "arch": "arch", "defconfig": "defconfig", "defconfig_full": "defconfig_full", "board": "board", "lab_name": "lab", "status": "PASS" }] self.compare_return = { "job": "job", "kernel": "kernel", "arch": "arch", "defconfig": "defconfig", "defconfig_full": "defconfig_full", "board": "board", "lab_name": "lab", "status": "PASS" }
def setUp(self): # Default Content-Type header returned by Tornado. self.content_type = "application/json; charset=UTF-8" self.req_token = mtoken.Token() self.database = mongomock.Connection()["kernel-ci"] self.redisdb = fakeredis.FakeStrictRedis() self.dboptions = { "mongodb_password": "", "mongodb_user": "" } self.mail_options = { "smtp_port": 465, "smtp_host": "localhost", "smtp_user": "******", "smtp_password": "******", "smtp_sender": "*****@*****.**", "smtp_sender_desc": "Me Email" } self.settings = { "dboptions": self.dboptions, "mailoptions": self.mail_options, "redis_connection": self.redisdb, "database": self.database, "executor": concurrent.futures.ThreadPoolExecutor(max_workers=1), "default_handler_class": handlers.app.AppHandler, "debug": False, "version": "foo", "master_key": "bar", "senddelay": 60 * 60 } super(TestHandlerBase, self).setUp() patched_find_token = mock.patch( "handlers.common.token.find_token") self.find_token = patched_find_token.start() self.find_token.return_value = self.req_token patched_validate_token = mock.patch( "handlers.common.token.validate_token") self.validate_token = patched_validate_token.start() self.validate_token.return_value = (True, self.req_token) self.addCleanup(patched_find_token.stop) self.addCleanup(patched_validate_token.stop) self.doc_id = "".join( [random.choice(string.digits) for x in xrange(24)])
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), "kernel-ci") self.today = datetime.datetime( 2015, 8, 10, hour=0, minute=1, second=0, microsecond=0) patcher = mock.patch("utils.db.get_db_connection") patched_db = patcher.start() patched_db.return_value = self.db self.addCleanup(patcher.stop) date_patcher = mock.patch("datetime.datetime", spec=True) patched_date = date_patcher.start() patched_date.now = mock.MagicMock() patched_date.now.return_value = self.today self.addCleanup(date_patcher.stop)
def test_taskstore(self): collection = mongomock.Connection().db.collection class MockedDummyTask(DummyTask): meta = { 'collection': collection, 'allow_inheritance': True, 'indexes': ['task_type'] } dummy_tasks = [{"a": 3, "b": 1}, {"a": 7, "b": 4}, {"a": 2, "b": 9}] dummy_tasks_objs = [ MockedDummyTask(task_type='dummy_task', task_data=task_data) for task_data in dummy_tasks ]
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), "kernel-ci") self.boot_id = "".join( [random.choice(string.digits) for x in xrange(24)]) self.pass_boot = { "status": "PASS", "job": "job", "kernel": "kernel", "arch": "arm", "defconfig_full": "defconfig-full", "defconfig": "defconfig", "build_environment": "gcc", "compiler": "gcc", "compiler_version": "5.1.1", "lab_name": "boot-lab", "board": "arm-board", "created_on": "2016-06-29" } self.fail_boot = { "status": "FAIL", "job": "job", "kernel": "kernel1", "arch": "arm", "defconfig_full": "defconfig-full", "defconfig": "defconfig", "build_environment": "gcc", "compiler": "gcc", "compiler_version": "5.1.1", "lab_name": "boot-lab", "board": "arm-board", "created_on": "2016-06-28" }
def setUp(self): self.db = resources.db = mongomock.Connection().db
def setUp(self): self.database = mongomock.Connection().db
def setUp(self): super(InsertedDocumentTest, self).setUp() self.collection = mongomock.Connection().db.collection self.data = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}} self.orig_data = copy.deepcopy(self.data) self.object_id = self.collection.insert(self.data)
def setUp(self): super(DatabaseGettingTest, self).setUp() self.conn = mongomock.Connection()
def test__can_create_db_without_path(self): conn = mongomock.Connection('mongodb://localhost') self.assertIsNotNone(conn)
def test__can_create_db_without_path(self): conn = mongomock.Connection() self.assertIsNotNone(conn)
def setUp(self): users = [{ 'uid': "user.app_no.sms_no", 'password_hash': ("$2a$12$a7rvlb1mKlMT4xQp7qW9p.W" "UkKm3gluuUor8/rvUu3BcB7xWoxr1a") }, { 'uid': "user.app_no.sms_yes", 'phone_number': "(415) 555-1212", 'totp_secret': "NVHWYJ4OV75YW3WC", 'totp_enabled_via_sms': True, 'password_hash': ("$2a$12$X0wec23GmmicEe/eYNOM/um" "KJoTivALHjhg5q/qJ9LtkV4mtri9Au") }, { 'uid': "user.app_yes.sms_no", 'totp_secret': "VRZQO34R4LHUH634", 'totp_enabled_via_app': True, 'password_hash': ("$2a$12$1ocOVI64R1L4vBJTLaYPjOg" "8PYqXzLoFPVf.vh7ZJ8QCv7U7.DIP6") }, { 'uid': "user.app_yes.sms_yes", 'totp_secret': "BOXB6K2SJCR5L7CR", 'totp_enabled_via_app': True, 'phone_number': "(415) 555-1213", 'totp_enabled_via_sms': True, 'password_hash': ("$2a$12$hW5/YxlP9RzbUN0k05.nsOt" "gDslFYjf34U2PH7JG6OeJacIFjx.e.") }, { 'uid': "user2", 'totp_secret': "R6LPJTVQXJFRYNDJ", 'password_hash': ("$2a$12$ISrqiMAN9JIo7zA/qbPVIuP" "rQN/ebVCKamM/HFth9Ka63PmyZ2S8q") }, { 'uid': "user", 'totp_secret': "R6LPJTVQXJFRYNDJ", 'password_hash': ("$2a$12$J2dTN4wMH7nbVDgkYq/d8uT" "siTw3DQHNF5Py98Mf27PJvnqkE94iK") }] connection = mongomock.Connection() db = connection['tfa'].users self.db = db for user in users: db.insert(user) test_config = { 'secret_key': 'testing', 'twilio_from_number': '+14155551212' } flask_app.konf.use_dict(test_config) flask_app.connection = connection flask_app.twilio = MagicMock(name='mock_twilio') create_sms_mock = MagicMock(name='mock_twilio.sms.messages.create') def side_effect(*args, **kwargs): """Simulate errors on bad inputs""" for num in ['Fake', '+14155551212']: if kwargs['to'] == num: raise TwilioRestException create_sms_mock.side_effect = side_effect flask_app.twilio.sms.messages.create = create_sms_mock self.create_sms_mock = create_sms_mock self.app = flask_app.app.test_client()
def setUp(self): super(DatabasesNamesTest, self).setUp() self.conn = mongomock.Connection()
def setUp(self): super(CollectionAPITest, self).setUp() self.conn = mongomock.Connection() self.db = self.conn['somedb']
def mongo_obs(): db = mongomock.Connection().db runs = db.runs fs = mock.MagicMock() return MongoObserver(runs, fs)
def setUp(self): self.database = mongomock.Connection().db self.repository = repository.MongoRepository(self.database)
These tests use `mongomock` instead of a real MongoDB server. """ from unittest import TestCase __author__ = 'Dan Gunter' __created__ = 'April 12, 2014' import mongomock import unittest from matgendb.builders.incr import * COLLECTION = 'my_collection' DATABASE = 'db' # Global collection object conn = mongomock.Connection() db = conn[DATABASE] coll = db.my_collection # Hacks for mongomock deficiencies coll.database = db db.collection_names = lambda x: [COLLECTION] def clear(): coll.remove() def add_records(n, offs=0): obj = None for i in range(n): obj = {"n": i + offs, "s": "foo-{:d}".format(i)}
def setUp(self): self.mongoconnection = mongomock.Connection() self.ws_arbiter_url = "http://*****:*****@influxdb:8086/db') class TestHook(hooks.PecanHook): def __init__(self, mongoclient, wsarbiterurl, influxdb_client): self.mongoclient = mongoclient self.ws_arbiter_url = wsarbiterurl self.influxdb_client = influxdb_client def before(self, state): state.request.mongo_connection = self.mongoclient state.request.ws_arbiter_url = self.ws_arbiter_url state.request.influxdb_client = self.influxdb_client app_hooks = [ TestHook(self.mongoconnection, self.ws_arbiter_url, self.influxdb_client) ] policy_path = os.path.dirname(os.path.realpath(__file__)) opts = [ cfg.StrOpt('config_dir', default=policy_path), cfg.StrOpt('config_file', default='policy.json'), cfg.StrOpt('project', default='surveil'), ] cfg.CONF.register_opts(opts) self.app = pecan.testing.load_test_app({ 'app': { 'root': 'surveil.api.controllers.root.RootController', 'modules': ['surveil.api'], 'debug': True, 'hooks': app_hooks } }) self.auth_headers = { 'X-Identity-Status': 'Confirmed', 'X-User-Id': 'surveil-default-user', 'X-Roles': 'admin,surveil', 'X-Service-Catalog': 'surveil', 'X-Service-Identity-Status': 'Confirmed', 'X-Service-Roles': 'surveil', } def make_action(verb): target = getattr(self.app, verb) def func(*args, **kwargs): kwargs.setdefault('headers', self.auth_headers) return target(*args, **kwargs) return func for action in ('get', 'post', 'put', 'delete', 'post', 'post_json', 'put_json', 'delete_json'): setattr(self, action, make_action(action))
def setUp(self): logging.disable(logging.CRITICAL) self.db = mongomock.Database(mongomock.Connection(), 'kernel-ci')