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


Python Mock.reset_mock方法代码示例

本文整理汇总了Python中unittest.mock.Mock.reset_mock方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.reset_mock方法的具体用法?Python Mock.reset_mock怎么用?Python Mock.reset_mock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在unittest.mock.Mock的用法示例。


在下文中一共展示了Mock.reset_mock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_subtable_listener

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_subtable_listener(table2, subtable1, subtable2, nt_flush):
    
    listener1 = Mock()
    
    table2.putBoolean("MyKey1", True)
    table2.putBoolean("MyKey1", False)
    table2.addSubTableListener(listener1.valueChanged, localNotify=True)
    table2.putBoolean("MyKey2", True)
    table2.putBoolean("MyKey4", False)

    subtable1.putBoolean("MyKey1", False)
    
    nt_flush()
    listener1.valueChanged.assert_called_once_with(table2, "sub1", subtable1, True)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
    
    subtable1.putBoolean("MyKey2", True)
    subtable1.putBoolean("MyKey1", True)
    subtable2.putBoolean('MyKey1', False)
    
    nt_flush()
    listener1.valueChanged.assert_called_once_with(table2, "sub2", subtable2, True)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
开发者ID:,项目名称:,代码行数:27,代码来源:

示例2: test_lru_with_kwargs

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_lru_with_kwargs():
    mock = Mock()
    decorated = lru(max_size=2)(mock)
    decorated(1, 2, foo='foo')
    mock.reset_mock()
    decorated(1, 2, foo='bar')
    mock.assert_called_once_with(1, 2, foo='bar')
开发者ID:renzon,项目名称:code_interview_training,代码行数:9,代码来源:lru.py

示例3: TestComponent

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
class TestComponent(unittest.TestCase):

  def setUp(self):
    self.component_under_test = Listener()
    self.on_test_mock = Mock(return_value=None)
    self.on_second_event_mock = Mock(return_value=None)
    Component._emitter._events['test'] = [self.on_test_mock]
    Component._emitter._events['test_1'] = [self.on_test_mock, self.on_second_event_mock]

  def tearDown(self):
    self.on_test_mock.reset_mock()
    self.on_second_event_mock.reset_mock()

  def test_on_test_is_called(self):
    self.component_under_test.emit(Test())
    self.on_test_mock.assert_called_once()

  def test_with_multiple_decorators(self):
    self.component_under_test.emit(Test_1())
    self.component_under_test.emit(Test())
    self.assertEqual(self.on_test_mock.call_count, 2)

  def test_with_multiple_methods(self):
    self.component_under_test.emit(Test_1())
    self.assertEqual(self.on_test_mock.call_count, 1)
    self.assertEqual(self.on_second_event_mock.call_count, 1)

  def test_case_insentive_event(self):
    class test_1(Event):
      pass
    self.component_under_test.emit(test_1())
    self.assertEqual(self.on_second_event_mock.call_count, 1)
开发者ID:giuse88,项目名称:forex,代码行数:34,代码来源:test_component.py

示例4: test_key_listener_not_immediate_notify

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_key_listener_not_immediate_notify(table1):
    
    listener1 = Mock()
    
    table1.putBoolean("MyKey1", True)
    table1.putBoolean("MyKey1", False)
    table1.putBoolean("MyKey2", True)
    table1.putBoolean("MyKey4", False)
    
    table1.addTableListener(listener1.valueChanged, False)
    assert len(listener1.mock_calls) == 0
    listener1.reset_mock()
    
    table1.putBoolean("MyKey", False)
    listener1.valueChanged.assert_called_once_with(table1, "MyKey", False, True)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
    
    table1.putBoolean("MyKey1", True)
    listener1.valueChanged.assert_called_once_with(table1, "MyKey1", True, False)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
    
    table1.putBoolean("MyKey1", False)
    listener1.valueChanged.assert_called_once_with(table1, "MyKey1", False, False)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
    
    table1.putBoolean("MyKey4", True)
    listener1.valueChanged.assert_called_once_with(table1, "MyKey4", True, False)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
开发者ID:Bobobalink,项目名称:pynetworktables,代码行数:34,代码来源:test_network_table_listener.py

示例5: test_run_command

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
    def test_run_command(self, subprocess):
        pdftk = PDFTKWrapper()
        comm_err = Mock(return_value=(b'', b'an error'))
        comm_out = Mock(return_value=(b'success', b''))
        proc_out = Mock(communicate=comm_out)
        proc_err = Mock(communicate=comm_err)
        popen_yes = Mock(return_value=proc_out)
        popen_bad = Mock(return_value=proc_err)

        # check the good case
        subprocess.Popen = popen_yes
        args = ['pdftk', 'go']
        result = pdftk.run_command(args)
        self.assertEqual('success', result)
        popen_yes.assert_called_once_with(args,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        comm_out.assert_called_once_with()
        proc_out.assert_not_called()

        # check the arg fixing
        popen_yes.reset_mock()
        result = pdftk.run_command(['dostuff'])
        popen_yes.assert_called_once_with(['pdftk','dostuff'],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        # check the bad case
        subprocess.reset_mock()
        subprocess.Popen = popen_bad
        args = ['go']
        with self.assertRaises(PdftkError):
            pdftk.run_command(args)
        proc_err.assert_not_called()
        comm_err.assert_called_once_with()
        popen_bad.assert_called_once_with(['pdftk','go'],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
开发者ID:18F,项目名称:pdfhook,代码行数:37,代码来源:test_pdftk.py

示例6: test_generate_credentials_set_credentials

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
    def test_generate_credentials_set_credentials(self):
        url = "http://www.google.com"
        payload = {'label': "test",
                   'scope': "read",
                   'token_expires_in': "200000"}
        test_vals = {'client_id': 'client-id',
                     'client_secret':  'client-secret'}
        response_vals = {'ok': True,
                         'json.return_value': test_vals}
        response = Mock()
        response.configure_mock(**response_vals)
        with patch.object(requests, 'post', return_value=response) as mocker:
            self.access.generate_new_credentials(url, self.label)
            self.assertEqual(self.access.client_id,
                             test_vals['client_id'])
            self.assertEqual(self.access.client_secret,
                             test_vals['client_secret'])
            self.assertEqual(self.access.expiration,
                             payload['token_expires_in'])

        response_vals['ok'] = False
        response.reset_mock()
        response.configure_mock(**response_vals)
        with patch.object(requests, 'post', return_value=response) as mocker:
            with self.assertRaises(BadRequest):
                self.access.generate_new_credentials(url, self.label)
开发者ID:KPBS,项目名称:py3-pmp-wrapper,代码行数:28,代码来源:test_access.py

示例7: test_wraps_calls

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
 def test_wraps_calls(self):
     real = Mock()
     mock = Mock(wraps=real)
     self.assertEqual(mock(), real())
     real.reset_mock()
     mock(1, 2, fish=3)
     real.assert_called_with(1, 2, fish=3)
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:9,代码来源:testmock.py

示例8: TestPing

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
class TestPing(unittest.TestCase):
    def setUp(self):
        self.bot = Mock()
        self.ping = Ping(self.bot)

    def test_ping(self):
        all_args = [
            ["ping"],
            ["ping", "pong"],
            ["ping", "pang", "poung"]
        ]
        for args in all_args:
            self.bot.reset_mock()
            serv = Mock()
            author = 'author'
            self.ping(serv, author, args)
            self.bot.say.assert_called_once_with(serv, 'author: pong')

    def test_invalid(self):
        all_args = [
            ["pong"],
            [],
            [""],
            ["baltazar"],
        ]
        for args in all_args:
            serv = Mock()
            author = Mock()
            self.ping(serv, author, args)
            self.assertEqual(len(self.bot.mock_calls), 0)
开发者ID:hackEns,项目名称:Jarvis,代码行数:32,代码来源:Ping.py

示例9: test_process_callback

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
    def test_process_callback(self):
        """Test if after_update_callback is called after update of Climate object was changed."""
        # pylint: disable=no-self-use
        xknx = XKNX(loop=self.loop)
        climate = Climate(
            xknx,
            'TestClimate',
            group_address_target_temperature='1/2/2',
            group_address_setpoint_shift='1/2/3',
            group_address_setpoint_shift_state='1/2/4')

        after_update_callback = Mock()

        async def async_after_update_callback(device):
            """Async callback."""
            after_update_callback(device)
        climate.register_device_updated_cb(async_after_update_callback)

        self.loop.run_until_complete(asyncio.Task(
            climate.target_temperature.set(23.00)))
        after_update_callback.assert_called_with(climate)
        after_update_callback.reset_mock()

        self.loop.run_until_complete(asyncio.Task(
            climate.setpoint_shift.set(-2)))
        after_update_callback.assert_called_with(climate)
        after_update_callback.reset_mock()
开发者ID:phbaer,项目名称:xknx,代码行数:29,代码来源:climate_test.py

示例10: test_torrent_remove

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
async def test_torrent_remove(loop, mock_alert):
    core = Mock(alert=mock_alert)
    torrent = Torrent(core)

    info_hash = '1234567890'
    torrent_handle = Mock(**{
        'info_hash.return_value': info_hash
    })

    remove_task = loop.create_task(torrent.remove(torrent_handle))
    # Make sure we allow a context switch to let remove_task run
    await asyncio.sleep(0)
    core.session.remove_torrent.assert_called_once_with(torrent_handle, 0)
    assert not remove_task.done()
    await core.alert.push_alert('torrent_removed_alert', info_hash=info_hash)
    await asyncio.wait_for(remove_task, 1)
    core.reset_mock()

    remove_task = loop.create_task(torrent.remove(torrent_handle, lt.options_t.delete_files))
    await asyncio.sleep(0)
    core.session.remove_torrent.assert_called_once_with(torrent_handle, lt.options_t.delete_files)
    assert not remove_task.done()
    await core.alert.push_alert('torrent_removed_alert', info_hash=info_hash)
    assert not remove_task.done()
    await core.alert.push_alert('torrent_deleted_alert', info_hash=info_hash)
    await asyncio.wait_for(remove_task, 1)
开发者ID:spritzle,项目名称:spritzle,代码行数:28,代码来源:test_torrent.py

示例11: test_poll_store

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_poll_store(tmpdir):
    fakemodel = tmpdir.join("fakemodel.json")
    app = CriticApp(ios=['app1', 'app2'], language=['ru'], persist=True, slack_webhook='http://www')
    app.model_file = fakemodel.strpath
    fake_fetcher = Mock(return_value=[Review(
        id=u'xfkew4ytwqqddid:2e22wdad',
        platform='ios',
        title=u'Great app! ♡',
        rating=2,
        summary=u'Here be\nDragons!',
        url=u'http://www',
        author=u'Here comes more BS',
        date='bull',
        language='en',
        version=None
    )])
    app.fetchers['ios'] = fake_fetcher
    fake_notifier = Mock()
    app.notifiers['slack'] = fake_notifier
    app.poll_store(platform='ios')

    assert fake_fetcher.call_count == 2
    assert fake_notifier.call_count == 1
    assert len(app.reviews['ios']) == 1

    fake_fetcher.reset_mock()
    fake_notifier.reset_mock()
    app.poll_store(platform='ios')
    assert fake_fetcher.call_count == 2
    assert fake_notifier.call_count == 0
    assert len(app.reviews['ios']) == 1
开发者ID:ozoli,项目名称:critics,代码行数:33,代码来源:test_core.py

示例12: test_lru_cache_overflow

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_lru_cache_overflow():
    mock = Mock()
    decorated = lru(max_size=2)(mock)
    decorated(1, 2)
    decorated(1, 3)
    decorated(1, 4)
    mock.reset_mock()  # previous calls reset
    decorated(1, 2)
    mock.assert_called_once_with(1, 2)
开发者ID:renzon,项目名称:code_interview_training,代码行数:11,代码来源:lru.py

示例13: testEventMask

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
    def testEventMask(self):
        handler_cb = Mock()
        with patch("blivet.events.manager.validate_cb", return_value=True):
            mgr = FakeEventManager(handler_cb=handler_cb)

        device = "sdc"
        action = "add"
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 1)
        event = handler_cb.call_args[1]["event"]  # pylint: disable=unsubscriptable-object
        self.assertEqual(event.device, device)
        self.assertEqual(event.action, action)

        # mask matches device but not action -> event is handled
        handler_cb.reset_mock()
        mask = mgr.add_mask(device=device, action=action + 'x')
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 1)
        event = handler_cb.call_args[1]["event"]  # pylint: disable=unsubscriptable-object
        self.assertEqual(event.device, device)
        self.assertEqual(event.action, action)

        # mask matches action but not device -> event is handled
        handler_cb.reset_mock()
        mask = mgr.add_mask(device=device + 'x', action=action)
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 1)
        event = handler_cb.call_args[1]["event"]  # pylint: disable=unsubscriptable-object
        self.assertEqual(event.device, device)
        self.assertEqual(event.action, action)

        # mask matches device and action -> event is ignored
        handler_cb.reset_mock()
        mgr.remove_mask(mask)
        mask = mgr.add_mask(device=device, action=action)
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 0)

        # device-only mask matches -> event is ignored
        handler_cb.reset_mock()
        mgr.remove_mask(mask)
        mask = mgr.add_mask(device=device)
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 0)

        # action-only mask matches -> event is ignored
        handler_cb.reset_mock()
        mgr.remove_mask(mask)
        mask = mgr.add_mask(action=action)
        mgr.handle_event(action, device)
        self.assertEqual(handler_cb.call_count, 0)
        mgr.remove_mask(mask)
开发者ID:afamilyman,项目名称:blivet,代码行数:54,代码来源:events_test.py

示例14: test_generate_test_metrics

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
    def test_generate_test_metrics(self):
        keys = [
            'm:test-slug:s:2000-01-02-03-04-05',
            'm:test-slug:i:2000-01-02-03-04',
            'm:test-slug:h:2000-01-02-03',
            'm:test-slug:2000-01-02',
            'm:test-slug:w:2000-01',
            'm:test-slug:m:2000-01',
            'm:test-slug:y:2000',
        ]
        config = {
            '_build_keys.return_value': keys,
            '_metric_slugs_key': 'MSK',
            '_date_range.return_value': [datetime.utcnow()],
        }
        mock_r = Mock(**config)
        config = {'return_value': mock_r}
        with patch("redis_metrics.utils.get_r", **config) as mock_get_r:
            # When called with random = True
            with patch("redis_metrics.utils.random") as mock_random:
                mock_random.randint.return_value = 9999
                utils.generate_test_metrics(
                    slug="test-slug", num=1, randomize=True, increment_value=1
                )
                mock_get_r.assert_called_once_with()
                mock_r.r.sadd.assert_called_once_with('MSK', 'test-slug')
                mock_random.seed.assert_called_once_with()
                mock_random.randint.assert_has_calls([
                    call(0, 1), call(0, 1), call(0, 1), call(0, 1),
                ])
                mock_r.r.incr.assert_has_calls([
                    call('m:test-slug:2000-01-02', 9999),
                    call('m:test-slug:w:2000-01', 9999),
                    call('m:test-slug:m:2000-01', 9999),
                    call('m:test-slug:y:2000', 9999),
                ])

            mock_get_r.reset_mock()
            mock_r.reset_mock()

            # When called with random = False
            utils.generate_test_metrics(
                slug="test-slug", num=1, randomize=False, increment_value=1
            )
            mock_get_r.assert_called_once_with()
            mock_r.r.sadd.assert_called_once_with('MSK', 'test-slug')
            mock_r.r.incr.assert_has_calls([
                call('m:test-slug:2000-01-02', 0),
                call('m:test-slug:w:2000-01', 0),
                call('m:test-slug:m:2000-01', 0),
                call('m:test-slug:y:2000', 0),
            ])
开发者ID:bradmontgomery,项目名称:django-redis-metrics,代码行数:54,代码来源:test_utils.py

示例15: test_specific_key_listener

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import reset_mock [as 别名]
def test_specific_key_listener(table1):
    
    listener1 = Mock()
    
    table1.addTableListener(listener1.valueChanged, False, key='MyKey1')
    
    table1.putBoolean('MyKey1', True)
    listener1.valueChanged.assert_called_once_with(table1, "MyKey1", True, True)
    assert len(listener1.mock_calls) == 1
    listener1.reset_mock()
    
    table1.putBoolean('MyKey2', True)
    assert len(listener1.mock_calls) == 0
开发者ID:Bobobalink,项目名称:pynetworktables,代码行数:15,代码来源:test_network_table_listener.py


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