我找到了有关如何向用 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/