[TIP] context manager and setUp/tearDown

Ronny Pfannschmidt Ronny.Pfannschmidt at gmx.de
Mon Feb 11 04:49:34 PST 2013


pytest-couchdbkit might be interesting for you

-- Ronny

On 02/11/2013 11: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)
>
> _______________________________________________
> 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