I'm trying to solve a bug in django. The bug involves a class called TextContextDecorator
which can be used a class decorator and/or context manager.
As the bug description mentions, when using TextContextDecorator
as class decorator enable
is called just before Test.setUp
, and disable
is called after Test.tearDown
.unfortunately, tearDown
is not called in the event of a failure inside setUp
. This can result in unexpected behaviour.
One of the proposed solutions is that to use addCleanUp
inside the setUp
of TestContextDecorator
, but I'm having difficulties in calling that function inside of decorator class.
Here is the sample code provided to reproduce the bug..
class example_decorator(TestContextDecorator):
some_var = False
def enable(self):
self.__class__.some_var = True
def disable(self):
self.__class__.some_var = False
class Example1TestCase(TestCase):
def test_var_is_false(self):
# some_var will be False
self.assertFalse(example_decorator.some_var)
@example_decorator()
class Example2TestCase(TestCase):
def setUp(self):
raise Exception
def test_var_is_true(self):
# won't be hit due to exception in setUp
self.assertTrue(example_decorator.some_var)
class Example3TestCase(TestCase):
def test_var_is_false(self):
# some_var will be True now due to no cleanup in Example2TestCase
self.assertFalse(example_decorator.some_var)
So far i have used try
and except
inside the setUp
of TestContextDecorator
and that seems to solve the bug but i'm not sure if its the best way to do it. Here are the changes i made (i have added try
and except
on line 30 of code provided in the link).
Question: What would be the correct way to run a function similar to tearDown
in the event of failure inside setUp
of Test when in a context manager? Is the try
and except
method that i used correct? or can we actually use addCleanup
inside of setUp
of TestContextDecorator
?