当前位置: 首页>>代码示例>>Python>>正文


Python MagicMock.reset_mock方法代码示例

本文整理汇总了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()
开发者ID:GEMScienceTools,项目名称:gmpe-smtk,代码行数:33,代码来源:residual_plotter_test.py

示例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)
开发者ID:WIPACrepo,项目名称:iceprod,代码行数:37,代码来源:dataset_monitor_test.py

示例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()
开发者ID:zalando,项目名称:lizzy-client,代码行数:36,代码来源:test_cli.py

示例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]
开发者ID:enenn,项目名称:freqtrade,代码行数:36,代码来源:test_rpc_telegram.py

示例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)
        ])
开发者ID:hiroaki-yamamoto,项目名称:mongoengine-goodjson,代码行数:62,代码来源:test_callable_recursion.py

示例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)
开发者ID:mfelsche,项目名称:lizzy-client,代码行数:29,代码来源:test_lizzy.py

示例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]
开发者ID:enenn,项目名称:freqtrade,代码行数:35,代码来源:test_rpc_telegram.py

示例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()
开发者ID:Eyepea,项目名称:cpython,代码行数:9,代码来源:testmagicmethods.py

示例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]
开发者ID:enenn,项目名称:freqtrade,代码行数:32,代码来源:test_rpc_telegram.py

示例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")
开发者ID:Nicoretti,项目名称:libslack,代码行数:61,代码来源:slackapi_tests.py

示例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 == [()]
开发者ID:yerejm,项目名称:ttt,代码行数:10,代码来源:test_reporter.py

示例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!'),)]
开发者ID:yerejm,项目名称:ttt,代码行数:10,代码来源:test_reporter.py

示例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 == [()]
开发者ID:yerejm,项目名称:ttt,代码行数:10,代码来源:test_reporter.py

示例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), [])
开发者ID:dstenb,项目名称:pylaunchr-mpd,代码行数:59,代码来源:search_test.py

示例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
开发者ID:Seamonsters-2605,项目名称:robotpy-wpilib,代码行数:12,代码来源:test_robotdrive.py


注:本文中的unittest.mock.MagicMock.reset_mock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。