从两个文件test_now.py和test_later.py如下:
# test_now.py
import unittest
class CommonClass(unittest.TestCase):
def hello(self):
print "Hello there"
def bye(self):
print "Bye"
def seeYouAgain(self):
print "See You Again"
def whatsUp(self):
print "What's up?"
def testNow(self):
self.hello()
self.bye()
if __name__ == '__main__':
unittest.main()
# test_later.py
import unittest
class CommonClass(unittest.TestCase):
def hello(self):
print "Hello there"
def bye(self):
print "Bye"
def seeYouAgain(self):
print "See You Again"
def whatsUp(self):
print "What's up?"
def testLater(self):
self.hello()
self.whatsUp()
if __name__ == '__main__':
unittest.main()
我重新组织了三个文件,如下所示:
# common_class.py
import unittest
class CommonClass(unittest.TestCase):
def hello(self):
print "Hello there"
def bye(self):
print "Bye"
def seeYouAgain(self):
print "See You Again"
def whatsUp(self):
print "What's up?"
# test_now.py
from common_class import *
def testNow(self)
self.hello()
self.bye()
setattr(CommonClass, 'testNow', testNow)
if __name__ == '__main__':
unittest.main()
# test_later.py
from common_class import *
def testLater(self):
self.hello()
self.whatsUp()
setattr(CommonClass, 'testLater', testLater)
if __name__ == '__main__':
unittest.main()
对这种DRY方法有什么顾虑?
答案 0 :(得分:0)
导入模块时修改其他模块是一个巨大的瑕疵。
相反,创建子类:
# test_now.py
from common_class import CommonClass
class TestNow(CommonClass):
def testNow(self)
self.hello()
self.bye()
# test_later.py
from common_class import CommonClass
class TestLater(CommonClass):
def testLater(self):
self.hello()
self.whatsUp()
或者你可以将这些功能移出课堂,因为他们不依赖self
中的任何内容。
或者,一旦你的问题超出了琐碎的例子,也许放弃使用标准unittest
框架并使用像py.test
这样的更健全的东西,这样你就可以使用适当的固定装置和各种各样的东西。