Skip to main content
 首页 » 编程设计

python之使用单独的测试文件运行 pytest

2025年05月04日9jirigala

我有 the pytest good integration practices guide 推荐的目录结构,看起来像这样:

. 
src/ 
    mypkg/ 
          __init__.py 
          mypkg.py 
tests/ 
      __init__.py 
      test_mypkg.py 

__init__.py文件都是空的,其他文件如下:

mypkg.py

def foo(x): 
    """ 
    Show x. 
    >>> foo(5) 
    x is 5 
    >>> foo("hello") 
    x is hello 
    """ 
    return "x is {0}".format(x) 

测试.py

from mypkg import * 
def test_foo(): 
    assert foo(5) == "x is 5" 

当我从根目录运行 pytest 时,我得到:

tests\test_foo.py:1: in <module> 
    from mypkg import * 
E   ModuleNotFoundError: No module named 'mypkg' 

推荐的设置方式是什么?

请您参考如下方法:

我不是 pytest 专家,但这看起来像是 conftest.py 的任务,conftest 允许从模块/包/共享装置等加载测试......

参见 this page了解更多信息。