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

Python mock.create_autospec函数代码示例

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

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



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

示例1: test_mongo_date_range_query

def test_mongo_date_range_query():
    self = create_autospec(TickStore)
    self._collection = create_autospec(Collection)
    self._symbol_query.return_value = {"sy": {"$in" : ["s1" , "s2"]}}
    self._collection.aggregate.return_value = iter([{"_id": "s1", "start": dt(2014, 1, 1, 0, 0, tzinfo=mktz())},
                                                    {"_id": "s2", "start": dt(2014, 1, 1, 12, 0, tzinfo=mktz())}])

    self._collection.find_one.side_effect = [
        {'e': dt(2014, 1, 1, 15, 0, tzinfo=mktz())},
        {'e': dt(2014, 1, 2, 12, 0, tzinfo=mktz())}]

    query = TickStore._mongo_date_range_query(self, 'sym', DateRange(dt(2014, 1, 2, 0, 0, tzinfo=mktz()),
                                                                     dt(2014, 1, 3, 0, 0, tzinfo=mktz())))

    assert self._collection.aggregate.call_args_list == [call([
     {"$match": {"s": {"$lte": dt(2014, 1, 2, 0, 0, tzinfo=mktz())}, "sy": {"$in" : ["s1" , "s2"]}}},
     {"$project": {"_id": 0, "s": 1, "sy": 1}},
     {"$group": {"_id": "$sy", "start": {"$max": "$s"}}},
     {"$sort": {"start": 1}}])]

    assert self._collection.find_one.call_args_list == [
        call({'sy': 's1', 's': dt(2014, 1, 1, 0, 0, tzinfo=mktz())}, {'e': 1}),
        call({'sy': 's2', 's': dt(2014, 1, 1, 12, 0, tzinfo=mktz())}, {'e': 1})]

    assert query == {'s': {'$gte': dt(2014, 1, 1, 12, 0, tzinfo=mktz()), '$lte': dt(2014, 1, 3, 0, 0, tzinfo=mktz())}}
开发者ID:manahl,项目名称:arctic,代码行数:25,代码来源:test_tickstore.py


示例2: test_handle_exception_timeout

 def test_handle_exception_timeout(self, mock_print_function):
     mock_request = mock.create_autospec(Request).return_value
     mock_request.url = "http://mockurl.mock"
     mock_exception = mock.create_autospec(exceptions.Timeout).return_value
     mock_exception.__str__.return_value = "Timeout reached"
     self.request_sender.handle_request_exception(mock_request, mock_exception)
     self.assertEquals(mock_print_function.call_count, 2)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py


示例3: setUp

    def setUp(self):
        self.vlan_id_gen = 'gen_id'
        self.name_gen = 'gen_name'
        self.spec = Mock()
        self.vm = Mock()
        self.pv_service = Mock()
        self.pv_service.find_by_uuid = Mock(self.vm)
        self.si = Mock()
        self.vm_uuid = 'uuid'
        self.vlan_id = 100
        self.spec_type = Mock()

        vnic_device_mapper = create_autospec(spec=VNicDeviceMapper)
        vnic_device_mapper.vnic = create_autospec(spec=vim.vm.device.VirtualEthernetCard)
        vnic_device_mapper.vnic.macAddress = 'AA-BB'
        vnic_device_mapper.vnic.deviceInfo = Mock()
        vnic_device_mapper.vnic.deviceInfo.label = 'AA-BB'
        vnic_device_mapper.network = Mock()
        vnic_device_mapper.network.name = 'the network'
        vnic_device_mapper.network.key = 'keyyyyyey'
        vnic_device_mapper.requested_vnic = 'requested'

        self.dv_connector = Mock()
        self.dv_connector.connect_by_mapping = Mock(return_value=[vnic_device_mapper])
        self.dv_port_name_gen = Mock()
        self.vlan_spec_factory = Mock()
        self.vlan_id_range_parser = Mock()
        self.vlan_id_range_parser.parse_vlan_id = Mock(return_value=self.vlan_id_gen)
        self.dv_port_name_gen.generate_port_group_name = Mock(return_value=self.name_gen)
        self.vlan_spec_factory.get_vlan_spec = Mock(return_value=self.spec)
开发者ID:AharonShachar,项目名称:vCenterShell,代码行数:30,代码来源:test_connect_vm.py


示例4: test_handle_exception_connection_error

 def test_handle_exception_connection_error(self, mock_print_function):
     mock_request = mock.create_autospec(Request).return_value
     mock_request.url = "htt;//mockurl.mock"
     mock_exception = mock.create_autospec(exceptions.ConnectionError).return_value
     mock_exception.__str__.return_value = "DNS failure"
     self.request_sender.handle_request_exception(mock_request, mock_exception)
     self.assertEquals(mock_print_function.call_count, 2)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py


示例5: test_handle_exception_urlrequired

 def test_handle_exception_urlrequired(self, mock_print_function):
     mock_request = mock.create_autospec(Request).return_value
     mock_request.url = "htt;//mockurl.mock"
     mock_exception = mock.create_autospec(exceptions.URLRequired).return_value
     mock_exception.__str__.return_value = "Invalid url"
     self.request_sender.handle_request_exception(mock_request, mock_exception)
     self.assertEquals(mock_print_function.call_count, 2)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py


示例6: test_evaluate_initializer_with_fallback_calls_fallback

def test_evaluate_initializer_with_fallback_calls_fallback():
    init = mock.create_autospec(Initializer())
    fallback = mock.create_autospec(Initializer())
    fallback.side_effect = lambda x: np.array(1)
    init.side_effect = InitializationError
    evaluate_initializer(init, (7, 5), fallback)
    fallback.assert_called_once_with((7, 5))
开发者ID:AdityoSanjaya,项目名称:brainstorm,代码行数:7,代码来源:test_initializers.py


示例7: test_handle_exception_baseexception

 def test_handle_exception_baseexception(self, mock_print_function):
     mock_request = mock.create_autospec(Request).return_value
     mock_request.url = "http://mockurl.mock"
     mock_exception = mock.create_autospec(BaseException).return_value
     mock_exception.__str__.return_value = "BaseException message"
     self.request_sender.handle_request_exception(mock_request, mock_exception)
     self.assertEquals(mock_print_function.call_count, 2)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py


示例8: setup_resource

 def setup_resource(self):
     self.mcp = mock.create_autospec(mcp.MasterControlProgram)
     self.resource = www.ConfigResource(self.mcp)
     self.controller = self.resource.controller = mock.create_autospec(
         controller.ConfigController)
     with mock.patch('tron.api.www.respond', autospec=True) as self.respond:
         yield
开发者ID:Feriority,项目名称:Tron,代码行数:7,代码来源:www_test.py


示例9: test_create_empty

    def test_create_empty(self):
        # Create a minimal fake GAPIC with a dummy response.
        from google.cloud.firestore_v1beta1.document import DocumentReference
        from google.cloud.firestore_v1beta1.document import DocumentSnapshot
        firestore_api = mock.Mock(spec=['commit'])
        document_reference = mock.create_autospec(DocumentReference)
        snapshot = mock.create_autospec(DocumentSnapshot)
        snapshot.exists = True
        document_reference.get.return_value = snapshot
        commit_response = mock.Mock(
            write_results=[document_reference],
            get=[snapshot],
            spec=['write_results'])
        firestore_api.commit.return_value = commit_response

        # Attach the fake GAPIC to a real client.
        client = _make_client('dignity')
        client._firestore_api_internal = firestore_api
        client.get_all = mock.MagicMock()
        client.get_all.exists.return_value = True

        # Actually make a document and call create().
        document = self._make_one('foo', 'twelve', client=client)
        document_data = {}
        write_result = document.create(document_data)
        self.assertTrue(write_result.get().exists)
开发者ID:longfengpili,项目名称:google-cloud-python,代码行数:26,代码来源:test_document.py


示例10: test_job_runs_from_state

 def test_job_runs_from_state(self):
     state_data = [
         dict(
             run_num=i,
             job_name="thename",
             run_time="sometime",
             start_time="start_time",
             end_time="sometime",
             cleanup_run=None,
             runs=[],
         ) for i in range(3, -1, -1)
     ]
     action_graph = mock.create_autospec(actiongraph.ActionGraph)
     output_path = mock.create_autospec(filehandler.OutputPath)
     context = mock.Mock()
     node_pool = mock.create_autospec(node.NodePool)
     runs = jobrun.job_runs_from_state(
         state_data,
         action_graph,
         output_path,
         context,
         node_pool,
     )
     assert len(runs) == 4
     assert all([type(job) == jobrun.JobRun for job in runs])
开发者ID:pombredanne,项目名称:Tron,代码行数:25,代码来源:jobrun_test.py


示例11: setup_jobrun

 def setup_jobrun(self):
     self.action_graph = mock.create_autospec(actiongraph.ActionGraph)
     self.run_time = datetime.datetime(2012, 3, 14, 15, 9, 26)
     self.path = ['base', 'path']
     self.output_path = mock.create_autospec(filehandler.OutputPath)
     self.node_pool = mock.create_autospec(node.NodePool)
     self.action_run_state_data = [{
         'job_run_id': 'thejobname.22',
         'action_name': 'blingaction',
         'state': 'succeeded',
         'run_time': 'sometime',
         'start_time': 'sometime',
         'end_time': 'sometime',
         'command': 'doit',
         'node_name': 'thenode',
     }]
     self.state_data = {
         'job_name': 'thejobname',
         'run_num': 22,
         'run_time': self.run_time,
         'node_name': 'thebox',
         'end_time': 'the_end',
         'start_time': 'start_time',
         'runs': self.action_run_state_data,
         'cleanup_run': None,
         'manual': True,
     }
     self.context = mock.Mock()
开发者ID:pombredanne,项目名称:Tron,代码行数:28,代码来源:jobrun_test.py


示例12: test_acquired

    def test_acquired(self):
        """
        Test the acquiring primitives
        """
        self.locker._sequence = '4'
        retval = ('/_locks/test_lock/4', None)
        self.locker._get_locker = mock.create_autospec(
            self.locker._get_locker, return_value=retval)
        self.assertTrue(self.locker._acquired())
        self.assertTrue(self.locker.is_taken)
        retval = ('/_locks/test_lock/1', '/_locks/test_lock/4')
        self.locker._get_locker = mock.MagicMock(return_value=retval)
        self.assertFalse(self.locker._acquired(blocking=False))
        self.assertFalse(self.locker.is_taken)
        d = {
            u'action': u'delete',
            u'node': {
                u'modifiedIndex': 190,
                u'key': u'/_locks/test_lock/1',
                u'value': self.locker.uuid
            }
        }
        self._mock_api(200, d)
        returns = [('/_locks/test_lock/1', '/_locks/test_lock/4'),  ('/_locks/test_lock/4', None)]

        def side_effect():
            return returns.pop()

        self.locker._get_locker = mock.create_autospec(
            self.locker._get_locker, side_effect=side_effect)
        self.assertTrue(self.locker._acquired())
开发者ID:kireal,项目名称:python-etcd,代码行数:31,代码来源:test_lock.py


示例13: create_blank_response

 def create_blank_response(cls, code, msg):
   # TODO(wfarner): Don't use a mock here.
   response = create_autospec(spec=Response, instance=True)
   response.responseCode = code
   response.result = create_autospec(spec=Result, instance=True)
   response.details = [ResponseDetail(message=msg)]
   return response
开发者ID:apache,项目名称:aurora,代码行数:7,代码来源:util.py


示例14: test_get_verbose_status_of_marathon_app_column_alignment

def test_get_verbose_status_of_marathon_app_column_alignment():
    fake_app = mock.create_autospec(marathon.models.app.MarathonApp)
    fake_app.version = '2015-01-15T05:30:49.862Z'
    fake_app.id = '/fake--service'

    fake_task1 = mock.create_autospec(marathon.models.app.MarathonTask)
    fake_task1.id = 'fake_task1_id'
    fake_task1.host = 'fake_deployed_host'
    fake_task1.ports = [6666]
    fake_task1.staged_at = datetime.datetime.fromtimestamp(0)
    fake_task1.health_check_results = []

    fake_task2 = mock.create_autospec(marathon.models.app.MarathonTask)
    fake_task2.id = 'fake_task2_id'
    fake_task2.host = 'fake_deployed_host_with_a_really_long_name'
    fake_task2.ports = [6666]
    fake_task2.staged_at = datetime.datetime.fromtimestamp(0)
    fake_task2.health_check_results = []

    fake_app.tasks = [fake_task1, fake_task2]
    tasks, out = marathon_serviceinit.get_verbose_status_of_marathon_app(fake_app)
    (_, _, _, headers_line, task1_line, task2_line) = out.split('\n')
    assert headers_line.index('Host deployed to') == task1_line.index('fake_deployed_host')
    assert headers_line.index('Host deployed to') == task2_line.index('fake_deployed_host_with_a_really_long_name')
    assert headers_line.index('Deployed at what localtime') == task1_line.index('1970-01-01T00:00')
    assert headers_line.index('Deployed at what localtime') == task2_line.index('1970-01-01T00:00')
开发者ID:somic,项目名称:paasta,代码行数:26,代码来源:test_marathon_serviceinit.py


示例15: test_invoke__triggers_max_errors

def test_invoke__triggers_max_errors():
    with open('imhotep/fixtures/10line.diff') as f:
        ten_diff = f.read()
    reporter = mock.create_autospec(PRReporter)
    tool = mock.create_autospec(Tool)
    manager = mock.create_autospec(RepoManager)
    tool.get_configs.side_effect = AttributeError
    tool.invoke.return_value = {
        'f1.txt': {
            '1': 'there was an error',
            '2': 'there was an error',
            '3': 'there was an error',
            '4': 'there was an error',
            '5': 'there was an error',
            '6': 'there was an error',
            '7': 'there was an error',
            '8': 'there was an error',
            '9': 'there was an error',
        }
    }
    manager.clone_repo.return_value.diff_commit.return_value = ten_diff
    manager.clone_repo.return_value.tools = [tool]
    imhotep = Imhotep(
        pr_number=1,
        repo_manager=manager,
        commit_info=mock.Mock(),
    )
    imhotep.invoke(reporter=reporter, max_errors=2)

    assert reporter.report_line.call_count == 2
    assert reporter.post_comment.called
开发者ID:daleathan,项目名称:imhotep,代码行数:31,代码来源:app_test.py


示例16: setUp

 def setUp(self):
     mock_config = mock_factory.create_mock_config()
     mock_item_queue = mock.create_autospec(queue).return_value
     mock_item_writer = mock.create_autospec(ItemWriter).return_value
     self.item_processor = ItemProcessor(mock_config, mock_item_queue)
     self.item_processor.item_writer = mock_item_writer
     self.item_processor.no_items_received = True
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_item_processor.py


示例17: test_get_object_by_path_checks_childEntity

    def test_get_object_by_path_checks_childEntity(self):
        """
        Checks whether the function can grab from child entities
        """
        "#arrange"
        pv_service = pyVmomiService(None, None)

        def search_child(*args, **keys):
            if args[0].name == pv_service.ChildEntity:
                return True
            return False

        class FolderMock:
            childEntity = None

        folder = Mock(spec=FolderMock())
        folder.name = pv_service.ChildEntity
        get_folder = MagicMock(return_value=folder)
        pv_service.get_folder = get_folder

        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock()
        si.content = create_autospec(spec=vim.ServiceInstanceContent())
        si.content.searchIndex = Mock()
        si.content.searchIndex.FindChild = MagicMock(side_effect=search_child)

        "#act"
        result = pv_service.find_obj_by_path(si, "", "", "")

        "#assert"
        self.assertTrue(result)
开发者ID:chengleft,项目名称:vCenterShell,代码行数:31,代码来源:test_common_pyvmomi.py


示例18: test_get_binary

 def test_get_binary(self):
     mock_request = mock.create_autospec(Request).return_value
     mock_response = mock.create_autospec(Response).return_value
     mock_response.content = "<html><a href='url1'>text1</a><a href='url2'>text2</a></html>"
     self.request_sender.session.send.return_value = mock_response
     result = self.request_sender.get_binary(mock_request)
     self.assertEquals(result, mock_response.content)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py


示例19: test_create_page_processor

 def test_create_page_processor(self, mock_item_processor_class):
     mock_config = mock.create_autospec(Config).return_value
     mock_item_queue = mock.create_autospec(queue).return_value
     mock_item_processor = mock.create_autospec(ItemProcessor).return_value
     mock_item_processor_class.return_value = mock_item_processor
     result = self.thread_factory.create_item_processor(mock_config, mock_item_queue)
     self.assertEquals(result, mock_item_processor)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_thread_factory.py


示例20: test_handle_exception_httperror

 def test_handle_exception_httperror(self, mock_print_function):
     mock_request = mock.create_autospec(Request).return_value
     mock_request.url = "http://mockurl.mock"
     mock_exception = mock.create_autospec(exceptions.HTTPError).return_value
     mock_exception.__str__.return_value = "Invalid HTTP respons"
     self.request_sender.handle_request_exception(mock_request, mock_exception)
     self.assertEquals(mock_print_function.call_count, 2)
开发者ID:cardsurf,项目名称:xcrawler,代码行数:7,代码来源:test_request_sender.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mock.mock_open函数代码示例发布时间:2022-05-27
下一篇:
Python mock.call函数代码示例发布时间: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