if __name__ ==' __ main __'不适用于unittest

时间:2018-05-22 12:07:22

标签: python python-unittest

当我运行此代码时:

from unittest import *


class TestSomething(TestCase):

    def test_thing(self):
        assert True


if __name__ == '__main__': main()

我得到了AttributeError:

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 个答案:

答案 0 :(得分:0)

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

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