【问题标题】:Attempting to run pytest and tox raises ModuleNotFoundError尝试运行 pytest 和 tox 引发 ModuleNotFoundError
【发布时间】:2021-11-09 01:38:42
【问题描述】:

我在使用 pytest 和 tox 测试我的包时遇到问题。尝试运行两者时,我收到ModuleNotFoundError。 Pytest 确实找到了 test_hello.py,但在尝试导入我的包进行测试时立即失败。

我正在使用 PyCharm IDE,它会自动为我的项目设置 pipenv 环境。我在 PyCharm 中使用终端 shell(Powershell 实例)来运行 pytest / tox / pip 命令。

我尝试过运行 pytest,有无 pip 先安装我的包:pip install -e . 两者都产生相同的 ModuleNotFoundError 结果。

追溯

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'

包结构

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

【问题讨论】:

    标签: python pycharm package pytest tox


    【解决方案1】:

    您没有向我们展示您的setup.py,但是当您使用src 目录结构时,您在调用setup 时很可能会遗漏以下参数:

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

    即最小的工作 setup.py 看起来像......

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

    【讨论】:

    • 我相信就是这样。还在 setup.py 中的分类器参数中添加了"Programming Language :: Python :: 3.9",它最初是错误的版本(3.7),可能已经破坏了一切。
    • 仅当您将包上传到 PyPI 时才会评估 Python 版本分类器。
    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 2013-11-07
    • 2019-04-17
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多