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

Python mock.create_autospec函数代码示例

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

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



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

示例1: test_pool_update

    def test_pool_update(self):
        """Test delete"""

        api = mock.create_autospec(BatchAppsApi)
        pool = Pool(api)
        api.get_pool.return_value = mock.create_autospec(Response)
        api.get_pool.return_value.success = True
        api.get_pool.return_value.result = {
            'targetDedicated':'5',
            'currentDedicated':'4',
            'state':'active',
            'allocationState':'test',
            }

        self.assertEqual(pool.target_size, 0)
        self.assertEqual(pool.current_size, 0)
        self.assertEqual(pool.state, None)
        self.assertEqual(pool.allocation_state, None)
        self.assertEqual(pool.resize_error, '')
        pool.update()
        api.get_pool.assert_called_with(pool_id=None)
        self.assertEqual(pool.target_size, 5)
        self.assertEqual(pool.current_size, 4)
        self.assertEqual(pool.state, 'active')
        self.assertEqual(pool.allocation_state, 'test')
        self.assertEqual(pool.resize_error, '')

        api.get_pool.return_value.success = False
        api.get_pool.return_value.result = RestCallException(None, "Test", None)

        with self.assertRaises(RestCallException):
            pool.update()
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:32,代码来源:unittest_pool.py


示例2: test_run_implementations_parallel_output_enabled_slow_implementations

	def test_run_implementations_parallel_output_enabled_slow_implementations(self, mock_loadImplementation):
		"""Coverage case for the display_progress option where the future is still not done after the timer expires."""
		test_implementation_mapping = {"foo": "bar", "baz": "bog"}
		test_command = CommandUnderTest()
		# create dummy imps where the side_effect of calling run is to sleep.
		mock_imp1 = create_autospec(spec = Implementation, spec_set = True, instance = True)
		mock_imp1.run.side_effect = lambda args: time.sleep(4)
		mock_imp2 = create_autospec(spec = Implementation, spec_set = True, instance = True)
		mock_imp2.run.side_effect = lambda args: time.sleep(5)
		gen = (impl for impl in (mock_imp1, mock_imp2))
		test_command.impl_list = {
			key: next(gen) for key in test_implementation_mapping
		}

		result = test_command.run_implementations_parallel(
			implementation_mapping = test_implementation_mapping,
			display_progress = True
		)

		assert result == {
			key: namedtuple("_", ("result", "exception"))(
				result = None,
				exception = None,
			)
			for key in test_implementation_mapping
		}
开发者ID:StackIQ,项目名称:stacki,代码行数:26,代码来源:test_command_stack_commands___init__.py


示例3: test_copy_target

def test_copy_target():
    src = create_autospec(Path, spec_set=True)
    dest = create_autospec(Path, spec_set=True)
    ct = CopyTarget(src, dest)

    assert ct.dest == dest

    ct.dest.exists.return_value = False
    with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
        cmp.return_value = False
        cres1 = ct.create()
        cres1.is_success
        assert copy2.call_count == 1
        assert cmp.call_count == 0

    ct.dest.exists.return_value = True
    with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
        cmp.return_value = False
        cres2 = ct.create()
        cres2.is_success
        assert copy2.call_count == 1
        assert cmp.call_count == 1

    ct.dest.exists.return_value = True
    with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
        cmp.return_value = True
        cres3 = ct.create()
        cres3.is_success
        assert copy2.call_count == 0
        assert cmp.call_count == 1
开发者ID:bow,项目名称:volt,代码行数:30,代码来源:test_targets.py


示例4: __init__

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.randomizer_mock = create_autospec(Randomizer)

        self.configuration = EvolutionConfiguration()
        self.configuration.operators = EvolutionOperatorsConfiguration()

        self.configuration.operators.inversion = EvolutionOperatorConfiguration()
        self.configuration.operators.inversion.chance = 0.5

        self.configuration.operators.mutation = EvolutionOperatorConfiguration()
        self.configuration.operators.mutation.chance = 0.2

        self.configuration.operators.crossover = EvolutionOperatorConfiguration()
        self.configuration.operators.crossover.chance = 0.3

        self.rule_population_mock = create_autospec(RulePopulation)

        self.service_mock = create_autospec(EvolutionService)
        self.service_mock.configure_mock(randomizer=self.randomizer_mock,
                                         configuration=self.configuration)

        self.rule_1 = Rule(Symbol('A'), Symbol('B'), Symbol('C'))
        self.rule_2 = Rule(Symbol('D'), Symbol('E'), Symbol('F'))

        self.sut = None
开发者ID:Michal-Stempkowski,项目名称:sgcs,代码行数:27,代码来源:test_evolution_operators.py


示例5: build_mock_player

def build_mock_player(position, pid):
    player = create_autospec(Player)
    pose = create_autospec(Pose)
    pose.position = position
    player.pose = pose
    player.id = pid
    return player
开发者ID:RoboCupULaval,项目名称:StrategyIA,代码行数:7,代码来源:test_evaluation_module.py


示例6: test_filecoll_extend

    def test_filecoll_extend(self, mock_api):
        """Test extend"""

        col = FileCollection(mock_api)
        col2 = FileCollection(mock_api)

        test_file = mock.create_autospec(UserFile)
        test_file2 = mock.create_autospec(UserFile)

        col._collection = [test_file]
        col2._collection = [test_file2, test_file]

        with self.assertRaises(AttributeError):
            col.extend(None)
        with self.assertRaises(AttributeError):
            col.extend("test")
        with self.assertRaises(AttributeError):
            col.extend([])

        col.extend(col2)
        self.assertEqual(len(col._collection), 2)
        self.assertTrue(all(i in [test_file, test_file2]
                            for i in col._collection))

        col2.extend(col)
        self.assertEqual(len(col._collection), 2)
        self.assertTrue(all(i in [test_file, test_file2]
                            for i in col._collection))
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:28,代码来源:unittest_files.py


示例7: test_filecoll_remove

    def test_filecoll_remove(self, mock_api):
        """Test remove"""

        col = FileCollection(mock_api)
        test_file = mock.create_autospec(UserFile)
        test_file.name = "test"
        col._collection = [test_file, 1, "2", None, []]

        with self.assertRaises(TypeError):
            col.remove(None)
        with self.assertRaises(TypeError):
            col.remove(10)

        col.remove(1)
        col.remove(-1)
        col.remove(slice(1))
        self.assertEqual(col._collection, ["2", None])

        test_file2 = mock.create_autospec(UserFile)
        test_file2.name = "test2"
        test_file3 = mock.create_autospec(UserFile)
        test_file3.name = "test3"
        col._collection = [test_file, test_file2, test_file3]
        col.remove("test")
        self.assertEqual(col._collection, [test_file2, test_file3])
        col.remove(["test2", "test3"])
        self.assertEqual(col._collection, [])
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:27,代码来源:unittest_files.py


示例8: test_engine_logger

    def test_engine_logger(self, mocked_application, mocked_adapter):
        logger = ema_logging.get_logger()
        mocked_logger = mock.Mock(spec=logger)
        mocked_logger.handlers = []
        mocked_logger.manager = mock.Mock(spec=logging.Manager)
        mocked_logger.manager.disable = 0
        ema_logging._logger = mocked_logger
        
        mocked_application.instance.return_value = mocked_application
        mocked_application.log = mocked_logger
        
        # no handlers    
        ema.set_engine_logger()
        logger = ema_logging._logger
#         self.assertTrue(type(logger) == type(mocked_adapter))
        mocked_logger.setLevel.assert_called_once_with(ema_logging.DEBUG)
        mocked_adapter.assert_called_with(mocked_logger, ema.SUBTOPIC)
        
        # with handlers
        mocked_logger = mock.create_autospec(logging.Logger)
        mock_engine_handler = mock.create_autospec(ipykernel.log.EnginePUBHandler)
        mocked_logger.handlers = [mock_engine_handler] 
        
        mocked_application.instance.return_value = mocked_application
        mocked_application.log = mocked_logger
        
        ema.set_engine_logger()
        logger = ema_logging._logger
#         self.assertTrue(type(logger) == ema.EngingeLoggerAdapter)
        mocked_logger.setLevel.assert_called_once_with(ema_logging.DEBUG)
        mocked_adapter.assert_called_with(mocked_logger, ema.SUBTOPIC)
        mock_engine_handler.setLevel.assert_called_once_with(ema_logging.DEBUG)
开发者ID:feilos,项目名称:EMAworkbench,代码行数:32,代码来源:test_ema_parallel_ipython.py


示例9: test_spec_inheritance_for_classes

    def test_spec_inheritance_for_classes(self):
        class Foo(object):
            def a(self):
                pass
            class Bar(object):
                def f(self):
                    pass

        class_mock = create_autospec(Foo)

        self.assertIsNot(class_mock, class_mock())

        for this_mock in class_mock, class_mock():
            this_mock.a()
            this_mock.a.assert_called_with()
            self.assertRaises(TypeError, this_mock.a, 'foo')
            self.assertRaises(AttributeError, getattr, this_mock, 'b')

        instance_mock = create_autospec(Foo())
        instance_mock.a()
        instance_mock.a.assert_called_with()
        self.assertRaises(TypeError, instance_mock.a, 'foo')
        self.assertRaises(AttributeError, getattr, instance_mock, 'b')

        # The return value isn't isn't callable
        self.assertRaises(TypeError, instance_mock)

        instance_mock.Bar.f()
        instance_mock.Bar.f.assert_called_with()
        self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')

        instance_mock.Bar().f()
        instance_mock.Bar().f.assert_called_with()
        self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
开发者ID:D3f0,项目名称:pinguinoweb,代码行数:34,代码来源:testhelpers.py


示例10: test_credentials_get_token

    def test_credentials_get_token(self):

        creds = mock.create_autospec(InteractiveCredentials)
        session = mock.create_autospec(OAuth2Session)
        creds._setup_session.return_value = session

        session.fetch_token.return_value = {
            'expires_at':'1',
            'expires_in':'2',
            'refresh_token':"test"}

        creds.redirect = "//my_service.com"
        creds.token_uri = "token_uri"
        creds._check_state.return_value = True
        creds.verify = True

        InteractiveCredentials.set_token(creds, "response")
        self.assertEqual(creds.token, session.fetch_token.return_value)
        session.fetch_token.assert_called_with(
            "token_uri",
            authorization_response="https://my_service.com/response",
            verify=True)

        creds._check_state.side_effect = ValueError("failed")
        with self.assertRaises(ValueError):
            InteractiveCredentials.set_token(creds, "response")

        creds._check_state.side_effect = None
        session.fetch_token.side_effect = oauthlib.oauth2.OAuth2Error
        with self.assertRaises(AuthenticationError):
            InteractiveCredentials.set_token(creds, "response")
开发者ID:BojanSavic,项目名称:autorest,代码行数:31,代码来源:unittest_auth.py


示例11: test_signature_callable

    def test_signature_callable(self):
        class Callable(object):
            def __init__(self):
                pass
            def __call__(self, a):
                pass

        mock = create_autospec(Callable)
        mock()
        mock.assert_called_once_with()
        self.assertRaises(TypeError, mock, 'a')

        instance = mock()
        self.assertRaises(TypeError, instance)
        instance(a='a')
        instance.assert_called_once_with(a='a')
        instance('a')
        instance.assert_called_with('a')

        mock = create_autospec(Callable())
        mock(a='a')
        mock.assert_called_once_with(a='a')
        self.assertRaises(TypeError, mock)
        mock('a')
        mock.assert_called_with('a')
开发者ID:D3f0,项目名称:pinguinoweb,代码行数:25,代码来源:testhelpers.py


示例12: test_spec_inheritance_for_classes

    def test_spec_inheritance_for_classes(self):

        class Foo(object):
            __qualname__ = 'SpecSignatureTest.test_spec_inheritance_for_classes.<locals>.Foo'

            def a(self):
                pass

            class Bar(object):
                __qualname__ = 'SpecSignatureTest.test_spec_inheritance_for_classes.<locals>.Foo.Bar'

                def f(self):
                    pass

        class_mock = create_autospec(Foo)
        self.assertIsNot(class_mock, class_mock())
        for this_mock in (class_mock, class_mock()):
            this_mock.a()
            this_mock.a.assert_called_with()
            self.assertRaises(TypeError, this_mock.a, 'foo')
            self.assertRaises(AttributeError, getattr, this_mock, 'b')
        instance_mock = create_autospec(Foo())
        instance_mock.a()
        instance_mock.a.assert_called_with()
        self.assertRaises(TypeError, instance_mock.a, 'foo')
        self.assertRaises(AttributeError, getattr, instance_mock, 'b')
        self.assertRaises(TypeError, instance_mock)
        instance_mock.Bar.f()
        instance_mock.Bar.f.assert_called_with()
        self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
        instance_mock.Bar().f()
        instance_mock.Bar().f.assert_called_with()
        self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:33,代码来源:testhelpers.py


示例13: test_create_autopsec

    def test_create_autopsec(self):
        mock = create_autospec(X)
        instance = mock()
        self.assertRaises(TypeError, instance)

        mock = create_autospec(X())
        self.assertRaises(TypeError, mock)
开发者ID:2014c2g10,项目名称:2014c2,代码行数:7,代码来源:testcallable.py


示例14: test_submittedjob_get_thumbnail

    def test_submittedjob_get_thumbnail(self, mock_prev):
        """Test get_thumbnail"""

        resp = mock.create_autospec(Response)
        resp.success = False
        resp.result = RestCallException(None, "test", None)
        mock_prev.return_value = resp
        api = mock.create_autospec(BatchAppsApi)

        job = SubmittedJob(api, "abc", None, None)

        with self.assertRaises(FileDownloadException):
            job.get_thumbnail()
        self.assertFalse(mock_prev.called)

        job = SubmittedJob(api,
                           "abc",
                           None,
                           None,
                           previewLink={'href':'http://'})

        with self.assertRaises(RestCallException):
            job.get_thumbnail()
        self.assertTrue(mock_prev.called)

        resp.success = True
        thumb = job.get_thumbnail(filename="thumb.png")
        mock_prev.assert_called_with(tempfile.gettempdir(), "thumb.png", True)

        thumb = job.get_thumbnail(download_dir="dir",
                                  filename="thumb.png",
                                  overwrite=False)
        mock_prev.assert_called_with("dir", "thumb.png", False)
        self.assertEqual(thumb, "dir\\thumb.png")
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:34,代码来源:unittest_job.py


示例15: mock_update

    def mock_update(url, headers=None):
        response = mock.create_autospec(Response)
        response.request = mock.create_autospec(Request)
        response.request.method = 'GET'
        
        if url == ASYNC_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response.content = ASYNC_BODY
            response.randomFieldFromPollAsyncOpHeader = None

        elif url == LOCATION_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response.content = LOCATION_BODY
            response.randomFieldFromPollLocationHeader = None

        elif url == ERROR:
            raise BadEndpointError("boom")

        elif url == RESOURCE_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response.content = RESOURCE_BODY

        else:
            raise Exception('URL does not match')
        response.json = lambda: json.loads(response.content)
        return response
开发者ID:AzCiS,项目名称:autorest,代码行数:29,代码来源:unittest_operation.py


示例16: test_submittedjob_get_output

    def test_submittedjob_get_output(self, mock_final, mock_int):
        """Test get_output"""

        _callback = mock.Mock()
        resp = mock.create_autospec(Response)
        resp.success = False
        resp.result = RestCallException(None, "test", None)
        api = mock.create_autospec(BatchAppsApi)

        mock_final.return_value = resp
        mock_int.return_value = resp

        job = SubmittedJob(api, "abc", None, None)

        with self.assertRaises(FileDownloadException):
            job.get_output("dir")

        job = SubmittedJob(api, "abc", None, None,
                           outputLink={'href':'http://'},
                           outputFileName="filename")
        with self.assertRaises(RestCallException):
            output = job.get_output("dir")
        mock_final.assert_called_with("dir", False, callback=None, block=4096)
        self.assertFalse(mock_int.called)

        resp.success = True
        output = job.get_output("dir")
        self.assertEqual(output, "dir\\filename")

        mock_final.called = False
        output = job.get_output("dir", output={'name':'test'}, overwrite=True, callback=_callback, block=1)
        self.assertFalse(mock_final.called)
        mock_int.assert_called_with({'name':'test'}, "dir", True, callback=_callback, block=1)
        self.assertEqual(output, "dir\\test")
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:34,代码来源:unittest_job.py


示例17: test_submittedjob_get_final_preview

    def test_submittedjob_get_final_preview(self):
        """Test _get_final_preview"""

        _callback = mock.Mock()
        resp = mock.create_autospec(Response)
        api = mock.create_autospec(BatchAppsApi)
        api.get_output.return_value = resp

        job = SubmittedJob(api, None, None, None)
        output = job._get_final_preview("dir", "name", True)
        api.get_output.assert_called_with("dir", 0, "name", True, url=None, callback=None, block=4096)
        self.assertEqual(output, resp)

        job = SubmittedJob(api,
                           None,
                           None,
                           None,
                           previewLink={'href':'http://thumb'})
        output = job._get_final_preview("dir", "name", False, callback=_callback, block=111)
        api.get_output.assert_called_with("dir",
                                          0,
                                          "name",
                                          False,
                                          url='http://thumb',
                                          callback=_callback,
                                          block=111)
        self.assertEqual(output, resp)
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:27,代码来源:unittest_job.py


示例18: test_jobsubmission_job_file

    def test_jobsubmission_job_file(self):
        """Test set_job_file"""

        jfile = mock.create_autospec(UserFile)
        coll = mock.create_autospec(FileCollection)
        api = mock.create_autospec(BatchAppsApi)
        jfile.name = "test"

        job = JobSubmission(api, "test_job")
        with self.assertRaises(ValueError):
            job.set_job_file(2)

        with self.assertRaises(ValueError):
            job.set_job_file(None)

        with self.assertRaises(ValueError):
            job.set_job_file("Something")

        with self.assertRaises(ValueError):
            job.set_job_file(jfile)

        job.required_files = coll
        job.set_job_file(jfile)
        self.assertEqual(job.source, "test")
        coll.add.assert_called_with(jfile)

        coll.__len__.return_value = 1
        job = JobSubmission(api, "test_job")
        job.required_files = coll
        job.set_job_file(0)
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:30,代码来源:unittest_job.py


示例19: test_userfile_is_uploaded

    def test_userfile_is_uploaded(self, mock_mod, mock_query, mock_ufile):
        """Test is_uploaded"""

        mock_mod.return_value = True
        result = mock.create_autospec(UserFile)
        result.name = "1"
        mock_ufile.return_value = result
        api = mock.create_autospec(batchapps.api.BatchAppsApi)

        ufile = UserFile(api, {'name':'1'})

        resp = mock.create_autospec(Response)
        resp.success = False
        resp.result = RestCallException(None, "Boom", None)
        api.query_files.return_value = resp

        with self.assertRaises(RestCallException):
            ufile.is_uploaded()

        resp.success = True
        resp.result = ['1', '2', '3']
        self.assertIsInstance(ufile.is_uploaded(), UserFile)
        self.assertTrue(api.query_files.called)
        self.assertTrue(mock_query.called)
        self.assertEqual(mock_ufile.call_count, 3)
        mock_ufile.assert_called_with(mock.ANY, '3')

        result.name = "4"
        self.assertIsNone(ufile.is_uploaded())
开发者ID:Azure,项目名称:azure-batch-apps-python,代码行数:29,代码来源:unittest_files.py


示例20: setUp

    def setUp(self):
        view = mock.create_autospec(PlotView)
        view.subplotRemovedSignal = mock.Mock()
        self.presenter = PlotPresenter(view)
        self.presenter.view.canvas = mock.Mock()
        self.presenter.view.canvas.draw = mock.Mock()

        self.view = self.presenter.view
        self.view.close = mock.Mock()
        self.view.get_subplots = mock.Mock(return_value={})
        self.view.removeLine = mock.Mock()

        # explicitly mock pop up
        self.mock_selector = mock.create_autospec(dummy_popup)
        self.mock_selector.subplotSelectorSignal = mock.Mock()
        self.mock_selector.closeEventSignal = mock.Mock()

        self.mock_rmWindow = mock.create_autospec(dummy_popup)
        self.mock_rmWindow.applyRemoveSignal = mock.Mock()
        self.mock_rmWindow.closeEventSignal = mock.Mock()
        self.mock_rmWindow.subplot = mock.Mock(return_value="plot")
        self.mock_rmWindow.getState = mock.Mock(side_effect=[True, True])
        self.mock_rmWindow.getLine = mock.Mock()

        # mock presenter to create mock pop ups
        self.presenter.createRmWindow = mock.Mock(
            return_value=self.mock_rmWindow)
        self.presenter.createSelectWindow = mock.Mock(
            return_value=self.mock_selector)

        self.mock_name = mock.Mock()
        self.mock_workspace = mock.Mock()
        self.mock_func = mock.Mock()
        self.mock_arbitrary_args = [mock.Mock() for i in range(3)]
开发者ID:samueljackson92,项目名称:mantid,代码行数:34,代码来源:PlottingPresenter_test.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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