shlomiLan
shlomiLan

Reputation: 716

Import error while running py.test

When I tried to run pytest I get an error, this is my project structure:

slots_tracker/
    README.md
    development.txt
    requirements.txt
    tasks.py
    venv/
    slots_tracker/
        __init__.py
        conf.py
        db.py
        expense.py
        server.py
        swagger.yml
        test_api.py

This is my test file:

from expense import create
from conf import PayMethods


def test_create_new_expense():
    response = create(dict(amount=200, desc='Random stuff',
                           pay_method=PayMethods.Visa.value))
# We got a success code
assert response[1] == 201

when I run pytest with:

pytest

I get this error:

ModuleNotFoundError: No module named 'expense'

If I run pytest with:

python -m pytest

I don't get any error, also I can run my app with and don't get any import error:

python server.py

I also noties that if I remove the __init__.py file I can run pytest with only:

pytest

any iade on I can fix this? removing the __init__.py doesn't look like the 'right' solution becuase I'm building a package so it should have an __init__.py file.

I'm running on a Mac with Python 3.6.5 in a virtual env.

Upvotes: 2

Views: 1143

Answers (1)

kchomski
kchomski

Reputation: 3010

Use absolute imports in your code and tests.

Change this:

from expense import create
from conf import PayMethods

to:

from slots_tracker.expense import create
from slots_tracker.conf import PayMethods

I've just tested it and it works.

Upvotes: 2

Related Questions