<?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>Mike&#039;s Blabberings &#187; patterns</title>
	<atom:link href="http://www.mike-griffith.com/blog/tag/patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mike-griffith.com/blog</link>
	<description>on software, testing, and the web.</description>
	<lastBuildDate>Tue, 29 Jun 2010 14:37:52 +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>Python decorators, SRP, and testability</title>
		<link>http://www.mike-griffith.com/blog/2010/06/python-decorators-srp-and-testability/</link>
		<comments>http://www.mike-griffith.com/blog/2010/06/python-decorators-srp-and-testability/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 06:30:02 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[software development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.mike-griffith.com/blog/?p=504</guid>
		<description><![CDATA[On the SRP:
For those unfamiliar with the Single Responsibility Principle (SRP), it states that there should never be more than one reason for a class to change.
That is to say: do one thing, do it well.
Decorators (not to be confused with the decorator pattern) can add behaviors or side-effects to a method, and this can [...]]]></description>
			<content:encoded><![CDATA[<p><strong>On the SRP:</strong><br />
For those unfamiliar with the <a href="http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" target="_blank">Single Responsibility Principle</a> (SRP), it states that <em>there should never be more than one reason for a class to change</em>.</p>
<p>That is to say: do one thing, do it well.</p>
<p><a href="http://www.python.org/dev/peps/pep-0318/" target="_blank">Decorators</a> (not to be confused with the <a href="http://en.wikipedia.org/wiki/Decorator_pattern" target="_blank">decorator pattern</a>) can add behaviors or side-effects to a method, and this can be dangerous.  It seems harmless, because by adding a decorator, you&#8217;re likely taking boilerplate code and shuffling it elsewhere.  However, they often encourage badness because of how easy it is to add these behaviors.</p>
<p><strong>On testing decorated methods:</strong></p>
<p>Adding an @decorator to a python object unarguably makes the undecorated code difficult to test in isolation.  Decorators are applied at compile-time, and cannot be mocked or made to not-execute without some pain.</p>
<p>There are certainly a few common tricks that can help test a decorated method with minimal side-effects, but they require changes to the decorator itself.  There&#8217;s just plain and simple no way to un-decorate a method for isolated testing.</p>
<p><strong>Let&#8217;s look at a few common examples:</strong></p>
<p><strong><em>@expose</em></strong>: register a URL for a view function in a web framework</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> BlogPostController<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @expose<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;/blog/{post_id}&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> index<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, request, post_id=<span style="color: #008000;">None</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot; show a blog post &quot;&quot;&quot;</span>
        post = adapter.<span style="color: black;">get_post</span><span style="color: black;">&#40;</span>post_id<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> render<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;show_entry.html&quot;</span>, <span style="color: #008000;">dict</span><span style="color: black;">&#40;</span>post=post<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Without the `@expose`, your `show_entry` knows how to get a given post and render it in the proper template.  With the decorator, it also now knows which URL corresponds to that.  You now have multiple reasons for this block of code to change, including pointing to a different URL or using a different template.  It&#8217;s preferred to have a separate module for managing which urls point to which views.</p>
<p>Harm factor: low.  Ick factor: medium &#8211; high.</p>
<p><strong><em>@cache</em></strong>: try to get the result from memcache, otherwise, execute the function and stick it in cache for next time</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> PostAdapter<span style="color: black;">&#40;</span>DataAdapter<span style="color: black;">&#41;</span>:
    @cache
    <span style="color: #ff7700;font-weight:bold;">def</span> get_post<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, post_id<span style="color: black;">&#41;</span>
        <span style="color: #483d8b;">&quot;&quot;&quot; grab a blog post from the database &quot;&quot;&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Post<span style="color: black;">&#41;</span>.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span>=post_id<span style="color: black;">&#41;</span>.<span style="color: black;">one</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;"># SQLAlchemy folks need to talk to Mr Demeter...</span></pre></div></div>

<p>OK this seems cool right?  You only hit the database when you have to, otherwise we get it even quicker by looking it up in the cache.</p>
<p>What happens if you want to disable caching?  A separate cache abstraction layer would reduce volatility in your data adapter.</p>
<p>And what does the unit test look like?</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> TestGettingAPost<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> setup<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">query</span> = Mock<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;">#don't hit the production database!</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">post_adapter</span> = PostAdapter<span style="color: black;">&#40;</span>query=<span style="color: #008000;">self</span>.<span style="color: black;">query</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> test_getting_a_post<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">assert</span> <span style="color: #008000;">self</span>.<span style="color: black;">post_adapter</span>.<span style="color: black;">get_post</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">123</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Damn, there&#8217;s no way to mock out the @cache decorator so it doesn&#8217;t run.  Try to, I dare you.  You&#8217;re likely going to actually get post 123 from your production memcache.  Crappy.  The only thing you can do is make the @cache grab the cache implementation from the PostAdapter instance (and mock that out in you test), or find some other sneaky way of disabling caching for test runs.  But the @cache decorator isn&#8217;t all self-contained and fun anymore.</p>
<p>Harm factor: medium &#8211; high.</p>
<p><strong><em>@validate</em></strong>: Make sure the request matches the specified schema, otherwise hand-off to error handler</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> EditPostController<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> _save_error<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, request, errors<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot; @validate decorator kicked flow here, redisplay edit page with errors &quot;&quot;&quot;</span>
        ...
    @validate<span style="color: black;">&#40;</span>schema, error_handler=_save_error<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> save<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, request<span style="color: black;">&#41;</span>
        post = <span style="color: #008000;">self</span>.<span style="color: black;">schema</span>.<span style="color: black;">to_python</span><span style="color: black;">&#40;</span>request.<span style="color: black;">params</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">post_adapter</span>.<span style="color: black;">save_post</span><span style="color: black;">&#40;</span>post<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> redirect<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;/blog/{0}&quot;</span>.<span style="color: black;">format</span><span style="color: black;">&#40;</span>post_id<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Without this @validate, there would be a lot of boilerplate code inside the `save` method.  With it, any unit test for the save method will be likely linked to your schema.  You&#8217;d have to make an actual valid request in order to test this method.  That&#8217;s outside of any tests for your schema directly. That means double-coverage but 2 tests to update when requirements shift.</p>
<p>Harm factor: low-medium</p>
<p><strong>Conclusions (or tl;dr):</strong></p>
<p>As easy as it is to become infatuated with Python decorators, they definitely encourage you to violate the SRP.  This can create a myriad of problems:</p>
<ul>
<li>Difficultly in isolating system under test</li>
<li>Added complexity to enable testing</li>
<li>Redundant redundant unit tests</li>
<li>Making a code module more volatile than it ought to</li>
</ul>
<p>They still have some valid use cases and can lead to cleaner code, however,  as Master Yoda once said, &#8220;when you look at the dark side, careful you must be&#8230;&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mike-griffith.com/blog/2010/06/python-decorators-srp-and-testability/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Including external data with your unit tests</title>
		<link>http://www.mike-griffith.com/blog/2009/01/including-external-data-with-your-unit-tests/</link>
		<comments>http://www.mike-griffith.com/blog/2009/01/including-external-data-with-your-unit-tests/#comments</comments>
		<pubDate>Tue, 13 Jan 2009 20:06:21 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[software development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.mike-griffith.com/blog/?p=191</guid>
		<description><![CDATA[We generally preach that you should not use real data in your unit tests.  You should instead mock said data out in an effort to lesson potential side-effects, including degrading test performance and adversely affecting live data.
Sometimes, you&#8217;d like to test actual file handling in a unit test.  If you do, you should [...]]]></description>
			<content:encoded><![CDATA[<p>We generally preach that you should not use real data in your unit tests.  You should instead mock said data out in an effort to lesson potential side-effects, including degrading test performance and adversely affecting live data.</p>
<p>Sometimes, you&#8217;d like to test actual file handling in a unit test.  If you do, you should provide a sample data set packaged with your code in a data directory within your test directory.</p>
<p>Your package would then resemble the following structure:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">/package
    /tests
        /data
            data.txt
        __init__.py
        test_module.py
    __init__.py
    module.py</pre></div></div>

<p>In your test, you&#8217;ll need to provide a relative path to the data file.  To do this, use the special <code>__file__</code> attribute of the package to provide a starting point.  This will let you know where the module lives on disk regardless of where the package is installed.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">from</span> package.<span style="color: black;">tests</span> <span style="color: #ff7700;font-weight:bold;">import</span> __file__ <span style="color: #ff7700;font-weight:bold;">as</span> test_directory
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> _data_dir<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>test_directory<span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'data'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> test_sample_data<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    file_path = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>_data_dir<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'data.txt'</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">with</span> <span style="color: #008000;">open</span><span style="color: black;">&#40;</span>file_path<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">as</span> f:
        package.<span style="color: black;">module</span>.<span style="color: black;">do_something</span><span style="color: black;">&#40;</span>f<span style="color: black;">&#41;</span></pre></div></div>

<p>There you have it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mike-griffith.com/blog/2009/01/including-external-data-with-your-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decorate a method with Dojo</title>
		<link>http://www.mike-griffith.com/blog/2008/10/decorator-pattern-in-dojo/</link>
		<comments>http://www.mike-griffith.com/blog/2008/10/decorator-pattern-in-dojo/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 18:54:35 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[software development]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.mike-griffith.com/blog/?p=112</guid>
		<description><![CDATA[Here&#8217;s a quick example of how to incorporate the Decorator Pattern into your javascript code using the Dojo framework.  Rather than decorating an entire class, this example merely decorates a single function, extending the original function with some extra logic.

// Instantiate widget class
var w = new core.widget.MyWidget&#40;&#41;;
&#160;
// Decorate the original &#34;method1&#34; function
var _old_method1 = [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick example of how to incorporate the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator Pattern</a> into your javascript code using the Dojo framework.  Rather than decorating an entire class, this example merely decorates a single function, extending the original function with some extra logic.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Instantiate widget class</span>
<span style="color: #003366; font-weight: bold;">var</span> w <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> core.<span style="color: #660066;">widget</span>.<span style="color: #660066;">MyWidget</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Decorate the original &quot;method1&quot; function</span>
<span style="color: #003366; font-weight: bold;">var</span> _old_method1 <span style="color: #339933;">=</span> dojo.<span style="color: #660066;">hitch</span><span style="color: #009900;">&#40;</span>w<span style="color: #339933;">,</span> w.<span style="color: #660066;">method1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
w.<span style="color: #660066;">method1</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> out <span style="color: #339933;">=</span> _old_method1<span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Decorations</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>param <span style="color: #339933;">==</span> <span style="color: #3366CC;">'foo'</span> <span style="color: #339933;">||</span> out <span style="color: #339933;">==</span> <span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'calling method2 as result of method1'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">method2</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'baz'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A few key points:</p>
<ul>
<li>dojo.hitch &#8211; used to provide proper context to the base &#8220;method1&#8243;, so that if anything relies on &#8220;this.&#8221; it will be handled as expected</li>
<li>The decorations can be applied either before or after the base method is called.  In the example, I chose to apply them after the base method to enable reaction based on the output.</li>
</ul>
<p>You may notice that this is a much uglier implementation than the coffee and condiments example in the linked Wikipedia article.  The wrap-add-and-return methodology didn&#8217;t work for me due to some class complexities and black magic.  There may be a better way, perhaps even built into the dojo class wizardry, but this fit my use case well enough.</p>
<p>A coworker pointed out that Dojo now has the fancy shmansy dojox.aspect package to deal with this.  And I found a <a href="http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/">great article detailing the new aspect wizardry in dojo</a>.  So my example could be revised using AOP, as follows.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Instantiate widget class</span>
<span style="color: #003366; font-weight: bold;">var</span> w <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> core.<span style="color: #660066;">widget</span>.<span style="color: #660066;">MyWidget</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Create an aspect to wrap the method</span>
dojo.<span style="color: #660066;">require</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;dojox.lang.aspect&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> aop <span style="color: #339933;">=</span> dojox.<span style="color: #660066;">lang</span>.<span style="color: #660066;">aspect</span><span style="color: #339933;">;</span>
aop.<span style="color: #660066;">advise</span><span style="color: #009900;">&#40;</span>w<span style="color: #339933;">,</span> <span style="color: #3366CC;">'method1'</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>around<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> out <span style="color: #339933;">=</span> aop.<span style="color: #660066;">proceed</span><span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Decorations</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>param <span style="color: #339933;">==</span> <span style="color: #3366CC;">'foo'</span> <span style="color: #339933;">||</span> out <span style="color: #339933;">==</span> <span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'calling method2 as result of method1'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">method2</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'baz'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.mike-griffith.com/blog/2008/10/decorator-pattern-in-dojo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
