lapots
lapots

Reputation: 13395

pytest cannot find pip module

I have the project structure that looks like this

\project
    \app.py
    \tests
        \__init__.py
        \test_startup.py

app.py looks like this

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 looks like this

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 is an empty file.

When I try to run pytest -v from my project directory it fails with the error

tests/test_startup.py:1: in <module>
    from starlette.testclient import TestClient
E   ModuleNotFoundError: No module named 'starlette'

I am able to run the application. Also I was trying to put conftest.py into both - tests and project folders and it did not help.

What is the problem?

Upvotes: 2

Views: 857

Answers (1)

Z4-tier
Z4-tier

Reputation: 7978

Try changing this import:

from ..app import app

to this:

from app import app

I ran your code exactly as posted, and got a E ValueError: attempted relative import beyond top-level package. Once the import was changed, pytest -v was successful:

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 $

If that doesn't work, probably do as @Krishnan Shankar suggests and take a look at what is installed in the venv.

Upvotes: 1

Related Questions