[TIP] context manager and setUp/tearDown
Michael Foord
michael at voidspace.org.uk
Mon Feb 11 05:39:17 PST 2013
On 11 Feb 2013, at 10:38, 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?
>
> 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)
Context managers are designed to be called in a particular way. They *are not* suitable for every situation. So if you've created a context manager as your *only* api for particular functionality then this problem is the result. Create a nicer api to access the functionality you want. :-)
mock.patch provides start and stop methods for this kind of use case.
All the best,
Michael Foord
>
> _______________________________________________
> 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