首页 > 解决方案 > 如何从 pytest 引用我的 Azure 函数?

问题描述

我将 Python 3.8 与 Azure 函数一起使用。我有以下项目布局......

myproject
    __app__
        __init__.py
        objects
            __init__.py
    tests
        __init__.py
        functions
            __init__.py
            objects
                __init__.py
                test_objects.py

我的应用程序/objects/ init .py 文件像这样开始......

import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    """."""
    ...

然后我的测试/函数/对象/ init .py 看起来像

import pytest
import azure.functions as func

_import = __import__('__app__/objects')

def test_objects():
    ...
    

但是,当我跑步时

pytest tests/functions/test_objects.py 

我得到错误

tests/functions/test_objects.py:8: in <module>
    _import = __import__('__app__/objects')
E   ModuleNotFoundError: No module named '__app__/objects'

引用我的函数的正确方法是什么?我也尝试了“对象”,但这会导致相同的 ModuleNotFoundError。

标签: python-3.ximportazure-functionspytestpython-import

解决方案


文档中我看到函数是直接导入的,即:

# tests/test_httptrigger.py
import unittest

import azure.functions as func
from __app__.HttpTrigger import my_function

也许您可以尝试像这样引用您的测试:

# tests/test_objects.py
import unittest

import azure.functions as func
from __app__.objects import main

+++ 更新 +++

现在我尝试自己做,偶然发现了一个类似的错误。经过一番谷歌搜索后,我还在github.com/Azure/azure-functions-python-worker找到了一个未解决的问题。

+++ 更新 2 +++

我设法通过向__init__.py测试文件夹添加一个空文件来使其运行。另一件要提的是,我已经适应了上述文档中的文件夹结构,并在根文件夹中运行了以下请求: pytest .

结果,测试成功执行。这是我创建的示例存储库: github.com/DSpirit/azure-functions-python-unit-testing


推荐阅读