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


Python Mock.assert_called_once_with方法代码示例

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


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

示例1: test_register_controller_extensions_without_mail

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_register_controller_extensions_without_mail(self):
        from horus.views        import RegisterController
        from horus.interfaces   import IRegisterSchema
        from horus.interfaces   import IRegisterForm
        from horus.interfaces   import IUserClass
        from horus.interfaces   import IUIStrings
        from horus.strings      import UIStringsBase
        from horus.tests.models import User
        from horus.interfaces   import IActivationClass
        from horus.tests.models import Activation
        self.config.registry.registerUtility(Activation, IActivationClass)
        self.config.registry.registerUtility(User, IUserClass)
        self.config.registry.registerUtility(UIStringsBase, IUIStrings)

        self.config.add_route('index', '/')

        request = testing.DummyRequest()

        getUtility = Mock()
        getUtility.return_value = True

        schema = Mock()
        form = Mock()

        self.config.registry.settings['horus.require_activation'] = False
        self.config.registry.registerUtility(schema, IRegisterSchema)
        self.config.registry.registerUtility(form, IRegisterForm)

        with patch('horus.views.get_mailer') as get_mailer:
            RegisterController(request)
            assert not get_mailer.called

        schema.assert_called_once_with()
        assert form.called
开发者ID:dobrite,项目名称:horus,代码行数:36,代码来源:test_views.py

示例2: test_main_loop_no_task

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_main_loop_no_task(self):
        config = Mock()
        pool_size = 4

        mocked_pool = Mock()
        mocked_pool.free_count = Mock(return_value=pool_size)

        mocked_done_with_processed_tasks = Mock(side_effect=self.main_loop_done_with_processed_tasks)

        mocked_worker = Mock()
        mocked_gevent_queue = Mock()

        mocked_task = Mock()

        mocked_tube = Mock(return_value=mocked_task)
        mocked_tube.take = Mock(return_value=None)

        mocked_tarantool_queue = Mock()
        mocked_tarantool_queue.tube = Mock(return_value=mocked_tube)

        with patch('notification_pusher.tarantool_queue.Queue', Mock(return_value=mocked_tarantool_queue)):
            with patch('notification_pusher.Pool', Mock(return_value=mocked_pool)):
                with patch('notification_pusher.done_with_processed_tasks', mocked_done_with_processed_tasks):
                    with patch('notification_pusher.Greenlet', Mock(return_value=mocked_worker)):
                        with patch('notification_pusher.gevent_queue.Queue', Mock(return_value=mocked_gevent_queue)):
                            notification_pusher.run_application = True
                            main_loop(config)

                            assert not mocked_worker.start.called
                            mocked_done_with_processed_tasks.assert_called_once_with(mocked_gevent_queue)
开发者ID:f1nality,项目名称:tech-testing-ha1,代码行数:32,代码来源:test_notification_pusher.py

示例3: LinkTests

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

    def setUp(self):
        self.other_page_cls = Mock()
        class TestPage(Page):
            clickme = Link('id=clickme')
            linktopage = Link('id=linktopage', to=self.other_page_cls)
        self.webelement = Mock()
        self.driver = Mock(**{'find_elements.return_value': [self.webelement]})
        set_driver(self.driver)
        self.page = TestPage(assert_is_on_page=False)

    def test_call(self):
        ret = self.page.clickme()
        self.assertIsNone(ret)
        self.webelement.click.assert_called_once_with()

    def test_click(self):
        ret = self.page.clickme.click()
        self.assertIsNone(ret)
        self.webelement.click.assert_called_once_with()

    def test_to_page(self):
        page = self.page.linktopage()
        self.other_page_cls.assert_called_once_with(assert_is_on_page=True)
        self.assertIs(page, self.other_page_cls())

    def test_to_page_without_url(self):
        other_page_cls = Mock(url=None)
        class TestPage(Page):
            linktopage = Link('id=linktopage', to=other_page_cls)
        page = TestPage()
        page.linktopage()
        other_page_cls.assert_called_once_with(assert_is_on_page=False)
开发者ID:x746e,项目名称:webel,代码行数:36,代码来源:tests.py

示例4: test_calls_provided_test

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_calls_provided_test(self):
        client = fake_juju_client()
        with temp_dir() as juju_home:
            client.env.juju_home = juju_home
            bs_manager = make_bootstrap_manager(client)
            bs_manager.log_dir = os.path.join(juju_home, 'log-dir')
            os.mkdir(bs_manager.log_dir)

            timing = gpr.TimingData(datetime.utcnow(), datetime.utcnow())
            deploy_details = gpr.DeployDetails('test', dict(), timing)
            noop_test = Mock(return_value=deploy_details)

            pprof_collector = Mock()

            with patch.object(gpr, 'dump_performance_metrics_logs',
                              autospec=True):
                with patch.object(gpr, 'generate_reports', autospec=True):
                    with patch.object(
                            gpr, 'PPROFCollector', autospec=True) as p_pc:
                        p_pc.return_value = pprof_collector
                        gpr.run_perfscale_test(
                            noop_test,
                            bs_manager,
                            get_default_args())

            noop_test.assert_called_once_with(
                client, pprof_collector, get_default_args())
开发者ID:mjs,项目名称:juju,代码行数:29,代码来源:test_generate_perfscale_results.py

示例5: test_multiple_errbacks

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_multiple_errbacks(self):
        session = self.make_session()
        pool = session._pools.get.return_value
        connection = Mock(spec=Connection)
        pool.borrow_connection.return_value = (connection, 1)

        query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)")
        query.retry_policy = Mock()
        query.retry_policy.on_unavailable.return_value = (RetryPolicy.RETHROW, None)
        message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE)

        rf = ResponseFuture(session, message, query, 1)
        rf.send_request()

        callback = Mock()
        arg = "positional"
        kwargs = {'one': 1, 'two': 2}
        rf.add_errback(callback, arg, **kwargs)

        callback2 = Mock()
        arg2 = "another"
        kwargs2 = {'three': 3, 'four': 4}
        rf.add_errback(callback2, arg2, **kwargs2)

        expected_exception = Unavailable("message", 1, 2, 3)
        result = Mock(spec=UnavailableErrorMessage, info={'something': 'here'})
        result.to_exception.return_value = expected_exception
        rf._set_result(result)
        self.assertRaises(Exception, rf.result)

        callback.assert_called_once_with(expected_exception, arg, **kwargs)
        callback2.assert_called_once_with(expected_exception, arg2, **kwargs2)
开发者ID:rainslytherin,项目名称:python-driver,代码行数:34,代码来源:test_response_future.py

示例6: test_rmtree_ignore_unlink_rmdir_exception

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_rmtree_ignore_unlink_rmdir_exception(self):
        dir1_list = ["dir2", "file"]
        empty_list = []
        mock_listdir = Mock()
        mock_listdir.side_effect = [dir1_list, empty_list]

        mock_isdir = Mock()
        mock_isdir.side_effect = [True, False]

        mock_unlink = Mock()
        mock_unlink.side_effect = [OSError]

        mock_rmdir = Mock()
        mock_rmdir.side_effect = [0, OSError]

        mock_islink = Mock()
        mock_islink.return_value = False

        with nested(patch("gluster.gfapi.Volume.listdir", mock_listdir),
                    patch("gluster.gfapi.Volume.isdir", mock_isdir),
                    patch("gluster.gfapi.Volume.islink", mock_islink),
                    patch("gluster.gfapi.Volume.unlink", mock_unlink),
                    patch("gluster.gfapi.Volume.rmdir", mock_rmdir)):
            self.vol.rmtree("dir1", True)
            mock_rmdir.assert_any_call("dir1/dir2")
            mock_unlink.assert_called_once_with("dir1/file")
            mock_rmdir.assert_called_with("dir1")
开发者ID:Alphadelta14,项目名称:libgfapi-python,代码行数:29,代码来源:test_gfapi.py

示例7: test_open

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
 def test_open(self, sleep):
     fn = Mock()
     connection = Mock(url=URL, retry=True)
     fx = retry(ConnectError)(fn)
     fx(connection)
     fn.assert_called_once_with(connection)
     self.assertFalse(sleep.called)
开发者ID:darinlively,项目名称:gofer,代码行数:9,代码来源:test_connect.py

示例8: test15_poll_notification

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test15_poll_notification(self):
        args = { 'type': ['tabs'],
                 'action': ['poll'],
                 'player_id': [13],
                 'game_id': [20],
                 'modified': [10000000000000000] }

        # Fake poll controlled from the test
        poll = defer.Deferred()
        mock_poll_tabs = Mock()
        mock_poll_tabs.return_value = poll
        orig_service_poll_tabs = self.service.poll_tabs
        self.service.poll_tabs = mock_poll_tabs

        mock_listener = Mock()
        self.service.listen().addCallback(mock_listener)
        self.service.poll(args)
        mock_listener.assert_called_once_with({'player_id': 13, 'type': 'poll_start'})

        mock_listener.reset_mock()
        self.service.listen().addCallback(mock_listener)
        poll.callback(args)
        mock_listener.assert_called_once_with({'player_id': 13, 'type': 'poll_end'})

        self.service.poll_tabs = orig_service_poll_tabs
开发者ID:arbrandes,项目名称:cardstories,代码行数:27,代码来源:test_service.py

示例9: test_trigger_events

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_trigger_events(self, mock_from):
        mock_after = Mock()
        mock_before = Mock()
        mock_from.return_value = {'foo': 1}
        ctx = Mock()
        view = Mock(
            request=Mock(action='index'),
            _json_params={'bar': 1},
            context=ctx,
            _silent=False)
        view.index._silent = False
        view.index._event_action = None

        with patch.dict(events.BEFORE_EVENTS, {'index': mock_before}):
            with patch.dict(events.AFTER_EVENTS, {'index': mock_after}):
                with events.trigger_events(view):
                    pass

        mock_after.assert_called_once_with(
            fields={'foo': 1}, model=view.Model, instance=ctx,
            view=view)
        mock_before.assert_called_once_with(
            fields={'foo': 1}, model=view.Model, instance=ctx,
            view=view)
        view.request.registry.notify.assert_has_calls([
            call(mock_before()),
            call(mock_after()),
        ])
        mock_from.assert_called_once_with({'bar': 1}, view.Model)
开发者ID:adam-codeberg,项目名称:nefertari,代码行数:31,代码来源:test_events.py

示例10: test_run_in_subprocess

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
def test_run_in_subprocess():
    with patch.multiple('pkglib_testing.cmdline', cPickle=DEFAULT, execnet=DEFAULT) as mocks:
        fn = Mock(__name__='fn')
        res = cmdline.run_in_subprocess(fn, python='sentinel.python')(sentinel.arg, kw=sentinel.kw)
        mocks['execnet'].makegateway.assert_called_once_with('popen//python=sentinel.python')
        gw = mocks['execnet'].makegateway.return_value
        ((remote_fn,), _) = gw.remote_exec.call_args
        chan = gw.remote_exec.return_value
        mocks['cPickle'].dumps.assert_called_with((fn, (sentinel.arg,), {'kw': sentinel.kw}), protocol=0)
        chan.send.assert_called_with(mocks['cPickle'].dumps.return_value)
        chan.receive.assert_has_calls([call(None) for _i in range(gw.remote_exec.call_count)])
        mocks['cPickle'].loads.assert_called_once_with(chan.receive.return_value)
        assert res is mocks['cPickle'].loads.return_value
        chan.close.assert_has_calls([call() for _i in range(gw.remote_exec.call_count)])
        gw.exit.assert_called_once_with()

    with patch('pkglib_util.six.moves.cPickle') as cPickle:
        channel, fn = Mock(), Mock()
        cPickle.loads.return_value = (fn, (sentinel.arg,), {'kw': sentinel.kw})
        remote_fn(channel)
        channel.receive.assert_called_once_with(None)
        cPickle.loads.assert_called_once_with(channel.receive.return_value)
        fn.assert_called_once_with(sentinel.arg, kw=sentinel.kw)
        cPickle.dumps.assert_called_once_with(fn.return_value, protocol=0)
        channel.send.assert_called_once_with(cPickle.dumps.return_value)
开发者ID:agiledata,项目名称:pkglib,代码行数:27,代码来源:test_cmdline.py

示例11: test12_player_info

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test12_player_info(self):
        player_id = 20
        player_name = u"pl\xe1y\u1ebdr"
        player_avatar_url = "http://example.com/test.jpg"
        player_score = 4141
        player_level, _, _ = cardstories.levels.calculate_level(player_score)

        sql = "INSERT INTO players (player_id, score) VALUES (%d, %d)"
        c = self.db.cursor()
        c.execute(sql % (player_id, player_score))
        self.db.commit()

        # Fake calls to auth module
        default_get_player_name = self.service.auth.get_player_name
        fake_get_player_name = Mock(return_value=player_name)
        self.service.auth.get_player_name = fake_get_player_name

        default_get_player_avatar_url = self.service.auth.get_player_avatar_url
        fake_get_player_avatar_url = Mock(return_value=player_avatar_url)
        self.service.auth.get_player_avatar_url = fake_get_player_avatar_url

        players_info = yield self.service.player_info({'type': 'player_info', 'player_id': [player_id]})
        fake_get_player_name.assert_called_once_with(player_id)
        fake_get_player_avatar_url.assert_called_once_with(player_id)

        self.assertEquals(players_info, [{ 'type': 'players_info',
                                           str(player_id): {'name': player_name,
                                                            'avatar_url': player_avatar_url,
                                                            'level': player_level}
                                         }])

        self.service.auth.get_player_name = default_get_player_name
        self.service.auth.get_player_avatar_url = default_get_player_avatar_url
开发者ID:arbrandes,项目名称:cardstories,代码行数:35,代码来源:test_service.py

示例12: test_accept

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_accept(self):
        rmock = Mock()
        rmock.return_value = sentinel.msg

        cacmock = Mock()
        transport = Mock()

        self.ch.recv = rmock
        self.ch._recv_queue.await_n = MagicMock()
        self.ch._create_accepted_channel = cacmock
        self.ch.on_channel_open(transport)
        self.ch._fsm.current_state = self.ch.S_ACTIVE
        self.ch._consuming = True

        retch = self.ch.accept()
        self.assertEquals(self.ch._fsm.current_state, self.ch.S_ACCEPTED)
        cacmock.assert_called_once_with(transport, [sentinel.msg])
        retch._recv_queue.put.assert_called_once_with(sentinel.msg)

        # we've mocked all the working machinery of accept's return etc, so we must manually exit accept
        # as if we've ack'd/reject'd
        self.ch.exit_accept()

        self.assertEquals(self.ch._fsm.current_state, self.ch.S_ACTIVE)
        self.assertTrue(self.ch._consuming)
开发者ID:ooici,项目名称:pyon,代码行数:27,代码来源:test_channel.py

示例13: test_exception_request_handlers

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
 def test_exception_request_handlers(self, f):
     ex = wac.requests.HTTPError()
     ex.response = Mock()
     ex.response.status_code = 402
     ex.response.content = (
         '{"status": "Bad Request", "status_code": '
         '"400", "description": "Invalid field \'your mom\' -- make '
         'sure its your dad too", "additional": "nothing personal"}')
     ex.response.headers = {
         'Content-Type': 'application/json',
     }
     f.__name__ = 'post'
     f.side_effect = ex
     before_request = Mock()
     after_request = Mock()
     with self.cli:
         self.cli.config.root_url = '/test'
         self.cli.config.keep_alive = False
         self.cli.config.before_request.append(before_request)
         self.cli.config.after_request.append(after_request)
         with self.assertRaises(wac.Error) as ex_ctx:
             self.cli.post('/a/post/w/hooks', data={'hi': 'ya'})
     self.assertEqual(ex_ctx.exception.status_code, 402)
     self.assertEqual(ex_ctx.exception.additional, 'nothing personal')
     before_request.assert_called_once_with(
         'POST',
         '/test/a/post/w/hooks',
         {'headers': {'Content-Type': 'application/json'},
          'allow_redirects': False,
          'data': '{"hi": "ya"}',
          }
     )
     after_request.assert_called_once_with(ex.response)
开发者ID:zmike808,项目名称:wac,代码行数:35,代码来源:tests.py

示例14: test_manual_execute_with_ids_ignored_while_in_execute

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_manual_execute_with_ids_ignored_while_in_execute(self):
        waiter = Event()

        long_execute_waiter = Event()

        # noinspection PyUnusedLocal
        def execute(*args, **kwargs):
            waiter.set()
            long_execute_waiter.wait(1)
            self.assertTrue(long_execute_waiter.is_set)

        execute_mock = Mock(side_effect=execute)
        self.trackers_manager.execute = execute_mock

        self.create_runner(interval=1)
        self.engine_runner.execute(None)
        waiter.wait(0.3)
        waiter.clear()
        ids = [1, 2, 3]
        self.engine_runner.execute(ids)
        long_execute_waiter.set()
        waiter.wait(0.3)
        self.assertTrue(waiter.is_set)

        self.stop_runner()

        execute_mock.assert_called_once_with(ANY, None)
开发者ID:werwolfby,项目名称:monitorrent,代码行数:29,代码来源:test_engine.py

示例15: test_new_mode_callback

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_called_once_with [as 别名]
    def test_new_mode_callback(self):
        """Create a Controller object, call on_new_mode_online method and
        check that the callback fires when set_composite_mode is called
        """
        self.setup_server()
        self.setup_controller()

        self.log.info("setting callback")
        test_cb = Mock(side_effect=self.quit_mainloop)
        self.controller.on_new_mode_online(test_cb)

        self.log.info("starting test-sources")
        self.setup_video_sources(count=2)

        self.log.info("waiting for initial callback with default-mode"
                      "COMPOSITE_DUAL_EQUAL")
        self.run_mainloop(timeout=5)
        test_cb.assert_called_once_with(Controller.COMPOSITE_DUAL_EQUAL)
        test_cb.reset_mock()

        self.log.info("setting new composite mode COMPOSITE_NONE")
        assert self.controller.set_composite_mode(Controller.COMPOSITE_NONE)
        self.run_mainloop(timeout=5)

        self.log.info("waiting for callback with new mode COMPOSITE_NONE")
        test_cb.assert_called_once_with(Controller.COMPOSITE_NONE)
开发者ID:a740122,项目名称:gst-switch,代码行数:28,代码来源:test_controller.py


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