How would I limit running a setUp method to only run when a specific test is run, e.g.
class Tests(unittest.TestCase):
setUpClass(cls):
#requirements for all tests
def test1(self):
#something
def test2(self):
#something else
def setUp(self):
#requirements for test 3
def test3(self):
#something requiring setup
In this case, I only want to run setUp when test3 is called
You can call a test-specific setup method inside test method, e.g.:
class Tests(unittest.TestCase):
setUpClass(cls):
#requirements for all tests
def test1(self):
#something
def test2(self):
#something else
def setUp(self):
#requirements for test 3
def test3(self):
self.prepareForTest3();
#execute test case
def prepareForTest3(self):
#do preparations here
Related
I have the following to do two unit tests:
import unittest
from unittest import TestCase
class TestUM(unittest.TestCase):
def setUp(self):
self.client = SeleniumClient()
def test_login(self):
self.client.login()
self.assertIn("my-data", self.client.driver.current_url)
print ('Log in successful.')
def test_logout(self):
self.client.logout()
print ('Log out successful.')
if __name__ == '__main__':
unittest.main()
However, it does setUp twice -- once for each of the unit tests. Is there a way I can do one setup across all the unittests for TestUM ? If so, how would I do that?
You can use setupClass for that:
class TestUM(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.client = SeleniumClient()
From the documentation, this method is called only once before tests in class are run.
Is there a function that is fired at the beginning/end of a scenario of tests? The functions setUp and tearDown are fired before/after every single test.
I typically would like to have this:
class TestSequenceFunctions(unittest.TestCase):
def setUpScenario(self):
start() #launched at the beginning, once
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
def tearDownScenario(self):
end() #launched at the end, once
For now, these setUp and tearDown are unit tests and spread in all my scenarios (containing many tests), one is the first test, the other is the last test.
As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).
Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent's run method.
I have the same scenario, for me setUpClass and tearDownClass methods works perfectly
import unittest
class Test(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls._connection = createExpensiveConnectionObject()
#classmethod
def tearDownClass(cls):
cls._connection.destroy()
Here is an example: 3 test methods access a shared resource, which is created once, not per test.
import unittest
import random
class TestSimulateLogistics(unittest.TestCase):
shared_resource = None
#classmethod
def setUpClass(cls):
cls.shared_resource = random.randint(1, 100)
#classmethod
def tearDownClass(cls):
cls.shared_resource = None
def test_1(self):
print('test 1:', self.shared_resource)
def test_2(self):
print('test 2:', self.shared_resource)
def test_3(self):
print('test 3:', self.shared_resource)
For python 2.5, and when working with pydev, it's a bit hard. It appears that pydev doesn't use the test suite, but finds all individual test cases and runs them all separately.
My solution for this was using a class variable like this:
class TestCase(unittest.TestCase):
runCount = 0
def setUpClass(self):
pass # overridden in actual testcases
def run(self, result=None):
if type(self).runCount == 0:
self.setUpClass()
super(TestCase, self).run(result)
type(self).runCount += 1
With this trick, when you inherit from this TestCase (instead of from the original unittest.TestCase), you'll also inherit the runCount of 0. Then in the run method, the runCount of the child testcase is checked and incremented. This leaves the runCount variable for this class at 0.
This means the setUpClass will only be ran once per class and not once per instance.
I don't have a tearDownClass method yet, but I guess something could be made with using that counter.
import unittest
class Test(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.shared_data = "dddd"
#classmethod
def tearDownClass(cls):
cls.shared_data.destroy()
def test_one(self):
print("Test one")
def test_two(self):
print("Test 2")
For more visit Python
unit test document
I am attempting to write a decorator which calls on two additional functions and runs them in addition to the function it is decorating in a specific order.
I have tried something along these lines:
class common():
def decorator(setup, teardown, test):
def wrapper(self):
setup
test
teardown
return wrapper
class run():
def setup(self):
print("in setup")
def teardown(self):
print("in teardown")
#common.decorator(setup, teardown)
def test(self):
print("in test")
The final goal would be to have the decorator make the test run with the following flow setup > test > teardown. I know I am not calling on the setup and teardown correctly however. I would appreciate any help in how I should do this, I am new in using python and my knowledge of decorators involving arguments is limited.
Decorators on methods are applied when the class is being defined, which means that the setup and teardown methods are not bound at that time. This just means you need to pass in the self argument manually.
You'll also need to create an outer decorator factory; something that returns the actual decorator, based on your arguments:
def decorator(setup, teardown):
def decorate_function(test):
def wrapper(self):
setup(self)
test(self)
teardown(self)
return wrapper
return decorate_function
Demo:
>>> def decorator(setup, teardown):
... def decorate_function(test):
... def wrapper(self):
... setup(self)
... test(self)
... teardown(self)
... return wrapper
... return decorate_function
...
>>> class run():
... def setup(self):
... print("in setup")
... def teardown(self):
... print("in teardown")
... #decorator(setup, teardown)
... def test(self):
... print("in test")
...
>>> run().test()
in setup
in test
in teardown
I can't seem to get the Test1.test_something() in test2 to work.. not sure if it's because they are both inheriting from the same base?
Helper.py:
class baseTest(unittest.TestCase):
def setUp(self, param="Something"):
print param
pass
Test1.py
from Helper import baseTest
class test1(baseTest):
def setUp(self):
super(test1, self).setUp('foo')
def test_something(self):
assert 1 == 1, "One does not equal one."
Test2.py
from Helper import baseTest
import Test1
class test2(baseTest):
def setUp(self):
super(test2, self).setUp('bar')
def test_something(self):
Test1.test_somehing()
Now, I had this working previously, when I had the setUp for test1 and test2 within their classes, but once I had them both inherit from baseTest, I started getting a unbound method <method> must be called with Test instance as first argument (got nothing instead). Any suggestions?
The problem is that Test1.test_something() is an instance method, not a class method. So you can't just call it like that (besides, even if it is class method, it should have been Test1.test1.test_something).
One way to do it (without messing around with the unittest.TestCase mechanism):
Test2.py
import Test1
class test2(Test1.test1):
# whatever else
And you're done, test2 inherits Test1.test1.test_something() automatically. If you need your test2's test_something to do extra stuff, just do super(test2, self).test_something() within your overridden definition of test_something in test2 class.
Move the tests that are shared by both Test1 and Test2 classes into BaseTest:
test.py:
import unittest
import sys
class BaseTest(unittest.TestCase):
def setUp(self, param="Something"):
print param
pass
def test_something(self):
assert 1 == 1, "One does not equal one."
class Test1(BaseTest):
def setUp(self):
super(Test1, self).setUp('foo')
test2.py:
import test
import unittest
import sys
class Test2(test.BaseTest):
def setUp(self):
super(Test2, self).setUp('bar')
My code is like this:
class class1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def testListRolesTitle(self):
driver=self.driver
driver.get("www.google.com")
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
asert...
class class2(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def testListRolesTitle(self):
driver=self.driver
driver.get("www.google.com")
assert...
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
def suite():
s1 = unittest.TestLoader().loadTestsFromTestCase(class1)
s2 = unittest.TestLoader().loadTestsFromTestCase(class2)
return unittest.TestSuite([s1,s2])
if __name__ == "__main__":
run(suite())
When I ran the suite both of the test classes started a new firefox instance in setup methord.
My question is if it's possible to make the two test classed use the same firefox instance?
I don't want to put them together in one class.
Any ideas?
You can have a setup function that applies to the whole module instead of just to the class as explained here.
In your case, that would be something like:
def setUpModule():
DRIVER = webdriver.Firefox()
def tearDownModule():
DRIVER.quit()
Note that DRIVER is a global variable in this case so that it's available to the objects of all classes.
Also, note that test case ordering might cause that your module setup functions are called multiple times as explained in the documentation:
The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.
It think this example should make clear when each setup method/function is executed:
import unittest
def setUpModule():
print 'Module setup...'
def tearDownModule():
print 'Module teardown...'
class Test(unittest.TestCase):
def setUp(self):
print 'Class setup...'
def tearDown(self):
print 'Class teardown...'
def test_one(self):
print 'One'
def test_two(self):
print 'Two'
The output from this is:
$ python -m unittest my_test.py
Module setup...
Class setup...
One
Class teardown...
.Class setup...
Two
Class teardown...
.Module teardown...
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK