<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Tom Moertel's Weblog: Tag nose</title>
    <link>http://blog.moertel.com/articles/tag/nose?tag=nose</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Quality rants on programming theory and stuff geeks like</description>
    <item>
      <title>Property checking with Python's nose testing framework</title>
      <description>&lt;p&gt;At work recently I was writing some tests with Python&amp;#8217;s out-of-the-box
unit-testing framework
&lt;a href="http://docs.python.org/lib/module-unittest.html"&gt;unittest&lt;/a&gt;.  I&amp;#8217;m new
to Python and accustomed to Perl and Haskell&amp;#8217;s testing frameworks,
which are lightweight and let you write tests without much
hoop-jumping.  In particular,
&lt;a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/"&gt;QuickCheck&lt;/a&gt; and
&lt;a href="http://search.cpan.org/dist/Test-LectroTest/"&gt;LectroTest&lt;/a&gt; make it easy
to test at the property level instead of the test-case level.
With unittest, I was having to write a lot of code
to get the same level of abstraction.&lt;/p&gt;


	&lt;p&gt;By &amp;#8220;property level,&amp;#8221; here&amp;#8217;s what I mean.  Say I&amp;#8217;m testing this thing,
let&amp;#8217;s call it a &lt;em&gt;subscriber pool&lt;/em&gt;.  It has two fundamental properties:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;strong&gt;Subscribe.&lt;/strong&gt; For all initial states of the pool, if you call &lt;em&gt;subscribe&lt;/em&gt;(&lt;em&gt;user&lt;/em&gt;), then, assuming there have been no other operations on the pool, &lt;em&gt;user&lt;/em&gt; must be in the pool.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Unsubscribe.&lt;/strong&gt; For all initial states of the pool, if you call &lt;em&gt;unsubscribe&lt;/em&gt;(&lt;em&gt;user&lt;/em&gt;), then, assuming there have been no other operations on the pool, &lt;em&gt;user&lt;/em&gt; must not be in the pool.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;That&amp;#8217;s it.  If my implementation satisfies both properties, it&amp;#8217;s
correct.  (This is a simplified version of my real testing problem,
which required additional property checks.)&lt;/p&gt;


	&lt;p&gt;To test whether my implementation satisfies each property, I must
write individual test cases that together &amp;#8220;cover&amp;#8221; the property.  For
example, to test whether the Subscribe property holds, I might write
four test cases:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;class SubscribeProperty(unittest.TestCase):

    def setUp(self):
        initialize_pool()

    def tearDown(self):
        destroy_pool()

    def testEmpty(self):
        load_pool_with_members([])
        subscribe("1")
        self.assert_("1" in pool_members())

    def testOtherGuyAlreadyInPool(self):
        load_pool_with_members(["2"])
        subscribe("1")
        self.assert_("1" in pool_members())

    def testSubscriberAlreadyInPool(self):
        load_pool_with_members(["1"])
        subscribe("1")
        self.assert_("1" in pool_members())

    def testSubscriberAndOtherGuyAlreadyInPool(self):
        load_pool_with_members(["1", "2"])
        subscribe("1")
        self.assert_("1" in pool_members())
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Every one of the test cases has the same form.  The repetition
makes me want to refactor the whole thing.&lt;/p&gt;


	&lt;p&gt;Okay, let&amp;#8217;s do it:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;INITIAL_POOL_STATES = [[], ["2"], ["1"], ["1", "2"]]

class SubscribeProperty(unittest.TestCase):

    def setUp(self):
        initialize_pool()

    def tearDown(self):
        destroy_pool()

    def testSubscribe(self):
        for case in INITIAL_POOL_STATES:
            self.setUp()
            try:
                load_pool_with_members(case)
                subscribe("1")
                self.assert_("1" in pool_members(), case)
            finally:
                self.tearDown()
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;We&amp;#8217;re fighting a bit with the testing framework because our notion of
when set-up and tear-down should occur doesn&amp;#8217;t match its own, but
otherwise our code is looking much more manageable.  In particular, if
we want to extend our property-check coverage with additional initial pool
states, we don&amp;#8217;t need to write additional tests; instead, we can just
extend a single list.&lt;/p&gt;


	&lt;p&gt;But we&amp;#8217;re only halfway done.  We must also check the Unsubscribe
property.  The code for it is virtually the same as for Subscribe, but
with &lt;em&gt;subscribe&lt;/em&gt; becoming &lt;em&gt;unsubscribe&lt;/em&gt; and &lt;em&gt;in&lt;/em&gt; becoming &lt;em&gt;not in&lt;/em&gt;.
Let&amp;#8217;s add it to our class:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;class SubscriberPoolProperties(unittest.TestCase):

    def setUp(self):
        initialize_pool()

    def tearDown(self):
        destroy_pool()

    def testSubscribe(self):
        for case in INITIAL_POOL_STATES:
            self.setUp()
            try:
                load_pool_with_members(case)
                subscribe("1")
                self.assert_("1" in pool_members(), case)
            finally:
                self.tearDown()

    def testUnsubscribe(self):
        for case in INITIAL_POOL_STATES:
            self.setUp()
            try:
                load_pool_with_members(case)
                unsubscribe("1")
                self.assert_("1" not in pool_members(), case)
            finally:
                self.tearDown()
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And now let&amp;#8217;s factor out the new redundancy:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;class SubscriberPoolProperties(unittest.TestCase):

    def setUp(self):
        initialize_pool()

    def tearDown(self):
        destroy_pool()

    def testSubscribe(self):
        def testfn(case):
            subscribe("1")
            self.assert_("1" in pool_members(), case)
        self._forall_test_cases(testfn)

    def testUnsubscribe(self):
        def testfn(case):
            unsubscribe("1")
            self.assert_("1" not in pool_members(), case)
        self._forall_test_cases(testfn)

    def _forall_test_cases(self, testfn):
        for case in INITIAL_POOL_STATES:
            self.setUp()
            try:
                load_pool_with_members(case)
                testfn(case)
            finally:
                self.tearDown()
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;It&amp;#8217;s not bad, but it&amp;#8217;s not great either.  There&amp;#8217;s still a
lot of noise in that code.&lt;/p&gt;


	&lt;p&gt;After discussing the situation with my more-Pythonic
colleague &lt;a href="http://apipes.blogspot.com/"&gt;Tim Lesher&lt;/a&gt;, I took his
advice to check out the &lt;a href="http://somethingaboutorange.com/mrl/projects/nose/"&gt;nose testing framework&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;One of the things I liked right away about nose was that it supports
&lt;a href="http://somethingaboutorange.com/mrl/projects/nose/#test-generators"&gt;test
generators&lt;/a&gt;,
which would let me represent each property-check as a generator that
yields the test cases needed to check the property.  Also, set-up and
tear-down would automatically occur per &lt;em&gt;generated&lt;/em&gt; test, so I
wouldn&amp;#8217;t have to invoke them manually.&lt;/p&gt;


	&lt;p&gt;Once I got familiar with nose, it was easy to create a decorator to
represent the forall-test-cases idiom:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;def forall_cases(cases):
    def decorate(testfn):
        def gen():
            for case in cases:
                yield testfn, case
        gen.__name__ = "test_%s_for_a_case" % testfn.__name__
        return gen
    return decorate
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Note that this decorator is not specific to our subscriber-pool tests.
It can be used in any situation where we need to check a property
across a collection of cases.  In fact, I keep this little gem in a
&amp;#8220;nosehelpers&amp;#8221; library, where I reuse it all the time.  Here&amp;#8217;s an
example of how to use it to check the trivial property that
&lt;em&gt;x&lt;/em&gt;&amp;#160;=&amp;#160;&lt;em&gt;x&lt;/em&gt; for all &lt;em&gt;x&lt;/em&gt; in 0&amp;#8211;99:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;@forall_cases(range(100))
def check_self_equality(x):
    assert x == x
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, back to our testing problem.  Here&amp;#8217;s how we can use the
decorator to check the Subscribe property:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;@forall_cases(INITIAL_POOL_STATES)
@with_setup(initialize_pool, destroy_pool)
def check_subscribe(case):
    load_pool_with_members(case)
    subscribe("1")
    assert "1" in pool_members()
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;(The &lt;em&gt;with_setup&lt;/em&gt; decorator is defined by nose and tells nose to run
the given set-up and tear-down functions before and after each of the
generated test cases.)&lt;/p&gt;


	&lt;p&gt;Not bad.  The only problem I have with that code is that it mixes the
&amp;#8220;For all initial states of the pool&amp;#8221; part of the property definition
into the &amp;#8220;if you call &lt;em&gt;subscribe&lt;/em&gt;(&lt;em&gt;user&lt;/em&gt;), then &amp;#8230;&amp;#8221; part.  I&amp;#8217;d like
the code to be more explicit about which part defines the scope of the
property claim and which part defines the test for whether the claim
holds for any particular test case within that scope.&lt;/p&gt;


	&lt;p&gt;Fortunately, we can build upon our existing decorator to create
exactly what we need:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;def forall_initial_pools(testfn):
    @forall_cases(INITIAL_POOL_STATES)
    @with_setup(initialize_pool, destroy_pool)
    def setup_case_and_test_it(case):
        load_pool_with_members(case)
        testfn(case)
    setup_case_and_test_it.__name__ = \
        "test_%s_for_a_subscriber_case" % testfn.__name__
    return setup_case_and_test_it
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Here&amp;#8217;s what the decorator does.  When you apply it to a test function
&lt;em&gt;testfn&lt;/em&gt;, it returns a test generator that yields a property-check
test for each of the initial pool states.  For each, it sets up a new
pool, loads it with the initial subscribers (as given by the
corresponding test case), runs the given check function &lt;em&gt;testfn&lt;/em&gt;, and
then cleans up after itself.&lt;/p&gt;


	&lt;p&gt;With this decorator, our Pythonic property definitions now mirror
the human-language definitions from the start of the article:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;@forall_initial_pools
def check_subscribe(case):
    subscribe("1")
    assert "1" in pool_members()

@forall_initial_pools
def check_unsubscribe(case):
    unsubscribe("1")
    assert "1" not in pool_members()
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And that&amp;#8217;s pretty much the solution I ended up using at work.  There,
as opposed to here, I got to reuse my decorators for many more tests,
making them all the more worth their small implementation price.&lt;/p&gt;</description>
      <pubDate>Wed, 19 Mar 2008 22:34:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:48416d65-7ef2-4453-9adc-6ee13f8e85b3</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2008/03/19/property-checking-with-pythons-nose-testing-framework</link>
      <category>testing</category>
      <category>testing</category>
      <category>python</category>
      <category>nose</category>
      <category>unittest</category>
      <category>properties</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/707</trackback:ping>
    </item>
  </channel>
</rss>
