本文整理汇总了Python中mock.patch方法的典型用法代码示例。如果您正苦于以下问题:Python mock.patch方法的具体用法?Python mock.patch怎么用?Python mock.patch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock
的用法示例。
在下文中一共展示了mock.patch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_callSnappy
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_callSnappy():
"""
Test pdinstall.snappy.callSnappy
"""
from pdinstall.snappy import callSnappy
with patch("pdinstall.snappy.subprocess") as subprocess:
proc = MagicMock()
subprocess.Popen.return_value = proc
proc.stdout = ["Output message"]
proc.stderr = ["Error message"]
proc.returncode = 0
assert callSnappy("install")
assert proc.wait.called
subprocess.Popen.side_effect = Exception("Boom!")
assert callSnappy("install") is False
示例2: test_installedSnaps
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_installedSnaps():
"""
Test pdinstall.snappy.installedSnaps
"""
from pdinstall.snappy import installedSnaps
with patch("pdinstall.snappy.subprocess") as subprocess:
proc = MagicMock()
subprocess.Popen.return_value = proc
proc.stdout = [
"Name Date Version Developer",
"bad line",
"paradrop 2015-01-01 0.1.0"
]
snaps = installedSnaps()
assert snaps == {'paradrop': '0.1.0'}
subprocess.Popen.side_effect = Exception("Boom!")
assert_raises(Exception, installedSnaps)
示例3: test_get_with_course_id_for_other_site
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_get_with_course_id_for_other_site(self):
"""
This tests if the course can't be found in the organization
This test is incomplete
"""
with mock.patch('figures.helpers.settings.FEATURES', {'FIGURES_IS_MULTISITE': True}):
assert figures.helpers.is_multisite()
# Stand up other site. Candidate for a fixture
other_site = SiteFactory(domain='other.site')
other_org = OrganizationFactory(sites=[other_site])
course = CourseOverviewFactory(org=other_org.short_name)
request = APIRequestFactory().get(self.request_path)
force_authenticate(request, user=self.staff_user)
view = self.view_class.as_view({'get': 'retrieve'})
response = view(request, pk=str(course.id))
assert response.status_code == 403
示例4: testUnzip
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def testUnzip(self, build_info, create_dir):
src = '/tmp/input.zip'
dst = '/out/dir/path'
# bad args
un = files.Unzip([], build_info)
self.assertRaises(files.ActionError, un.Run)
un = files.Unzip([src], build_info)
self.assertRaises(files.ActionError, un.Run)
# bad path
un = files.Unzip([src, dst], build_info)
self.assertRaises(files.ActionError, un.Run)
# create error
create_dir.side_effect = files.file_util.Error
self.assertRaises(files.ActionError, un.Run)
# good
create_dir.side_effect = None
with mock.patch.object(files.zipfile, 'ZipFile', autospec=True) as z:
un = files.Unzip([src, dst], build_info)
un.Run()
z.assert_called_with(src)
z.return_value.extractall.assert_called_with(dst)
create_dir.assert_called_with(dst)
示例5: logger
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def logger():
# Configure logger mock
logger = mock.MagicMock()
logger_patch = mock.patch('logging.getLogger', mock.MagicMock(return_value=logger))
logger_patch.start()
yield logger
logger_patch.stop()
# Clear jira module configuration
jira.enabled = None
jira.execution_url = None
jira.summary_prefix = None
jira.labels = None
jira.comments = None
jira.fix_version = None
jira.build = None
jira.only_if_changes = None
jira.jira_tests_status.clear()
jira.attachments = []
示例6: test_wait_until_done
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_wait_until_done(self):
mock_projects = mock.Mock()
mock_opearations = mock.Mock()
mock_request = mock.Mock()
self._mock_service.projects = mock.Mock(return_value=mock_projects)
mock_projects.operations = mock.Mock(return_value=mock_opearations)
mock_opearations.get = mock.Mock(return_value=mock_request)
mock_request.execute = mock.Mock(return_value={'done': True, 'error': {}})
test_instance = self._create_test_instance()
with patch('apache_beam.io.filesystems.FileSystems', _MockFileSystems):
test_instance.run_on_all_files()
with self.assertRaisesRegexp(AssertionError, '.*already.*running.*'):
# Since there are running operations, the next call raises an exception.
test_instance.run_on_all_files()
test_instance.wait_until_done()
# Since all operations are done, the next call should raise no exceptions.
test_instance.run_on_all_files()
示例7: test_corrupted_split
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_corrupted_split(self):
self.incoming.add_measures(self.metric.id, [
incoming.Measure(datetime64(2014, 1, 1, 12, 0, 1), 69),
])
self.trigger_processing()
aggregation = self.metric.archive_policy.get_aggregation(
"mean", numpy.timedelta64(5, 'm'))
with mock.patch('gnocchi.carbonara.AggregatedTimeSerie.unserialize',
side_effect=carbonara.InvalidData()):
results = self.storage._get_splits_and_unserialize({
self.metric: {
aggregation: [
carbonara.SplitKey(
numpy.datetime64(1387800000, 's'),
numpy.timedelta64(5, 'm'))
],
},
})[self.metric][aggregation]
self.assertEqual(1, len(results))
self.assertIsInstance(results[0], carbonara.AggregatedTimeSerie)
# Assert it's an empty one since corrupted
self.assertEqual(0, len(results[0]))
self.assertEqual(results[0].aggregation, aggregation)
示例8: test_add_measures_update_subset
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_add_measures_update_subset(self):
m, m_sql = self._create_metric('medium')
measures = [
incoming.Measure(datetime64(2014, 1, 6, i, j, 0), 100)
for i in six.moves.range(2) for j in six.moves.range(0, 60, 2)]
self.incoming.add_measures(m.id, measures)
self.trigger_processing([m])
# add measure to end, in same aggregate time as last point.
new_point = datetime64(2014, 1, 6, 1, 58, 1)
self.incoming.add_measures(m.id, [incoming.Measure(new_point, 100)])
with mock.patch.object(self.incoming, 'add_measures') as c:
self.trigger_processing([m])
for __, args, __ in c.mock_calls:
self.assertEqual(
list(args[3])[0][0], carbonara.round_timestamp(
new_point, args[1].granularity * 10e8))
示例9: test_bad_filter_lambda2
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_bad_filter_lambda2(self):
# Causes error because not every d has the attribute "real"
# but error only shows on grow
filter_lambda = "d['real']"
self.display_a()
self.a.remove_filter(self.filter_lambda)
self.check_num_nodes_edges(6, 8)
with patch(SHOWERROR_FUNC) as errorMsgBox:
self.a.add_filter(filter_lambda)
self.assertFalse(errorMsgBox.called)
with patch(SHOWERROR_FUNC) as errorMsgBox:
try:
self.a.grow_node(self.a._find_disp_node('out'))
except Exception:
pass
self.assertTrue(errorMsgBox.called)
# Make sure no edges added or removed
#self.check_num_nodes_edges(6, 8)
示例10: test_interrupted_flush_index
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_interrupted_flush_index(self, local_client):
target_index = {"red": {"local_timestamp": 4000, "remote_timestamp": 4000}}
utils.set_local_index(local_client, target_index)
local_client.index = {"invalid_data": []}
with mock.patch("json.dump") as json_dump:
json_dump.side_effect = ValueError("something went wrong")
with pytest.raises(ValueError):
local_client.flush_index(compressed=False)
with open(local_client.index_path(), "rt") as fp:
index = json.load(fp)
assert index == target_index
示例11: test_get_index_timestamps
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_get_index_timestamps(self, s3_client, compression, magic_result):
with mock.patch("magic.from_buffer") as from_buffer:
# given
from_buffer.return_value = magic_result
utils.set_s3_index(
s3_client,
{
"hello": {"remote_timestamp": 1234, "local_timestamp": 1200},
"world": {"remote_timestamp": 5000},
},
compression=compression,
)
# then
assert s3_client.get_remote_timestamp("hello") == 1234
assert s3_client.get_index_local_timestamp("hello") == 1200
assert s3_client.get_remote_timestamp("world") == 5000
assert s3_client.get_index_local_timestamp("world") is None
示例12: test_injector_does_not_fail_for_401_responses_with_no_content_type
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_injector_does_not_fail_for_401_responses_with_no_content_type():
bower = bowerstatic.Bower()
components = bower.components('components', os.path.join(
os.path.dirname(__file__), 'bower_components'))
def wsgi(environ, start_response):
# Can not use 401 here as webtest only accepts 200 or 3xx, which is ok
# as we want to test the behaviour if no content type is given
start_response('302', [('Content-Type', None)])
include = components.includer(environ)
with pytest.raises(bowerstatic.Error):
include('jquery/nonexistent.js')
return [b'<html><head></head><body>Hello!</body></html>']
injector = bower.injector(wsgi)
c = Client(injector)
# webtest checks, in contracy to pyramid, the headers and breaks if one of
# them is not a string.
with mock.patch('webtest.lint.check_headers'):
c.get('/')
示例13: setUp
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def setUp(self):
self.patcher = patch('requests.get', side_effect=mock_requestsGithub)
self.patcher.start()
示例14: test_load_with_include
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_load_with_include(main_contents, inner_contents):
with mock.patch('pca.utils.serialization.yaml.read_from_file') as mocked_read_from_file:
mocked_read_from_file.return_value = inner_contents
result = serialization.load_yaml(main_contents)
assert result == {
'foo': ['spam', 'eggs'],
'included': {'bar': ['spam', 'eggs']},
}
示例15: test_load_from_file
# 需要导入模块: import mock [as 别名]
# 或者: from mock import patch [as 别名]
def test_load_from_file():
contents = (
"---\n"
"foo: bar\n"
)
with mock.patch('pca.utils.serialization.yaml.read_from_file') as mocked_read_from_file:
mocked_read_from_file.return_value = contents
result = serialization.load_yaml_from_filepath('path/to/a/file.yaml')
assert result == {'foo': 'bar'}
mocked_read_from_file.assert_called_with('path/to/a/file.yaml')