【问题标题】:pytest cannot find pip modulepytest 找不到 pip 模块
【发布时间】:2020-05-24 07:00:20
【问题描述】:

我的项目结构是这样的

\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 文件夹中,但没有帮助。

有什么问题?

【问题讨论】:

  • 你是在虚拟环境中安装starlette还是到你的主要python解释器?
  • @KrishnanShankar 是的,我已经全部安装并能够单独运行它——就像执行app.py 文件一样。但在测试中它失败了

标签: python pytest


【解决方案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 中安装的内容。

【讨论】:

  • 成功了!虽然我还必须安装 requests 模块。那么 pytest 是从顶级包中执行测试文件吗? (来自与 app.py 相同的文件夹)
猜你喜欢
  • 2020-04-29
  • 2020-09-28
  • 1970-01-01
  • 2022-01-05
  • 2015-05-27
  • 2019-02-12
  • 2022-08-17
  • 2020-01-26
  • 2020-07-11
相关资源
最近更新 更多