unit testing - Is it unconventional to override unittest.TestCase's init in Python -
whenever single initialization required before tests (independent) invoked, , not before each tests, in separate function outside test class. wondering if possible override __init__ method of unittest.testcase , initialization there.
here's do:
import unittest basket = {} def initiate(): """update fruit basket - fruits , ages.""" fruits = {2: "apples", 4: "grapes", 3: "bananas"} basket.update(fruits) class fruitbasket(unittest.testcase): def test_grapes(self): """any grapes in basket.""" self.assertin("grapes", basket.values()) def test_rotten(self): """stinky test.""" age in basket.keys(): self.assertless(age, 4) if __name__ == "__main__": initiate() unittest.main() the initiate() independent of fruitbasket test class. becomes problem when module imported in others (repeated manual initialization). there improve way of achieving within same class? haven't seen __init__() of testcase overridden anywhere before. if not ok (adhering pythonic style), must done? setup() instance method inappropriate here, since called before each test , not once.
note testcase.__init__ used when building suites , running test select test method run. in fact when want manually create testsuite run tests without using higher-level interface of test runners do:
import unittest class mytestcase(unittest.testcase): def test_one(self): print("one") def test_two(self): print("two") suite = unittest.testsuite([mytestcase('test_one'), mytestcase('test_two')]) suite.run(unittest.testresult()) and behold! creating mytestcase instance every test!
keep in mind when utilize higher level interface run tests, hides steps building testsuites above.
this shows shouldn't override __init__ since called 1 time every test.
however unittest module provides mechanisms add together fixtures classes , modules. see class , module fixtures section of unittest documentation.
in particular setupclass , teardownclass want: called once before , after running tests of testcase subclass.
note setupclass might called more once. happen when building testsuites manually. illustration code:
import unittest class mytestcase(unittest.testcase): @classmethod def setupclass(cls): print('mytestcase.setupclass') def test_one(self): print("one") def test_two(self): print("two") class mytestcase2(unittest.testcase): @classmethod def setupclass(cls): print('mytestcase2.setupclass') def test_three(self): print('three') suite = unittest.testsuite([mytestcase('test_one'), mytestcase2('test_three'), mytestcase('test_two')]) suite.run(unittest.testresult()) produces output:
mytestcase.setupclass 1 mytestcase2.setupclass 3 mytestcase.setupclass 2 the testsuite executes tests in order. whenever sees class test taken changes calls teardownclass "current" class , calls "setupclass" next class. if mix tests of different classes may see setupclass , teardownclass called more once.
python unit-testing python-3.x
No comments:
Post a Comment