I need a tearDownClass(cls) method for the instance.
I mean one where I can refer to self (the instance), not to cls (the class).
A sort of tearDownTestCase(self).
My intention is to cleanup the database after ALL the test cases have been run.
tearDown(self) is executed at the end of every test and I don't want use it.
tearDownClass(cls) is executed once when ALL the tests finished but it does not contain a reference to self, and I need to access to a property of self (more precisely to a function).
There is a way to achieve this?
Python 3.6
Example of real scenario:
import unittest
'''
The real records saved in the database came from an external source (an API) so the ID is preassigned.
For the test I use everywhere a predefined fixed id, so the code result more clean.
'''
record_id = "TEST"
class RepositoryTest(unittest.TestCase):
def setUp(self):
# real initialization, reading connection string from config, database name, collection...
self.repository = None
# self._cleanup_record() # maybe here is executed too many unnecessary times
def tearDown(self):
# here is executed unnecessarily, because (where needed) the cleanup is eventually executed BEFORE the test (or in its beginning)
self._cleanup_record()
### pseudo (desired) method ###
def tearDownTestCase(self):
self._cleanup_record()
def tearDownClass(cls):
# self._cleanup_record() # self is not available
# rewrite the same code of initialization and _cleanup_record()
# I want to a void (or simplify this)
pass
# this is 1 of N tests
def test_save_record(self):
# cleanup (because I don't know in which state the database is)
self._cleanup_record() # almost every test require this, so it can be done in setUp()
# arrange
record = self._create_record()
# act
self.repository.save_record(record)
# assert
saved_record = self._get_record()
self.assertEquals(saved_record["my field"], record["my field"])
# utility methods
def _get_record(self):
# use self.repository and return the record with id = record_id
pass # return the record
def _create_record(self):
# use self.repository and create (and save) a record with id = record_id
return None # return the saved record
def _cleanup_record(self):
# use self.repository and delete the record with id = record_id (if exists)
pass
Doing the cleanup in the tearDown() method it results in:
setUp
.test 1
cleanup
test
cleanup (= redundant)
. . .
.test N
cleanup
test
cleanup
Instead I want this:
(and it is possible if a tearDownX() method is executed after ALL the tests are finished)
setUp
(test 1)
cleaup
test
. . .
(test N)
cleaup
test
tearDownX (self)
cleanup (final)
This is more or less how I ended in the design of the tests in the last years.
It try to be bullet proof against interrupted debug sessions (no cleanup) and dirty initial database state.
As a temporary solution I have replicated the cleanup method in the tearDownClass(cls) method, but I'm not happy. Ideally I could simply call the self._cleanup_record but this is not possible because tearDownClass is a class method.
I hope all that makes sense.
Thank you,
Alessandro
Yes, there is a pair of instance methods setUp and tearDown under the unittest.TestCase, executed before and after each test respectively.
From the docs:
setUp()
Method called to prepare the test fixture. This is called
immediately before calling the test method; other than AssertionError
or SkipTest, any exception raised by this method will be considered an
error rather than a test failure. The default implementation does
nothing.
tearDown()
Method called immediately after the test method has been
called and the result recorded. This is called even if the test method
raised an exception, so the implementation in subclasses may need to
be particularly careful about checking internal state. Any exception,
other than AssertionError or SkipTest, raised by this method will be
considered an additional error rather than a test failure (thus
increasing the total number of reported errors). This method will only
be called if the setUp() succeeds, regardless of the outcome of the
test method. The default implementation does nothing.
UPDATE (after comments)
Well, you probably have no choice but to re-design your code. You can make the db cleanup method a class method instead of instance method.
Anyways, since you shouldl't count on the test execution order, nor have your tests dependent on each other, it would be still smart to create the db fixture for each test with the setUp method and clean it with tearDown method after each test.
Another option would be using a mock for the db in your tests, so you won't need to worry about cleaning it up.
Related
I want to do tests with randomized parameters of a class with a very slow init method. The tests themself are very quick, but require a time consuming initialization step.
Of course. I do something like this:
#pytest.mark.parametrize("params", LIST_OF_RANDOMIZED_PARAMS)
def test_one(params):
state = very_slow_initialization(params)
assert state.fast_test()
#pytest.mark.parametrize("params", LIST_OF_RANDOMIZED_PARAMS)
def test_two(params):
state = very_slow_initialization(params)
assert state.another_fast_test()
From my unsuccessful tries so far I've learnt:
initializing a Testclass with a parametrized set_class(params) method is not supported
Using a fixture that initialized the class still calls the slow initialization every time
I could create a list with all initialized states in advance, however they demand a lot of memory. Furthermore sometimes I like to rune a lot of randomized tests overnight and just stop them the next morning. This this I would need to know precisely how many tests I should to so that all initializations are finished before that.
If possible I would prefer a solution that runs both tests for the first parameter, then runs both with the second parameter and so on.
There is probably a really simple solution for this.
pytest fixtures is a solution for you. Lifetime of fixture might be a single test, class, module or whole test session.
fixture management scales from simple unit to complex functional testing, allowing to parametrize fixtures and tests according to configuration and component options, or to re-use fixtures across function, class, module or whole test session scopes.
Per Fixture availability paragraph, you need to define feature in class, or on module level.
Consider using module-scoped ones (pay attention, that initialization launched only once):
import pytest
#pytest.fixture(scope="module")
def heavy_context():
# Use your LIST_OF_RANDOMIZED_PARAMS randomized parameters here
# to initialize whatever you want.
print("Slow fixture initialized")
return ["I'm heavy"]
def test_1(heavy_context):
print(f"\nUse of heavy context: {heavy_context[0]}")
def test_2(heavy_context):
print(f"\nUse of heavy context: {heavy_context[0]}")
Tests output:
...
collecting ... collected 2 items
test_basic.py::test_1 Slow fixture initialized
PASSED [ 50%]
Use of heavy context: I'm heavy
test_basic.py::test_2 PASSED [100%]
Use of heavy context: I'm heavy
Now, if you need it to be assertion safe (release resources even when test fails), consider creating heavy_context in a context-manager manner (much more details here: Fixture, Running multiple assert statements safely):
import pytest
#pytest.fixture(scope="module")
def heavy_context():
print("Slow context initialized")
obj = ["I'm heavy"]
# It is mandatory to put deinitialiation into "finally" scope
# otherwise in case of exception it won't be executed
try:
yield obj[0]
finally:
print("Slow context released")
def test_1(heavy_context):
# Pay attention, that in fact heavy_context now
# is what we initialized as 'obj' in heavy_context
# function.
print(f"\nUse of heavy context: {heavy_context}")
def test_2(heavy_context):
print(f"\nUse of heavy context: {heavy_context}")
Output:
collecting ... collected 2 items
test_basic.py::test_1 Slow context initialized
PASSED [ 50%]
Use of heavy context: I'm heavy
test_basic.py::test_2 PASSED [100%]
Use of heavy context: I'm heavy
Slow context released
============================== 2 passed in 0.01s ===============================
Process finished with exit code 0
Could you perhaps run the tests one after another without initializing the object again, e.g.:
#pytest.mark.parametrize("params", LIST_OF_RANDOMIZED_PARAMS)
def test_one(params):
state = very_slow_initialization(params)
assert state.fast_test()
assert state.another_fast_test()
or using separate functions for organization:
#pytest.mark.parametrize("params", LIST_OF_RANDOMIZED_PARAMS)
def test_main(params):
state = very_slow_initialization(params)
step_one(state)
step_two(state)
def step_one(state):
assert state.fast_test()
def step_two(state):
assert state.another_fast_test()
Although it's a test script, you can still use functions to organize your code. In the version with separate functions you may even declare a fixture, in case the state may be needed in other tests, too:
#pytest.fixture(scope="module", params=LIST_OF_RANDOMIZED_PARAMS)
def state(request):
return very_slow_initialization(request.param)
def test_main(state):
step_one(state)
step_two(state)
def step_one(state):
assert state.fast_test()
def step_two(state):
assert state.another_fast_test()
I hope I didn't do a mistake here, but it should work like this.
I have a couple of fixtures that do some initialization that is rather expensive. Some of those fixtures can take parameters, altering their behaviour slightly.
Because these are so expensive, I wanted to do initialisation of them once per test class. However, it does not destroy and reinit the fixtures on the next permutation of parameters.
See this example: https://gist.github.com/vhdirk/3d7bd632c8433eaaa481555a149168c2
I would expect that StuffStub would be a different instance when DBStub is recreated for parameters 'foo' and 'bar'.
Did I misunderstand something? Is this a bug?
I've recently encountered the same problem and wanted to share another solution. In my case the graph of fixtures that required regenerating for each parameter set was very deep and it's not so easy to control. An alternative is to bypass the pytest parametrization system and programmatically generate the test classes like so:
import pytest
import random
def make_test_class(name):
class TestFoo:
#pytest.fixture(scope="class")
def random_int(self):
return random.randint(1, 100)
def test_someting(self, random_int):
assert random_int and name == "foo"
return TestFoo
TestFooGood = make_test_class("foo")
TestFooBad = make_test_class("bar")
TestFooBad2 = make_test_class("wibble")
You can see from this that three tests are run, one passes (where "foo" == "foo") the other two fail, but you can see that the class scope fixtures have been recreated.
This is not a bug. There is no relation between the fixtures so one of them is not going to get called again just because the other one was due to having multiple params.
In your case db is called twice because db_factory that it uses has 2 params. The stuff fixture on the other hand is called only once because stuff_factory has only one item in params.
You should get what you expect if stuff would include db_factory as well without actually using its output (db_factory would not be called more than twice):
#pytest.fixture(scope="class")
def stuff(stuff_factory, db_factory):
return stuff_factory()
How can I find out from the current test if its the last to be run? (Python unittest / nosetests)
I have some specific fixture teardown to be done at the very end of the test run and it would be a lot easier if on a test by test basis I could just determine:
if last_test:
hard_fixture_teardown()
else:
soft_fixture_teardown()
I have a package teardown which would work perfectly but it seems very messy passing the fixture information back to the __init__.teardown_package().
You can use a combination of TestCase.tearDown() and TestCase.tearDownClass() to achieve this. tearDown() is called for each test method while tearDownClass() is called after all tests in the class have run.
As stated here unit test are not meant to have an order, unit tests depending on the order are either not well conceived or just have to be merged in a monolithic one. (merging separate functions in a single test is the accepted answer )
[edit after comment]
If the order is not important you can do this (quite messy, imo we are still forcing the boundaries of how unit tests should be used)
in every test package you put:
def tearDownModule():
xxx = int(os.getenv('XXX', '0')) + 1
if xxx == NUMBER_OF_TEST_PACKAGES:
print "hard tear down"
else:
print "not yet"
os.environ['XXX'] = str(xxx)
with NUMBER_OF_TEST_PACKAGES imported from somewhere global.
also if the order is not important I suppose that when used the fixture is only readed and not modified, if so you can setup that as a class method
#classmethod
def setUpClass(cls):
print "I'll take a lot of time here"
I'd like that every assertion test in a TestCase is actually tested, even if the first one fails. In my situation, all the assertions are of the same nature.
Actually I have something that evaluates formulas written as Python objects (figure it as formulas written as strings to be eval'd). I'd like to do something like:
class MyTest(TestCase):
def test_something(self):
for id in ids:
for expression in get_formulas(id):
for variable in extract_variables(expression):
self.assertIn(variable, list_of_all_variables)
=> I want to see printed all of the variables that are not in the list_of_all_variables!
This is necessary for me to review all my so-called formulas and be able to correct errors.
Some more context:
I'm having a variable number of tests to perform (depending on a list of IDs written in a versioned data file) in one app.
To have a variable number of TestCase instances, I did write a base class (mixin), then build on-the-fly classes with the use of 3-args type function (that is creating classes).
This way, I have n tests, corresponding to the n different ids. It's a first step, but what I want is that each and every assertion in those tests gets tested and the corresponding assertion errors get printed.
As referenced in the question Continuing in Python's unittest when an assertion fails, failing at assertion errors is the hardcoded behavior of the TestCase class.
So instead of changing it's behavior, I generated a lot of different test_... methods to my classes, in the following style:
from django.test import TestCase
from sys import modules
# The list of all objects against which the tests have to be performed
formids = [12,124,234]
# get_formulas returns a list of formulas I have to test independently, linked to a formid
formulas = {id: get_formulas(id) for id in formids}
current_module = sys.modules(__name__)
def test_formula_method(self, formula):
# Does some assertions
self.assertNotEqual(formula.id, 0)
for formid in formids:
attrs = {'formid': formid}
for f in formulas[formid]:
# f=f so the 2nd arg to test_formula_method is staying local
# and not overwritten by last one in loop
attrs['test_formula_%s' % f.name] = lambda self, f=f: test_formula_method(self, f)
klass_name = "TestForm%s" % formid
klass = type(klass_name, (TestCase,), attrs)
setattr(current_module, klass_name, klass)
I'm new to testing and I would like to
1) test the login
2) create a folder
3) add content (a page) into the folder
I have each of the tests written and they work but obviously I would like to build ontop of each other, eg, in order to do 3 I need to do 1 then 2. In order to do 2 I need to do 1. This is my basic test structure:
class TestSelenium(unittest.TestCase):
def setUp(self):
# Create a new instance of the Firefox driver
self.driver = webdriver.Firefox()
def testLogin(self):
print '1'
...
def testFolderCreation(self):
print '2'
...
def testContentCreation(self):
print '3'
...
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
At first, I thought the tests would run in order and the 2nd function would continue off where the first one left off, but I've found this is not the case, it seems to be starting over with each test. I've also realized that they execute in reverse order. I get an output of 3,2,1 in the terminal. How should I achieve what I want? If I call the previous functions before I run the one I want, I feel like it's repetitively testing the same thing over and over since each one is a test (eg, in testContentCreation, I would call 'testLogin' then call testFolderCreation and inside testFolderCreation call testLogin. If I were to do more, the testLogin would've been called a number of times!). Should I instead turn the previous steps into regular non-test functions and in the final last one (the test function) call the previous ones in order? If I do it that way then I guess if any of the steps fail, the last one fails, there would be one big test function.
Any suggestions on how you should write this type of test?
Also, why are the tests running in reverse order?
Thanks!
You are seeing what you are seeing, I think, because you are making some incorrect assumptions about the assumptions unittest makes. Each test case is assumed to be a self-contained entity, so there is no run order imposed. In addition, SetUp() and TearDown() operate before and after each individual case. If you want global setup/teardown, you need to make classmethods named SetUpClass() and TearDownClass(). You may also want to look in to the TestSuite class. More here: http://docs.python.org/library/unittest.html
Keep in mind that when the unittest library does test discovery (reflects your testcase class to find the test cases to run), it is essentially limited to looking at the .__dict__ and dir() values for the object, which are inherently unordered.