[TIP] context manager and setUp/tearDown

Chris Jerdonek chris.jerdonek at gmail.com
Mon Feb 11 11:11:32 PST 2013


On Mon, Feb 11, 2013 at 2:38 AM, andrea crotti
<andrea.crotti.0 at gmail.com> 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?

I filed an issue in the Python tracker some months ago to address
precisely this use case:

http://bugs.python.org/issue15351

For discussion purposes, I proposed an API on TestCase (along with a
working patch) that would let one use context managers as is.

One thing that hasn't been addressed by other responders is context
managers coming from an outside source (that you might not have the
luxury of modifying).

--Chris


>
> 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)
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python



More information about the testing-in-python mailing list