@dmvianna 的回答让我非常接近能够在 jupyter (ipython) 笔记本中运行 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)
suite = unittest.TestLoader().loadTestsFromModule (TestStringMethods)
unittest.TextTestRunner().run(suite)
我明白了
在 0.000 秒内运行 0 次测试
好的
它没有损坏,但没有运行任何测试!如果我实例化了测试类
suite = unittest.TestLoader().loadTestsFromModule (TestStringMethods())
(注意行尾的括号;这是唯一的变化)我得到了
ValueError Traceback(最近一次调用最后一次)
在 ()
----> 1 个套件 = unittest.TestLoader().loadTestsFromModule (TestStringMethods())
/usr/lib/python2.7/unittest/case.pyc in init(self, methodName)
189 除了属性错误:
190 raise ValueError("在 %s 中没有这样的测试方法: %s" %
--> 191 (self.class, methodName))
192 self._testMethodDoc = testMethod.文档
193 自我._cleanups = []
ValueError: runTest 中没有这样的测试方法
现在修复相当明确:将 runTest 添加到测试类:
class TestStringMethods(unittest.TestCase):
def runTest(self):
test_upper (self)
test_isupper (self)
test_split (self)
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)
suite = unittest.TestLoader().loadTestsFromModule (TestStringMethods())
unittest.TextTestRunner().run(suite)
在 0.002 秒内运行 3 次测试
好的
按照@Darren 的建议,如果我的runTest 只是passes,它也可以正常工作(并运行3 个测试)。
这有点麻烦,我需要一些体力劳动,但也更明确,这是 Python 的优点,不是吗?
我无法通过调用unittest.main 并从这里或从这个相关问题Unable to run unittest's main function in ipython/jupyter notebook 中获得任何技术来在jupyter 笔记本中工作,但我带着满满一罐油回到了路上。