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


Python Mock.code方法代码示例

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


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

示例1: test_rpc_request

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
 def test_rpc_request(self):
     response = Mock()
     response.code = 200
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     result = yield self.client.foo()
     self.assertTrue(result)
开发者ID:fiorix,项目名称:cyclone,代码行数:9,代码来源:test_httpclient.py

示例2: test_handle_smart_errors

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        view = flask_restful.Resource

        exception = Mock()
        exception.code = 404
        exception.data = {"status": 404, "message": "Not Found"}
        api.add_resource(view, '/foo', endpoint='bor')
        api.add_resource(view, '/fee', endpoint='bir')
        api.add_resource(view, '/fii', endpoint='ber')


        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "Not Found",
            }))

        with app.test_request_context("/fOo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "Not Found. You have requested this URI [/fOo] but did you mean /foo ?",
            }))

        with app.test_request_context("/fOo"):
            del exception.data["message"]
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?",
            }))
开发者ID:undeadking,项目名称:flask-restful,代码行数:36,代码来源:test_api.py

示例3: test_post_with_bad_data

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
def test_post_with_bad_data(service_client, get_repositories, get_repository):
    get_repositories.return_value = future_repositories
    get_repository.return_value = future_repository

    mock_response = Mock()
    mock_response.body = '{"errors": [{"source_id_type": "", "message": "not supported asset id type"}]}'
    mock_response.code = 400
    exc = httpclient.HTTPError(400, response=mock_response)
    service_client.return_value = make_future(MagicMock())
    client = yield service_client()
    endpoint = client.repository.repositories[''].search.offers
    endpoint.post.side_effect = exc

    handler = _create_offers_handler()

    # MUT
    handler.request.body = ('[{"source_id":' +
                            '"https://openpermissions.org/s0/hub1/asset/exampleco/ExampleCoPictureID/1",' +
                            '"source_id_type":""}]')

    with pytest.raises(HTTPError) as excinfo:
        handler.post().result()

    assert excinfo.value.status_code == mock_response.code
    assert excinfo.value.errors == json.loads(mock_response.body)
开发者ID:openpermissions,项目名称:query-srv,代码行数:27,代码来源:test_offers_handler.py

示例4: test_onionoo_too_many_answers

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_onionoo_too_many_answers(self):
        agent = Mock()
        resp = Mock()
        resp.code = 200

        def feed_response(protocol):
            config = {
                "relays": [
                    {
                        "fingerprint": "00786E43CCC5409753F25E36031C5CEA6EA43702",
                    },
                    {
                        "fingerprint": "boom",
                    }
                ]
            }
            protocol.dataReceived(json.dumps(config).encode())
            protocol.connectionLost(Failure(ResponseDone()))
        resp.deliverBody = Mock(side_effect=feed_response)
        agent.request = Mock(return_value=defer.succeed(resp))

        with self.assertRaises(Exception) as ctx:
            yield self.router.get_onionoo_details(agent)

        self.assertTrue(
            "multiple relays for" in str(ctx.exception)
        )
开发者ID:felipedau,项目名称:txtorcon,代码行数:29,代码来源:test_router.py

示例5: test_handle_error_signal

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_handle_error_signal(self):
        if not signals_available:
            # This test requires the blinker lib to run.
            print("Can't test signals without signal support")
            return
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {'foo': 'bar'}

        recorded = []

        def record(sender, exception):
            recorded.append(exception)

        got_request_exception.connect(record, app)
        try:
            with app.test_request_context("/foo"):
                api.handle_error(exception)
                self.assertEquals(len(recorded), 1)
                self.assertTrue(exception is recorded[0])
        finally:
            got_request_exception.disconnect(record, app)
开发者ID:fengshao0907,项目名称:flask-restful,代码行数:27,代码来源:test_api.py

示例6: test_rpc_request_404

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
 def test_rpc_request_404(self):
     response = Mock()
     response.code = 404
     response.phrase = "Not found."
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     return self.assertFailure(self.client.foo(), HTTPError)
开发者ID:fiorix,项目名称:cyclone,代码行数:9,代码来源:test_httpclient.py

示例7: dummy_balance_code

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
def dummy_balance_code():
    m = Mock()
    m.pk = random.randint(1, 999)
    m.value = 100
    m.code = generate_balance_code()
    m.refill_series.pk = random.randint(1, 99)
    m.refill_series.least_valid_until = date.today()
    return m
开发者ID:Baljan,项目名称:cafesys,代码行数:10,代码来源:pdfstimuli.py

示例8: test_call

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
 def test_call(self, treq_mock):
     """A call to a Mandrill API endpoint will return a deferred."""
     response_mock = Mock()
     response_mock.json.return_value = {'some': 'response'}
     response_mock.code = 200
     treq_mock.post.return_value = succeed(response_mock)
     m = TXMandrill('nah')
     result = yield m.users.info()
     self.assertEquals(result, {'some': 'response'})
开发者ID:lextoumbourou,项目名称:txmandrill-api,代码行数:11,代码来源:tests.py

示例9: test_generate_key_module

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_generate_key_module(self):
        """ Test that a key is generated for module functions """
        def test_func(): pass

        stat = Mock()
        stat.code = test_func.__code__

        expected_key = "%s.%s" % (self.__module__, stat.code.co_name)
        key = linesman._generate_key(stat)
        assert_equals(key, expected_key)
开发者ID:cpennington,项目名称:linesman,代码行数:12,代码来源:test_graphs.py

示例10: test_failure

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
 def test_failure(self, treq_mock):
     """An error HTTP response will raise an exception."""
     response_mock = Mock()
     response_mock.json.return_value = {
         'name': 'ValidationError',
         'status': 'error', 'message': 'Validation failed.'}
     response_mock.code = 404
     treq_mock.post.return_value = succeed(response_mock)
     m = TXMandrill('nah')
     yield self.assertFailure(m.users.info(), ValidationError)
开发者ID:lextoumbourou,项目名称:txmandrill-api,代码行数:12,代码来源:tests.py

示例11: test_generate_key_unknown

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_generate_key_unknown(self):
        """ Test that unknown module functions return as strings """
        def test_func(): pass

        stat = Mock()
        stat.code = test_func.__code__

        expected_key = "%s.%s" % (stat.code.co_filename, stat.code.co_name)
        key = linesman._generate_key(stat)
        assert_equals(key, expected_key)
开发者ID:cpennington,项目名称:linesman,代码行数:12,代码来源:test_graphs.py

示例12: test_fetch_redirect_empty

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
 def test_fetch_redirect_empty(self):
     client = HTTPClient("http://example.com")
     client.agent = Mock()
     client.followRedirect = True
     client.maxRedirects = 1
     _response1 = Mock()
     _response1.code = 302
     _response1.headers.getAllRawHeaders.return_value = {}
     _response1.deliverBody = lambda x: x.connectionLost(None)
     _response2 = Mock()
     _response2.code = 200
     _response2.headers.getAllRawHeaders.return_value = {}
     _response2.deliverBody = lambda x: x.connectionLost(None)
     client.agent.request.side_effect = [
         succeed(_response1),
         succeed(_response2)
     ]
     response = yield client.fetch()
     self.assertEqual(response.body, "")
开发者ID:fiorix,项目名称:cyclone,代码行数:21,代码来源:test_httpclient.py

示例13: test_connect_while_connected

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_connect_while_connected(self, mock_endpoint):
        "should pass http request body to TwitterStreamingProtocol"
        mock_http_response = Mock()
        mock_http_response.code = 200
        mock_http_response.deliverBody = Mock()

        self._connect(mock_endpoint, mock_http_response)
        self.assertEquals(CONNECTED, self.stream.state)

        with self.assertRaises(ValueError):
            self.stream.track(TestReceiver(), ['track'])
开发者ID:gareth-lloyd,项目名称:twistedstream,代码行数:13,代码来源:test_connect.py

示例14: test_onionoo_get_fails

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_onionoo_get_fails(self):
        agent = Mock()
        resp = Mock()
        resp.code = 500
        agent.request = Mock(return_value=defer.succeed(resp))

        with self.assertRaises(Exception) as ctx:
            yield self.router.get_onionoo_details(agent)
        self.assertTrue(
            "Failed to lookup" in str(ctx.exception)
        )
开发者ID:felipedau,项目名称:txtorcon,代码行数:13,代码来源:test_router.py

示例15: test_handle_error_401_no_challenge_by_default

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import code [as 别名]
    def test_handle_error_401_no_challenge_by_default(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        exception = Mock()
        exception.code = 401
        exception.data = {'foo': 'bar'}

        with app.test_request_context('/foo'):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 401)
            assert_false('WWW-Autheneticate' in resp.headers)
开发者ID:ZhangBohan,项目名称:flask-restful,代码行数:13,代码来源:test_api.py


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