<?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>Belchak.com &#187; Uncategorized</title>
	<atom:link href="http://www.belchak.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.belchak.com</link>
	<description>Technology and Awesome</description>
	<lastBuildDate>Sat, 21 Jan 2012 19:25:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Unit Testing Your Django Application</title>
		<link>http://www.belchak.com/2011/02/05/unit-testing-your-django-application/</link>
		<comments>http://www.belchak.com/2011/02/05/unit-testing-your-django-application/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 04:33:40 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.belchak.com/?p=24</guid>
		<description><![CDATA[Unit testing is a very important part of any software project. It helps you know that the new code you are deploying works, and isn&#8217;t going to blow up in your face. It also helps you feel good about changing large chunks of code without destroying everything you&#8217;ve done for the last 3 years. Unit [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Unit testing is a very important part of any software project. It helps you know that the new code you are deploying works, and isn&#8217;t going to blow up in your face. It also helps you feel good about changing large chunks of code without destroying everything you&#8217;ve done for the last 3 years.</p>
<p>Unit testing with django is as simple as pie. <a href="http://docs.djangoproject.com/en/dev/topics/testing/" target="_blank">The documentation</a> is very good, and you can learn a lot about more advanced testing methods from <a href="http://docs.python.org/library/unittest.html" target="_blank">the python documentation</a>. In this blog post, I aim to show a quick way to get up and running with testing your django application.</p>
<p>First, if you are just starting out, make sure you put a high emphasis on testing your application, otherwise you are going to end up with a bunch of code that has never been tested and you will find yourself writing code for weeks just to get partial coverage on the code you&#8217;ve already written. Starting off on the right foot is a much better approach, and you will find life much more enjoyable.</p>
<p>Let&#8217;s get started&#8230;<br />
<span id="more-24"></span></p>
<p>First of all, you need to define your models:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">db</span> <span style="color: #ff7700;font-weight:bold;">import</span> models
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">contrib</span>.<span style="color: black;">auth</span>.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> User
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Post<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    title = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">50</span><span style="color: black;">&#41;</span>
    body = models.<span style="color: black;">TextField</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    author = models.<span style="color: black;">ForeignKey</span><span style="color: black;">&#40;</span>User, related_name=<span style="color: #483d8b;">&quot;news_post&quot;</span><span style="color: black;">&#41;</span>
    date = models.<span style="color: black;">DateTimeField</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    users_read = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>User, related_name=<span style="color: #483d8b;">&quot;users&quot;</span>, blank=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>  
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__str__</span><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;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">title</span></pre></td></tr></table></div>

<p>What we have done here is created a news post item. Let&#8217;s test it!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> PostTestCase<span style="color: black;">&#40;</span>TestCase<span style="color: black;">&#41;</span>:
    fixtures = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'test_data.json'</span><span style="color: black;">&#93;</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: #dc143c;">user</span> = User.<span style="color: black;">objects</span>.<span style="color: black;">create_user</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'newsposter'</span>, 
                                             <span style="color: #483d8b;">'newsposter@news.com'</span>, <span style="color: #483d8b;">'newspass'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">post</span> = Post.<span style="color: black;">objects</span>.<span style="color: black;">create</span><span style="color: black;">&#40;</span>title=<span style="color: #483d8b;">&quot;Test Post #1&quot;</span>,
                body=<span style="color: #483d8b;">&quot;Test Post #1 Body&quot;</span>,
                author=<span style="color: #008000;">self</span>.<span style="color: #dc143c;">user</span>,
                date=<span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">now</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">c</span> = Client<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> test_post_creation<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;
        Tests that we can create a Post
        &quot;&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertEqual</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">post</span>.<span style="color: black;">title</span>, <span style="color: #483d8b;">&quot;Test Post #1&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertEqual</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">post</span>.<span style="color: black;">author</span>, <span style="color: #008000;">self</span>.<span style="color: #dc143c;">user</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> test_user_can_read<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;
        Tests that a user is allowed to read.
        &quot;&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">c</span>.<span style="color: black;">login</span><span style="color: black;">&#40;</span>username=<span style="color: #483d8b;">'newsposter'</span>, password=<span style="color: #483d8b;">'newspass'</span><span style="color: black;">&#41;</span>
        response = <span style="color: #008000;">self</span>.<span style="color: black;">c</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'/news/get_post/1/'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertEqual</span><span style="color: black;">&#40;</span>response.<span style="color: black;">status_code</span>, <span style="color: #ff4500;">200</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertNotEqual</span><span style="color: black;">&#40;</span>response.<span style="color: black;">content</span>, <span style="color: #483d8b;">'{}'</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>One of the really cool thing about testing with django is that it comes with a testing client that allows you to make requests just like a real user would. As you can see in our <code>test_user_can_read()</code> method, we have used the client to make a GET request against a URL. You can make a POST request just as easily:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="python" style="font-family:monospace;">    <span style="color: #ff7700;font-weight:bold;">def</span> test_i_read_this<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;
        Tests a new user marking the story as read.
        &quot;&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">c</span>.<span style="color: black;">login</span><span style="color: black;">&#40;</span>username=<span style="color: #483d8b;">'newsposter'</span>, password=<span style="color: #483d8b;">'newspass'</span><span style="color: black;">&#41;</span>
        response = <span style="color: #008000;">self</span>.<span style="color: black;">c</span>.<span style="color: black;">post</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'/news/read/1/'</span>, <span style="color: black;">&#123;</span><span style="color: #483d8b;">'add'</span>:<span style="color: #008000;">True</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertEqual</span><span style="color: black;">&#40;</span>response.<span style="color: black;">status_code</span>, <span style="color: #ff4500;">200</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">assertEquals</span><span style="color: black;">&#40;</span>response.<span style="color: black;">content</span>, <span style="color: #483d8b;">'{<span style="color: #000099; font-weight: bold;">\n</span>    &quot;read&quot;: true<span style="color: #000099; font-weight: bold;">\n</span>}'</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>In the previous code sample, the client sends a POST request to <code>/news/read/1/</code> with the <code>{'add':True}</code> data. This gets converted to form data and submitted via the POST. The request returns back JSON, which we match up against what we expect it to return.</p>
<p>Here are some things to remember when you are writing your test cases:</p>
<ul>
<li><code>setUp()</code> gets called before <strong>every</strong> test method in your TestCase.</li>
<li><code>tearDown()</code> gets called after <strong>every</strong> test method in your TestCase.</li>
<li>Test methods <strong>must</strong> start with &#8220;test&#8221; otherwise they will not be executed. It is safe to have other methods in your TestCase that do not begin with &#8220;test&#8221; if you want to abstract functionality for multiple test methods into a single function.</li>
<li>Django creates a test database for you, populates it, runs any south migrations (if you are using south), and then destroys it.</li>
<li>Do not expect that data that is available in one of your test methods will be available in another. Each test method starts with a blank data slate. If you need data instantiated before your tests are run, consider using the <code>setUp()</code> and <code>tearDown()</code> methods, or using fixtures. You can specify fixtures other than your initial_data fixtures by adding <code>fixtures = ['test_data.json']</code> to your TestCase class.</li>
</ul>
<p>Here is in-depth documentation about what assert methods are available to you in different versions of Python in <a href="http://docs.python.org/library/unittest.html#test-cases">the official Python unittest documentation</a>.</p>
<p>As you can see, testing with django is really really simple, but very powerful. In my next post, I will discuss how to test django with a MongoDB backend that does not use the ORM.</p>
<div class="shr-publisher-24"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.belchak.com/2011/02/05/unit-testing-your-django-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

