python - 如何模拟用 Python 编写的 Azure 函数中使用的对象

标签 python azure unit-testing dependency-injection azure-functions

我找到了有关如何向用 C# 编写的 Azure Functions 添加自定义绑定(bind)以及如何模拟它们的资源,但是,我无法在 Python 中找到解决方案。

描述我的用例:

我有一个http触发的函数,它创建一个到SQL数据库的连接,检索一些值并返回它们,即。一个简单的 GET。数据库连接包装在一个对象中,该对象提供执行 SELECT 查询的方法。

现在,该数据库是无服务器 Azure SQL 数据库。我想避免在手动测试或单元测试中实际查询它。我怎样才能做到这一点?有什么方法可以将模拟注入(inject)到Azure函数的主体中吗?

到目前为止我唯一能想到的是这样的:

def main(req: func.HttpRequest) -> func.HttpResponse:
    if req.headers.get("is-test", False):
        database = Database()
    else:
        database = MockDatabase()

    ...

这是我真正想避免的事情。

最佳答案

我认为我有一个对于单元测试非常有用的解决方案,但对于本地部署没有任何作用。

__init__py:

def main(req: func.HttpRequest) -> func.HttpResponse:
    wrapper = MyFunctionWrap(Database())
    return wrapper.exec(req)

myfunctionwrap.py:

class MyFunctionWrap:

    def __init__(self, dependency: Dependency):
        self._dependency = dependency

    def exec(self, req: func.HttpRequest) -> func.HttpResponse:
        ...

test_myfunction.py:

class TestFunction(unittest.TestCase):

    def test_my_function(self):
        req = func.HttpRequest(...)

        database = MockDatabase()
        wrapper = MyFunctionWrap(database)
        resp = wrapper.exec(req)

        ...

关于python - 如何模拟用 Python 编写的 Azure 函数中使用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62541200/

相关文章:

Azure AKS 群集管理员访问权限

asp.net-mvc-4 - 如何在我的 Azure 应用服务防火墙中允许 IP 地址

eclipse - 如何对 Eclipse 命令处理程序进行单元测试?

database - 何时模拟数据库访问

python - 如何使用 Python 的 svgwrite 模块应用 alpha 掩码?

python - 如何使用 python3 将更改模式 json 插入 mysql 中?

javascript - Selenium (Python): How to insert value on a hidden input?

git错误: fatal: unable to access 'https://dev.azure.com/****/' : Recv failure: Connection was reset while cloning

java - 不满意的链接器错误 : library file not found

python - 无论如何,排除 H2O 中的截距(python 和 R)都会产生非零截距系数