Python中的UNITTEST不起作用
Posted
技术标签:
【中文标题】Python中的UNITTEST不起作用【英文标题】:UNITTEST in Python is not working 【发布时间】:2017-05-06 08:32:55 【问题描述】:我以python网站为例,尝试在community.databricks.com平台上运行。我收到属性错误。请指教
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
AttributeError: 'module' object has no attribute '41750'
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-88-3ccf7d7a57bd> in <module>()
18
19 if __name__ == '__main__':
---> 20 unittest.main()
/usr/lib/python2.7/unittest/main.pyc in __init__(self, module, defaultTest, argv, testRunner, testLoader, exit, verbosity, failfast, catchbreak, buffer)
92 self.testLoader = testLoader
93 self.progName = os.path.basename(argv[0])
---> 94 self.parseArgs(argv)
95 self.runTests()
96
/usr/lib/python2.7/unittest/main.pyc in parseArgs(self, argv)
147 else:
148 self.testNames = (self.defaultTest,)
--> 149 self.createTests()
150 except getopt.error, msg:
151 self.usageExit(msg)
/usr/lib/python2.7/unittest/main.pyc in createTests(self)
156 else:
157 self.test = self.testLoader.loadTestsFromNames(self.testNames,
--> 158 self.module)
159
160 def _do_discovery(self, argv, Loader=None):
/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromNames(self, names, module)
128 of string specifiers. See 'loadTestsFromName()'.
129 """
--> 130 suites = [self.loadTestsFromName(name, module) for name in names]
131 return self.suiteClass(suites)
132
/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromName(self, name, module)
98 obj = module
99 for part in parts:
--> 100 parent, obj = obj, getattr(obj, part)
101
102 if isinstance(obj, types.ModuleType):
AttributeError: 'module' object has no attribute '41750'
【问题讨论】:
从哪些文件夹和文件以及如何运行测试? 【参考方案1】:试试这个:
if __name__ == '__main__':
unittest.main(defaultTest='suite')
【讨论】:
调用该类中所有函数的任何其他方式。而不是调用 unittest.main() ?? 你可以用这个代替那个,suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods) unittest.TextTestRunner(verbosity=2).run(suite) 如果不起作用则删除 ' if name == 'main': ' line too 它运行良好,但如果我给 self.assertEqual('foo'.upper(), 'FOOD') 就不会出现断言错误 你可以像这样使用 TRY CATCH 来显示错误,尝试:self.assertEqual('foo'.upper(), 'FOOD') except AssertionError as e: print(e)以上是关于Python中的UNITTEST不起作用的主要内容,如果未能解决你的问题,请参考以下文章
Python Mocking assert_called不起作用