Skip to main content
 首页 » 编程设计

python之金字塔在主包之外运行测试

2025年05月04日9shihaiming

我是 python 的新手,所以我认为这更像是我缺少的理解,因为它不起作用。

我首先创建了一个新的 Pyramid 项目,因此我的目录结构如下所示:

MyProject / 
    - myproject / 
        - static 
        - templates 
        - tests.py 
        - views.py 
    - development.ini 
    - production.ini 
    - setup.py 
    - setup.cfg 

然而,我将大量业务/服务逻辑添加到根包目录下的 myprojectlib 包中,并且还创建了一个测试包,如下所示:

MyProject / 
    - myproject / 
        - tests.py 
        - views.py 
    - myprojectlib / 
        - user_service.py 
    - tests / 
        - user_tests.py 
    - setup.py 

我已将 init.py 文件添加到“myprojectlib”和“tests”文件夹中以将它们打包,但我似乎无法获取 user_tests.py 文件(以及后续测试代码)包含在 python setup.py test 命令中。仅包含 myproject/tests.py 测试。

到目前为止,我的 user_tests.py 文件包含一个测试:

import unittest 
 
class UserTests(unittest.TestCase): 
 
    def test_user_can_register(self): 
 
        #code removed for example 
 

我如何告诉 python 也在/tests 目录中查找测试?

我看过这篇文章,看来我正在做它建议的所有事情:Having tests in multiple files

在此先感谢您的帮助:)

干杯, 贾斯汀

请您参考如下方法:

在 setup.py 的 setup 调用中,尝试添加以下内容:

  test_suite="tests", 

因为这是包含您的测试的目录。我通常像这样构建我的新样式包并使用 nose 进行测试,所以我的 setup.py 中没有它。添加该声明后,现在会在调用 python setup.py test 时执行测试。

来源:https://pythonhosted.org/setuptools/setuptools.html#test-build-package-and-run-a-unittest-suite

再次确保在测试目录中有一个 __init__.py,否则 setuptools 测试运行器会提示缺少 tests 模块。