python - 如何测试使用 Context 的 Azure Function?

标签 python azure unit-testing azure-functions

我正在编写一个使用上下文(用于监视目的)的 Azure 函数,这就是我的函数的样子:

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    logging.info(
        "{}\t{}".format(
            context.invocation_id, context.function_name
        )
    )
    reponse = "foo"    
    return func.HttpResponse(json.dumps(reponse), mimetype="application/json")

我想为此函数编写集成测试,如下所示:

import unittest
import azure.functions as func
from MyFunc import main    

class TestMyFunc(unittest.TestCase):
    def test_myfunc(self):
        req = func.HttpRequest(
            method="GET",
            body=None,
            url="/api/myfunc",
        )
        ctx = ??
        reponse = main(req, ctx) # This part fails because of the context

        self.assertEqual(
            reponse.get_body(),
            b'foo',
        )

如何创建 Context对象传递给我的 Azure 函数?

最佳答案

看起来像Context is an ABC(Abstract Base Class) class ,所以不能直接实例化。相反,您可以 subclass the func.Context class并将该类的实例用作 ctx

class MockContext(func.Context):
    def __init__(self, ii, fn, fd):
        self._invocation_id = ii
        self._function_name = fn
        self._function_directory = fd

    @property
    def invocation_id(self):
        return self._invocation_id

    @property
    def function_name(self):
        return self._function_name

    @property
    def function_directory(self):
        return self._function_directory

ctx = MockContext("Some dummy values")

关于python - 如何测试使用 Context 的 Azure Function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69390154/

相关文章:

json - 实现 IoT PowerBI 表架构

angularjs - 使用 Angular 2 模拟组件

python - Alembic:IntegrityError:添加不可为空的列时出现 "column contains null values"

python - Django 自定义文件存储系统

python |避免从列表中随机选择先前的值

java - 自动(半)创建单元测试?

单元测试的图像比较算法

python - DelegatorBot 在 TelePot 中是如何工作的?

azure - 我应该如何验证 Azure CLI 以便在没有 SAS 的情况下进行访问?

sql - 如果存在重复项且重复项超过 30 天,则从 SQL 表中删除