本文整理汇总了Python中mock.patch.object方法的典型用法代码示例。如果您正苦于以下问题:Python patch.object方法的具体用法?Python patch.object怎么用?Python patch.object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.patch
的用法示例。
在下文中一共展示了patch.object方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_git_diff
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_git_diff():
with patch.object(git, 'execute') as mock:
mock.return_value = '\n'.join(diff)
result = git.git_diff()
expected_cmd = [
'git', '-c', 'diff.mnemonicprefix=no',
'diff', '--no-color', '--no-ext-diff'
]
mock.assert_called_once_with(expected_cmd)
[[[a, b, c, d, e, f, g]]] = result
assert a.is_context
assert b.is_context
assert c.is_context
assert d.is_added
assert e.is_context
assert f.is_context
assert g.is_context
示例2: test_categorization_response_error
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_categorization_response_error(self):
"""Tests whether the ResponseError is raised when the response
returned from the actual API call is empty.
"""
domains = ['yosemite.gov', 'joushuatree.gov', 'deathvalley.gov']
# empty responses should raise an error
all_responses = [{}]
# mock cache file
mock_read = mock_open(read_data="{}")
with patch.object(
builtins, 'open', mock_read, create=True
), patch.object(
ApiCache, 'bulk_lookup', autospec=True, return_value={}
), patch.object(
MultiRequest, 'multi_post', autospec=True, return_value=all_responses
):
i = InvestigateApi('hocus pocus', 'cache.json')
with T.assert_raises(ResponseError):
i.categorization(domains)
示例3: _test_api_call_get
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def _test_api_call_get(self, call, endpoint, request, expected_url_params,
api_response, expected_result, expected_query_params=None):
"""
Tests a OpenDNS call by mocking out the HTTP GET request.
Args:
call: function in OpenDNSApi to call.
endpoint: endpoint of OpenDNS API that is hit (appended to base url)
request: call arguments
expected_url_params: URL parameters that should be passed to API
api_response: the expected response by the API
expected_result: what call should return (given the api response provided)
expected_query_params: query parameters that should be passed to API
"""
with patch.object(self.opendns, '_requests') as request_mock:
request_mock.multi_get.return_value = api_response
result = call(request)
url = self.opendns._to_url(endpoint.format(expected_url_params))
request_mock.multi_get.assert_called_with([url], expected_query_params)
T.assert_equal(result, expected_result)
示例4: _test_api_call
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def _test_api_call(
self, call, request, expected_query_params, api_response,
expected_result):
"""
Tests a AlexaRankingApi call by mocking out the HTTP request.
Args:
call: Function in AlexaRankingApi to call.
endpoint: Endpoint of AlexaRanking API that is hit.
request: Call arguments.
expected_query_params: Parameters that should be passed to API.
api_response: The expected response by the API.
expected_result: What the call should return.
"""
with patch.object(self.ar, '_requests') as request_mock:
request_mock.multi_get.return_value = api_response
result = call(request)
request_mock.multi_get.assert_called_with(
self.ar.BASE_URL,
to_json=False,
query_params=expected_query_params)
T.assert_equal(result, expected_result)
示例5: _open_cache
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def _open_cache(self, initial_contents=None, update_cache=True):
"""Creates an ApiCache object, mocking the contents of the cache on disk.
Args:
initial_contents: A dict containing the initial contents of the cache
update_cache: Specifies whether ApiCache should write out the
cache file when closing it
Returns:
ApiCache
"""
if not initial_contents:
initial_contents = {}
file_contents = simplejson.dumps(initial_contents)
mock_read = mock_open(read_data=file_contents)
with patch.object(builtins, 'open', mock_read, create=True):
api_cache = ApiCache(self._file_name, update_cache=update_cache)
return api_cache
示例6: _test_api_call
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def _test_api_call(self, call, endpoint, request, expected_query_params, api_response, expected_result):
"""
Tests a VirusTotalApi call by mocking out the HTTP request.
Args:
call: function in VirusTotalApi to call.
endpoint: endpoint of VirusTotal API that is hit (appended to base url)
request: call arguments
expected_query_params: query parameters that should be passed to API
api_response: the expected response by the API
expected_result: what call should return (given the api response provided)
"""
with patch.object(self.vt, '_requests') as request_mock:
request_mock.multi_get.return_value = api_response
result = call(request)
param_list = [self.vt.BASE_DOMAIN + endpoint.format(param) for param in expected_query_params]
request_mock.multi_get.assert_called_with(param_list, file_download=ANY)
T.assert_equal(result, expected_result)
示例7: test_ctor
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_ctor(refresher):
"""
Refresher object should contain a few handlers
:param refresher:
:return:
"""
assert len(refresher.refreshers) > 0
actual_handlers = list(refresher.refreshers.keys())
expected_handlers = [
"schemata",
"tables",
"views",
"types",
"databases",
"casing",
"functions",
]
assert expected_handlers == actual_handlers
示例8: test_refresh_called_once
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_refresh_called_once(refresher):
"""
:param refresher:
:return:
"""
callbacks = Mock()
pgexecute = Mock()
special = Mock()
with patch.object(refresher, "_bg_refresh") as bg_refresh:
actual = refresher.refresh(pgexecute, special, callbacks)
time.sleep(1) # Wait for the thread to work.
assert len(actual) == 1
assert len(actual[0]) == 4
assert actual[0][3] == "Auto-completion refresh started in the background."
bg_refresh.assert_called_with(pgexecute, special, callbacks, None, None)
示例9: test_exit_without_active_connection
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_exit_without_active_connection(executor):
quit_handler = MagicMock()
pgspecial = PGSpecial()
pgspecial.register(
quit_handler,
"\\q",
"\\q",
"Quit pgcli.",
arg_type=NO_QUERY,
case_sensitive=True,
aliases=(":q",),
)
with patch.object(executor, "conn", BrokenConnection()):
# we should be able to quit the app, even without active connection
run(executor, "\\q", pgspecial=pgspecial)
quit_handler.assert_called_once()
# an exception should be raised when running a query without active connection
with pytest.raises(psycopg2.InterfaceError):
run(executor, "select 1", pgspecial=pgspecial)
示例10: test_date_range_end_not_in_range
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_date_range_end_not_in_range(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'b': 2.,
'index': dt(2013, 1, 1, tzinfo=mktz('Europe/London'))
},
{'b': 3.,
'c': 4.,
'index': dt(2013, 1, 2, 10, 1, tzinfo=mktz('Europe/London'))
},
]
tickstore_lib._chunk_size = 1
tickstore_lib.write('SYM', DUMMY_DATA)
with patch.object(tickstore_lib._collection, 'find', side_effect=tickstore_lib._collection.find) as f:
df = tickstore_lib.read('SYM', date_range=DateRange(20130101, dt(2013, 1, 2, 9, 0)), columns=None)
assert_array_equal(df['b'].values, np.array([2.]))
assert mongo_count(tickstore_lib._collection, filter=f.call_args_list[-1][0][0]) == 1
示例11: test_prune_previous_versions_retries_find_calls
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_prune_previous_versions_retries_find_calls(library, fw_pointers_cfg):
with FwPointersCtx(fw_pointers_cfg):
original_next = pymongo.cursor.Cursor.next
callers = set()
def _next(*args, **kwargs):
vs_caller_name = next(c for c in inspect.stack() if c[1].endswith('arctic/store/version_store.py'))[3]
if vs_caller_name not in callers:
callers.add(vs_caller_name)
raise OperationFailure(0)
else:
return original_next(*args, **kwargs)
library.write(symbol, ts1, prune_previous_version=False)
library.write(symbol, ts2, prune_previous_version=False)
with patch.object(pymongo.cursor.Cursor, "next", autospec=True, side_effect=_next):
library._prune_previous_versions(symbol, keep_mins=0)
assert mongo_count(library._versions, filter={'symbol': symbol}) == 1
示例12: test_ArcticLibraryBinding_db
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_ArcticLibraryBinding_db():
arctic = create_autospec(Arctic)
arctic._conn = create_autospec(MongoClient)
alb = ArcticLibraryBinding(arctic, "sentinel.library")
with patch.object(alb, '_auth') as _auth:
# connection is cached during __init__
alb._db
assert _auth.call_count == 0
# Change the arctic connection
arctic._conn = create_autospec(MongoClient)
alb._db
assert _auth.call_count == 1
# connection is still cached
alb._db
assert _auth.call_count == 1
示例13: test_sending_to_multiple_numbers
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_sending_to_multiple_numbers(self):
class TestNotification(TwilioTextNotification):
from_number = '1231231234'
template_name = 'hello_world'
def get_recipients(self):
return ['1234567890', '0987654321']
with patch.object(MessageList, 'create') as mocked_create:
notification = TestNotification()
notification.send()
self.assertEqual(mocked_create.call_count, 2)
for recipient in notification.get_recipients():
mocked_create.assert_any_call(
body='Hello World',
to=recipient,
from_=notification.get_sent_from()
)
示例14: test_git_show
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def test_git_show():
with patch.object(git, 'execute') as mock:
git.git_show(None, 'a')
mock.assert_called_once_with(['git', 'show', ':a'])
with patch.object(git, 'execute') as mock:
git.git_show('origin/master', 'a')
mock.assert_called_once_with(['git', 'show', 'origin/master:a'])
示例15: _patch_and_assert_categorization
# 需要导入模块: from mock import patch [as 别名]
# 或者: from mock.patch import object [as 别名]
def _patch_and_assert_categorization(self, all_responses, expected_responses, domains, expected_url, expected_data):
with patch.object(MultiRequest, 'multi_post', autospec=True, return_value=all_responses) as patched_multi_post:
actual_responses = self.opendns.categorization(domains)
patched_multi_post.assert_called_with(ANY, expected_url, data=expected_data)
assert expected_responses == actual_responses