[TIP] context manager and setUp/tearDown

Michael Foord michael at voidspace.org.uk
Mon Feb 11 12:55:33 PST 2013


On 11 Feb 2013, at 17:59, Ned Batchelder <ned at nedbatchelder.com> wrote:

> On 2/11/2013 5:38 AM, andrea crotti wrote:
>> I created a context manager to create a temporary database to play
>> around in couchdb, like this:
>> 
>> __metaclass__ = type
>> """
>> Utilities functions manipulate the database
>> """
>> 
>> from couchdbkit import Server
>> 
>> TEMP_DB = 'unit_test_database'
>> LOCAL_URI = 'http://localhost:5984'
>> 
>> 
>> class TemporaryDb:
>>     def __init__(self):
>>         self.server = Server(LOCAL_URI)
>> 
>>     def _remove_if_there(self):
>>         if TEMP_DB in self.server.all_dbs():
>>             self.server.delete_db(TEMP_DB)
>> 
>>     def __enter__(self):
>>         self._remove_if_there()
>>         return self.server.create_db(TEMP_DB)
>> 
>>     def __exit__(self, type, value, traceback):
>>         self._remove_if_there()
>> 
>> Now I want to use it in my unit tests, and I have a "problem" which I
>> already saw other times, how do I use it nicely with setUp/tearDown?
>> 
>> This basically works but I don't like it very much..
>> 
>> class TestCouchOo(unittest.TestCase):
>>     """Create a CouchObject and test storing the various values
>>     """
>>     def setUp(self):
>>         self.temp = TemporaryDb()
>>         self.db = self.temp.__enter__()
>> 
>>     def tearDown(self):
>>         self.temp.__exit__(None, None, None)
> 
> I have been in this same situation, and refactored my context manager to be based on an object which I could then use with unittest.TestCase.addCleanup().  But now I wonder about code like this instead (untested):
> 
> class TestCaseMixin(object):
>    def setup_context_manager(self, cm):
>        val = cm.__enter__()
>        self.addCleanup(functools.partial(cm.__exit__, None, None, None))


Or even:

	self.addCleanup(cm.__exit__, None, None, None)

(I believe.)

Michael

>        return val
> 
> Then you can add this to a test case class, and use this:
> 
>    def setUp(self):
>        self.temp = self.setup_context_manager(TemporaryDb())
> 
> and it will be cleaned up automatically
> 
> --Ned.
> 
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>> 
> 
> 
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
> 


--
http://www.voidspace.org.uk/


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing 
http://www.sqlite.org/different.html








More information about the testing-in-python mailing list