【问题标题】:py.test can't import my modulepy.test 无法导入我的模块
【发布时间】:2015-12-05 01:06:03
【问题描述】:

我正在努力获得正确的 python 导入。我想要实现的是拥有一个包含多个源文件的模块和一个包含单元测试的测试文件夹。

无论我做什么,我都无法让 py.test-3 执行我的测试。我的目录布局如下:

.
├── module
│   ├── __init__.py
│   └── testclass.py
└── tests
    └── test_testclass.py

__init__.py 文件如下所示:

__all__ = ['testclass']

testclass.py 文件如下所示:

class TestClass(object):

    def __init__(self):
        self.id = 1

我的单元测试是这样的:

import pytest
from module import TestClass

def test_test_class():
    tc = TestClass()
    assert(tc.id==1)

无论我如何调用 py.test-3,我最终都会得到:

E   ImportError: No module named 'module'

【问题讨论】:

    标签: python unit-testing python-3.x pytest


    【解决方案1】:

    首先,除非您更改tests/test_testclass.py,否则您需要更改module/__init__.py,如下所示:

    from .testclass import TestClass
    
    __all__ = ['TestClass']
    

    并且,当您运行 py.test 时,设置PYTHONPATH 环境变量让解释器知道何时找到模块:

    PYTHONPATH=. py.test
    

    【讨论】:

    • 这对我有用!这会是pythonic的方式吗?仍在为图书馆布局应该如何看起来最好而苦苦挣扎。
    • @Fabian,我想是的。它至少不需要您更改测试代码。
    • 哇,我刚看到你的视频。感谢您的努力!你的奉献精神是惊人的。
    【解决方案2】:

    我会将 pytest 的路径执行放入 testfile 的标题中:

    示例:

    import os, sys                                                                  
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
    

    这样我就可以知道我的(测试)项目中任何子文件夹的路径

    【讨论】:

    • 我不是这个解决方案的真正粉丝,因为我必须在任何违反 DRY 原则的测试文件中重复它。
    • 这可以放在tests/文件夹的“_init_.py”中,整个目录都不需要重复。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多