[英]Python unittest does not run tests
I made a small project called demo, with a single test in it我做了一个名为 demo 的小项目,里面有一个测试
import unittest
class Test(unittest.TestCase):
def testName1(self):
self.assertEqual(5+9, 14)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
However, from command line但是,从命令行
ThinkPad-T520:~/workspacep/demo$ python -m unittest
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Why doesn't this work?为什么这不起作用? In general, how can I run all unit tests from command line with a single line?
一般来说,我怎样才能用一行从命令行运行所有单元测试?
The structure of the directory is目录的结构是
demo
tests
demo_test1.py __init__.py
There are three gotcha's that I know of:我知道三个问题:
test_*
test_*
test*.py
(by default, you can change it with the -p
flag when running the tests).test*.py
(默认情况下,您可以在运行测试时使用-p
标志更改它)。 eg test_demo1.py
test_demo1.py
tests
folder needs to have an __init__.py
file in it, or else it won't be considered a valid location to import from.tests
文件夹中需要有一个__init__.py
文件,否则它不会被视为一个有效的导入位置。 So, for #1, you need to rename the test to test_name_1
.因此,对于 #1,您需要将测试重命名为
test_name_1
。 And for #2, there's two options:对于#2,有两个选项:
A - Restructure your files like this: A - 像这样重组你的文件:
demo
tests
__init__.py
test_demo1.py
Then run python -m unittest
and it should find the test cases.然后运行
python -m unittest
它应该会找到测试用例。
B - Just run it like: python -m unittest discover -p *test.py
B - 像这样运行它:
python -m unittest discover -p *test.py
I fought with the same exact problem a while ago and I solved it by using test discovery command.我刚才遇到了同样的问题,我通过使用测试发现命令解决了它。
python -m unittest discover -s.
You can pass in your test file pattern as well and a whole other options https://docs.python.org/2/library/unittest.html#test-discovery您也可以传入测试文件模式和其他所有选项https://docs.python.org/2/library/unittest.html#test-discovery
You need to pass in a list of modules .您需要传入一个模块列表。
For example, if your test file is foo.py
, then you can run python -m unittest foo
.例如,如果您的测试文件是
foo.py
,那么您可以运行python -m unittest foo
。
For me (running tests from IntelliJ IDEA ) I had to remove the class' 'Run configuration' .对我来说(从IntelliJ IDEA运行测试)我不得不删除类' '运行配置' 。 Earlier on I had wrongly imported the unittest as _pytest.unittest and ran the test class.
早些时候我错误地将 unittest 导入为 _pytest.unittest 并运行了测试类。 Of course that didn't work.
当然那没有用。
I corrected the module import, but the 'run configuration' was still there, causing it to run as a Python script and not as 'Python tests'.我更正了模块导入,但“运行配置”仍然存在,导致它作为 Python 脚本运行,而不是作为“Python 测试”运行。
I had a similar issue and figured out that I had to run python3 -m unittest
instead as I had forgotten python
defaults to Python 2 on my system我有一个类似的问题,我发现我必须运行
python3 -m unittest
而不是因为我忘记了我系统上的python
默认为 Python 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.