Tutorial :overloading __init__ of unittest.testcase



Question:

I want to add two variables to my subclass which is inherited from unittest.testcase

like I have:

import unittest    class mrp_repair_test_case(unittest.TestCase):         def __init__(self, a=None, b=None, methodName=['runTest']):               unittest.TestCase.__init__(self)               self.a= a                self.b = b         def test1(self):             ..........             .......    def runtest()      mrp_repair_test_case(a=10,b=20)      suite = unittest.TestLoader().loadTestsFromTestCase(mrp_repair_test_case)      res = unittest.TextTestRunner(stream=out,verbosity=2).run(suite)  

how can I acvhieve this: I am getting this error:

ValueError: no such test method in ****<class 'mrp_repair.unit_test.test.mrp_repair_test_case'>:**** runTest  

thanks


Solution:1

At first glance, it looks like you need to create an instance of mrp_repair_test_case. Your current line:

mrp_repair_test_case(a=10,b=20)  

doesn't actually do anything.

Try (not tested):

def runtest():      m = mrp_repair_test_case(a=10, b=20)      suite = unittest.TestLoader().loadsTestsFromTestCase(m)      res = unittest.TextTestRunner(stream=out, verbosity=2).run(suite)  

This assumes you've set up 'out' as a stream already.

Edit:

By the way, is there any reason you're not using a setUp method to set these values? That would be normal best practice. Looking at the documentation of loadTestsFromTestCase it looks like it will only accept the Class itself not an instance of it, which would mean you're rather working against the design of the unittest module.

Edit 2:

In response to your further information, I would actually set your uid and cursor values seperately at module level before calling the tests. I'm not a huge fan of globals normally, but if I'm understanding you correctly these values will be A) read-only B) always the same for the same customer which avoids most of the normal pitfalls in using them.

Edit 3:

To answer your edit, if you really want to use __init__ you probably can, but you will have to roll your own loadsTestsFromTestCase alternative, and possibly your own TestSuite (you'll have to check the internals of how it works). As I said above, you'll be working against the existing design of the module - to the extent that if you decide to do your testing that way it might be easier to roll your own solution completely from scratch than use unittest. Amend: just checked, you'd definately have to roll your own version of TestSuite, as the existing one creates a new instance of the TestCaseClass for each test.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »