在 python 的 Azure 函数中测试两种方法

Testing two methods in an Azure function in python

我正在为我的 azure 函数编写测试,出于某种原因 - 我无法模拟函数调用。我还应该提一下,这是我第一次编写 python 测试用例,所以很好 :)

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
    except ValueError as error:
        logging.info(error)
    download_excel(req_body)
    return func.HttpResponse(
            "This HTTP triggered function executed successfully.",
            status_code=200
    )

这就是初始函数。此函数调用 download_excel 并传递请求正文。下一个函数接收请求主体,并将 excel 写入 blob 存储。

def download_excel(request_body: Any):
    excel_file = request_body["items_excel"]

    #initiate the blob storage client
    blob_service_client = BlobServiceClient.from_connection_string(os.environ["AzureWebJobsStorage"])
    container = blob_service_client.get_container_client(CONTAINER_NAME)
    blob_path = "excel-path/items.xlsx"
    blob_client = container.get_blob_client(blob_path)
    blob_client.upload_blob_from_url(excel_file)

这是两个函数。收到一个文件,将其保存到 blob 存储中,但我无法在主函数中模拟 download_excel 调用。我试过使用模拟、补丁,浏览了各种链接,但我就是找不到实现这一目标的方法。任何帮助,将不胜感激。这是我目前在测试文件中的内容。

class TestFunction(unittest.TestCase):
    #@patch('download_excel')
    def get_excel_files_main(self):
        """Test main function"""
        req = Mock()
        resp = main(req)
        # download_excel= MagicMock()
        self.assertEqual(resp.status_code, 200)

在函数和测试中注释掉函数调用使测试通过,但我需要知道如何模拟 download_excel 调用。我仍然会为 download_excel 函数编写一个测试用例,但是当我到达它时会穿过那座桥。

想通了。我很傻。主要问题出在 azure 函数中,我认为因为没有 class 我可以忽略文档中与 classes.

有关的每个示例

诀窍是将函数名称用作 class。假设您有函数名称 - http_trigger,以及该函数文件夹中的 init.py 文件。在那个 init 文件中——你有你的主要方法,以及从主要方法调用的第二个方法——你可以使用 MagicMock。

import function_name

def test_main_function(self):
    """Testing main function"""
    function_name.second_method_being_called = MagicMock()

就是这样。你就是这么嘲笑它的! *捂脸