如何在不安装包的情况下运行测试?

2024-04-23 07:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些Python包和一些测试。文件在http://pytest.org/latest/goodpractices.html#choosing-a-test-layout-import-rules之后分层

Putting tests into an extra directory outside your actual application code, useful if you have many functional tests or for other reasons want to keep tests separate from actual application code (often a good idea):

setup.py   # your distutils/setuptools Python package metadata
mypkg/
    __init__.py
    appmodule.py
tests/
        test_app.py

我的问题是,当我运行测试py.test时,我得到一个错误

ImportError: No module named 'mypkg'

我可以通过安装包python setup.py install来解决这个问题,但这意味着测试是针对安装的包而不是本地包运行的,这使得开发非常繁琐。每当我做了更改并想运行测试时,我需要重新安装,否则我将测试旧代码。

我能做什么?


Tags: 文件pyorgtesthttpyourapplicationpytest
3条回答

我知道这个问题已经结束了,但是我经常使用的一个简单方法是从根(包的父)通过python -m调用pytest

$ python -m pytest tests

这是因为-m选项将当前目录添加到python路径,因此mypkg被检测为本地包(而不是已安装的包)。

见: https://docs.pytest.org/en/latest/usage.html#calling-pytest-through-python-m-pytest

使用from .. import mypkg导入包。为此,您需要将(空的)__init__.py文件添加到tests目录和包含目录。py.test应该处理好其余的事情。

通常的开发方法是使用virtualenv并在virtualenv中使用pip install -e .(这几乎相当于python setup.py develop)。现在,您的源目录被用作sys.path上的已安装包。

当然,还有很多其他方法可以让您的包在sys.path上进行测试,请参见Ensuring py.test includes the application directory in sys.path以获得关于这个完全相同的问题的更完整的答案。

相关问题 更多 >