<?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>DestaqueBlog &#187; teste</title>
	<atom:link href="http://weblog.destaquenet.com/tag/teste/feed/" rel="self" type="application/rss+xml" />
	<link>http://weblog.destaquenet.com</link>
	<description>Blog da equipe Destaquenet.</description>
	<lastBuildDate>Tue, 23 Nov 2010 17:06:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>JsHamcrest: um alívio à dor de se testar código JavaScript</title>
		<link>http://weblog.destaquenet.com/2009/07/13/jshamcrest-um-alivio-a-dor-de-se-testar-codigo-javascript/</link>
		<comments>http://weblog.destaquenet.com/2009/07/13/jshamcrest-um-alivio-a-dor-de-se-testar-codigo-javascript/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 14:10:21 +0000</pubDate>
		<dc:creator>Daniel Martins</dc:creator>
				<category><![CDATA[Português]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[destaquenet]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jshamcrest]]></category>
		<category><![CDATA[jstestdriver]]></category>
		<category><![CDATA[jsunittest]]></category>
		<category><![CDATA[jsunity]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[projeto]]></category>
		<category><![CDATA[qunit]]></category>
		<category><![CDATA[teste]]></category>
		<category><![CDATA[yuitest]]></category>

		<guid isPermaLink="false">http://weblog.destaquenet.com/?p=584</guid>
		<description><![CDATA[Há não muito tempo atrás, escrever testes automatizados era coisa para poucos. Nem tanto por obstáculos técnicos, mas porque, na verdade, ninguém se importava muito com isso. A boa notícia é que a importância dos testes automatizados vem aumentando com &#8230; <a href="http://weblog.destaquenet.com/2009/07/13/jshamcrest-um-alivio-a-dor-de-se-testar-codigo-javascript/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Há não muito tempo atrás, escrever testes automatizados era coisa para poucos. Nem tanto por obstáculos técnicos, mas porque, na verdade, ninguém se importava muito com isso.</p>
<p>A boa notícia é que a importância dos testes automatizados vem aumentando com o tempo e hoje, felizmente, já não é mais necessário &#8220;vender&#8221; a idéia. O aumento absurdo de ferramentas destinadas a facilitar a aplicação desta prática é uma prova disso.</p>
<p>Falando em ferramentas, neste texto mostrarei o <a href="http://jshamcrest.destaquenet.com/">JsHamcrest</a>, um projeto <em>open source</em> desenvolvido pela <a href="http://www.destaquenet.com/">Destaquenet</a> cujo objetivo é fornecer uma versão incrementada, em JavaScript, da biblioteca <a href="http://code.google.com/p/hamcrest/">Hamcrest</a>. Para quem não conhece, Hamcrest é  uma <a href="http://code.google.com/p/hamcrest/wiki/Tutorial">biblioteca de <em>matchers</em></a> que permite que regras sejam definidas declarativamente para uso em outros <em>frameworks</em> e bibliotecas.</p>
<p><span id="more-584"></span></p>
<h3>Para apreciar é preciso antes viver sem</h3>
<p>Para dar uma idéia do quão útil JsHamcrest pode ser, segue abaixo um exemplo de suite de testes criado com <a href="http://docs.jquery.com/QUnit">QUnit</a>, ainda sem apoio do JsHamcrest, onde testamos o funcionamento de algumas funcionalidades da classe <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Literal&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        ok<span style="color: #009900;">&#40;</span>arr <span style="color: #000066; font-weight: bold;">instanceof</span> Array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        equals<span style="color: #009900;">&#40;</span>arr.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Reverse&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">reverse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        equals<span style="color: #009900;">&#40;</span>arr.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">// This assertion fails</span>
        <span style="color: #006600; font-style: italic;">// equals(arr, [5, 4, 3, 2, 1]);</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">// These assertions work, but in an ideal world you shouldn't do such a thing</span>
        <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> j <span style="color: #339933;">=</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> arr.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++,</span> j<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            equals<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> j<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;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Slice&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        equals<span style="color: #009900;">&#40;</span>arr.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">// This assertion fails</span>
        <span style="color: #006600; font-style: italic;">// equals(arr, [3, 4, 5]);</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">// These assertions work, but in an ideal world you shouldn't do such a thing</span>
        <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> arr.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            equals<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> i<span style="color: #339933;">+</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">// Another example of complex assertion</span>
        <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> arr.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            ok<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">3</span> <span style="color: #339933;">&amp;&amp;</span> arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&lt;=</span> <span style="color: #CC0000;">5</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;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O código, mesmo sendo feio e confuso, funciona:</p>
<div id="attachment_591" class="wp-caption aligncenter" style="width: 315px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit1.png"><img class="size-full wp-image-591 " title="Primeira versão da suite de testes" src="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit1.png" alt="Primeira versão da suite de testes" width="305" height="314" /></a><p class="wp-caption-text">Primeira versão da suite de testes</p></div>
<p>O código desta suite de testes está <a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/qunit_testsuite.zip">disponível para download</a>.</p>
<h3>(Muitas) Limitações</h3>
<p>O primeiro teste, que verifica o funcionamento do literal <code>[]</code>, foi muito simples de implementar até porque não há praticamente nada a ser testado. Mas não fique feliz; no mundo real, as chances de seus testes serem assim tão simples são muito baixas.</p>
<p>Isso começa a ficar evidente à partir do segundo teste, onde é preciso apelar para o bom (?) e velho <code>for</code> para conferir o conteúdo do array, uma vez que QUnit não os suporta em comparações de igualdade.</p>
<p>Obviamente a mesma coisa também acontece no terceiro teste. E para mostrar que a a sitiuação só tende a piorar, ainda no terceiro teste temos um outro exemplo de asserção (tão feio quanto) que verifica  se todos os elementos do array estão num determinado intervalo.</p>
<p>Infelizmente, a &#8220;feiura&#8221; não é a única coisa que incomoda nesse código. Para ilustrar, suponha que o terceiro teste estivesse quebrado:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Slice&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    equals<span style="color: #009900;">&#40;</span>arr.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// ...</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Another example of complex assertion</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;=</span> arr.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        ok<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">3</span> <span style="color: #339933;">&amp;&amp;</span> arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&lt;=</span> <span style="color: #CC0000;">5</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;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Como esperado, ao rodar os testes, o relatório mostra a ocorrência de um erro. O problema é que esse relatório faz um <em>péssimo</em> trabalho ao tentar mostrar o que de fato falhou:</p>
<div id="attachment_592" class="wp-caption aligncenter" style="width: 317px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_error1.png"><img class="size-full wp-image-592 " title="Relatório de erro não muito amigável" src="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_error1.png" alt="Relatório de erro não muito amigável" width="307" height="248" /></a><p class="wp-caption-text">Relatório de erro não muito amigável</p></div>
<p>Uma forma de se amenizar este problema é passar um texto descritivo aos métodos <code>ok()</code> e <code>equals()</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">ok<span style="color: #009900;">&#40;</span>num1 <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">3</span> <span style="color: #339933;">&amp;&amp;</span> num1 <span style="color: #339933;">&lt;=</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;Expected num1 between 3 and 5&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
equals<span style="color: #009900;">&#40;</span>num2<span style="color: #339933;">,</span> <span style="color: #CC0000;">10</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;Checking value of num2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O problema é que, ao fazer isso, passa a ser necessário um certo cuidado para manter os textos descritivos em sincronia com o código das asserções.</p>
<h4>Se QUnit é assim tão ruim&#8230;</h4>
<p>&#8230;por que não o trocar por outra coisa?</p>
<p>Apesar de existirem várias alternativas ao QUnit, nenhuma delas parece ser capaz de resolver problemas como os mostrados aqui. Portanto, trocar de <em>framework</em>, por enquanto, não é a solução.</p>
<p>Mas nem tudo está perdido.</p>
<h3>Viva melhor  com JsHamcrest</h3>
<p>O código mostrado anteriormente pode ser facilmente adaptado para usar JsHamcrest:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Integrates JsHamcrest with QUnit</span>
JsHamcrest.<span style="color: #660066;">Integration</span>.<span style="color: #660066;">QUnit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Literal&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">instanceOf</span><span style="color: #009900;">&#40;</span>Array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> empty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Reverse&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">reverse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> hasSize<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> equalTo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Slice&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> hasSize<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> equalTo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> everyItem<span style="color: #009900;">&#40;</span>between<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">and</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Gostou? <img src='http://weblog.destaquenet.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>A primeira coisa que salta aos olhos é a simplicidade do código. Basta uma olhada rápida para saber exatamente o que ele faz. Note que mesmo asserções mais complexas como as mostradas nos dois últimos testes são implementadas com facilidade.</p>
<p>O resultado:</p>
<div id="attachment_588" class="wp-caption aligncenter" style="width: 315px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_jshamcrest.png"><img class="size-full wp-image-588  " title="Relatório com dados detalhados das asserções" src="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_jshamcrest.png" alt="Testes com dados detalhados das asserções" width="305" height="239" /></a><p class="wp-caption-text">Relatório com dados detalhados das asserções</p></div>
<p>O código desta suite de testes está <a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/qunit_jshamcrest_testsuite.zip">disponível para download</a>.</p>
<p>E não é só isso. Ao mesmo tempo em que temos um vocabulário <em>riquíssimo</em> de asserções, JsHamcrest também fornece informações detalhadas sobre as mesmas, numa linguagem fácil de entender. E isso tudo isso sem <em>nenhum</em> esforço!</p>
<p>Mais informações sobre a  API podem ser encontradas no pacote de documentação do projeto, também <a href="http://github.com/danielfm/jshamcrest/downloads">disponível para download</a>.</p>
<p>Mas, e quanto ao problema do relatório de erro? Vamos quebrar uma asserção e  ver o que acontece:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">test<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Slice&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> hasSize<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> equalTo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> everyItem<span style="color: #009900;">&#40;</span>between<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">and</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">4</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O resultado:</p>
<div id="attachment_590" class="wp-caption aligncenter" style="width: 319px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_jshamcrest_error.png"><img class="size-full wp-image-590 " title="Mensagem de erro amigável" src="http://weblog.destaquenet.com/wp-content/uploads/2009/07/test_suite_qunit_jshamcrest_error.png" alt="Mensagem de erro amigável" width="309" height="202" /></a><p class="wp-caption-text">Mensagem de erro amigável</p></div>
<p>Muito melhor! Basta olhar a mensagem de erro para descobrir o que está errado.</p>
<h3>Posso usar JsHamcrest com outro <em>framework</em>?</h3>
<p>Atualmente, JsHamcrest integra com cinco <em>frameworks</em>: <a href="http://code.google.com/p/js-test-driver/">JsTestDriver</a>, <a href="http://jsunittest.com/">JsUnitTest</a>, <a href="http://jsunity.com/">jsUnity</a>, <a href="http://developer.yahoo.com/yui/yuitest/">YUITest</a> e QUnit.</p>
<p>Outra coisa legal é que integração feita pelo JsHamcrest leva em conta as convenções definidas pelo <em>framework</em> escolhido. Veja, por exemplo, como ficaria o código se tivéssemos optado pelo YUITest em vez do QUnit:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Integrates JsHamcrest and YUITest</span>
JsHamcrest.<span style="color: #660066;">Integration</span>.<span style="color: #660066;">YUITest</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
YAHOO.<span style="color: #003366; font-weight: bold;">namespace</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;array&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
YAHOO.<span style="color: #660066;">array</span>.<span style="color: #660066;">TestCase</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> YAHOO.<span style="color: #660066;">tool</span>.<span style="color: #660066;">TestCase</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">name</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Array tests&quot;</span><span style="color: #339933;">,</span>
&nbsp;
    testLiteral<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">instanceOf</span><span style="color: #009900;">&#40;</span>Array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> empty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    testReverse<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">reverse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> hasSize<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> equalTo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    testSlice<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> arr <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> hasSize<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> equalTo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Assert.<span style="color: #660066;">that</span><span style="color: #009900;">&#40;</span>arr<span style="color: #339933;">,</span> everyItem<span style="color: #009900;">&#40;</span>between<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">and</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</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;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h4>Mas meu <em>framework</em> predileto não está nessa lista&#8230;</h4>
<p>JsHamcrest pode vir a suportar outros <em>frameworks</em> no futuro. Se seu <em>framework</em> predileto não está na lista dos atualmente suportados, entre em contato conosco.</p>
<h3>E aí, o que achou?</h3>
<p>Gostou? Odiou? Tem sugestões de melhorias? Gostaríamos muito de ouvir sua opinião!</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.destaquenet.com/2009/07/13/jshamcrest-um-alivio-a-dor-de-se-testar-codigo-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fabric + VirtualEnv: uma combinação explosiva (no bom sentido)</title>
		<link>http://weblog.destaquenet.com/2009/07/01/fabric-virtualenv-uma-combinacao-explosiva-no-bom-sentido/</link>
		<comments>http://weblog.destaquenet.com/2009/07/01/fabric-virtualenv-uma-combinacao-explosiva-no-bom-sentido/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 04:20:01 +0000</pubDate>
		<dc:creator>Daniel Martins</dc:creator>
				<category><![CDATA[Português]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[automatização]]></category>
		<category><![CDATA[debian]]></category>
		<category><![CDATA[django-flash]]></category>
		<category><![CDATA[fabric]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[pypi]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[setuptools]]></category>
		<category><![CDATA[teste]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[virtualenv]]></category>

		<guid isPermaLink="false">http://weblog.destaquenet.com/?p=554</guid>
		<description><![CDATA[Escreveu uma super-hiper-biblioteca ou aplicação em Python mas quer se certificar de que ela funciona em diferentes versões do interpretador? Embora isso possa ser resolvido através da execução manual dos testes com os vários interpretadores, isso é chato e improdutivo. &#8230; <a href="http://weblog.destaquenet.com/2009/07/01/fabric-virtualenv-uma-combinacao-explosiva-no-bom-sentido/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Escreveu uma super-hiper-biblioteca ou aplicação em <a href="http://python.org">Python</a> mas quer se certificar de que ela funciona em diferentes versões do interpretador? Embora isso possa ser resolvido através da execução <em>manual</em> dos testes com os vários interpretadores, isso é chato e improdutivo. Além do mais, cada versão do Python pode ter diferentes bibliotecas instaladas, o que pode acabar influenciando no resultado dos testes.</p>
<p>Temos portanto dois problemas a serem resolvidos. O primeiro problema, relacionado a automatização de tarefas repetitivas, pode ser facilmente solucionado com <a href="http://docs.fabfile.org/">Fabric</a>, uma ferramenta muito útil para criação de scripts de build e deployment de aplicações. Já escrevemos <a href="http://weblog.destaquenet.com/2008/10/05/deployment-de-aplicacoes-python-com-fabric/">um texto introdutório</a> sobre a mesma, não deixe de conferir.</p>
<p>O segundo problema, entretanto, é um pouco mais complicado de se resolver, mas não é nenhum bicho de sete cabeças. Com <a href="http://pypi.python.org/pypi/virtualenv/">VirtualEnv</a>, é possível criar ambientes Python isolados com o objetivo de testar e executar aplicações em uma espécie de sandbox onde temos total controle sobre as bibliotecas ali instaladas.</p>
<p><span id="more-554"></span></p>
<h3>Instalando as diferentes versões do Python</h3>
<p>O primeiro passo é instalar as versões do Python a serem usadas nos testes. Rode o comando abaixo para instalar os diferentes interpretadores, supondo que você utilize <a href="http://www.debian.org/">Debian</a> e sua aplicação precise funcionar nas versões 2.4, 2.5 e 2.6 do Python:</p>
<pre>$ sudo apt-get install python2.4 python2.4-dev \
    python2.5 python2.5-dev \
    python2.6 python2.6-dev</pre>
<p>A versão atual do Ubuntu já inclui o Python 2.6 por padrão. Veja também que aproveitamos para instalar os arquivos de desenvolvimento para cada versão, pois eventualmente precisamos deles para compilar bibliotecas com extensões escritas em C.</p>
<h3>Instalando Fabric e VirtualEnv</h3>
<p>Da mesma forma:</p>
<pre>$ sudo apt-get install python-setuptools</pre>
<p>Após a instalação do <a href="http://pypi.python.org/pypi/setuptools/">SetupTools</a>, execute o seguinte comando para instalar o Fabric e o VirtualEnv:</p>
<pre>$ sudo easy_install Fabric virtualenv</pre>
<h3>Configurando ambientes isolados para sua aplicação</h3>
<p>O próximo passo é criar ambientes de execução isolados para sua aplicação, sendo que cada ambiente deve usar uma versão diferente do interpretador do Python. Para fazer isso, execute os comandos abaixo, substituindo o <code>APP</code> pelo nome da sua aplicação ou biblioteca:</p>
<pre>$ mkdir ~/.virtualenvs
$ cd ~/.virtualenvs
$ virtualenv --python=/usr/bin/python2.6 --no-site-packages APP-py2.6
$ virtualenv --python=/usr/bin/python2.5 --no-site-packages APP-py2.5
$ virtualenv --python=/usr/bin/python2.4 --no-site-packages APP-py2.4</pre>
<p>Primeiramente criamos o diretório <code>~/.virtualenvs</code>, que é por convenção o diretório padrão para armazenamento dos ambientes. Em seguida, criamos três ambientes para nossa aplicação <code>APP</code>. A flag <code>--no-site-packages</code> é <em>opcional</em> e indica que as bibliotecas instaladas no diretório <code>site-packages</code> do Python em questão não devem ser visíveis ao ambiente sendo criado.</p>
<p>Finalmente, não esqueça de instalar, em cada um dos ambientes, as dependências exigidas pela sua aplicação:</p>
<pre>$ source ~/.virtualenvs/APP-py2.6/bin/activate
(APP-py2.6) $ easy_install biblioteca1 biblioteca2 ... bibliotecaN
(APP-py2.6) $ source ~/.virtualenvs/APP-py2.5/bin/activate
(APP-py2.5) $ easy_install biblioteca1 biblioteca2 ... bibliotecaN
(APP-py2.5) $ source ~/.virtualenvs/APP-py2.4/bin/activate
(APP-py2.4) $ easy_install biblioteca1 biblioteca2 ... bibliotecaN</pre>
<p>Supondo que sua aplicação utilize o SetupTools para a configuração dos metadados do projeto (através do script <code>setup.py</code>), os comandos abaixo devem indicar se a aplicação funciona nos ambientes que criamos:</p>
<pre>$ source ~/.virtualenvs/APP-py2.6/bin/activate
(APP-py2.6) $ python setup.py test
...
(APP-py2.6) $ source ~/.virtualenvs/APP-py2.5/bin/activate
(APP-py2.5) $ python setup.py test
...
(APP-py2.5) $ source ~/.virtualenvs/APP-py2.4/bin/activate
(APP-py2.4) $ python setup.py test
...</pre>
<h3>Automatizando!</h3>
<p>Se tudo funcionou até aqui, estamos prontos para criar um script que nos permita rodar os testes de forma automática, nos diferentes ambientes.</p>
<p>Supondo que sua aplicação utilize o SetupTools para a configuração dos metadados do projeto, o exemplo abaixo resolve o problema:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># -*- coding: utf-8 -*-</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Environment info</span>
config.<span style="color: black;">project</span> = <span style="color: #483d8b;">'APP'</span>
config.<span style="color: black;">virtualenv_dir</span> = <span style="color: #483d8b;">'~/.virtualenvs'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Supported Python versions</span>
config.<span style="color: black;">versions</span> = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'2.4'</span>, <span style="color: #483d8b;">'2.5'</span>, <span style="color: #483d8b;">'2.6'</span>,<span style="color: black;">&#41;</span>
config.<span style="color: black;">default_version</span> = <span style="color: #483d8b;">'2.6'</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> setup<span style="color: black;">&#40;</span>command, version=config.<span style="color: black;">default_version</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;Executes the given setup command with a virtual Python installation.
    &quot;&quot;&quot;</span>
    local<span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s/%s-py%s/bin/python setup.py %s'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>config.<span style="color: black;">virtualenv_dir</span>, config.<span style="color: black;">project</span>, version, command<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #dc143c;">test</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;Runs all tests in different Python versions.
    &quot;&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> version <span style="color: #ff7700;font-weight:bold;">in</span> config.<span style="color: black;">versions</span>:
        setup<span style="color: black;">&#40;</span><span style="color: #483d8b;">'test'</span>, version<span style="color: black;">&#41;</span></pre></div></div>

<p>Agora é só alegria:</p>
<pre>$ fab test
Fabric v. 0.1.1.
Running test...
[localhost] run: ~/.virtualenvs/APP-py2.4/bin/python setup.py test
...
[localhost] run: ~/.virtualenvs/APP-py2.5/bin/python setup.py test
...
[localhost] run: ~/.virtualenvs/APP-py2.6/bin/python setup.py test
...</pre>
<p>Devo lembrar que o script mostrado é só um exemplo. Você pode (e <strong>deve</strong>) modificá-lo para que este atenda às suas necessidades.</p>
<h3>(Bônus!) Distribuindo sua aplicação para diferentes versões do Python</h3>
<p>Com mais algumas linhas de código, podemos criar tasks que nos permitam gerar arquivos para distribuição da aplicação para diferentes versões do Python:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> dist_src<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;Create source archive.
    &quot;&quot;&quot;</span>
    setup<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sdist'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> dist_eggs<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;Create binary archives, one for each Python version.
    &quot;&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> version <span style="color: #ff7700;font-weight:bold;">in</span> config.<span style="color: black;">versions</span>:
        setup<span style="color: black;">&#40;</span><span style="color: #483d8b;">'bdist_egg'</span>, version<span style="color: black;">&#41;</span></pre></div></div>

<h3>(Bônus!) Automatizando geração de documentação e upload para o PyPI</h3>
<p>Ainda acha pouco? <a href="http://github.com/danielfm/django-flash/blob/master/fabfile.py">Este outro exemplo</a> de script vai além e mostra, numa aplicação real, como automatizar o registro e upload dos pacotes para o <a href="http://pypi.python.org/pypi/">PyPI</a>, atualizar site de documentação, entre outras coisas.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.destaquenet.com/2009/07/01/fabric-virtualenv-uma-combinacao-explosiva-no-bom-sentido/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

