Python mox.IsA() Examples

The following are 30 code examples of mox.IsA(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mox , or try the search function .
Example #1
Source File: blob_image_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def expect_crop(self, left_x=None, right_x=None, top_y=None, bottom_y=None):
    """Setup a mox expectation to images_stub._Crop."""
    crop_xform = images_service_pb.Transform()
    if left_x is not None:
      if not isinstance(left_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_left_x(left_x)
    if right_x is not None:
      if not isinstance(right_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_right_x(right_x)
    if top_y is not None:
      if not isinstance(top_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_top_y(top_y)
    if bottom_y is not None:
      if not isinstance(bottom_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_bottom_y(bottom_y)
    self._images_stub._Crop(mox.IsA(Image.Image), crop_xform).AndReturn(
        self._image) 
Example #2
Source File: blob_image_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def expect_crop(self, left_x=None, right_x=None, top_y=None, bottom_y=None):
    """Setup a mox expectation to images_stub._Crop."""
    crop_xform = images_service_pb.Transform()
    if left_x is not None:
      if not isinstance(left_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_left_x(left_x)
    if right_x is not None:
      if not isinstance(right_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_right_x(right_x)
    if top_y is not None:
      if not isinstance(top_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_top_y(top_y)
    if bottom_y is not None:
      if not isinstance(bottom_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_bottom_y(bottom_y)
    self._images_stub._Crop(mox.IsA(MockImage), crop_xform).AndReturn(
        self._image) 
Example #3
Source File: module_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_add_while_started(self):
    servr = ManualScalingModuleFacade(instance_factory=self.factory)

    inst = self.mox.CreateMock(instance.Instance)
    self.mox.StubOutWithMock(module._THREAD_POOL, 'submit')
    self.mox.StubOutWithMock(wsgi_server.WsgiServer, 'start')
    self.mox.StubOutWithMock(wsgi_server.WsgiServer, 'port')
    wsgi_server.WsgiServer.port = 12345
    self.factory.new_instance(0, expect_ready_request=True).AndReturn(inst)
    wsgi_server.WsgiServer.start()
    module._THREAD_POOL.submit(servr._start_instance,
                               mox.IsA(wsgi_server.WsgiServer), inst)

    self.mox.ReplayAll()
    servr._add_instance()
    self.mox.VerifyAll()
    self.assertIn(inst, servr._instances)
    self.assertEqual((servr, inst), servr._port_registry.get(12345)) 
Example #4
Source File: discovery_service_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_generate_directory(self):
    body = json.dumps({'kind': 'discovery#directoryItem'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_directory(
        mox.IsA(list)).AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._LIST_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #5
Source File: discovery_service_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_generate_discovery_doc_rpc(self):
    body = json.dumps({'rpcUrl': 'https://tictactoe.appspot.com/_ah/api/rpc'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_discovery_doc(
        mox.IsA(object), 'rpc').AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._GET_RPC_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #6
Source File: discovery_service_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_generate_discovery_doc_rest(self):
    body = json.dumps(
        {'baseUrl': 'https://tictactoe.appspot.com/_ah/api/tictactoe/v1/'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_discovery_doc(
        mox.IsA(object), 'rest').AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._GET_REST_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #7
Source File: xmpp_request_handler_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_send(self):
    self.mox.StubOutWithMock(xmpp_request_handler.XmppRequestHandler,
                             'dispatcher')

    handler = xmpp_request_handler.XmppRequestHandler()
    handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)
    handler.dispatcher.add_request(
        method='POST',
        relative_url='url',
        headers=[('Content-Type',
                  mox.Regex('multipart/form-data; boundary=".*?"'))],
        body=mox.IsA(str),
        source_ip='0.1.0.10',
        fake_login=True)

    data = xmpp_request_handler._FormData()
    self.mox.ReplayAll()
    handler._send('url', data)
    self.mox.VerifyAll() 
Example #8
Source File: periodic_statistics_test.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def testCollectSample(self):
    obj_name = 'InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.'
    obj_param = 'TotalBytesSent'
    sampled_param = periodic_statistics.PeriodicStatistics.SampleSet.Parameter()
    sampled_param.Enable = True
    sampled_param.Reference = obj_name + obj_param
    sample_set = periodic_statistics.PeriodicStatistics.SampleSet()
    m = mox.Mox()
    mock_root = m.CreateMock(tr.core.Exporter)
    mock_root.GetExport(mox.IsA(str)).AndReturn(1000)
    m.ReplayAll()

    sample_set.SetCpeAndRoot(cpe=object(), root=mock_root)
    sample_set.SetParameter('1', sampled_param)
    sample_set.CollectSample()
    m.VerifyAll()

    # Check that the sampled_param updated it's values.
    self.assertEqual('1000', sampled_param.Values) 
Example #9
Source File: runner_test.py    From closure-linter with Apache License 2.0 6 votes vote down vote up
def testBadTokenization(self):
    mock_error_handler = self.mox.CreateMock(errorhandler.ErrorHandler)

    def ValidateError(err):
      return (isinstance(err, error.Error) and
              err.code is errors.FILE_IN_BLOCK and
              err.token.string == '}')

    mock_error_handler.HandleFile('foo.js', mox.IsA(tokens.Token))
    mock_error_handler.HandleError(mox.Func(ValidateError))
    mock_error_handler.HandleError(mox.IsA(error.Error))
    mock_error_handler.FinishFile()

    self.mox.ReplayAll()

    source = StringIO.StringIO(_BAD_TOKENIZATION_SCRIPT)
    runner.Run('foo.js', mock_error_handler, source)

    self.mox.VerifyAll() 
Example #10
Source File: test_e2e.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def expectSubscribe(self, phone=None, pledgePageSlug=None):
    if phone is None:
      phone = '212-234-5432'
    if pledgePageSlug is None:
      pledgePageSlug = '28e9-Team-Shant-is-Shant'
    self.mailing_list_subscriber \
        .Subscribe(email=self.pledge['email'],
                   first_name=u'Pik\u00E1',
                   last_name='Chu',
                   amount_cents=4200,
                   ip_addr=None,  # Not sure why this is None in unittests
                   time=mox.IsA(datetime.datetime),
                   phone=phone,
                   source='pledge',
                   nonce=mox.Regex('.*'),)
                   # pledgePageSlug=pledgePageSlug) 
Example #11
Source File: server_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_add_while_started(self):
    servr = ManualScalingServerFacade(instance_factory=self.factory)

    inst = self.mox.CreateMock(instance.Instance)
    self.mox.StubOutWithMock(server._THREAD_POOL, 'submit')
    self.mox.StubOutWithMock(wsgi_server.WsgiServer, 'start')
    self.mox.StubOutWithMock(wsgi_server.WsgiServer, 'port')
    wsgi_server.WsgiServer.port = 12345
    self.factory.new_instance(0, expect_ready_request=True).AndReturn(inst)
    wsgi_server.WsgiServer.start()
    server._THREAD_POOL.submit(servr._start_instance,
                               mox.IsA(wsgi_server.WsgiServer), inst)

    self.mox.ReplayAll()
    servr._add_instance()
    self.mox.VerifyAll()
    self.assertIn(inst, servr._instances)
    self.assertEqual((servr, inst), servr._port_registry.get(12345)) 
Example #12
Source File: handlers_test.py    From appengine-mapreduce with Apache License 2.0 6 votes vote down vote up
def testContextFlush(self):
    """Test context handling."""
    TestEntity().put()

    # Stub out context
    m = mox.Mox()
    m.StubOutWithMock(context.Context, "_set", use_mock_anything=True)
    m.StubOutWithMock(context.Context, "flush", use_mock_anything=True)

    # Record calls
    context.Context._set(mox.IsA(context.Context))
    context.Context.flush()
    context.Context._set(None)

    m.ReplayAll()
    try: # test, verify
      self.handler.post()

      #  1 entity should be processed
      self.assertEquals(1, len(TestHandler.processed_keys))

      m.VerifyAll()
    finally:
      m.UnsetStubs() 
Example #13
Source File: service_handlers_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testFirstMapper(self):
    """Make sure service attribute works when matches first RPCMapper."""
    self.rpc_mapper1.build_request(
        self.handler, Request1).AndReturn(self.request)

    def build_response(handler, response):
      output = '%s %s %s' % (response.integer_field,
                             response.string_field,
                             response.enum_field)
      handler.response.headers['content-type'] = (
        'application/x-www-form-urlencoded')
      handler.response.out.write(output)
    self.rpc_mapper1.build_response(
        self.handler, mox.IsA(Response1)).WithSideEffects(build_response)

    self.mox.ReplayAll()

    self.handler.handle('POST', '/my_service', 'method1')

    self.VerifyResponse('200', 'OK', '1 a VAL1')

    self.mox.VerifyAll() 
Example #14
Source File: discovery_service_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_generate_directory(self):
    body = json.dumps({'kind': 'discovery#directoryItem'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_directory(
        mox.IsA(list)).AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._LIST_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #15
Source File: test_datachecks.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def _test_deadline_exceeded(run_task_func, task_url):
    mox_obj = mox.Mox()
    mox_obj.StubOutWithMock(taskqueue, 'add')
    taskqueue.add(
        method='POST',
        url=task_url,
        params={'cursor': None},
        queue_name='datachecks',
        retry_options=mox.IsA(taskqueue.taskqueue.TaskRetryOptions),
        name=mox.IsA(unicode))
    mox_obj.ReplayAll()
    with mock.patch('utils.validate_email') as mock_validate_email:
        mock_validate_email.side_effect = deadline_exceeded_side_effect
        run_task_func()
    mox_obj.VerifyAll()
    mox_obj.UnsetStubs() 
Example #16
Source File: discovery_service_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_generate_discovery_doc_rest(self):
    body = json.dumps(
        {'baseUrl': 'https://tictactoe.appspot.com/_ah/api/tictactoe/v1/'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_discovery_doc(
        mox.IsA(object), 'rest').AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._GET_REST_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #17
Source File: xmpp_request_handler_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_send(self):
    self.mox.StubOutWithMock(xmpp_request_handler.XmppRequestHandler,
                             'dispatcher')

    handler = xmpp_request_handler.XmppRequestHandler()
    handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)
    handler.dispatcher.add_request(
        method='POST',
        relative_url='url',
        headers=[('Content-Type',
                  mox.Regex('multipart/form-data; boundary=".*?"'))],
        body=mox.IsA(str),
        source_ip='0.1.0.10',
        fake_login=True)

    data = xmpp_request_handler._FormData()
    self.mox.ReplayAll()
    handler._send('url', data)
    self.mox.VerifyAll() 
Example #18
Source File: mox_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def testMultipleTimesUsingIsAParameter(self):
    """Test if MultipleTimesGroup works with a IsA parameter."""
    mock_obj = self.mox.CreateMockAnything()
    mock_obj.Open()
    mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
    mock_obj.Close()
    self.mox.ReplayAll()

    mock_obj.Open()
    actual_one = mock_obj.Method("1")
    second_one = mock_obj.Method("2") # This tests MultipleTimes.
    mock_obj.Close()

    self.assertEquals(9, actual_one)
    self.assertEquals(9, second_one) # Repeated calls should return same number.

    self.mox.VerifyAll() 
Example #19
Source File: test_deletion.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def test_task_rescheduling(self):
        """Tests that task is rescheduled for continuation."""
        tq_mock = mox.Mox()
        tq_mock.StubOutWithMock(taskqueue, 'add')
        taskqueue.add(name=mox.IsA(unicode),
                      method='POST',
                      url='/haiti/tasks/process_expirations',
                      queue_name='expiry',
                      params={'cursor': ''})
        tq_mock.ReplayAll()
        # DeadlineExceededErrors can be raised at any time. A convenient way for
        # us to raise it during this test execution is with utils.get_utcnow.
        with mock.patch('utils.get_utcnow') as get_utcnow_mock:
            get_utcnow_mock.side_effect = runtime.DeadlineExceededError()
            self.run_task('/haiti/tasks/process_expirations', method='POST')
        tq_mock.VerifyAll()
        tq_mock.UnsetStubs() 
Example #20
Source File: discovery_service_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_generate_discovery_doc_rpc(self):
    body = json.dumps({'rpcUrl': 'https://tictactoe.appspot.com/_ah/api/rpc'})
    discovery = self.prepare_discovery_request(body)
    discovery._discovery_proxy.generate_discovery_doc(
        mox.IsA(object), 'rpc').AndReturn(body)

    self.mox.ReplayAll()
    response = discovery.handle_discovery_request(
        discovery_service.DiscoveryService._GET_RPC_API, self.api_request,
        self.start_response)
    self.mox.VerifyAll()

    self.assert_http_match(response, 200,
                           [('Content-Type', 'application/json; charset=UTF-8'),
                            ('Content-Length', '%d' % len(body))],
                           body) 
Example #21
Source File: service_handlers_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testResponseException(self):
    """Test what happens when build_response raises ResponseError."""
    self.rpc_mapper1.build_request(
        self.handler, Request1).AndReturn(self.request)

    self.rpc_mapper1.build_response(
        self.handler, mox.IsA(Response1)).AndRaise(
        service_handlers.ResponseError)

    self.ExpectRpcError(self.rpc_mapper1,
                        remote.RpcState.SERVER_ERROR,
                        'Internal Server Error')

    self.mox.ReplayAll()

    self.handler.handle('POST', '/my_service', 'method1')

    self.VerifyResponse('500', 'Internal Server Error', '')

    self.mox.VerifyAll() 
Example #22
Source File: handlers_test.py    From appengine-mapreduce with Apache License 2.0 5 votes vote down vote up
def testFailJobExceptionInHandler(self):
    """Test behavior when handler throws exception."""
    self.init(__name__ + ".test_handler_raise_fail_job_exception")
    TestEntity().put()

    # Stub out context._set
    m = mox.Mox()
    m.StubOutWithMock(context.Context, "_set", use_mock_anything=True)

    # Record calls
    context.Context._set(mox.IsA(context.Context))
    context.Context._set(None)

    m.ReplayAll()
    try: # test, verify
      self.handler.post()

      # slice should not be active
      shard_state = model.ShardState.get_by_shard_id(self.shard_id)
      self.verify_shard_state(
          shard_state,
          processed=1,
          active=False,
          result_status = model.ShardState.RESULT_FAILED)
      self.assertEquals(1, shard_state.counters_map.get(
          context.COUNTER_MAPPER_CALLS))

      # new task should not be spawned
      tasks = self.taskqueue.GetTasks("default")
      self.assertEquals(0, len(tasks))

      m.VerifyAll()
    finally:
      m.UnsetStubs() 
Example #23
Source File: test_tasks.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def ignore_call_to_send_delete_notice(self):
        """Replaces delete.send_delete_notice() with empty implementation."""
        self.mox.StubOutWithMock(delete, 'send_delete_notice')
        (delete.send_delete_notice(
                mox.IsA(tasks.CleanUpInTestMode), mox.IsA(model.Person)).
            MultipleTimes()) 
Example #24
Source File: blob_image_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def expect_resize(self, resize):
    """Setup a mox expectation to images_stub._Resize."""
    resize_xform = images_service_pb.Transform()
    resize_xform.set_width(resize)
    resize_xform.set_height(resize)
    self._images_stub._Resize(mox.IsA(MockImage),
                              resize_xform).AndReturn(self._image) 
Example #25
Source File: test_deletion.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def test_task_scheduling(self):
        tq_mock = mox.Mox()
        tq_mock.StubOutWithMock(taskqueue, 'add')
        taskqueue.add(name=mox.IsA(unicode),
                      method='POST',
                      url='/haiti/tasks/process_expirations',
                      queue_name='expiry',
                      params={'cursor': ''})
        tq_mock.ReplayAll()
        self.run_task('/global/tasks/process_expirations')
        tq_mock.VerifyAll()
        tq_mock.UnsetStubs() 
Example #26
Source File: service_handlers_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testRequestState_MissingHosts(self):
    """Make sure missing state environment values are handled gracefully."""
    class ServiceWithState(object):

      initialize_request_state = self.mox.CreateMockAnything()

      @remote.method(Request1, Response1)
      def method1(self, request):
        return Response1()

    self.service_factory = ServiceWithState
    self.remote_host = None
    self.server_host = None

    # Reset handler with new service type.
    self.ResetRequestHandler()

    self.rpc_mapper1.build_request(
        self.handler, Request1).AndReturn(Request1())

    def build_response(handler, response):
      handler.response.headers['Content-Type'] = (
        'application/x-www-form-urlencoded')
      handler.response.out.write('whatever')
    self.rpc_mapper1.build_response(
        self.handler, mox.IsA(Response1)).WithSideEffects(build_response)

    def verify_state(state):
      return (None is state.remote_host and
              '127.0.0.1' == state.remote_address and
              None is state.server_host and
              8080 == state.server_port)
    ServiceWithState.initialize_request_state(mox.Func(verify_state))

    self.mox.ReplayAll()

    self.handler.handle('POST', '/my_service', 'method1')

    self.VerifyResponse('200', 'OK', 'whatever')

    self.mox.VerifyAll() 
Example #27
Source File: blob_image_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def expect_encode_image(self, data,
                          mime_type=images_service_pb.OutputSettings.JPEG):
    """Setup a mox expectation to images_stub._EncodeImage."""
    output_settings = images_service_pb.OutputSettings()
    output_settings.set_mime_type(mime_type)
    self._images_stub._EncodeImage(mox.IsA(MockImage),
                                   output_settings).AndReturn(data) 
Example #28
Source File: handlers_test.py    From appengine-mapreduce with Apache License 2.0 5 votes vote down vote up
def testExceptionInHandler(self):
    """Test behavior when handler throws exception."""
    self.init(__name__ + ".test_handler_raise_exception")
    TestEntity().put()

    # Stub out context._set
    m = mox.Mox()
    m.StubOutWithMock(context.Context, "_set", use_mock_anything=True)

    # Record calls
    context.Context._set(mox.IsA(context.Context))
    context.Context._set(None)

    m.ReplayAll()
    try: # test, verify
      self.handler.post()
      self.assertEqual(httplib.SERVICE_UNAVAILABLE,
                       self.handler.response.status)

      # slice should be still active
      shard_state = model.ShardState.get_by_shard_id(self.shard_id)
      self.verify_shard_state(shard_state, processed=0, slice_retries=1)
      # mapper calls counter should not be incremented
      self.assertEquals(0, shard_state.counters_map.get(
          context.COUNTER_MAPPER_CALLS))

      # new task should not be spawned
      tasks = self.taskqueue.GetTasks("default")
      self.assertEquals(0, len(tasks))

      m.VerifyAll()
    finally:
      m.UnsetStubs() 
Example #29
Source File: service_handlers_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testContentFromHeaderOnly(self):
    """Test getting content-type from HTTP_CONTENT_TYPE directly.

    Some bad web server implementations might decide not to set CONTENT_TYPE for
    POST requests where there is an empty body.  In these cases, need to get
    content-type directly from webob environ key HTTP_CONTENT_TYPE.
    """
    request = Request1()
    request.integer_field = 1
    request.string_field = 'a'
    request.enum_field = Enum1.VAL1
    self.rpc_mapper1.build_request(self.handler,
                                   Request1).AndReturn(self.request)

    def build_response(handler, response):
      output = '%s %s %s' % (response.integer_field,
                             response.string_field,
                             response.enum_field)
      handler.response.headers['Content-Type'] = (
        'application/x-www-form-urlencoded')
      handler.response.out.write(output)
    self.rpc_mapper1.build_response(
        self.handler, mox.IsA(Response1)).WithSideEffects(build_response)

    self.mox.ReplayAll()

    self.handler.request.headers['Content-Type'] = None
    self.handler.request.environ['HTTP_CONTENT_TYPE'] = (
      'application/x-www-form-urlencoded')

    self.handler.handle('POST', '/my_service', 'method1')

    self.VerifyResponse('200', 'OK', '1 a VAL1',
                        'application/x-www-form-urlencoded')

    self.mox.VerifyAll() 
Example #30
Source File: service_handlers_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testContentTypeWithParameters(self):
    """Test that content types have parameters parsed out."""
    request = Request1()
    request.integer_field = 1
    request.string_field = 'a'
    request.enum_field = Enum1.VAL1
    self.rpc_mapper1.build_request(self.handler,
                                   Request1).AndReturn(self.request)

    def build_response(handler, response):
      output = '%s %s %s' % (response.integer_field,
                             response.string_field,
                             response.enum_field)
      handler.response.headers['content-type'] = (
        'application/x-www-form-urlencoded')
      handler.response.out.write(output)
    self.rpc_mapper1.build_response(
        self.handler, mox.IsA(Response1)).WithSideEffects(build_response)

    self.mox.ReplayAll()

    self.handler.request.headers['Content-Type'] = ('application/'
                                                    'x-www-form-urlencoded' +
                                                    '; a=b; c=d')

    self.handler.handle('POST', '/my_service', 'method1')

    self.VerifyResponse('200', 'OK', '1 a VAL1')

    self.mox.VerifyAll()