You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构造Azure Function Context对象对使用Context的函数进行测试

解决方案

你可以通过两种方式构造测试用的Context对象:

方法1:使用Mock对象(推荐,适配绝大多数测试场景)

直接用unittest.mock.Mock构造对象,仅赋值你业务代码中用到的属性即可,无需完整实现Context的所有接口。
修改后的测试代码如下:

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

class TestMyFunc(unittest.TestCase):
    def test_myfunc(self):
        req = func.HttpRequest(
            method="GET",
            body=None,
            url="/api/myfunc",
        )
        # 构造测试用Context
        ctx = Mock()
        ctx.invocation_id = "test-invocation-001"
        ctx.function_name = "MyFunc"
        
        response = main(req, ctx)
        # 注意:json.dumps("foo")会生成带双引号的字符串,因此对比值需要带引号
        self.assertEqual(
            response.get_body(),
            b'"foo"',
        )

方法2:自定义Context子类

如果你需要更贴合运行时的Context行为,可以自行实现继承自func.Context的测试类:

import azure.functions as func

class TestContext(func.Context):
    def __init__(self, invocation_id: str, function_name: str):
        self._invocation_id = invocation_id
        self._function_name = function_name
    
    @property
    def invocation_id(self) -> str:
        return self._invocation_id
    
    @property
    def function_name(self) -> str:
        return self._function_name

# 测试时直接实例化即可
ctx = TestContext(invocation_id="test-invocation-001", function_name="MyFunc")

如果你的业务代码用到了Context的其他属性(比如trace_context、retry_context等),在Mock对象或者自定义类中补充对应属性即可。

内容的提问来源于stack exchange,提问作者Be Chiller Too

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:54:03