本文整理汇总了Python中unittest.mock.MagicMock.reset_mock方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.reset_mock方法的具体用法?Python MagicMock.reset_mock怎么用?Python MagicMock.reset_mock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.reset_mock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tests_residual_plotter
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def tests_residual_plotter(self, mock_pyplot, mock_pyplot_subplot):
"""
Tests basic execution of residual plot.
Simply tests pyplot show is called by mocking its `show` method
"""
# setup a mock which will handle all calls to matplotlib Axes calls
# (e.g., bar, plot or semilogx) so we can test what has been called:
mocked_axes_obj = MagicMock()
mock_pyplot_subplot.side_effect = lambda *a, **v: mocked_axes_obj
residuals = res.Residuals(self.gsims, self.imts)
residuals.get_residuals(self.database, component="Geometric")
for gsim in self.gsims:
for imt in self.imts:
ResidualPlot(residuals, gsim, imt, bin_width=0.1)
# assert we called pyplot show:
self.assertTrue(mock_pyplot.show.call_count == 1)
ResidualPlot(residuals, gsim, imt, bin_width=0.1,
show=False)
# assert we did NOT call pyplot show (call count still 1):
self.assertTrue(mock_pyplot.show.call_count == 1)
# reset mock:
mock_pyplot.show.reset_mock()
# assert we called the right matplotlib plotting functions:
self.assertTrue(mocked_axes_obj.bar.called)
self.assertTrue(mocked_axes_obj.plot.called)
self.assertFalse(mocked_axes_obj.semilogx.called)
# reset mock:
mocked_axes_obj.reset_mock()
示例2: test_200_run
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
async def test_200_run(self):
rc = MagicMock(spec=RestClient)
pilots = {}
jobs = {}
tasks = defaultdict(dict)
async def client(method, url, args=None):
logger.info('REST: %s, %s', method, url)
if url.startswith('/dataset_summaries/status'):
return {'processing':['foo']}
elif url.startswith('/datasets/foo/job_counts/status'):
return jobs
elif url.startswith('/datasets/foo/task_counts/name_status'):
client.called = True
return tasks
if url.startswith('/datasets/foo'):
return {'dataset':123,'status':'processing'}
else:
raise Exception()
client.called = False
rc.request = client
mon = MagicMock(spec=StatsClient)
await dataset_monitor.run(rc, mon, debug=True)
self.assertTrue(client.called)
self.assertTrue(mon.gauge.called)
jobs['processing'] = 1
mon.reset_mock()
await dataset_monitor.run(rc, mon, debug=True)
self.assertTrue(mon.gauge.called)
tasks['generate']['queued'] = 1
mon.reset_mock()
await dataset_monitor.run(rc, mon, debug=True)
self.assertTrue(mon.gauge.called)
示例3: test_default_does_not_call_traffic
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_default_does_not_call_traffic(mock_get_token, mock_fake_lizzy,
mock_lizzy_get, mock_lizzy_post: MagicMock):
runner = CliRunner()
result = runner.invoke(main, ['create', config_path,
'42', '1.0', '--region', 'aa-bbbb-1'],
env=FAKE_ENV, catch_exceptions=False)
assert 'Fetching authentication token.. . OK' in result.output
assert 'Requesting new stack.. OK' in result.output
assert 'Stack ID: stack1-d42' in result.output
assert 'Waiting for new stack... . . OK' in result.output
assert 'Deployment Successful' in result.output
assert 'kio version approve' not in result.output
mock_lizzy_post.assert_called_once_with('https://localhost/stacks',
data=None,
headers={
'Content-type': 'application/json',
'Authorization': 'Bearer TOKEN'
},
json={
'keep_stacks': None,
'disable_rollback': False,
'region': 'aa-bbbb-1',
'parameters': ['1.0', ],
'dry_run': False,
'senza_yaml': 'SenzaInfo: [Something]\n',
'new_traffic': None,
'stack_version': '42',
'tags': ()
},
verify=False)
FakeLizzy.traffic.assert_not_called()
mock_fake_lizzy._delete_mock.assert_not_called()
mock_lizzy_post.reset_mock()
FakeLizzy.reset()
示例4: test_forcesell_handle_invalid
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_forcesell_handle_invalid(default_conf, update, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf)
mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True)
msg_mock = MagicMock()
mocker.patch.multiple('freqtrade.rpc.telegram',
_CONF=default_conf,
init=MagicMock(),
send_msg=msg_mock)
mocker.patch.multiple('freqtrade.main.exchange',
validate_pairs=MagicMock())
init(default_conf, create_engine('sqlite://'))
# Trader is not running
update_state(State.STOPPED)
update.message.text = '/forcesell 1'
_forcesell(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'not running' in msg_mock.call_args_list[0][0][0]
# No argument
msg_mock.reset_mock()
update_state(State.RUNNING)
update.message.text = '/forcesell'
_forcesell(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'Invalid argument' in msg_mock.call_args_list[0][0][0]
# Invalid argument
msg_mock.reset_mock()
update_state(State.RUNNING)
update.message.text = '/forcesell 123456'
_forcesell(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'Invalid argument.' in msg_mock.call_args_list[0][0][0]
示例5: CallableRecursionTest
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
class CallableRecursionTest(DBConBase):
"""Callable recursion test."""
def setUp(self):
"""Setup."""
super(CallableRecursionTest, self).setUp()
self.check_depth = MagicMock(
side_effect=lambda doc, cur_depth: doc.is_last
)
class TestDoc(gj.Document):
"""Test document."""
name = db.StringField()
is_last = db.BooleanField()
ref = gj.FollowReferenceField(
"self", max_depth=self.check_depth
)
def __str__(self):
"""Return stringified summary."""
return ("TestDoc<ID: {}, is_last: {}, ref: {}>").format(
self.name, self.is_last, getattr(self.ref, "id", None)
)
def to_dict(self):
"""Return the dict."""
return str(self.id) if self.is_last else {
"id": str(self.id),
"name": self.name,
"is_last": self.is_last,
"ref": self.ref.to_dict()
}
self.docs = [
TestDoc.objects.create(
name=("Test {}").format(count),
is_last=(count == 4)
) for count in range(6)
]
for (index, doc) in enumerate(self.docs):
doc.ref = self.docs[(index + 1) % len(self.docs)]
doc.save()
# Needs to reset mock because doc.save calls to_mongo
self.check_depth.reset_mock()
def test_from_first(self):
"""Should encode the element from first to the element is_last=True."""
max_depth_level = 4
correct_data = self.docs[0].to_dict()
actual_data = json.loads(self.docs[0].to_json())
self.maxDiff = None
self.assertEqual(correct_data, actual_data)
self.assertEqual(self.check_depth.call_count, max_depth_level)
self.check_depth.assert_has_calls([
call(self.docs[count], count - 1)
for count in range(1, max_depth_level + 1)
])
示例6: test_traffic
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_traffic(monkeypatch):
mock_patch = MagicMock()
mock_patch.return_value = FakeResponse(200, '["stack1","stack2"]')
monkeypatch.setattr('requests.patch', mock_patch)
lizzy = Lizzy('https://lizzy.example', '7E5770K3N')
lizzy.traffic('574CC', 42)
header = make_header('7E5770K3N')
mock_patch.assert_called_once_with('https://lizzy.example/api/stacks/574CC',
headers=header,
data=None,
json={"new_traffic": 42},
verify=False)
# call with region payload
mock_patch.reset_mock()
lizzy = Lizzy('https://lizzy.example', '7E5770K3N')
lizzy.traffic('574CC', 42, region='ab-foo-7')
header = make_header('7E5770K3N')
mock_patch.assert_called_once_with('https://lizzy.example/api/stacks/574CC',
headers=header,
data=None,
json={'new_traffic': 42,
'region': 'ab-foo-7'},
verify=False)
示例7: test_status_handle
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_status_handle(default_conf, update, ticker, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf)
mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True)
msg_mock = MagicMock()
mocker.patch('freqtrade.main.rpc.send_msg', MagicMock())
mocker.patch.multiple('freqtrade.rpc.telegram',
_CONF=default_conf,
init=MagicMock(),
send_msg=msg_mock)
mocker.patch.multiple('freqtrade.main.exchange',
validate_pairs=MagicMock(),
get_ticker=ticker)
init(default_conf, create_engine('sqlite://'))
update_state(State.STOPPED)
_status(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'trader is not running' in msg_mock.call_args_list[0][0][0]
msg_mock.reset_mock()
update_state(State.RUNNING)
_status(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'no active trade' in msg_mock.call_args_list[0][0][0]
msg_mock.reset_mock()
# Create some test data
create_trade(0.001)
# Trigger status while we have a fulfilled order for the open trade
_status(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert '[BTC_ETH]' in msg_mock.call_args_list[0][0][0]
示例8: test_magic_methods_fspath
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_magic_methods_fspath(self):
mock = MagicMock()
expected_path = mock.__fspath__()
mock.reset_mock()
self.assertEqual(os.fspath(mock), expected_path)
mock.__fspath__.assert_called_once()
示例9: test_count_handle
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_count_handle(default_conf, update, ticker, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf)
mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True)
msg_mock = MagicMock()
mocker.patch.multiple(
'freqtrade.rpc.telegram',
_CONF=default_conf,
init=MagicMock(),
send_msg=msg_mock)
mocker.patch.multiple('freqtrade.main.exchange',
validate_pairs=MagicMock(),
get_ticker=ticker,
buy=MagicMock(return_value='mocked_order_id'))
init(default_conf, create_engine('sqlite://'))
update_state(State.STOPPED)
_count(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1
assert 'not running' in msg_mock.call_args_list[0][0][0]
msg_mock.reset_mock()
update_state(State.RUNNING)
# Create some test data
create_trade(0.001)
msg_mock.reset_mock()
_count(bot=MagicMock(), update=update)
msg = '<pre> current max\n--------- -----\n 1 {}</pre>'.format(
default_conf['max_open_trades']
)
assert msg in msg_mock.call_args_list[0][0][0]
示例10: ApiRequestTests
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
class ApiRequestTests(unittest.TestCase):
def setUp(self):
self.api_call = 'api.test'
self.token = "TestToken"
self.http_status_code = http.client.OK
self.mocked_https_connection = MagicMock()
self.mocked_https_response = MagicMock()
self.parameters = {"token": self.token}
def tearDown(self):
self.mocked_https_connection.reset_mock()
def test_api_request_is_successful(self):
api_call = "api.test"
parameters = urllib.parse.urlencode(self.parameters)
api_request = SlackApiRequest(api_call, self.token)
response_data = {'ok': True, 'args': {'foo': 'bar'}}
response_json = json.dumps(response_data)
response_data = bytes(response_json.encode("utf-8"))
self.mocked_https_response.status = http.client.OK
self.mocked_https_response.read = MagicMock(return_value=response_data)
self.mocked_https_connection.getresponse = MagicMock(return_value=self.mocked_https_response)
api_request._connection = self.mocked_https_connection
api_request.execute("api.test")
expected_call_url = slackapi.API_BASE_URL + api_call + "?" + parameters
self.mocked_https_connection.request.assert_called_with("GET", expected_call_url)
def test_api_request_with_paramerters_is_successful(self):
api_call = "api.test"
self.parameters.update({'param': 10})
parameters = urllib.parse.urlencode(self.parameters)
api_request = SlackApiRequest(api_call, self.token)
response_data = {'ok': True, 'args': {'foo': 'bar'}}
response_json = json.dumps(response_data)
response_data = bytes(response_json.encode("utf-8"))
self.mocked_https_response.status = http.client.OK
self.mocked_https_response.read = MagicMock(return_value=response_data)
self.mocked_https_connection.getresponse = MagicMock(return_value=self.mocked_https_response)
api_request._connection = self.mocked_https_connection
api_request.execute(self.parameters)
expected_call_url = slackapi.API_BASE_URL + api_call + "?" + parameters
self.mocked_https_connection.request.assert_called_with("GET", expected_call_url)
def test_api_request_is_fails_because_of_invalid_http_status(self):
api_call = "api.test"
parameters = urllib.parse.urlencode(self.parameters)
api_request = SlackApiRequest(api_call, self.token)
response_data = {'ok': True, 'args': {'foo': 'bar'}}
response_json = json.dumps(response_data)
response_data = bytes(response_json.encode("utf-8"))
self.mocked_https_response.status = http.client.BAD_REQUEST
self.mocked_https_response.read = MagicMock(return_value=response_data)
self.mocked_https_connection.getresponse = MagicMock(return_value=self.mocked_https_response)
api_request._connection = self.mocked_https_connection
self.assertRaises(Exception, api_request.execute, "api.test")
示例11: test_wait
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_wait(self):
irc = MagicMock()
irc.poll = MagicMock()
r = IRCReporter(irc)
irc.reset_mock()
r.wait()
assert irc.poll.call_args == [()]
示例12: test_report_build_failure
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_report_build_failure(self):
irc = MagicMock()
irc.say = MagicMock()
r = IRCReporter(irc)
irc.reset_mock()
r.report_build_failure()
assert irc.say.call_args == [(('TTT: Build failure!'),)]
示例13: test_halt
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def test_halt(self):
irc = MagicMock()
irc.disconnect = MagicMock()
r = IRCReporter(irc)
irc.reset_mock()
r.halt()
assert irc.disconnect.call_args == [()]
示例14: TestMpdSearchStore
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
class TestMpdSearchStore(unittest.TestCase):
def setUp(self):
self.sender = MagicMock(spec=MpdCommandSender)
self.search = MpdSearchStore(self.sender)
self.observer = MagicMock(spec=SearchStoreListener)
self.search.add_listener(self.observer)
def tearDown(self):
pass
def test_search_ok(self):
args = ["artist", "test"]
self.search.begin_search(args)
sender_calls = [call.send("search", args, self.search._on_load)]
self.assertListEqual(self.sender.mock_calls, sender_calls)
observer_calls = [call.search_started(self.search)]
self.assertListEqual(self.observer.mock_calls, observer_calls)
self.observer.reset_mock()
result = CallbackResult(CALLBACK_OK, "search", args, SEARCH_RESULTS)
self.search._on_load(result)
observer_calls = [call.store_changed(self.search),
call.search_finished(self.search)]
self.assertListEqual(self.observer.mock_calls, observer_calls)
expected = [Song(item) for item in SEARCH_RESULTS]
self.assertListEqual(list(self.search), expected)
def test_search_failed(self):
args = ["artist", "test"]
self.search.begin_search(args)
sender_calls = [call.send("search", args, self.search._on_load)]
self.assertListEqual(self.sender.mock_calls, sender_calls)
observer_calls = [call.search_started(self.search)]
self.assertListEqual(self.observer.mock_calls, observer_calls)
self.observer.reset_mock()
result = CallbackResult(CALLBACK_ERR_NOT_CONNECTED, "search", args,
error=None)
self.search._on_load(result)
observer_calls = [call.store_changed(self.search),
call.search_cleared(self.search),
call.search_failed(self.search)]
self.assertListEqual(self.observer.mock_calls, observer_calls)
self.assertListEqual(list(self.search), [])
示例15: drive_lr
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import reset_mock [as 别名]
def drive_lr(wpimock, halmock):
"""Left/right drive (mocks out setLeftRightMotorOutputs)."""
halmock.getFPGATime.return_value = 1000
left = MagicMock()
right = MagicMock()
drive = wpimock.RobotDrive(left, right)
drive.setLeftRightMotorOutputs = MagicMock()
left.reset_mock()
right.reset_mock()
return drive