简体   繁体   中英

DRY in Unit Test for Python

From two files test_now.py and test_later.py as follows:

# 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()

I reorganize in three files as follows:

# 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()

What are the concerns about this DRY approach?

Modifying other modules when your module is imported is a huge wart.

Instead, create subclasses:

# 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()

Or you could just move the functions out of the class since they don't depend on anything in self .

Or, once your problem grows beyond trivial examples, maybe give up on using the standard unittest framework and use something saner like py.test so you can use proper fixtures and all sorts of things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM