首页 > 解决方案 > 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-testsproject文件夹,但没有帮助。

问题是什么?

标签: pythonpytest

解决方案


尝试更改此导入:

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


推荐阅读