[TIP] context manager and setUp/tearDown
andrea crotti
andrea.crotti.0 at gmail.com
Mon Feb 11 02:38:35 PST 2013
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)
More information about the testing-in-python
mailing list