【问题标题】:How to run a unitest testsuite from parent directory如何从父目录运行 unitest 测试套件
【发布时间】:2018-10-14 01:25:52
【问题描述】:

我的目录结构如下:

.
├── README.md
├── src
│   ├── __init__.py
│   └── foo.py
└── test
    ├── __init__.py
    └── runner.py
    └── test_foo.py

测试文件如下所示:

test_foo.py

import unittest
from ..src.foo import *

class TestFoo(unittest.TestCase):
        def setUp(self):
            pass
        
        def test_foo(self):
            foo = Foo()
            res = foo.get_something('bar')
        
            if res is None:
                self.fail('something bad happened')

if __name__ == '__main__':
    unittest.main(self)

runner.py

import unittest

# import test modules
import test_foo

# initialize the test suite
loader = unittest.TestLoader()
suite  = unittest.TestSuite()

# add tests to the test suite
suite.addTests(loader.loadTestsFromModule(test_foo))

# initialize a runner, pass it your suite and run it
runner = unittest.TextTestRunner(verbosity=3)
result = runner.run(suite)

我想在测试套件的父目录中运行我的所有测试,所以我尝试像这样调用 unites:

python -m test/runner.py

但它抱怨以下内容:

$ python -m test/runner.py 
/usr/bin/python: Import by filename is not supported.

如果我移动到测试目录,我会得到一个不同的错误:

$ python -m runner
  File "test_foo.py", line 2, in <module>
    from ..src.foo import *
ValueError: Attempted relative import in non-package

如果可能的话,我想将所有与测试相关的东西保留在父/测试目录中。

知道我在这里做错了什么吗?

谢谢!

【问题讨论】:

  • 我强烈推荐使用pytest 而不是unittest
  • 为什么你会推荐 pytest 而不是 unitest?
  • 尝试使用python -m test.runner运行
  • 我现在远离我的代码,但我相信我试过了,但它抱怨找不到名为“runner”的模块

标签: python python-unittest test-suite


【解决方案1】:

试试python -m unittest test.runner。这是我使用的结构。

├── README.md
├── src
│   ├── __init__.py
│   └── foo.py
└── test
    ├── __init__.py
    └── test_foo.py
    └── runner.py

我的foo.py 包含一个简单的函数foo。我将test_foo.py 中的导入语句更改为以下内容:

from src.foo import foo.

我还直接从runner.py 运行,并进行了以下更改。

from test import test_foo

然后在父目录的命令行中,python -m unittest test.runner

此结构仅适用于父目录。如果我在测试目录中尝试,它无法导入。

【讨论】:

  • 我不想使用 discover 方法,因为我想显式地将测试添加到我的套件中。我试着打电话给python -m unittest test/runner.py,但又遇到了一些错误:ImportError: Import by filename is not supported.
  • 什么python版本?如果是 2,请尝试 from __future__ import absolute_import
  • 我尝试了 2 和 3。当然我不需要导入额外的库来运行具有标准目录结构的单元?
  • 我用 python3 得到了这个:ModuleNotFoundError: No module named 'test.runner'
  • 我只能说,“它可以在我的计算机上运行”:( . 在 py2.7 和 3.5 中。现在我真的很想知道为什么它不能在你的计算机上运行。跨度>
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2010-12-03
  • 2015-05-09
  • 2016-11-24
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
相关资源
最近更新 更多