pytest找不到模块

Sar*_*ica 3 python pytest python-3.x

我正在遵循pytest的良好做法,或者至少我认为我是.但是,pytest无法找到我的模块.似乎不包括当前目录PYTHONPATH.

源文件:

def add(x, y):
    return x + y
Run Code Online (Sandbox Code Playgroud)

测试文件:

import pytest
from junk.ook import add


def test_add_true():
    assert add(1, 1) == 2
Run Code Online (Sandbox Code Playgroud)

而shell输出的Python 3虚拟环境称为"p3".

p3; pwd          
/home/usr/tmp/junk
p3; ls           
total 0
0 junk/  0 tests/
p3; ls junk      
total 4.0K
4.0K ook.py     0 __init__.py
p3; ls tests 
total 4.0K
4.0K test_ook.py     0 __pycache__/
p3; pytest
============================= test session starts ==============================
platform linux -- Python 3.4.5, pytest-3.4.1, py-1.5.2, pluggy-0.6.0
rootdir: /home/usr/tmp/junk, inifile:
collected 0 items / 1 errors                                                   

==================================== ERRORS ====================================
______________________ ERROR collecting tests/test_ook.py ______________________
ImportError while importing test module '/home/usr/tmp/junk/tests/test_ook.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_ook.py:2: in <module>
    from junk.ook import add
E   ImportError: No module named 'junk'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.08 seconds ============================

    def test_add_true():
        assert add(1, 1) == 2
Run Code Online (Sandbox Code Playgroud)

但是,运行以下操作确实可以正常工作.

p3; python -m pytest tests/
============================= test session starts ==============================
platform linux -- Python 3.4.5, pytest-3.4.1, py-1.5.2, pluggy-0.6.0
rootdir: /home/usr/tmp/junk, inifile:
collected 1 item                                                               

tests/test_ook.py .                                                      [100%]

=========================== 1 passed in 0.02 seconds ===========================
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

DBe*_*nko 17

只需添加__init__.pytests目录中,并递归地添加到其中包含测试文件的所有目录中。

  • 我很担心为什么 `pytest` 不工作而 `python -m pytest` 工作。谢谢。 (5认同)
  • 如果测试已安装的版本对您很重要,那么这只是一个问题。如果你没有对包装做任何奇怪的事情,那么大多数时候都不会产生什么影响。 (2认同)
  • python -m 为您执行导入,然后将文件作为脚本运行,因此它可以解析相对导入 (2认同)

hoe*_*ing 11

只需conftest.py在项目根目录中放入一个空文件:

$ pwd
/home/usr/tmp/junk
$ touch conftest.py
Run Code Online (Sandbox Code Playgroud)

您的项目结构应该成为:

junk
??? conftest.py
??? junk
?   ??? __init__.py
?   ??? ook.py
??? tests
    ??? test_ook.py
Run Code Online (Sandbox Code Playgroud)

这里发生了什么:当pytest发现a时conftest.py,它会修改,sys.path以便它可以从conftest模块导入内容.所以,由于现在conftest.py在rootdir中找到一个空,pytest将被强制附加到sys.path.这样做的副作用是您的junk模块可导入.

  • 不用担心!顺便说一下,检查链接问题中的答案,以可编辑模式安装包的建议可能是比滥用“pytest”测试发现机制更可行的解决方案。 (3认同)
  • 我已经尝试过这个解决方案,但它似乎不再起作用...Python 3.7,pytest 版本 6.2.1。但是,运行“python3.7 -m pytest”而不仅仅是“pytest”可以工作 (3认同)
  • 谢谢!添加 `conftest.py` 适用于 pytest 6.2.4。 (2认同)