如何测试使用上下文的Azure函数?



我正在编写一个使用上下文的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',
)

我如何创建一个上下文对象传递给我的Azure函数?

看起来Context是一个ABC(抽象基类)类,所以你不能直接实例化。相反,您可以创建func.Context类的子类,并使用该类的实例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")

相关内容

最新更新