在Flask App中模拟gRPC状态代码("RpcError"对象没有属性"code") [英] Mocking gRPC status code ('RpcError' object has no attribute 'code') in Flask App

查看:191
本文介绍了在Flask App中模拟gRPC状态代码("RpcError"对象没有属性"code")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个可以模拟特定grpc状态代码的单元测试(在我的情况下,我需要NOT_FOUND状态).

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

这是我要嘲笑的东西:

 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

首先,当我运行我的flask应用程序并请求具有特定正文的URL时,应该引发RpcError,一切正常.可以识别 e.code().另一方面,当我想运行该单元测试时,我得到 AttributeError:'RpcError'对象没有属性'code'.

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'.

有什么想法吗?

推荐答案

似乎无法像在 grpc RpcError 对象>代码(用C编写).但是,您可以使用以下方法来模拟行为:

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 code(self):
        return self._code

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

更新:
添加了丢失的 code 方法,如MartinGrůber在评论中所述.

Update:
Added missing code method as mentioned by Martin Grůber in the comments.

这篇关于在Flask App中模拟gRPC状态代码("RpcError"对象没有属性"code")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆