gpt4 book ai didi

python - pytest 找不到 pip 模块

转载 作者:行者123 更新时间:2023-12-04 16:45:49 25 4
gpt4 key购买 nike

我的项目结构看起来像这样

\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进入两者 - testsproject文件夹,它没有帮助。

问题是什么?

最佳答案

尝试更改此导入:

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 中安装的内容。

关于python - pytest 找不到 pip 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61979366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com