Python mock.patch.dict() Examples
The following are 30
code examples of mock.patch.dict().
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
mock.patch
, or try the search function
.
Example #1
Source File: test_unit_test_helpers.py From n6 with GNU Affero General Public License v3.0 | 6 votes |
def test_success_for_unspecified_module(self, mocked__testmod, mocked__stdout): with patch.dict(sys.modules, {'__main__': self.module}): failures, tests = run_module_doctests(bar='spam') mocked__testmod.assert_called_once_with(None, bar='spam') self._do_assertions_for_success(mocked__stdout, failures, tests)
Example #2
Source File: soft_display.py From Pi-ST7565 with MIT License | 5 votes |
def mock_gpio(): try: import RPi.GPIO as GPIO except: from mock import MagicMock, patch import sys mymodule = MagicMock() modules = { 'spidev': mymodule, 'RPi': mymodule, 'RPi.GPIO': mymodule } patcher = patch.dict('sys.modules', modules) patcher.start()
Example #3
Source File: test_infosource.py From supvisors with Apache License 2.0 | 5 votes |
def test_unix_server(self): """ Test the values set at construction. """ from supvisors.infosource import SupervisordSource with patch.dict(self.supervisor.options.server_configs[0], {'section': 'unix_http_server'}): with self.assertRaises(ValueError): SupervisordSource(self.supervisor)
Example #4
Source File: test_pagerdutyv1.py From awslimitchecker with GNU Affero General Public License v3.0 | 5 votes |
def test_happy_path(self): self.cls._service_key_crit = 'cKey' self.cls._service_key_warn = 'wKey' self.cls._account_alias = 'myAcct' with patch('%s._event_dict' % pb, autospec=True) as m_ed: m_ed.return_value = {'event': 'dict', 'details': {}} with patch('%s._send_event' % pb, autospec=True) as m_send: self.cls.on_success(duration=12.34567) assert m_ed.mock_calls == [call(self.cls)] assert m_send.mock_calls == [ call(self.cls, 'cKey', { 'event': 'dict', 'details': { 'duration_seconds': 12.34567 }, 'event_type': 'resolve', 'description': 'awslimitchecker in myAcct rname found ' 'no problems; run completed in 12.35 ' 'seconds' }), call(self.cls, 'wKey', { 'event': 'dict', 'details': { 'duration_seconds': 12.34567 }, 'event_type': 'resolve', 'description': 'awslimitchecker in myAcct rname found ' 'no problems; run completed in 12.35 ' 'seconds' }) ]
Example #5
Source File: test_image_imports.py From PyBloqs with GNU Lesser General Public License v2.1 | 5 votes |
def test_missing_plotly_does_not_raise_error(): with patch.dict('sys.modules', {'plotly': None}): # Force re-import if imported in previous test if 'pybloqs.block.image' in sys.modules: del sys.modules['pybloqs.block.image'] import pybloqs.block.image # noqa: F401
Example #6
Source File: test_image_imports.py From PyBloqs with GNU Lesser General Public License v2.1 | 5 votes |
def test_missing_bokeh_does_not_raise_error(): with patch.dict('sys.modules', {'bokeh': None}): # Force re-import if imported in previous test if 'pybloqs.block.image' in sys.modules: del sys.modules['pybloqs.block.image'] import pybloqs.block.image # noqa: F401
Example #7
Source File: test_image_imports.py From PyBloqs with GNU Lesser General Public License v2.1 | 5 votes |
def test_missing_matplotlib_raises_error(): with pytest.raises(ImportError): with patch.dict('sys.modules', {'matplotlib.pyplot': None}): # Force re-import if imported in previous test if 'pybloqs.block.image' in sys.modules: del sys.modules['pybloqs.block.image'] import pybloqs.block.image # noqa: F401
Example #8
Source File: test_tenants.py From cloudify-manager with Apache License 2.0 | 5 votes |
def test_get_tenant_permission(self): """Getting a tenant with the credentials permission, the full tenant details, including the rabbitmq credentials. """ with patch.dict(config.instance.authorization_permissions, {CREDENTIALS_PERMISSION: ['user']}): result = self.client.tenants.get(constants.DEFAULT_TENANT_NAME) self.assertEqual(result['name'], constants.DEFAULT_TENANT_NAME) for key in ['username', 'password', 'vhost']: self.assertIsNotNone(result['rabbitmq_' + key])
Example #9
Source File: test_tenants.py From cloudify-manager with Apache License 2.0 | 5 votes |
def test_get_tenant_no_permission(self): """Getting a tenant without the credentials permission, gives the tenants details but without rabbitmq credentials. """ with patch.dict(config.instance.authorization_permissions, {CREDENTIALS_PERMISSION: []}): result = self.client.tenants.get(constants.DEFAULT_TENANT_NAME) self.assertEqual(result['name'], constants.DEFAULT_TENANT_NAME) for key in ['username', 'password', 'vhost']: self.assertIsNone(result['rabbitmq_' + key])
Example #10
Source File: test_pagerdutyv1.py From awslimitchecker with GNU Affero General Public License v3.0 | 5 votes |
def test_no_service_key_warn(self): self.cls._service_key_crit = 'cKey' self.cls._account_alias = 'myAcct' with patch('%s._event_dict' % pb, autospec=True) as m_ed: m_ed.return_value = {'event': 'dict', 'details': {}} with patch('%s._send_event' % pb, autospec=True) as m_send: self.cls.on_success(duration=12.3) assert m_ed.mock_calls == [call(self.cls)] assert m_send.mock_calls == [ call(self.cls, 'cKey', { 'event': 'dict', 'details': { 'duration_seconds': 12.3 }, 'event_type': 'resolve', 'description': 'awslimitchecker in myAcct rname found ' 'no problems; run completed in ' '12.30 seconds' }) ]
Example #11
Source File: test_pagerdutyv1.py From awslimitchecker with GNU Affero General Public License v3.0 | 5 votes |
def test_no_account_alias(self): self.cls._service_key_crit = 'cKey' self.cls._service_key_warn = 'wKey' with patch('%s._event_dict' % pb, autospec=True) as m_ed: m_ed.return_value = {'event': 'dict', 'details': {}} with patch('%s._send_event' % pb, autospec=True) as m_send: self.cls.on_success(duration=12.3) assert m_ed.mock_calls == [call(self.cls)] assert m_send.mock_calls == [ call(self.cls, 'cKey', { 'event': 'dict', 'details': { 'duration_seconds': 12.3 }, 'event_type': 'resolve', 'description': 'awslimitchecker in rname found ' 'no problems; run completed in ' '12.30 seconds' }), call(self.cls, 'wKey', { 'event': 'dict', 'details': { 'duration_seconds': 12.3 }, 'event_type': 'resolve', 'description': 'awslimitchecker in rname found ' 'no problems; run completed in ' '12.30 seconds' }) ]
Example #12
Source File: test_commandline.py From pip-install-privates with MIT License | 5 votes |
def test_uses_github_token_environment_variable_if_no_token_supplied(self): with patch.dict('pip_install_privates.install.os.environ', {'GITHUB_TOKEN': 'my-token'}): with patch.object(sys, 'argv', ['pip-install', 'requirements.txt']): install() self.mock_collect.assert_called_once_with('requirements.txt', transform_with_token='my-token')
Example #13
Source File: test_manager.py From scale with Apache License 2.0 | 5 votes |
def test_generate_silo_status(self): """Tests the _generate_silo_status method""" silo = dependency_mgr._generate_silo_status() self.assertDictEqual(silo, {'OK': False, 'detail': {'url': None}, 'errors': [{'NO_SILO_DEFINED': 'No silo URL defined in environment. SOS.'}], 'warnings': []}) with patch.dict('os.environ', {'SILO_URL': 'https://localhost'}): silo = dependency_mgr._generate_silo_status() self.assertFalse(silo['OK']) with patch.dict('os.environ', {'SILO_URL': 'https://en.wikipedia.org/wiki/Silo'}): silo = dependency_mgr._generate_silo_status() self.assertDictEqual(silo, {'OK': True, 'detail': {'msg': 'Silo is alive and connected', 'url': 'https://en.wikipedia.org/wiki/Silo'}, 'errors': [], 'warnings': []})
Example #14
Source File: test_progressbar.py From mmcv with Apache License 2.0 | 5 votes |
def test_adaptive_length(self): with patch.dict('os.environ', {'COLUMNS': '80'}): out = StringIO() bar_width = 20 prog_bar = mmcv.ProgressBar(10, bar_width=bar_width, file=out) time.sleep(1) reset_string_io(out) prog_bar.update() assert len(out.getvalue()) == 66 os.environ['COLUMNS'] = '30' reset_string_io(out) prog_bar.update() assert len(out.getvalue()) == 48 os.environ['COLUMNS'] = '60' reset_string_io(out) prog_bar.update() assert len(out.getvalue()) == 60
Example #15
Source File: test_log_helpers.py From n6 with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): self._pika_patcher = patch('n6lib.amqp_getters_pushers.pika') self.pika_mock = self._pika_patcher.start() self.addCleanup(self._pika_patcher.stop) self.pika_mock.BasicProperties.side_effect = lambda **kwargs: kwargs conn_mock = self.pika_mock.BlockingConnection.return_value = MagicMock() self.channel_mock = conn_mock.channel.return_value = MagicMock() self.error_logger = logging.getLogger('TestAMQPHandler_logger.errors') self.error_logger._log = MagicMock(side_effect=self.error_logger._log) self.handler = AMQPHandler(connection_params_dict={}, error_logger_name='TestAMQPHandler_logger.errors') self.addCleanup(self.handler.close) self.logger = logging.getLogger('TestAMQPHandler_logger') self.logger.propagate = False self.logger.setLevel(logging.INFO) self.logger.addHandler(self.handler) self.addCleanup(self.logger.removeHandler, self.handler) self.rk_template = '{hostname}.{script_basename}.{{levelname}}.{loggername}'.format( hostname=self.get_hostname(), script_basename=self.get_script_basename(), loggername='TestAMQPHandler_logger') self.constant_log_record_items = self.get_constant_log_record_items(dict( name='TestAMQPHandler_logger', filename='test_log_helpers.py', funcName='test', module='test_log_helpers', )) class UnRepr(object): def __repr__(self): raise RuntimeError('boom!') self.unserializable = UnRepr()
Example #16
Source File: test_unit_test_helpers.py From n6 with GNU Affero General Public License v3.0 | 5 votes |
def test_failure_for_unspecified_module(self, mocked__testmod, mocked__stdout): with patch.dict(sys.modules, {'__main__': self.module}): failures, tests = run_module_doctests(bar='spam') mocked__testmod.assert_called_once_with(None, bar='spam') self._do_assertions_for_failure(mocked__stdout, failures, tests)
Example #17
Source File: test_debug.py From deepstar with BSD 3-Clause Clear License | 5 votes |
def test_debug_level_1(self): try: with patch.dict(os.environ, {'DEBUG_LEVEL': '1'}): sys.stdout = StringIO() debug('test', 0) self.assertEqual(sys.stdout.getvalue().strip(), 'test') sys.stdout = StringIO() debug('test', 1) self.assertEqual(sys.stdout.getvalue().strip(), 'test') sys.stdout = StringIO() debug('test', 2) self.assertEqual(sys.stdout.getvalue().strip(), '') sys.stdout = StringIO() debug('test', 3) self.assertEqual(sys.stdout.getvalue().strip(), '') sys.stdout = StringIO() debug('test', 4) self.assertEqual(sys.stdout.getvalue().strip(), '') sys.stdout = StringIO() debug('test', 5) self.assertEqual(sys.stdout.getvalue().strip(), '') finally: sys.stdout = sys.__stdout__
Example #18
Source File: test_I2C.py From Adafruit_Python_GPIO with MIT License | 5 votes |
def safe_import_i2c(): # Mock the smbus module and inject it into the global namespace so the # Adafruit_GPIO.I2C module can be imported. The imported I2C module is # returned so global functions can be called on it. with patch.dict('sys.modules', {'smbus': Mock() }): import Adafruit_GPIO.I2C as I2C return I2C
Example #19
Source File: test_I2C.py From Adafruit_Python_GPIO with MIT License | 5 votes |
def create_device(address, busnum): # Mock the smbus module and inject it into the global namespace so the # Adafruit_GPIO.I2C module can be imported. Also inject a mock SMBus # instance to be returned by smbus.SMBus function calls. smbus = Mock() mockbus = MockSMBus() smbus.SMBus.return_value = mockbus with patch.dict('sys.modules', {'smbus': smbus}): import Adafruit_GPIO.I2C as I2C return (I2C.Device(address, busnum), smbus, mockbus)
Example #20
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_sh_exec1(self, mocked_chdir): """Test sh exec with cd, user home and shell variable""" self.pymp.locals['path'] = "~/${RUNTIME}/location" with patch.dict(pythonrc.os.environ, {'RUNTIME': 'dummy', 'HOME': '/home/me/'}): self.pymp.process_sh_cmd('cd {path}') mocked_chdir.assert_called_once_with('/home/me/dummy/location')
Example #21
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_raw_input_list_cmd1(self, ignored): mocked_cmd = Mock() with patch.dict(self.pymp.commands, {r'\l': mocked_cmd}): self.pymp.raw_input('>>> ') mocked_cmd.assert_called_once_with('global')
Example #22
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_raw_input_list_cmd0(self, ignored): mocked_cmd = Mock() with patch.dict(self.pymp.commands, {r'\l': mocked_cmd}): ret = self.pymp.raw_input('>>> ') mocked_cmd.assert_called_once_with('shutil')
Example #23
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_raw_input_edit_cmd(self, ignored): mocked_cmd = Mock() with patch.dict(self.pymp.commands, {r'\e': mocked_cmd}): self.pymp.raw_input('>>> ') mocked_cmd.assert_called_once_with('code')
Example #24
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_init_prompt(self): self.assertRegex( sys.ps1, ('\001\033' r'\[1;3[23]m\002>>> ' '\001\033' r'\[0m\002') ) self.assertEqual(sys.ps2, '\001\033[1;31m\002... \001\033[0m\002') with patch.dict(os.environ, {'SSH_CONNECTION': '1.1.1.1 10240 127.0.0.1 22'}): self.pymp.init_prompt() self.assertIn('[127.0.0.1]>>> ', sys.ps1) self.assertIn('[127.0.0.1]... ', sys.ps2)
Example #25
Source File: test_interpreter.py From pex with Apache License 2.0 | 5 votes |
def test_all_does_not_raise_with_empty_path_envvar(self): """ additionally, tests that the module does not raise at import """ with patch.dict(os.environ, clear=True): if PY3: import importlib importlib.reload(interpreter) else: reload(interpreter) interpreter.PythonInterpreter.all()
Example #26
Source File: handler.py From streamalert with Apache License 2.0 | 5 votes |
def __init__(self, options, config): self._config = config self._options = options self._type = options.subcommand self._files_filter = options.files self._rules = options.rules self._rules_dirs = options.rules_dir self._rules_engine = self._setup_rules_engine(options.rules_dir) self._verbose = options.verbose self._quiet = options.quiet self._s3_mocker = patch('streamalert.classifier.payload.s3.boto3.resource').start() self._tested_rules = set() self._passed = 0 self._failed = 0 prefix = self._config['global']['account']['prefix'] env = { 'CLUSTER': 'prod', 'STREAMALERT_PREFIX': prefix, 'AWS_ACCOUNT_ID': self._config['global']['account']['aws_account_id'], 'ALERTS_TABLE': '{}_streamalert_alerts'.format(prefix), } if 'stats' in options and options.stats: env['STREAMALERT_TRACK_RULE_STATS'] = '1' patch.dict( os.environ, env ).start()
Example #27
Source File: test_config.py From streamalert with Apache License 2.0 | 5 votes |
def test_get_parameters_invalid_json(self): """AppConfig - Get Parameters, Invalid JSON""" with patch.dict(os.environ, {'AWS_DEFAULT_REGION': 'us-east-1'}): key = '{}_state'.format(self._test_app_name) boto3.client('ssm').put_parameter( Name=key, Value='foobar', Type='SecureString', Overwrite=True ) self._config._get_parameters(key)
Example #28
Source File: test_app_base.py From streamalert with Apache License 2.0 | 5 votes |
def test_required_auth_info(self, auth_mock): """App Integration - Required Auth Info""" expected_result = {'host': 'host_name'} auth_mock.return_value = expected_result assert_equal(self._app.required_auth_info(), expected_result) auth_mock.return_value = None assert_equal(self._app.required_auth_info(), dict())
Example #29
Source File: test_slack.py From streamalert with Apache License 2.0 | 5 votes |
def test_filter_entries_not_implemented(): """SlackApp - Subclass Filter Entries Not Implemented""" # pylint: disable=protected-access,abstract-method class SlackFakeApp(SlackApp): """Fake Slack app that should raise a NotImplementedError""" @classmethod def _type(cls): return 'fake' @classmethod def _endpoint(cls): return 0 app_name = 'fake' event = get_event(app_name) context = get_mock_lambda_context(app_name) context.function_name = app_name with patch.dict(os.environ, {'AWS_DEFAULT_REGION': 'us-east-1'}): put_mock_params(app_name) SlackFakeApp(event, context)._filter_response_entries("")
Example #30
Source File: test_classifier.py From streamalert with Apache License 2.0 | 5 votes |
def setup(self): """Classifier - Setup""" with patch.object(classifier_module, 'Normalizer'), \ patch.object(classifier_module, 'FirehoseClient'), \ patch.object(classifier_module, 'SQSClient'), \ patch.dict(os.environ, {'CLUSTER': 'prod'}), \ patch('streamalert.classifier.classifier.config.load_config', Mock(return_value=self._mock_conf())): self._classifier = Classifier()