【问题标题】:Python not able to find tests when test files are in different module当测试文件位于不同的模块中时,Python 无法找到测试
【发布时间】:2018-09-06 17:03:19
【问题描述】:

我有一个像下面这样的目录结构

horizontalupgrade
  common/
    __init__.py
    upgradestate.py
  tests/
    common/
      __init__.py
      testupgradestate.py

testupgradestate.py的内容

import unittest
from upgradestate import UpgradeState

class UpgradeStateTest(unittest.TestCase):

    def setUp(self):
        print "Setup Called"

    def test_copy(self):
        u = UpgradeState("")
        print "test_copy Called"

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(UpgradeStateTest)
    runner = unittest.TextTestRunner()
    runner.run(suite)

但是在尝试执行测试时,python 无法找到测试

(venv) dmanna-a01:horizontalupgrade dmanna$ python -m unittest discover  -v

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

但是,如果我将目录结构设置为如下所示

horizontalupgrade
  common/
    __init__.py
    upgradestate.py
    testupgradestate.py

然后测试运行良好

(venv) dmanna-a01:horizontalupgrade dmanna$ python -m unittest discover  -v
test_copy (common.testupgradestate.UpgradeStateTest) ... Setup Called
test_copy Called
ok

----------------------------------------------------------------------
Ran 1 tests in 0.000s

OK

谁能告诉我我做错了什么?如何使测试从不同的测试包运行?

  • Python - 2.7

【问题讨论】:

    标签: python python-2.7 python-unittest


    【解决方案1】:

    您需要tests/ 中的__init__.py。 Unittest 的发现仅适用于包。 https://docs.python.org/3/library/unittest.html

    【讨论】:

      【解决方案2】:

      试试这个,在你的开头添加这些代码:

      import sys
      sys.path.append('.../common')
      

      或者你可以在 append 中使用绝对路径。

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2016-09-15
        • 1970-01-01
        • 2011-01-16
        • 2019-09-22
        • 2019-03-14
        • 1970-01-01
        • 2020-06-22
        • 1970-01-01
        相关资源
        最近更新 更多