很抱歉,标题需要一些时间才能理解。所以这是文件夹结构:
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框架,并在测试部分遇到错误。
========== UPDATE =========
pytest
找不到模块的原因是因为sys.path
没有../falcon_tut/falcon_tut
。
当我运行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...