python - pytest 找不到 pip 模块
问题描述
我的项目结构看起来像这样
\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
文件夹,但没有帮助。
问题是什么?
解决方案
尝试更改此导入:
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 中安装的内容。
推荐阅读
- arrays - C中的指针数组如何使用运算符[]
- c# - 如何在不使用 Kibana 的情况下直接从 elasticsearch 读取日志
- node.js - 面对此错误“ValidationException:参数无法转换为数值:NaN”
- python - 如何在 Python 中将一个列表中的整数添加到另一个列表中
- python - Django - 如果存在则更新数据库项,如果不存在则插入
- vba - 如何将 3 个 VBA 子程序合二为一?
- jquery - 如何在 URL 路径的开头插入文本/路径
- python - 长类型的较短类型提示
- power-automate - 避免不必要的应用到每个
- r - 如何概括一个函数,以便在不更改参数的情况下传递任何数据集?