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


Python MagicMock.body方法代码示例

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


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

示例1: test_format

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def test_format(self):
        req = MagicMock()
        resp = MagicMock()
        resp.body = {"example": "JSON"}
        resp.content_type = None

        hook_format(req, resp)

        resp.body = '{"example": "JSON"}'
        resp.content_type = 'application/json'
开发者ID:ajiang38740,项目名称:jumpgate,代码行数:12,代码来源:test_hooks.py

示例2: test_parseRequestBody

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def test_parseRequestBody(self):
        req = MagicMock()
        req.body = '{"key":"value"}'

        data = self.rest_app._parseRequestBody(req)
        self.assertEqual(data, {'key': 'value'})
        self.assertEqual(data.keys(), ['key'])
        self.assertEqual(type(data.keys()[0]), str)

        # test some bad data
        req.body = '{aaaaaaa}'
        self.assertRaises(HTTPBadRequest, self.rest_app._parseRequestBody, req)
开发者ID:agrueneberg,项目名称:anki-sync-server,代码行数:14,代码来源:test_rest_app.py

示例3: remove_public_id

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def remove_public_id(self, last_public_id, original_id, HTTPCallbackGroup,
                                                            get_associated_privates,
                                                            get_associated_publics,
                                                            _delete_number):
        # Setup
        HTTPCallbackGroup.return_value = MagicMock()
        on_success_handler = MagicMock()
        on_failure_handler = MagicMock()
        self.handler.forward_error = MagicMock()
        if original_id:
            sip_uri = SIP_URI
        else:
            sip_uri = SIP_URI2

        # Test
        numbers.remove_public_id(self.db_sess,
                                 sip_uri,
                                 on_success_handler,
                                 on_failure_handler,
                                 False)

        # Asserts
        get_associated_privates.assert_called_once_with(sip_uri, ANY)
        HTTPCallbackGroup.assert_called_once_with(ANY, ANY)

        # Extract inner function and can call it with response
        on_get_privates_success = HTTPCallbackGroup.call_args[0][0]
        response = MagicMock()
        response.body = '{"public_id": "%s", "private_ids": ["%s"]}' % (sip_uri, PRIVATE_ID)
        on_get_privates_success([response])

        # Response should have been parsed now and a new call invoked
        get_associated_publics.assert_called_once_with(PRIVATE_ID, ANY)
        on_get_publics_success = HTTPCallbackGroup.call_args[0][0]
        response = MagicMock()
        if last_public_id:
            response.body = '{"associated_public_ids": ["%s"]}' % (sip_uri)
        else:
            response.body = '{"associated_public_ids": ["[email protected]", "%s"]}' % (sip_uri)

        on_get_publics_success([response])
        if original_id and not last_public_id:
            # When deleting the originally created public identity we want the request to fail
            # if other public identities are associated with the private id
            on_failure_handler.assert_called_once_with(response)
        else:
            _delete_number.assert_called_once_with(self.db_sess,
                                                   sip_uri,
                                                   PRIVATE_ID,
                                                   last_public_id,
                                                   on_success_handler,
                                                   on_failure_handler,
                                                   False)
开发者ID:rkday,项目名称:ellis,代码行数:55,代码来源:numbers.py

示例4: _setup

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def _setup():
    global reconnect_handler, session_manager, session_list, path, kernel_id, kernel_manager,\
     individual_kernel_manager, response_id, good_msg, client, spark_events, request

    # Mock kernel manager
    client = MagicMock()
    client.execute = MagicMock(return_value=response_id)
    client.get_shell_msg = MagicMock(return_value=good_msg)
    individual_kernel_manager = MagicMock()
    individual_kernel_manager.client = MagicMock(return_value=client)
    kernel_manager = MagicMock()
    kernel_manager.get_kernel = MagicMock(return_value=individual_kernel_manager)

    # Mock session manager
    session_list = [create_session_dict(path, kernel_id)]
    session_manager = MagicMock()
    session_manager.list_sessions = MagicMock(return_value=session_list)

    # Mock spark events
    spark_events = MagicMock()

    # Mock request 
    request = MagicMock()
    request.body = json.dumps({"path": path, "username": username, "password": password, "endpoint": endpoint})

    # Create mocked reconnect_handler        
    ReconnectHandler.__bases__ = (SimpleObject,)
    reconnect_handler = ReconnectHandler()
    reconnect_handler.spark_events = spark_events
    reconnect_handler.session_manager = session_manager
    reconnect_handler.kernel_manager = kernel_manager
    reconnect_handler.set_status = MagicMock()
    reconnect_handler.finish = MagicMock()
    reconnect_handler.current_user = 'alex'
    reconnect_handler.request = request
开发者ID:jupyter-incubator,项目名称:sparkmagic,代码行数:37,代码来源:test_handlers.py

示例5: test_get_one_number

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def test_get_one_number(self, get_numbers,
                                  HTTPCallbackGroup,
                                  get_associated_privates):
        self.handler.get_and_check_user_id = MagicMock(return_value=USER_ID)
        get_numbers.return_value = [{"number": SIP_URI, "number_id": NUMBER_ID, "gab_listed": GAB_LISTED}]
        HTTPCallbackGroup.return_value = MagicMock()

        self.handler.get("foobar")
        # Assert that we kick off asynchronous GET at homestead
        self.handler.get_and_check_user_id.assert_called_once_with("foobar")
        HTTPCallbackGroup.assert_called_once_with(ANY, # functools.partial object
                                                  self.handler._on_get_failure)

        get_associated_privates.assert_called_once_with(SIP_URI,
                                                        ANY # function
                                                        # argument
                                                        )
        # Simulate success of all requests.
        response = MagicMock()
        response.body = '{"private_ids": ["[email protected]"]}'
        self.handler._on_get_success(SIP_URI, [response])

        self.handler.finish.assert_called_once_with(
            {
                "numbers": [
                     {"number_id": NUMBER_ID_HEX,
                      "number": "5555550123",
                      "sip_username": "5555550123",
                      "domain": REALM,
                      "gab_listed": GAB_LISTED,
                      "formatted_number": "(555) 555-0123",
                      "sip_uri": SIP_URI,
                      "private_id": "[email protected]", }
                 ]
            })
开发者ID:rkday,项目名称:ellis,代码行数:37,代码来源:numbers.py

示例6: test_ping_fail

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
 def test_ping_fail(self, settings, AsyncHTTPClient):
     self.standard_setup(settings, AsyncHTTPClient)
     homestead.ping()
     self.mock_httpclient.fetch.assert_called_once_with("http://homestead/ping", ANY)
     mock_response = MagicMock()
     mock_response.body = "Failure"
     self.mock_httpclient.fetch.call_args[0][1](mock_response)
开发者ID:ClearwaterCore,项目名称:ellis,代码行数:9,代码来源:homestead.py

示例7: test__validate_body_empty_body

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test__validate_body_empty_body():
    request = MagicMock()
    request.body = ''
    with pytest.raises(exceptions.HTTPError) as exc:
        _validate_body(request)
    assert exc.value.status_code == 400
    assert exc.value.errors == 'Body is empty string'
开发者ID:openpermissions,项目名称:repository-srv,代码行数:9,代码来源:test_assets_handler.py

示例8: TestCommandParsing

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
 def TestCommandParsing(self):
     request = MagicMock()
     request.path = "/test"
     request.query = "item1=value1"
     request.remote_ip = "1.2.3.4"
     request.method = "PUT"
     request.headers = {
         'User': 'test_user',
         'Creation-Time': 'test_time',
         'User-Agent': 'test_user_agent'
     }
     request.body="item2=value2&item2=value3&item2=value4"
     self.command = Command(request)
     self.assertEqual(self.command.command_name, 'test')
     self.assertEqual(self.command.command_type, 'PUT')
     self.assertEqual(self.command.has_param('item1'), True)
     self.assertEqual(self.command.has_param('item2'), True)
     self.assertEqual(self.command.has_param('item3'), False)
     self.assertEqual(self.command.get_param('item1'), 'value1')
     self.assertEqual('value2' in self.command.get_param('item2'), True)
     self.assertEqual('value3' in self.command.get_param('item2'), True)
     self.assertEqual('value4' in self.command.get_param('item2'), True)
     data = self.command.format_trace
     self.assertEqual(data['Username'], 'test_user')
     self.assertEqual(data['Created'], 'test_time')
     self.assertEqual(data['Source_Address'], '1.2.3.4')
     self.assertEqual(data['Source_ID'], 'test_user_agent')
开发者ID:percival-detector,项目名称:percivalui,代码行数:29,代码来源:test_command.py

示例9: test__validate_body_no_body

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test__validate_body_no_body():
    request = MagicMock()
    request.body = None
    with pytest.raises(exceptions.HTTPError) as exc:
        _validate_body(request)
    assert exc.value.status_code == 400
    assert exc.value.errors == 'No Data in Body'
开发者ID:openpermissions,项目名称:repository-srv,代码行数:9,代码来源:test_assets_handler.py

示例10: testHandleBatchSingle

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def testHandleBatchSingle(self, mockEngine, addMetricMock):
        # Create mocks
        metric_storer.gCustomMetrics = {}
        metricMock = MagicMock()

        def addMetricSideEffect(*_args, **_kwargs):
            metric_storer.gCustomMetrics["test.metric"] = [metricMock, datetime.datetime.utcnow()]

        addMetricMock.side_effect = addMetricSideEffect
        modelSwapperMock = MagicMock()
        metricStreamerMock = MagicMock()
        body = '{"protocol": "plain", "data": ["test.metric 4.0 1386792175"]}'
        message = MagicMock()
        message.body = body
        # Call the function under test
        metric_storer._handleBatch(mockEngine, [message], [], metricStreamerMock, modelSwapperMock)
        # Check the results
        addMetricMock.assert_called_once_with(mockEngine, "test.metric")
        metricStreamerMock.streamMetricData.assert_called_once()
        data, _uid, modelSwapper = metricStreamerMock.streamMetricData.call_args[0]
        self.assertIs(modelSwapper, modelSwapperMock)
        self.assertEqual(len(data), 1)
        self.assertEqual(len(data[0]), 2)
        self.assertEqual(repr(data[0][0]), "datetime.datetime(2013, 12, 11, 20, 2, 55)")
        self.assertAlmostEqual(data[0][1], 4.0)
开发者ID:sergius,项目名称:numenta-apps,代码行数:27,代码来源:metric_storer_test.py

示例11: test_ping_http

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
 def test_ping_http(self, settings, AsyncHTTPClient):
     self.standard_setup(settings, AsyncHTTPClient)
     mock_response = MagicMock()
     mock_response.body = "OK"
     self.mock_httpclient.fetch.return_value = mock_response
     homestead.ping()
     self.mock_httpclient.fetch.assert_called_once_with("http://homestead/ping", ANY)
开发者ID:biddyweb,项目名称:ellis,代码行数:9,代码来源:homestead.py

示例12: get_two_numbers

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
    def get_two_numbers(self, shared_private_id, get_numbers,
                                                 HTTPCallbackGroup,
                                                 get_associated_privates):
        self.handler.get_and_check_user_id = MagicMock(return_value=USER_ID)
        get_numbers.return_value = [{"number": "sip:[email protected]", "number_id": NUMBER_ID, "gab_listed": 0},
                                    {"number": "sip:[email protected]", "number_id": NUMBER_ID2, "gab_listed": 1}]
        HTTPCallbackGroup.return_value = MagicMock()

        self.handler.get("foobar")

        # Simulate success of all requests.
        response1 = MagicMock()
        response1.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
        response2 = MagicMock()
        if shared_private_id:
            response2.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
        else:
            response2.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
        self.handler._on_get_success("sip:[email protected]", [response1])
        self.handler._on_get_success("sip:[email protected]", [response2])

        self.handler.finish.assert_called_once_with(
                {
                    "numbers": [
                        {
                            "number_id": NUMBER_ID_HEX,
                            "number": "4155551234",
                            "sip_username": "4155551234",
                            "domain": "sip.com",
                            "gab_listed": 0,
                            "formatted_number": "(415) 555-1234",
                            "sip_uri": "sip:[email protected]",
                            "private_id": "[email protected]",
                        },
                        {
                            "number_id": NUMBER_ID2_HEX,
                            "number": "4155555678",
                            "sip_username": "4155555678",
                            "domain": "sip.com",
                            "gab_listed": 1,
                            "formatted_number": "(415) 555-5678",
                            "sip_uri": "sip:[email protected]",
                            "private_id": (shared_private_id and "[email protected]" or "[email protected]"),
                        }
                    ]
                })
开发者ID:rkday,项目名称:ellis,代码行数:48,代码来源:numbers.py

示例13: testHandleDataInvalidProtocol

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
 def testHandleDataInvalidProtocol(self, mockEngine, loggingMock):
     """Ensure _handleData doesn't throw an exception for unknown protocol."""
     # Call the function under test
     body = '{"protocol": "unknown_protocol",' ' "data": ["test.metric 4.0 1386792175"]}'
     message = MagicMock()
     message.body = body
     metric_storer._handleBatch(mockEngine, [message], [], MagicMock(), MagicMock())
     # Check the results
     self.assertTrue(loggingMock.warn.called)
开发者ID:sergius,项目名称:numenta-apps,代码行数:11,代码来源:metric_storer_test.py

示例14: test_process_data

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
 def test_process_data(self):
     """
     CoinbaseProvider.process_data() returns a correct HTTP response
     """
     request = MagicMock()
     request.body = json.dumps(COINBASE_REQUEST)
     response = self.provider.process_data(self.payment, request)
     self.assertEqual(type(response), HttpResponse)
     self.assertEqual(self.payment.status, "confirmed")
开发者ID:u2rafi,项目名称:django-payments,代码行数:11,代码来源:test_coinbase.py

示例15: phonable_task

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def phonable_task(func, url):
    number = '+12103004000' if url.endswith('abc') else '+13103004000'
    reply = MagicMock()
    reply.code = 200
    reply.body = json.dumps({"number": number})

    task = MagicMock(spec=YieldPoint)
    task.get_result.return_value = reply
    return task
开发者ID:ojengwa,项目名称:phonio,代码行数:11,代码来源:rooming_test.py


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