当测试文件中导入的模块导入导入模块同一目录中的另一个模块时,pytest返回ModuleNotFoundError

2024-02-08

如果标题需要一些时间才能理解,我很抱歉。这是文件夹结构:

falcon_tut/
    falcon_tut/
        app.py
        images.py
        __init__.py
    tests/
        test_app.py
        __init__.py

以及一些代码

####################
# app.py
####################



from images import Resource

images = Resource()

api = application = falcon.API()
api.add_route('/images', images)

# ... few more codes


####################
# test_app.py
####################



import falcon
from falcon import testing
import ujson
import pytest

from falcon_tut.app import api

@pytest.fixture
def client():
    return testing.TestClient(api)


def test_list_images(client):
    doc = {
        'images': [
            {
                'href': '/images/1eaf6ef1-7f2d-4ecc-a8d5-6e8adba7cc0e.png'
            }
        ]
    }

response = client.simulate_get('/images')
result_doc = ujson.loads(response.content)

assert result_doc == doc
assert response.status == falcon.HTTP_OK

运行时效果很好python falcon_tut/app.py并以响应卷曲它200和图像的有效负载

直到运行pytest tests/ 从项目根目录它输出这个:

ImportError while importing test module ../falcon_tut/tests/test_app.py
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_app.py:6: in <module>
    from falcon_tut.app import api
E   ModuleNotFoundError: No module named 'falcon_tut'

我尝试创建__init__.py在项目根目录,但它仍然输出上面相同的错误

Python 版本 3.7.0,带有 falcon 1.4.1、cpython 0.28.5、pytest 3.7.3,我没有使用 Gunicorn,而是使用 bjoern 2.2.2

我正在尝试 python falcon 框架并在测试部分遇到错误。

=========更新===========

之所以pytest找不到模块是因为sys.path不具有../falcon_tut/falcon_tut exists.

当我跑的时候pytest编辑这两个文件并打印出来sys.path,它只有[../falcon_tut/tests, ../falcon_tut, ..]。解决方法是将包的路径附加到sys.path。所以这是编辑后的app.py

#############
# app.py
#############

import sys

# this line is just example, please rewrite this properly if you wants to use this workaround
# sys_path[1] only applied to my situation, again this is just example to know that it works
# the idea is to make sure the path to your module exists in sys.path
# in this case, I appended ../falcon_tut/falcon_tut to sys.path
# so that now ../falcon_tut/falcon_tut/images.py can be found by pytest
sys.path.insert(0, '{}/falcon_tut'.format(sys_path[1]))

# body codes...

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当测试文件中导入的模块导入导入模块同一目录中的另一个模块时,pytest返回ModuleNotFoundError 的相关文章

随机推荐