Skynet
Skynet

Reputation: 84

Attempting to run pytest and tox raises ModuleNotFoundError

I'm having issues testing my package with pytest and tox. When attempting to run both I receive ModuleNotFoundError. Pytest does find test_hello.py but fails immediate on trying to import my package for the test.

I am using PyCharm IDE which automatically sets up a pipenv environment for my project. I am using the terminal shell (Powershell instance) within PyCharm to run pytest / tox / pip commands.

I've tried running pytest with and without pip installing my package first: pip install -e . Both yields the same ModuleNotFoundError result.

Traceback

ImportError while importing test module 'C:\Users\USERNAME\Workspace\hello2\tests\test_hello.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\appdata\local\programs\python\python39\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_hello.py:2: in <module>
    from hello import Hello
E   ModuleNotFoundError: No module named 'hello'

Package Structure

root/
  +--- src/
  |     +--- hello/
  |            +--- __init__.py
  |            +--- hello.py
  |
  +--- tests/
  |      +--- test_hello.py
  |
  +--- setup.py
  +--- tox.ini

init.py

from .hello import Hello  # noqa    

tox.ini

[tox]
envlist = py39
skipsdist = True

[testenv]
deps =
  flake8
  pytest
  pytest-cov
  safety
commands =
  pip install -e .
  safety check --full-report
  flake8 --max-line-length=120 --statistics setup.py src/ tests/
  pytest -p no:warnings --cov=src --cov-fail-under=80 --cov-report=term --cov-report=xml -- 
  junit-xml report.xml

test_hello.py

import os
from hello import Hello

running_in_ci = os.environ.get('CI_JOB_ID') is not None
test_name = 'Bob'


def test_hello():
    """Check if search returns expected results."""
    cli = Hello(name=test_name)
    assert cli.say_hello() is None
    assert cli.say_hello(by_name=True) is None

Upvotes: 3

Views: 1789

Answers (1)

J&#252;rgen Gmach
J&#252;rgen Gmach

Reputation: 6121

You don't show us your setup.py, but as you use a src directory structure, you most likely miss the following arguments when calling setup:

    packages=find_packages(where="src"),
    package_dir={"": "src"},

i.e a minimal working setup.py would look like...

from setuptools import setup, find_packages

setup(
    name='MyPackageName',
    version='1.0.0',
    url='https://github.com/mypackage.git',
    author='Author Name',
    author_email='[email protected]',
    description='Description of my package',
    packages=find_packages(where="src"),
    package_dir={"": "src"},
)

Upvotes: 4

Related Questions