我的项目结构看起来像这样
\project
\app.py
\tests
\__init__.py
\test_startup.py
app.py
看起来像这样
from starlette.applications import Starlette
from starlette.responses import UJSONResponse
from starlette.routing import Route
async def homepage(request):
return UJSONResponse({'hello': 'world'})
app = Starlette(debug=True, routes=[
Route('/', homepage)
])
test_startup.py
看起来像这样
from starlette.testclient import TestClient
from ..app import app
def test_app():
client = TestClient(app)
response = client.get('/')
assert response.status_code == 200
__init__.py
是一个空文件。
当我尝试从项目目录运行pytest -v
时,它失败并显示错误
tests/test_startup.py:1: in <module>
from starlette.testclient import TestClient
E ModuleNotFoundError: No module named 'starlette'
我能够运行该应用程序。另外,我试图将conftest.py
放入-tests
和project
文件夹中,但这没有帮助。
出什么问题了?
答案 0 :(得分:1)
尝试更改此导入:
from ..app import app
对此:
from app import app
我完全按照您发布的代码运行,并得到了E ValueError: attempted relative import beyond top-level package
。更改导入后,pytest -v
成功:
darkstar:~/tmp/project $ cat app.py
from starlette.applications import Starlette
from starlette.responses import UJSONResponse
from starlette.routing import Route
async def homepage(request):
return UJSONResponse({'hello': 'world'})
app = Starlette(debug=True, routes=[
Route('/', homepage)
])
darkstar:~/tmp/project $ cat tests/__init__.py
darkstar:~/tmp/project $ cat tests/test_startup.py
from starlette.testclient import TestClient
from app import app
def test_app():
client = TestClient(app)
response = client.get('/')
assert response.status_code == 200
darkstar:~/tmp/project $ pytest -v
================================================================================= test session starts =================================================================================
platform darwin -- Python 3.7.7, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- /usr/local/opt/python/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/some_guy/tmp/project
collected 1 item
tests/test_startup.py::test_app PASSED [100%]
================================================================================== 1 passed in 0.16s ==================================================================================
darkstar:~/tmp/project $
如果这不起作用,请按照@Krishnan Shankar的建议进行操作,并看看venv中安装了什么。