如果 __name__ == '__main__' 不适用于单元测试

if __name__ == '__main__' doesn't work with unittest

当我运行这段代码时:

from unittest import *


class TestSomething(TestCase):

    def test_thing(self):
        assert True


if __name__ == '__main__': main()

我收到属性错误:

Launching unittests with arguments python -m unittest
__________________
|Long stack trace|
------------------
  File "C:\Users\Mykola_Zomchak\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 588, in run
    result.startTest(self)
  File "C:\programs\PyCharm\helpers\pycharm\teamcity\unittestpy.py", line 226, in startTest
    test_id = self.get_test_id(test)
  File "C:\programs\PyCharm\helpers\pycharm\teamcity\unittestpy.py", line 40, in get_test_id
    test_id = test.id()
  File "C:\Users\Mykola_Zomchak\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 1383, in id
    return self._testFunc.__name__
AttributeError: 'str' object has no attribute '__name__'

Process finished with exit code 1
Empty test suite.

我在 win32 上使用 Python 3.7.0b4(v3.7.0b4:eb96c37699,2018 年 5 月 2 日,19:02:22)[MSC v.1913 64 位 (AMD64)]。 有人可以帮忙吗?

我无法解释原因,但如果我像下面那样更新您的代码,它会按预期工作。我只是按照文档示例 1:1 但使用了您的 class 代码。

import unittest

class TestSomething(unittest.TestCase):
    def test_thing(self):
        assert True


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

输出:

[zaphoxx]> uni.py
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK