• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mock.Mock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: fake_supplier

def fake_supplier(seed, fake_data):
	result = Mock()
	result.metadata = {'entries' : len(fake_data)}
	result.data = {'data' : fake_data}
	result.kurfile.get_seed.return_value = seed
	result.downselect = partial(SpeechRecognitionSupplier.downselect, result)
	return result
开发者ID:Navdevl,项目名称:kur,代码行数:7,代码来源:test_speechrec.py


示例2: filter_by_mock_concept

def filter_by_mock_concept(**kwargs):
    filter_mock = Mock()
    concept_id = None
    conceptscheme_id = None
    if 'concept_id' in kwargs:
        concept_id = kwargs['concept_id']
    if 'conceptscheme_id' in kwargs:
        conceptscheme_id = kwargs['conceptscheme_id']
    if concept_id == '1':
        c = Concept(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        c.type = 'concept'
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '3':
        c = Collection(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        c.type = 'collection'
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '555':
        c = Thing(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '666':
        raise NoResultFound

    a_concept = Concept(concept_id=7895, conceptscheme_id=conceptscheme_id, type='concept')
    a_labels = [Label(label='De Paardekastanje', language_id='nl'), Label(label='The Chestnut', language_id='en'),
                Label(label='la châtaigne', language_id='fr')]
    a_concept.labels = a_labels
    b_concept = Concept(concept_id=9863, conceptscheme_id=conceptscheme_id, type='concept')
    b_labels = [Label(label='test', language_id='nl')]
    b_concept.labels = b_labels
    filter_mock.all = Mock(return_value=[a_concept, b_concept])
    return filter_mock
开发者ID:JDeVos,项目名称:atramhasis,代码行数:31,代码来源:test_views.py


示例3: test_setup_entry_no_available_bridge

async def test_setup_entry_no_available_bridge(hass):
    """Test setup entry fails if deCONZ is not available."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    with patch('pydeconz.DeconzSession.async_load_parameters',
               return_value=mock_coro(False)):
        assert await deconz.async_setup_entry(hass, entry) is False
开发者ID:,项目名称:,代码行数:7,代码来源:


示例4: test_side_effect

    def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError('kablooie')

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]
        def effect():
            return results.pop()
        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
                          "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side effect in constructor not used")

        def side_effect():
            return DEFAULT
        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN)
开发者ID:MarkTseng,项目名称:cpython,代码行数:26,代码来源:testmock.py


示例5: test_alert_error

async def test_alert_error():
    async with unit(1) as unit1:
        async with unit(2) as unit2:

            def err(x):
                raise RuntimeError("dad")

            error_me1 = Mock(side_effect=err)
            await unit1.register(error_me1, "my.error1", call_conv=CC_DATA, multiple=True)
            called = False
            async for d in unit2.poll("my.error1", min_replies=1, max_replies=2, max_delay=TIMEOUT,
                                      result_conv=CC_MSG, debug=True):
                assert not called
                assert d.error.cls == "RuntimeError"
                assert d.error.message == "dad"
                called = True
            error_me1.assert_called_with(None)

            with pytest.raises(RuntimeError):
                async for d in unit2.poll("my.error1", result_conv=CC_DATA, min_replies=1,
                                          max_replies=2, max_delay=TIMEOUT):
                    assert False

            with pytest.raises(RuntimeError):
                await unit2.poll_first("my.error1")
开发者ID:M-o-a-T,项目名称:qbroker,代码行数:25,代码来源:test_unit.py


示例6: filter_by_mock_language

def filter_by_mock_language(id):
    filter_mock = Mock()
    if id in ['af', 'flup']:
        filter_mock.count = Mock(return_value=0)
    else:
        filter_mock.count = Mock(return_value=1)
    return filter_mock
开发者ID:OnroerendErfgoed,项目名称:atramhasis,代码行数:7,代码来源:test_validation.py


示例7: test_fail_excess_multiple

 def test_fail_excess_multiple(self):
     # When multiple consumers require less than pg output
     # alone, but in sum want more than total output, it should
     # be erroneous situation
     item = self.ch.type_(type_id=1, attributes={Attribute.power: 0})
     holder1 = Mock(state=State.online, item=item, _domain=Domain.ship, spec_set=ModuleHigh(1))
     holder1.attributes = {Attribute.power: 25}
     self.track_holder(holder1)
     holder2 = Mock(state=State.online, item=item, _domain=Domain.ship, spec_set=ModuleHigh(1))
     holder2.attributes = {Attribute.power: 20}
     self.track_holder(holder2)
     self.fit.stats.powergrid.used = 45
     self.fit.stats.powergrid.output = 40
     restriction_error1 = self.get_restriction_error(holder1, Restriction.powergrid)
     self.assertIsNotNone(restriction_error1)
     self.assertEqual(restriction_error1.output, 40)
     self.assertEqual(restriction_error1.total_use, 45)
     self.assertEqual(restriction_error1.holder_use, 25)
     restriction_error2 = self.get_restriction_error(holder2, Restriction.powergrid)
     self.assertIsNotNone(restriction_error2)
     self.assertEqual(restriction_error2.output, 40)
     self.assertEqual(restriction_error2.total_use, 45)
     self.assertEqual(restriction_error2.holder_use, 20)
     self.untrack_holder(holder1)
     self.untrack_holder(holder2)
     self.assertEqual(len(self.log), 0)
     self.assert_restriction_buffers_empty()
开发者ID:,项目名称:,代码行数:27,代码来源:


示例8: test_conflict_SSLContext_with_ws_url

        def test_conflict_SSLContext_with_ws_url(self):
            '''
            ApplicationRunner must raise an exception if given an ssl value that is
            an instance of SSLContext, but only a "ws:" URL.
            '''
            import ssl
            try:
                # Try to create an SSLContext, to be as rigorous as we can be
                # by avoiding making assumptions about the ApplicationRunner
                # implementation. If we happen to be on a Python that has no
                # SSLContext, we pass ssl=True, which will simply cause this
                # test to degenerate to the behavior of
                # test_conflict_SSL_True_with_ws_url (above). In fact, at the
                # moment (2015-05-10), none of this matters because the
                # ApplicationRunner implementation does not check to require
                # that its ssl argument is either a bool or an SSLContext. But
                # that may change, so we should be careful.
                ssl.create_default_context
            except AttributeError:
                context = True
            else:
                context = ssl.create_default_context()

            loop = Mock()
            loop.run_until_complete = Mock(return_value=(Mock(), Mock()))
            with patch.object(asyncio, 'get_event_loop', return_value=loop):
                runner = ApplicationRunner(u'ws://127.0.0.1:8080/wss', u'realm',
                                           ssl=context)
                error = ('^ssl argument value passed to ApplicationRunner '
                         'conflicts with the "ws:" prefix of the url '
                         'argument\. Did you mean to use "wss:"\?$')
                self._assertRaisesRegex(Exception, error, runner.run, '_unused_')
开发者ID:nucular,项目名称:AutobahnPython,代码行数:32,代码来源:test_runner.py


示例9: test_build_create

def test_build_create():
    population_class = Mock()
    create_function = common.build_create(population_class)
    assert isfunction(create_function)

    p = create_function("cell class", "cell params", n=999)
    population_class.assert_called_with(999, "cell class", cellparams="cell params")
开发者ID:NeuralEnsemble,项目名称:PyNN,代码行数:7,代码来源:test_lowlevelapi.py


示例10: test_data_route_match

    def test_data_route_match(self):
        endpoint = Mock(return_value="cats")

        f = self.app
        f.debug = True

        route = {
            "product": {
                (("year", None), ("location", "department")): {
                    "name": "department_product_year",
                    "action": endpoint
                },
            },
            "year": {
            }
        }

        routing.add_routes(f, route)

        factories.Location(level="department", id=2)
        db.session.commit()

        with f.test_client() as c:
            response = c.get("/product?location=2&year=2007")
            assert response.status_code == 200
            assert response.data == b"cats"
            endpoint.assert_called_with(location=2, year=2007)
开发者ID:Bancoldexprueba,项目名称:atlas-subnational-api,代码行数:27,代码来源:test_data.py


示例11: test_input_text_callback

    def test_input_text_callback(self):
        """An input text runs callback with the result as argument"""
        callback_fn = Mock()
        inter = InputText("Content", callback_fn)
        inter.run_callback("Foo Bar Baz")

        callback_fn.assert_called_once_with("Foo Bar Baz")
开发者ID:champ1,项目名称:ubuntu-make,代码行数:7,代码来源:test_interactions.py


示例12: test_calling_main

def test_calling_main(start_mock, monkeypatch):
    from bigchaindb.commands.bigchaindb import main

    argparser_mock = Mock()
    parser = Mock()
    subparsers = Mock()
    subsubparsers = Mock()
    subparsers.add_parser.return_value = subsubparsers
    parser.add_subparsers.return_value = subparsers
    argparser_mock.return_value = parser
    monkeypatch.setattr('argparse.ArgumentParser', argparser_mock)
    main()

    assert argparser_mock.called is True
    parser.add_subparsers.assert_called_with(title='Commands',
                                             dest='command')
    subparsers.add_parser.assert_any_call('configure',
                                          help='Prepare the config file.')
    subparsers.add_parser.assert_any_call('show-config',
                                          help='Show the current '
                                          'configuration')
    subparsers.add_parser.assert_any_call('init', help='Init the database')
    subparsers.add_parser.assert_any_call('drop', help='Drop the database')

    subparsers.add_parser.assert_any_call('start', help='Start BigchainDB')

    assert start_mock.called is True
开发者ID:vrde,项目名称:bigchaindb,代码行数:27,代码来源:test_commands.py


示例13: test_valid_both_no_reverse_links

    def test_valid_both_no_reverse_links(self):
        """Verify an item can be checked against both (no reverse links)."""

        def mock_iter(self):  # pylint: disable=W0613
            """Mock Tree.__iter__ to yield a mock Document."""
            mock_document = Mock()
            mock_document.parent = 'RQ'

            def mock_iter2(self):  # pylint: disable=W0613
                """Mock Document.__iter__ to yield a mock Item."""
                mock_item = Mock()
                mock_item.id = 'TST001'
                mock_item.links = []
                yield mock_item

            mock_document.__iter__ = mock_iter2
            yield mock_document

        self.item.add_link('fake1')

        mock_document = Mock()
        mock_document.prefix = 'RQ'

        mock_tree = Mock()
        mock_tree.__iter__ = mock_iter
        mock_tree.find_item = lambda identifier: Mock(id='fake1')

        self.assertTrue(self.item.valid(document=mock_document,
                                        tree=mock_tree))
开发者ID:jacebrowning,项目名称:doorstop-demo,代码行数:29,代码来源:test_item.py


示例14: test_find_rlinks

    def test_find_rlinks(self):
        """Verify an item's reverse links can be found."""

        mock_document_p = Mock()
        mock_document_p.prefix = 'RQ'

        mock_document_c = Mock()
        mock_document_c.parent = 'RQ'

        mock_item = Mock()
        mock_item.id = 'TST001'
        mock_item.links = ['RQ001']

        def mock_iter(self):  # pylint: disable=W0613
            """Mock Tree.__iter__ to yield a mock Document."""

            def mock_iter2(self):  # pylint: disable=W0613
                """Mock Document.__iter__ to yield a mock Item."""
                yield mock_item

            mock_document_c.__iter__ = mock_iter2
            yield mock_document_c

        self.item.add_link('fake1')
        mock_tree = Mock()
        mock_tree.__iter__ = mock_iter
        mock_tree.find_item = lambda identifier: Mock(id='fake1')
        rlinks, childrem = self.item.find_rlinks(mock_document_p, mock_tree)
        self.assertEqual(['TST001'], rlinks)
        self.assertEqual([mock_document_c], childrem)
开发者ID:jacebrowning,项目名称:doorstop-demo,代码行数:30,代码来源:test_item.py


示例15: setUp

    def setUp(self):
        self.db = NonCallableMagicMock(SQLiteDB)
        self.setup = Mock([])
        self.teardown = Mock([])
        self.table = table = CacheTable(self.setup, self.teardown)

        self.manager = CacheTableManager(self.db, [table])
开发者ID:,项目名称:,代码行数:7,代码来源:


示例16: testGet_namespaceClass

 def testGet_namespaceClass(self):
     view = Mock()
     view.find = Mock()
     view.substr = Mock(side_effect=['namespace test1\\test2;','class test3'])
     window = Mock()
     window.active_view = Mock(return_value=view)
     assert get_namespace(window) == 'test1\\test2\\test3'
开发者ID:Brandon0,项目名称:dotfiles,代码行数:7,代码来源:test_namespaces.py


示例17: test_import_with_existing_config

async def test_import_with_existing_config(hass):
    """Test importing a host with an existing config file."""
    flow = config_flow.HueFlowHandler()
    flow.hass = hass

    bridge = Mock()
    bridge.username = 'username-abc'
    bridge.config.bridgeid = 'bridge-id-1234'
    bridge.config.name = 'Mock Bridge'
    bridge.host = '0.0.0.0'

    with patch.object(config_flow, '_find_username_from_config',
                      return_value='mock-user'), \
            patch.object(config_flow, 'get_bridge',
                         return_value=mock_coro(bridge)):
        result = await flow.async_step_import({
            'host': '0.0.0.0',
            'path': 'bla.conf'
        })

    assert result['type'] == 'create_entry'
    assert result['title'] == 'Mock Bridge'
    assert result['data'] == {
        'host': '0.0.0.0',
        'bridge_id': 'bridge-id-1234',
        'username': 'username-abc'
    }
开发者ID:DavidMStraub,项目名称:home-assistant,代码行数:27,代码来源:test_config_flow.py


示例18: testGet_namespaceInterface

 def testGet_namespaceInterface(self):
     view = Mock()
     view.find = Mock()
     view.substr = Mock(side_effect=['namespace test1\\test2\\test3;','interface test4'])
     window = Mock()
     window.active_view = Mock(return_value=view)
     assert get_namespace(window) == 'test1\\test2\\test3\\test4'
开发者ID:Brandon0,项目名称:dotfiles,代码行数:7,代码来源:test_namespaces.py


示例19: dummy_callback

 def dummy_callback(self):
     from skorch.callbacks import Callback
     cb = Mock(spec=Callback)
     # make dummy behave like an estimator
     cb.get_params.return_value = {}
     cb.set_params = lambda **kwargs: cb
     return cb
开发者ID:YangHaha11514,项目名称:skorch,代码行数:7,代码来源:test_net.py


示例20: main

 def main(argument_namespace_callback, **kwargs):
     from PyOpenWorm.context import Context
     argument_namespace_callback.output_mode = 'json'
     m = Mock(name='context_result', spec=Context())
     m.identifier = 'ident'
     m.base_namespace = 'base_namespace'
     return m
开发者ID:openworm,项目名称:PyOpenWorm,代码行数:7,代码来源:CLITest.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python call.foo函数代码示例发布时间:2022-05-27
下一篇:
Python mock.MagicMock类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap