I'm trying to test an add function that excites in calc.py
import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self):
result = calc.add(10,5)
self.assertEqual(result,15)
My question is what does self means in this example
I know that self is an instance of a class.But, can you give me an example of what the value of self would be in my example.
self is a reference to the instance of TestCalc that is instantiated by the test runner from unittest when you run your tests.
More generally, when an object is instantiated and one of its methods is called (such as test_add(), called by unittest's test runner in your case), self is used to refer to the instance the method is called on, allowing access to its other properties and methods (such as assertEqual(), inherited from unittest.TestCase, in your case).
Related
I have a class and I need to test it
class ToBeTested():
def my_method():
pass
I have designed some unittests in python.
import unittest
class MyFirstUnitTest(unittest.TestCase):
def setUp(self):
# prepare some data
# run a method
# collect results
def test_one_assumption_about_results(self):
#self.assertEqual(...)
def test_another_assumption_about_results(self):
#self.assertEqual(...)
if __name__ == '__main__':
unittest.main()
I have designed this code looking at the examples.
Now I do not understand how to interface it the tesing class MyFirstUnitTest with the classe to be tested ToBeTested?
By inheritance?
class MyFirstUnitTest(unittest.TestCase,ToBeTested):
######
By creating a object of class ToBeTested as static member of
MyFirstUnitTest class definition?
class MyFirstUnitTest(unittest.TestCase):
mytestobj=ToBeTested()
def setUp(self):
By creating a object of class ToBeTested within each of the test
cases of MyFirstUnitTest class definition?
class MyFirstUnitTest(unittest.TestCase):
def setUp(self):
###
def test_one():
mytestobj=ToBeTested()
def test_two():
mytestobj=ToBeTested()
please suggest alternatives and why you would prefer any of them
There is a drawback to using inheritance and static member instead of creating a new object for every test: If tests change the state of the object, then the tests influence each other with their side effects. This gets even worse if the order of the test method calls are not guaranteed and changes (say, you rename a test and suddenly a different test case fails - these things have happened before!)
Additionally, having your test case inherit from the SUT (subject under test) means you only get to test one constructor.
I don't see any advantage to having the testcase inherit from the SUT, especially in python where there are no private members. If for some reason inheritance is necessary for the test (which sometimes IS the case), then having a seperate TestAdapter class that inherits and is instantiated by the test is the best practice.
There are other questions with answers which go more in depth:
https://softwareengineering.stackexchange.com/questions/366425/making-a-test-fixture-inherit-from-the-sut-class
https://softwareengineering.stackexchange.com/questions/154144/how-to-define-implementation-details
You can create an instance of your class(es) in your setup if it will not have to be reinstantiated.
And if you have to create a new instance in every test then just create a new instance in every test.
What is the purpose of subclassing an instance of a class in Python? Here's an example:
class A:
def __init__(*args): print(args)
base = A()
class Test(base): pass
This code works properly under Python, but base is an instance of class A (1) Why do we need to subclass an instance of a class? Is it related to metaclasses?
From this question:
What happens when you inherent from a module instead of a class in Python?
I understand that Test(base) will become type(base).__init__, (2) does this happen at definition time, when the class is defined? (3) How does Python know/decide that base is an instance of a class? Is it becuase type(base) doesn't return type?
Python actually uses type(base)(classname, bases, body) to produce the class object. This is the normal metaclass invocation (unless the class specifies a specific metaclass directly).
For an instance (or a module, which is basically an instance too), that means the class __new__ static method is called to produce a new instance, and on that new instance __init__ is called. So for your class Test(base): pass syntax, you are essentially creating a new instance of A, when Python executes the class statement.
This isn't really 'definition time'; there is no such phase in Python code. Python loads the bytecode for a module and executes it when it is imported for the first time. Class statements at the top of the module (so not inside functions) are executed at that time. It is at that time then that the type(base)(...) call is executed, yes.
Python doesn't 'know' or 'decide' anything about the base class. Python's philosophy is to trust the developer that writes code in it. The assumption is that you know what you are doing, and the base classes are just treated as if they'll respond correctly. Since type(base)(....) didn't raise an exception, Python just continued.
You can use anything that's callable as a metaclass, really.
So I'm using pytest and everything works ok, but something bothers me. When I put some method in my TestClass definition, it's y default a bound method, but I never actually get to use "self".
Now, the "setup_class" (or teardown_class) methods are necessarily classmethods, hence I cannot call my bound methods from setup_class.
So do I define every method as classmethods and get along with it, or am I missing something ? Should I simply never use bound methods ?
class TestSomething(object):
#classmethod
def setup_class(cls):
"do something"
cls.bound_method(?) #how do I call it ?
def bound_method(self):
"do something I'd like to do in setup_class"
You can use method setup and teardown methods in a class
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
class. setup_method is invoked for every test method of a class.
"""
def teardown_method(self, method):
""" teardown any state that was previously setup with a setup_method
call.
"""
That runs on every test method (bound test function) defined in the class
I am relatively new to Python. According to unittest.setUp documentation:
setUp()
Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.
My question about setUp is as follows:
In our testing code base, I have seen that we customized the Python testing framework by inheriting from unittest.TestCase. Originally, unittest.TestCase has names setUp and tearDown.In the customized class, we have setUpTestCase and tearDownTestCase. So each time those two functions will be called instead of those original counterparts.
My questions are:
How are those setUp and tearDown functions being called by the underlying test runner?
Is it required that those functions used to set up test cases should start with setUp and functions used to tear down test cases should start with tearDown? Or it can be named as any valid identifier?
Thank you.
setUp() and tearDown() methods are automatically used when they are available in your classes inheriting from unittest.TestCase.
They should be named setUp() and tearDown(), only those are used when test methods are executed.
Example:
class MyTestCase(unittest.TestCase):
def setUp(self):
self.setUpMyStuff()
def tearDown(self):
self.tearDownMyStuff()
class TestSpam(MyTestCase):
def setUpMyStuff(self):
# called before execution of every method named test_...
self.cnx = # ... connect to database
def tearDownMyStuff(self):
# called after execution of every method named test_...
self.cnx.close()
def test_get_data(self):
cur = self.cnx.cursor()
...
I am unit testing mercurial integration and have a test class which currently creates a repository with a file and a clone of that repository in its setUp method and removes them in its tearDown method.
As you can probably imagine, this gets quite performance heavy very fast, especially if I have to do this for every test individually.
So what I would like to do is create the folders and initialize them for mercurial on loading the class, so each and every unittest in the TestCase class can use these repositories. Then when all the tests are run, I'd like to remove them. The only thing my setUp and tearDown methods then have to take care of is that the two repositories are in the same state between each test.
Basically what I'm looking for is a python equivalent of JUnit's #BeforeClass and #AfterClass annotations.
I've now done it by subclassing the TestSuite class, since the standard loader wraps all the test methods in an instance of the TestCase in which they're defined and puts them together in a TestSuite. I have the TestSuite call the before() and after() methods of the first TestCase. This of course means that you can't initialize any values to your TestCase object, but you probably want to do this in your setUp anyway.
The TestSuite looks like this:
class BeforeAfterSuite(unittest.TestSuite):
def run(self, result):
if len(self._tests) < 1:
return unittest.TestSuite.run(self, result)
first_test = self._tests[0]
if "before" in dir(first_test):
first_test.before()
result = unittest.TestSuite.run(self, result)
if "after" in dir(first_test):
first_test.after()
return result
For some slightly more finegrained control I also created the custom TestLoader which makes sure the BeforeAfterSuite is only used to wrap test-method-TestCase objects in, which looks like this:
class BeforeAfterLoader(unittest.TestLoader):
def loadTestsFromTestCase(self, testCaseClass):
self.suiteClass = BeforeAfterSuite
suite = unittest.TestLoader.loadTestsFromTestCase(self, testCaseClass)
self.suiteClass = unittest.TestLoader.suiteClass
return suite
Probably missing here is a try/except block around the before and after which could fail all the testcases in the suite or something.
from the Python unittest documentation :
setUpClass() :
A class method called before tests in an individual class run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():
#classmethod
def setUpClass(cls):
...
New in version 2.7.
tearDownClass() :
A class method called after tests in an individual class have run. tearDownClass is called with the class as the only argument and must be decorated as a classmethod():
#classmethod
def tearDownClass(cls):
...