Mocking gRPC status code ('RpcError' object has no attribute 'code') in Flask App

北慕城南 提交于 2021-01-29 14:51:50

问题


I have to create a unittest that should mock a specific grpc status code (in my case I need NOT_FOUND status).

This is what i want to mock:

 try:
    # my mocked function
 except grpc.RpcError as e:
        if e.code() == grpc.StatusCode.NOT_FOUND:
            # do something

My unittest until now looks like this:

def mock_function_which_raise_RpcError():
    e = grpc.RpcError(grpc.StatusCode.NOT_FOUND)
    raise e


class MyTestCase(BaseViewTestCase):
   @property
   def base_url(self):
      return '/myurl'

   @mock.patch('my_func', mock_function_which_raise_RpcError)
   def test_service_config_with_grpc_status_error(self):
       # some code

       assert resp.status_code == 404

First thing first, when I run my flask app and make a request to a URL with a specific body which should raise that RpcError, everything works just fine. e.code() is recognized. On the other hand, when i want to run that unittest, I get AttributeError: 'RpcError' object has no attribute 'code'.

Any thoughts?


回答1:


Looks like you cannot construct a valid RpcError object from Python the same way it is created in the grpc code (which is written in C). You can, however, emulate the behavior by using:

def mock_function_which_raise_RpcError():
    e = grpc.RpcError()
    e.code = lambda: grpc.StatusCode.NOT_FOUND
    raise e

Alternatively, you can derive your own exception:

class MyRpcError(grpc.RpcError):
    def __init__(self, code):
        self.code = code

def mock_function_which_raise_RpcError():
    raise MyRpcError(grpc.StatusCode.NOT_FOUND)


来源:https://stackoverflow.com/questions/61726226/mocking-grpc-status-code-rpcerror-object-has-no-attribute-code-in-flask-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!