<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Reliably Broken &#187; with</title>
	<atom:link href="http://reliablybroken.com/b/tag/with/feed/" rel="self" type="application/rss+xml" />
	<link>http://reliablybroken.com/b</link>
	<description>It&#039;s a blog: let&#039;s do funch!</description>
	<lastBuildDate>Sat, 31 Jul 2010 01:07:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Context managers</title>
		<link>http://reliablybroken.com/b/2009/12/context-managers/</link>
		<comments>http://reliablybroken.com/b/2009/12/context-managers/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 15:10:45 +0000</pubDate>
		<dc:creator>david</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[with]]></category>

		<guid isPermaLink="false">http://reliablybroken.com/b/?p=367</guid>
		<description><![CDATA[I was re-writing the exellent watchedinstall tool and needed to simplify a particularly gnarly chunk of code that required three sub-proceses to be started and then killed after invoking another process. It occurred to me I could make these into context managers.

Previously the code was something like&#8230;

start(program1)
try:
    start(program2)
except:
    stop(program1)
 [...]]]></description>
			<content:encoded><![CDATA[<p>I was re-writing the exellent <a href="http://bitbucket.org/ptone/watchedinstall/">watchedinstall</a> tool and needed to simplify a particularly gnarly chunk of code that required three sub-proceses to be started and then killed after invoking another process. It occurred to me I could make these into context managers.</p>

<p>Previously the code was something like&#8230;</p>

<pre><code>start(program1)
try:
    start(program2)
except:
    stop(program1)
    raise

try:
    start(program3)
except:
    stop(program2)
    stop(program1)
    raise

try:
    mainprogram()
finally:
    stop(program3)
    stop(program2)
    stop(program1)
</code></pre>

<p>Of course that could have been written with nested try / except / else / finally blocks as well, which I did start with but found not much shorter while almost incomprehensible.</p>

<p><a href="http://docs.python.org/library/stdtypes.html#typecontextmanager">With context managers</a> the whole thing was written as&#8230;</p>

<pre><code># from __future__ import with_statement, Python 2.5

with start(program1):
    with start(program2):
        with start(program3):
            mainprogram()
</code></pre>

<p>So much more comprehensible! Here&#8217;s the implementation of the context manager (using the <code>contextlib.contextmanager</code> decorator for a triple word score):</p>

<pre><code>import contextlib
import os
import signal
import subprocess


@contextlib.contextmanager
def start(program_args):
    prog = subprocess.Popen(program_args)
    if prog.poll(): # Anything other than None or 0 is BAD
        raise subprocess.CalledProcessError(prog.returncode, program_args[0])

    try:
        yield
    finally:
        if prog.poll() is None:
            os.kill(prog.pid, signal.SIGTERM)
</code></pre>

<p>For bonus points I might have used <a href="http://docs.python.org/library/contextlib.html"><code>contexlib.nested()</code></a> to put the three <code>start()</code> calls on one line but then what would I do for the rest of the day?</p>
]]></content:encoded>
			<wfw:commentRss>http://reliablybroken.com/b/2009/12/context-managers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django test database runner as a context manager</title>
		<link>http://reliablybroken.com/b/2009/03/django-test-database-runner-as-a-context-manager/</link>
		<comments>http://reliablybroken.com/b/2009/03/django-test-database-runner-as-a-context-manager/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 00:07:45 +0000</pubDate>
		<dc:creator>david</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[with]]></category>

		<guid isPermaLink="false">http://reliablybroken.com/b/?p=98</guid>
		<description><![CDATA[In my last post I mentioned it might be an idea to wrap up the Django test
database setup / teardown in a context manager for use with Python&#8217;s
with statement. Here&#8217;s my first stab, which seems to work.

from contextlib import contextmanager


@contextmanager
def test_db_connection():
    """A context manager for Django's test runner.

    For [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I mentioned it might be an idea to <a href="http://reliablybroken.com/b/2009/03/creating-a-django-test-database-for-unit-testing/">wrap up the Django test
database setup / teardown in a context manager</a> for use with <a href="http://docs.python.org/reference/datamodel.html#context-managers">Python&#8217;s
<code>with</code> statement</a>. Here&#8217;s my first stab, which seems to work.</p>

<pre><code>from contextlib import contextmanager


@contextmanager
def test_db_connection():
    """A context manager for Django's test runner.

    For Python 2.5 you will need
        from __future__ import with_statement
    """

    from django.conf import settings
    from django.test.utils import setup_test_environment, teardown_test_environment
    from django.db import connection

    setup_test_environment()

    settings.DEBUG = False    
    verbosity = 0
    interactive = False

    old_name = settings.DATABASE_NAME
    connection.creation.create_test_db(verbosity, autoclobber=not interactive)

    yield connection

    connection.creation.destroy_test_db(old_name, verbosity)
    teardown_test_environment()
</code></pre>

<p>All of this requires Python 2.5 or later.</p>

<p>So with that snippet you could write a test something like so:</p>

<pre><code>import unittest


class MyTestCase(unittest.TestCase):
    def test_myModelTest(self):
        with test_db_connection():
            from myproject.myapp.models import MyModel

            obj = MyModel()
            obj.save()
            self.assert_(obj.pk)
</code></pre>

<p>&#8230; and just as with Django&#8217;s <code>manage.py test</code> command the objects would be
created within the test database then destroyed when the
<code>with test_db_connection()</code> block is finished.</p>

<p>Everything&#8217;s going to be hunky dory.</p>
]]></content:encoded>
			<wfw:commentRss>http://reliablybroken.com/b/2009/03/django-test-database-runner-as-a-context-manager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
