本文整理汇总了Python中mock.patch.dict方法的典型用法代码示例。如果您正苦于以下问题:Python patch.dict方法的具体用法?Python patch.dict怎么用?Python patch.dict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.patch
的用法示例。
在下文中一共展示了patch.dict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_initialize_library_too_many_ns
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_initialize_library_too_many_ns():
self = create_autospec(Arctic)
self._conn = create_autospec(MongoClient)
self._cache = create_autospec(Cache)
lib = create_autospec(ArcticLibraryBinding)
lib.database_name = sentinel.db_name
self._conn.__getitem__.return_value.list_collection_names.return_value = [x for x in six.moves.xrange(5001)]
lib_type = Mock()
with pytest.raises(ArcticException) as e:
with patch.dict('arctic.arctic.LIBRARY_TYPES', {sentinel.lib_type: lib_type}), \
patch('arctic.arctic.ArcticLibraryBinding', return_value=lib, autospec=True) as ML:
Arctic.initialize_library(self, sentinel.lib_name, sentinel.lib_type, thing=sentinel.thing)
assert self._conn.__getitem__.call_args_list == [call(sentinel.db_name),
call(sentinel.db_name)]
assert lib_type.initialize_library.call_count == 0
assert 'Too many namespaces 5001, not creating: sentinel.lib_name' in str(e.value)
示例2: test_initialize_library_with_list_coll_names
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_initialize_library_with_list_coll_names():
self = create_autospec(Arctic)
self._conn = create_autospec(MongoClient)
self._cache = create_autospec(Cache)
lib = create_autospec(ArcticLibraryBinding)
lib.database_name = sentinel.db_name
lib.get_quota.return_value = None
self._conn.__getitem__.return_value.list_collection_names.return_value = [x for x in six.moves.xrange(5001)]
lib_type = Mock()
with patch.dict('arctic.arctic.LIBRARY_TYPES', {sentinel.lib_type: lib_type}), \
patch('arctic.arctic.ArcticLibraryBinding', return_value=lib, autospec=True) as ML:
Arctic.initialize_library(self, sentinel.lib_name, sentinel.lib_type, thing=sentinel.thing, check_library_count=False)
assert ML.call_args_list == [call(self, sentinel.lib_name)]
assert ML.return_value.set_library_type.call_args_list == [call(sentinel.lib_type)]
assert ML.return_value.set_quota.call_args_list == [call(10 * 1024 * 1024 * 1024)]
assert lib_type.initialize_library.call_args_list == [call(ML.return_value, thing=sentinel.thing)]
示例3: test_graph_multiple_custom_x
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_graph_multiple_custom_x(builddir):
""" Test the graph feature with multiple metrics """
runner = CliRunner()
with patch.dict("os.environ", values=PATCHED_ENV, clear=True):
result = runner.invoke(
main.cli,
[
"--path",
builddir,
"graph",
_path,
"raw.loc",
"raw.comments",
"-x",
"raw.sloc",
],
)
assert result.exit_code == 0, result.stdout
示例4: test_graph_output
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_graph_output(builddir):
""" Test the graph feature with target output file """
runner = CliRunner()
with patch.dict("os.environ", values=PATCHED_ENV, clear=True):
result = runner.invoke(
main.cli,
[
"--debug",
"--path",
builddir,
"graph",
_path,
"raw.loc",
"-o",
"test.html",
],
)
assert result.exit_code == 0, result.stdout
示例5: test_filter_entries_not_implemented
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
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("")
示例6: test_adaptive_length
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
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
示例7: test__get_version_info_loggers_enabled
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test__get_version_info_loggers_enabled(self):
mock_loggers = {
'versionfinder': Mock(),
'pip': Mock(),
'git': Mock()
}
def se_getLogger(lname):
return mock_loggers[lname]
with patch('awslimitchecker.version.logging.getLogger') as mock_logger:
mock_logger.side_effect = se_getLogger
with patch.dict(
'awslimitchecker.version.os.environ',
{'VERSIONCHECK_DEBUG': 'true'}, clear=True
):
with patch('awslimitchecker.version.find_version'):
version._get_version_info()
assert mock_logger.mock_calls == []
assert mock_loggers['versionfinder'].mock_calls == []
assert mock_loggers['pip'].mock_calls == []
assert mock_loggers['git'].mock_calls == []
示例8: test_no_service_key_warn
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
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'
})
]
示例9: test_main
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_main(self):
with patch('find_forks.find_forks.find_forks', return_value=None) as find_forks_mock:
main()
sent_args = CONFIG.copy()
sent_args.update({'user': None, 'repo': None, 'no_fetch': False})
find_forks_mock.assert_called_once_with(**sent_args)
# Test __version__ exceptions.
find_forks_mock = MagicMock(side_effect=SystemError())
del find_forks_mock.__version__
modules = {
'find_forks.__init__': find_forks_mock
}
with patch.dict('sys.modules', modules):
self.assertRaises(ImportError, main)
示例10: test_load_settings
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_load_settings():
"""
Test updateSettings function
"""
with patch.dict(os.environ, {'DEBUG_MODE': 'true'}):
settings.loadSettings("unittest", ["PD_TEST_VAR:stuff"])
assert settings.PD_TEST_VAR == "stuff"
assert settings.DEBUG_MODE is True
示例11: patch_module
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def patch_module(module_path, extra_properties=None):
"""
Patch an entirely new module.
This can be used as both decorator or a context (e.g. `with patch_module(...):`).
:param module_path: lms.djangoapps.certificates.models
:param extra_properties: {'SomeClass': Mock()}
:return:
"""
if not module_path:
raise ValueError('module_path is required')
path_parts = module_path.split('.')
patch_specs = {}
for i, part in enumerate(path_parts):
sub_path = '.'.join(path_parts[:i+1])
print('sub_path', sub_path)
module = ModuleType(sub_path)
patch_specs[sub_path] = module
if i == (len(path_parts) - 1): # Leaf module
if extra_properties:
for key, value in six.iteritems(extra_properties):
setattr(module, key, value)
return patch.dict('sys.modules', patch_specs)
示例12: test_course_grade_factory_with_ginkgo
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_course_grade_factory_with_ginkgo():
hawthorn_key = 'lms.djangoapps.grades.course_grade_factory'
with patch.dict('sys.modules', {hawthorn_key: None}):
with patch_module('lms.djangoapps.grades.new.course_grade_factory', {'CourseGradeFactory': 'hi'}):
import figures.compat
reload(figures.compat)
assert figures.compat.CourseGradeFactory == 'hi'
示例13: test_env_var_setting_single_and_multi_model
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_env_var_setting_single_and_multi_model(start_model_server, mock_get_num_cpu):
test_handler_str = 'foo'
with patch.dict('os.environ', {}):
serving_mms._set_mms_configs(True, test_handler_str)
assert os.environ["SAGEMAKER_NUM_MODEL_WORKERS"] == '1'
assert os.environ["SAGEMAKER_MMS_MODEL_STORE"] == '/'
assert os.environ["SAGEMAKER_MMS_LOAD_MODELS"] == ''
assert os.environ["SAGEMAKER_MAX_REQUEST_SIZE"] == str(serving_mms.DEFAULT_MAX_CONTENT_LEN)
assert os.environ["SAGEMAKER_MMS_DEFAULT_HANDLER"] == test_handler_str
示例14: test_set_max_content_len
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_set_max_content_len(start_model_server):
test_handler_str = 'foo'
with patch.dict('os.environ', {}):
serving_mms._set_mms_configs(False, test_handler_str)
assert os.environ['SAGEMAKER_MAX_REQUEST_SIZE'] == str(serving_mms.DEFAULT_MAX_CONTENT_LEN)
with patch.dict('os.environ', {'MAX_CONTENT_LENGTH': str(TEST_MAX_CONTENT_LEN)}):
serving_mms._set_mms_configs(False, test_handler_str)
assert os.environ['SAGEMAKER_MAX_REQUEST_SIZE'] == str(TEST_MAX_CONTENT_LEN)
示例15: test_decode
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import dict [as 别名]
def test_decode(content_type):
decoder = Mock()
with patch.dict(encoder._dmatrix_decoders_map, {content_type: decoder}, clear=True):
encoder.decode(42, content_type)
decoder.assert_called_once_with(42)