<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>unit-test &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/unit-test/</link>
	<description>Feed of posts on WordPress.com tagged "unit-test"</description>
	<pubDate>Sat, 26 Dec 2009 15:55:26 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[cfix finished 2nd in ATI's Automation Honors Awards, surpassed only by JUnit]]></title>
<link>http://jpassing.wordpress.com/2009/12/19/cfix-finished-2nd-in-atis-automation-honors-awards/</link>
<pubDate>Sat, 19 Dec 2009 14:25:13 +0000</pubDate>
<dc:creator>jpassing</dc:creator>
<guid>http://jpassing.wordpress.com/2009/12/19/cfix-finished-2nd-in-atis-automation-honors-awards/</guid>
<description><![CDATA[Along with JUnit, JWebUnit, NUnit, and SimpleTest, cfix was one of the nominees for the Automated Te]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Along with JUnit, JWebUnit, NUnit, and SimpleTest, cfix was one of the nominees for the <a href='http://www.atihonors.automatedtestinginstitute.com/'>Automated Testing Institute&#8217;s Automation Honors Award 2009</a> in the category <i>Best Open Source Unit Automated Test Tool</i>. A few days ago, the results were published and cfix finished second &#8212; surpassed only by JUnit, which finished 1st (No real surprise here). If you are interested, there is a <a href='http://www.automatedtestinginstitute.com/home/index.php?option=com_content&#38;view=article&#38;id=1262&#38;Itemid=131'>video</a> in which the results are presented.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Running NUnit 2.53 tests for Silverlight]]></title>
<link>http://greenicicle.wordpress.com/2009/12/18/running-nunit-2-53-tests-for-silverlight/</link>
<pubDate>Fri, 18 Dec 2009 09:29:04 +0000</pubDate>
<dc:creator>Christian</dc:creator>
<guid>http://greenicicle.wordpress.com/2009/12/18/running-nunit-2-53-tests-for-silverlight/</guid>
<description><![CDATA[Jeff Wilcox has described in this article how to make NUnit tests run in the Silverlight unit testin]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.jeff.wilcox.name/">Jeff Wilcox</a> has described in <a href="http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/">this article</a> how to make NUnit tests run in the <a href="http://code.msdn.microsoft.com/silverlightut/">Silverlight unit testing framework</a>. That article provides all the groundwork for what you need to do:</p>
<ul>
<li>Compile a version of the NUnit framework that runs in the Silverlight 3 context</li>
<li>Provide metadata for the Silverlight unit testing framework so it knows which attributes to look for in order to locate what method is a test (and a little more)</li>
<li>Register this metadata in your Silverlight unit test project.</li>
</ul>
<p>I&#8217;d like to thank Jeff for his great work, and provide some raisins on top: an update to version 2.53 of NUnit.  Here&#8217;s what&#8217;s to do:</p>
<ul>
<li>Take the compatibility shim and test metadata provider from Jeff&#8217;s article.</li>
<li>Download the current NUnit source code (in this case 2.5.3). Create a new Silverlight project, and add the code for the NUnit framework into it. Compile: a whole bunch of exceptions come up.</li>
<li>NUnit&#8217;s source code uses the #if precompiler directive in order to exclude parts that are incompatible with different version of the runtime. By defining the NET_2_0 symbols, we can make a lot of the errors disappear: the nongeneric implementation of Stack, for example, is excluded now. We need to exclude some more code: Instead of deleting it altogether, I chose to use the SILVERLIGHT symbol and add a #if !SILVERLIGHT directive to get rid of unsupported code instead. In cases where a whole method body is excluded, add a section on the bottom that throws a NotSupportedException:
<pre class="brush: plain;">
#if SILVERLIGHT
      throw new NotSupportedException( &#34;Not supported in Silverlight&#34; );
#endif
</pre>
</li>
<li>We need to get rid of the serialization constructors from all the exceptions. </li>
<li>Remove the attributes for threading demands &#8211; they&#8217;re useless in Silverlight anyway.</li>
<li>Remove the attributes for threading demands &#8211; they&#8217;re useless in Silverlight anyway.</li>
<li>Add a new shim class for the non-generic System.Collections.Specialized.ListDictionary to the Compatibility project. It is a simple derivation of the genetic Dictionary.</li>
<li>In the PathComparison class, there are some unsupported string operations. I didin&#8217;t bother exluding and replacing these, and just refactored them to supported alternatives. (Thinking about it, I should probably have used the .NET2.0 switch. Next time, promised)</li>
<li>Finally, the metadata provider uses a changed property for in the ExpectedException attribute. Corrected, aaaaaand&#8230;</li>
<li>Done. Now all you need to do is reference the three generated assemblies, follow Jeff&#8217;s article on how to set up the testing framework for the NUnit provider, and start writing tests.</li>
</ul>
<p>This was easy enough that I hope it can be done for any upcoming version of NUnit.</p>
<p><strong><a href="http://dl.dropbox.com/u/1900064/GreenIcicle/NUnit.Silverlight.zip">DOWNLOAD SOURCE CODE</a><br />
<a href="http://dl.dropbox.com/u/1900064/GreenIcicle/NUnit.Silverlight.bin.zip">DOWNLOAD BINARIES</a></strong></p>
<p>The point where I&#8217;d like to disagree with Jeff Wilcox the idea that NUnit was a legacy solution, and that you should start new projects with Visual Studio testing. NUnit provides much richer assertions,  and a better syntax for setting them up: you won&#8217;t find <a href="http://www.nunit.org/index.php?p=collectionConstraints&#38;r=2.5.3">assertions for examining collection content</a> or <a href="http://www.nunit.org/index.php?p=throwsConstraint&#38;r=2.5.3">thrown exceptions</a> in Visual Studio testing. Or the upcoming ability to <a href="http://www.nunit.org/index.php?p=pnunit&#38;r=2.5.3">run tests in parallel compartments</a> to simulate a distributed environment. NUnit is far from being a discontinued legacy solution, it is the de facto standard and quickly developing. And: thanks to the extensibility of the Silverlight unit testing framework, there&#8217;s not a reason not to use it for Silverlight as well.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Wrestling with Scaling Software Agility]]></title>
<link>http://theagileexecutive.com/2009/12/15/wrestling-with-scaling-software-agility/</link>
<pubDate>Tue, 15 Dec 2009 19:20:57 +0000</pubDate>
<dc:creator>israelgat</dc:creator>
<guid>http://theagileexecutive.com/2009/12/15/wrestling-with-scaling-software-agility/</guid>
<description><![CDATA[Software Development Times has just published Guest View: Wrestling with Scaling Software Agility by]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Software Development Times has just published <em><a href="http://sdtimes.com/link/33988">Guest View: Wrestling with Scaling Software Agility</a></em> by <a href="http://www.rallydev.com/agileblog/about/#ryan-martens">Ryan Martens</a> and me. This Guest View is a little unique in that Ryan and I actually try to wrestle each other to the ground&#8230; Here is why we try to do so:</p>
<blockquote><p>Agile champions spend a lot of time trying to communicate the agile premise to the executives in their organization. The difference in context between the champion and the executive often makes it a difficult conversation. A Scrum Master versed in behavior-driven design is not always able to relate to the frustrations of a sales executive who gets free advice on how to sell from everyone and his grandmother.</p>
<p>Conversely, a CFO does not necessarily understand why unit test coverage on the company&#8217;s legacy code is still inadequate after a full year of investment in agile methods that embrace refactoring as a core practice.</p>
<p>To bridge the chasm through this article, we resort to role-playing. Ryan Martens plays the Agile Champion; Israel Gat plays the Skeptical Executive. Metaphorically speaking, each one tries to wrestle the other to the ground.</p></blockquote>
<p>Before you get into this Guest View, I would like to reinforce an important disclaimer:</p>
<blockquote><p>A note of caution before Ryan and Israel make irreparable damage to their long-standing relationship: The two actually understand each other extremely well and rarely are they of different opinions on the fundamentals of agile in real life&#8230;</p></blockquote>
<p>Enjoy the article!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[PHPUnit ]]></title>
<link>http://mcloide.wordpress.com/2009/12/09/phpunit/</link>
<pubDate>Wed, 09 Dec 2009 15:51:23 +0000</pubDate>
<dc:creator>mcloide</dc:creator>
<guid>http://mcloide.wordpress.com/2009/12/09/phpunit/</guid>
<description><![CDATA[I have just started to play with PHPUnit and I can easily say that this is a must have tool for ever]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.phpunit.de/"><img class="alignleft" style="border:0 none;margin:10px;" title="PHPUnit" src="http://www.phpunit.de/manual/phpunit-logo.gif" alt="" width="94" height="80" /></a>I have just started to play with <a href="http://www.phpunit.de" target="_blank"><strong>PHPUnit</strong></a> and I can easily say that this is a must have tool for every PHP developer.</p>
<p>Quoting <strong>Matthew Weiner O&#8217;Phinney</strong>:</p>
<blockquote><p>&#8220;If you are not doing unit-testing, then you are not a good developer.&#8221;</p></blockquote>
<p>This might sound harsh but is in fact a bit of a truth since most of the developers don&#8217;t really mind or have the time to go on testing the scripts in a block or whole application overview.</p>
<p>Developing the scripts for <strong>PHPUnit</strong> are not hard, even though I&#8217;m not an expert on the area, it don&#8217;t take too much time to develop a good script to test your scripts.</p>
<p>The tests are based on assertions and mock-ups from how your script should work. It will basically create a very least minimal requirement to see if your script is working.</p>
<p>Let&#8217;s say, if your object have to set 3 properties, call a method and then another object should load this just created object, the test script should cover all of this.</p>
<p>Afterwards is just run, at command prompt, phpunit yourScript.php and check for the results.</p>
<p>As I have mentioned before, I&#8217;m no expert since I have just started to learn PHPUnit, so I&#8217;m going to keep this post small until I can create a small tutorial of how to work with PHPUnit but meanwhile:</p>
<p>To install:</p>
<p>Install it using PEAR &#8211; It&#8217;s the easier way. If the install fails because PEAR is out of date, then run <strong>pear upgrade-all</strong> to update pear and all packages installed.</p>
<p>Check out <a href="http://www.phpunit.de/manual/3.0/en/installation.html" target="_blank">Chapter 3 of PHPUnit online documentation</a> to learn how to fully install it: <a href="http://www.phpunit.de/manual/3.0/en/installation.html" target="_blank">http://www.phpunit.de/manual/3.0/en/installation.html</a></p>
<p>To write tests:</p>
<p>Check out <a href="http://www.phpunit.de/manual/3.0/en/writing-tests-for-phpunit.html" target="_blank">Chapter 4</a> to learn the basics of writting tests to run PHPUnit. The online documentation is not big and it&#8217;s worth to read it fully. Anyway keep the <a href="http://www.phpunit.de/manual/3.0/en/api.html" target="_blank">Chapter 20</a>, about the API, in your perspective to really see how PHPUnit can help you to make your scripts even stronger.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Unit Testing Griffon Apps with the GSql plugin]]></title>
<link>http://javaproof.wordpress.com/2009/12/04/unit-testing-griffon-apps-with-the-gsql-plugin/</link>
<pubDate>Fri, 04 Dec 2009 23:07:37 +0000</pubDate>
<dc:creator>dmullins78</dc:creator>
<guid>http://javaproof.wordpress.com/2009/12/04/unit-testing-griffon-apps-with-the-gsql-plugin/</guid>
<description><![CDATA[After giving a co-worker a hard time for not using TDD to create his Android app, I realised I was d]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>After giving a co-worker a hard time for not using TDD to create his Android app, I realised I was doing the same thing on my Griffon app. Unfortunately, I had a hard time testing the &#8220;withSql&#8221; closure and wanted a way to verify my sql statements were legit. Groovy metaClass came in handy again.</p>
<p>Method under test in my Controller<code><br />
def downloadHorses = { horse -&#62;<br />
&#160;&#160;withSql { sql -&#62;<br />
&#160;&#160;&#160;&#160;sql.execute("insert into horse (id, name) values (?,?)", [it.id, it.name])<br />
&#160;&#160;}<br />
}</code></p>
<p>Corresponding GroovyTestCase method<code><br />
void testDownloadHorses() {<br />
&#160;&#160;model.availableHorses &#60;&#60; new HorseModel(id: &#34;1&#34;, name: &#34;Horse 1&#34;)<br />
&#160;&#160;def fake = new FakeWithSql()<br />
&#160;&#160;controller.metaClass.withSql = fake.withSql<br />
&#160;&#160;controller.downloadCourses()<br />
&#160;&#160;assertEquals([1, &#34;Horse 1&#34;], fake.params)<br />
&#160;&#160;assertEquals(&#34;insert into horse (id, name) values (?,?)&#34;, fake.statement)<br />
}</code></p>
<p>FakeController class that returns the sql statement and parameters.<code><br />
class FakeWithSql {<br />
&#160;&#160;def params<br />
&#160;&#160;def sql = new Expando()<br />
&#160;&#160;public withSql = {Closure closure -&#62;<br />
&#160;&#160;&#160;&#160;sql.execute = {sql, parameters -&#62;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;statement = sql<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;params = parameters<br />
&#160;&#160;&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;closure(sql)<br />
&#160;&#160;}<br />
}</code></p>
<p>As I think about it, I will run into problems with multiple sql statements (only keeps track of last) and select statements (returning a set of data). This works well enough for now, but I will look into using an actual GroovyMock class instead of the ExpandoClass</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Senior SharePoint Developer/Business Analyst]]></title>
<link>http://mindsourceinc.wordpress.com/2009/11/25/senior-sharepoint-developerbusiness-analyst/</link>
<pubDate>Wed, 25 Nov 2009 20:38:44 +0000</pubDate>
<dc:creator>Michelle</dc:creator>
<guid>http://mindsourceinc.wordpress.com/2009/11/25/senior-sharepoint-developerbusiness-analyst/</guid>
<description><![CDATA[We have an immediate need for a SENIOR SHAREPOINT DEVELOPER/BUSINESS ANALYST with our client in FREM]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>We have an immediate need for a <strong>SENIOR SHAREPOINT DEVELOPER/BUSINESS ANALYST</strong> with our client in <strong>FREMONT, CA</strong>. This is a <strong>CONTRACT POSITION</strong> for 6 months with possible extension.</p>
<p>The ideal candidate should be able to work with the business team to articulate functional requirements, priorities requirements in terms of business value, prepare technical designs that will accommodate the requirements, and configure /develop the requisite solutions.</p>
<ul>
<li>Work with business users to identify, prioritize, and document the requirements</li>
<li>Work with the requirements and prepare an implementation plan to address the requirements</li>
<li>Prepare technical design that will accommodate the identified requirements/priorities.</li>
<li>Develop/program/configure the SharePoint solutions based on the documented requirements and technical design.</li>
<li>Participate in all development lifecycle activities: unit test, systems test, data migration, integration.</li>
<li>Experience as a business analyst and Sharepoint developer designing and building MOSS solutions</li>
<li>Must have experience working with business users to identify and document business requirements related to content management/document management/collaboration needs</li>
<li>Must have strong experience using Visual Studio/.NET/SharePoint Designer, including the design and implementation of custom web parts and other programs that leverage the SharePoint object model.</li>
</ul>
<p>If you are interested, please send us your resume along with the hourly rate, contact number, and availability for a phone interview to <a href="mailto:raj@mindsource.com?subject=Senior SharePoint Developer/Business Analyst">raj@mindsource.com</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Testen von Exceptions mit JMockit]]></title>
<link>http://graberj.wordpress.com/2009/11/23/testen-von-exceptions-mit-jmockit/</link>
<pubDate>Mon, 23 Nov 2009 19:00:43 +0000</pubDate>
<dc:creator>Johnny Graber</dc:creator>
<guid>http://graberj.wordpress.com/2009/11/23/testen-von-exceptions-mit-jmockit/</guid>
<description><![CDATA[Für einen Unit-Test benötigt man meistens nur gewisse Teile eines &#8220;fremden&#8221; Objekts. Oft]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Für einen Unit-Test benötigt man meistens nur gewisse Teile eines &#8220;fremden&#8221; Objekts. Oft genügt einem eine fixe Anzahl definierter Rückgabewerte. Statt das man nun das &#8220;fremde&#8221; Objekt erzeugt und die Werte aus einer Datenbank holt, setzt man eine Testattrappe ein. Diese Attrappe liefert einem die definierten Rückgabewerte oder Exceptions, ohne dabei wirklich mit der Datenbank, dem Dateisystem oder dem Netzwerk zu sprechen. So eine Attrappe kann ein <a href="http://de.wikipedia.org/wiki/Mock-Objekt">Mock</a> oder <a href="http://de.wikipedia.org/wiki/Stub_%28Programmierung%29">Stub</a> sein.</p>
<p><a href="https://jmockit.dev.java.net/">JMockit</a> ist ein Framework für Java, das einem bei der Erstellung von Mocks und Stubs hilft. Für Java gibt es zahlreiche solcher <a href="http://www.sizovpoint.com/2009/03/java-mock-frameworks-comparison.html">Frameworks</a>. JMockit hat aber einige besondere Fähigkeiten, was das Testen deutlich erleichtern kann.</p>
<p>Für <a href="http://bit.ly/1ADdxP">AtaraxiS</a> war ich in den letzten Tagen am erweitern der Unit-Tests. Die Testabdeckung war noch nicht überall so gut, wie ich diese haben will. Es fehlten vor allem noch die zahlreichen Catch-Blocke für die Exceptions. <br />
(Wieso überhaupt Exceptions testen? AtaraxiS will die Verschlüsselung abstrahieren und reduziert die dabei möglichen Exceptions auf eine handlichere Anzahl. Diese Tests dienen der Kontrolle, ob auch nach dem anstehenden Umbau noch alles wie gewohnt läuft.)</p>
<pre class="brush: java;">
	public ACDecryptInputStream (File inFile, SecretKey aesKey) throws IOException
	{
		try
		{
			// Parse the Header of the File
			AtaraxisHeaderParser ahParser = new AtaraxisHeaderParser(inFile);

			// When it contains a Header, then prepare all for CBC-Mode
			IvParameterSpec ivSpec = new IvParameterSpec(ahParser.getIV());

			fis = new FileInputStream(inFile);
			fis.skip(ahParser.bytesToSkip());

			cipher = Cipher.getInstance(&#34;AES/CBC/PKCS7Padding&#34;, &#34;BC&#34;);
			cipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec);

			// Create the CipherInputStream
			decryptedInputStream = new CipherInputStream(fis, cipher);
		}
		catch (NoSuchAlgorithmException e)
		{
			LOGGER.error(&#34;NoSuchAlgorithmException&#34;, e);
			throw new IOException(&#34;NoSuchAlgorithmException&#34;);
		}
		.....
	}
</pre>
<p>Um dies zu testen, müsste die Klasse Cipher bei getInstance() eine NoSuchAlgorithmException werfen. Dies könnte ich durch eine Abstraktionsschicht zwischen unserem Code und dem von <a href="http://bouncycastle.org/">BouncyCastle</a> machen. Das bedingt aber eine Änderung am Code. Hier wäre das zwar möglich, doch geht das nicht immer. </p>
<p>JMockit hat dafür eine passende Methode. Mittels Mockit.redefineMethods() kann eine Methode umgeleitet werden. Das angegebene Ziel kann genau das machen, was man von ihm erwartet. Um die Exception zu werfen, dient dieser Aufruf:</p>
<pre class="brush: java;">
	@Test(expected=IOException.class)
	public void ACDecryptInputStream_NoSuchAlgorithmException() throws Exception
	{
		Mockit.redefineMethods(javax.crypto.Cipher.class, new Object() {
			@SuppressWarnings(&#34;unused&#34;)
			public final Cipher getInstance(String transformation,
                    Provider provider)
             throws NoSuchAlgorithmException,
                    NoSuchPaddingException
			{
				throw new NoSuchAlgorithmException();
			}
		});

		ACDecryptInputStream acI = new ACDecryptInputStream(testFile, key);
		fail(&#34;IOException missing for &#34; + acI);
	}
</pre>
<p>Dies ist nur eine der unzähligen Möglichkeiten, die JMockit bietet. Nach dem gleichen Prinzip kann man beliebige Rückgabewerte zurückliefern. Wer mehr dazu wissen will, findet auf der Projektseite von JMockit eine sehr detaillierte <a href="https://jmockit.dev.java.net/tutorial.html">Anleitung</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[String Distance and Refactoring in Scala]]></title>
<link>http://oldfashionedsoftware.com/2009/11/19/string-distance-and-refactoring-in-scala/</link>
<pubDate>Thu, 19 Nov 2009 05:19:04 +0000</pubDate>
<dc:creator>Matt</dc:creator>
<guid>http://oldfashionedsoftware.com/2009/11/19/string-distance-and-refactoring-in-scala/</guid>
<description><![CDATA[Here&#8217;s a three-for-one special for you: A post about implementing the Levenshtein string dista]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here&#8217;s a three-for-one special for you: A post about implementing the Levenshtein string distance algorithm in Scala AND refactoring it from an imperative style to a functional style AND I even throw in a short lesson on memoization. To make sure that our refactoring is correct and preserves the expected behavior, I&#8217;ll unit test the code along the way using ScalaTest. ScalaCheck, JUnit, or TestNG would work just as well, but I used ScalaTest.</p>
<h2>First Things First</h2>
<p>&#8220;What, exactly,&#8221; some of you may be asking, &#8220;is Levenshtein string distance?  Some kind of Teutonic tailoring terminology?&#8221; Not at all.  It&#8217;s a way of measuring how alike or different two strings of symbols are.  For example, the string &#8220;sturgeon&#8221; is a lot more similar to &#8220;surgeon&#8221; than to &#8220;urgently&#8221;.  &#8220;Sturgeon&#8221; and &#8220;surgeon&#8221; are only a single letter (t) apart.  They have a string distance of 1.  &#8220;Sturgeon&#8221; and &#8220;urgently&#8221; share some letters, but each has some letters not present in the other.  So what&#8217;s their string distance?  It&#8217;s not so obvious now.</p>
<p>String distance is useful.  The use that most quickly springs to mind is spelling correction.  If I type &#8220;computwr&#8221; a string distance algoritm could tell us that &#8220;computwr&#8221; is very close to the dictionary word &#8220;computer&#8221;.  But there&#8217;s more to it than that.  There are a lot of fuzzy problems in which you want to find which two sets of complex data are most similar.  One way to solve a problem like that is to encode it into a string compare using string distance.  For example, you could write a program to find pen strokes in an image and encode their shapes (up, curve left, down, angle right, etc) as a string which could be compared to known encodings for handwritten letters.  By finding the closest matches you can create a handwriting recognition program.  String distance is useful in DNA analysis, of course, recognizing patterns in signals, and a host of other situations.</p>
<p>The Levenshtein string distance algorithm was developed by Vladimir Levenshtein in 1965.  It can easily tell us the distance from &#8220;sturgeon&#8221; to &#8220;urgently&#8221;.  This algorithm breaks down string transformation into three basic operations:  adding a character, deleting a character, and replacing a character.  Each of these operations is assigned a cost, usually a cost of 1 for each operation.  Leaving a character unchanged has a cost of 0.  So to go from &#8220;sturgeon&#8221; to &#8220;surgeon&#8221; you leave the &#8220;s&#8221; unchanged for a cost of 0.  Then you add a &#8220;t&#8221; for a cost of 1.  All the other letters also remained unchanged, so the total cost is 1, just as we expected.</p>
<p>To change &#8220;sturgeon&#8221; to &#8220;urgently&#8221; is harder.  They have the same number of letters, so we could just do a replacement on each one for a distance of 8.  But is that the shortest distance?  What if we try to re-use that &#8220;urge&#8221; from &#8220;sturgeon&#8221;?  Can we re-use the &#8220;n&#8221;?  Does that help?  What about the &#8220;t&#8221;?  We need an algorithm that we can follow.</p>
<h2>The Grid</h2>
<p>What we need is a way to find the cheapest combination of operations which changes the first string to the second.  That&#8217;s the Levenshtein algorithm.  It works like this.  Write the first string vertically from top to bottom.  To the right of each letter write 1, 2, 3, etc.  Write a 0 above the number 1.  Then write the second string horizontally and again add the numbers 1, 2, 3 etc. to the right of the 0.  It will look something like this:</p>
<pre class="brush: python;">
    u r g e n t l y
  0 1 2 3 4 5 6 7 8
s 1
t 2
u 3
r 4
g 5
e 6
o 7
n 8
</pre>
<p>That&#8217;s the first step.  The grid remains un-filled-in at this point.  Can you guess what the grid positions are going to hold?  They are going to hold the cost to convert the various prefixes of &#8220;sturgeon&#8221; to the various prefixes of &#8220;urgently&#8221;.  The position at the intersection of row r4, and the column a2, for example, will contain the cost to convert &#8220;stur&#8221; to &#8220;ur&#8221;.  We fill in these positions (left-to-right then top to bottom) with the smallest of the following three numbers:</p>
<ul>
<li>The number above the current position plus one.</li>
<li>The number to the left of the current position plus one.</li>
<li>The above-left number if row letter and column letter are the same, or the above-left number plus one otherwise.</li>
</ul>
<p>When we finish, the bottom right corner contains the cost to convert the first string to the second.</p>
<h2>But Why?  (Understanding the Algorithm)</h2>
<p>Those are some shockingly simple rules!  Let&#8217;s examine how they translate into string distance.</p>
<p>First, what are those numbers 0 to n that we write along the top and left?  They&#8217;re not just indices.  The numbers along the top represent the cost to convert the empty string to the various prefixes of &#8220;urgently&#8221;.  The cost is 0 to convert &#8220;&#8221; to &#8220;&#8221;, 1 to convert &#8220;&#8221; to &#8220;u&#8221;, 2 to convert &#8220;&#8221; to &#8220;ur&#8221;, and so on.  The numbers on the left are the cost to convert the prefixes of &#8220;sturgeon&#8221; to the the empty string .  &#8220;&#8221; to &#8220;&#8221; is 0, &#8220;s&#8221; to &#8220;&#8221; is 1, and so forth.  These costs are obvious.  The only way to convert &#8220;&#8221; to &#8220;urgently&#8221; is to add eight letters.  There&#8217;s nothing to delete, nothing to replace.  The only way to convert &#8220;sturgeon&#8221; to &#8220;&#8221; is to delete all eight letters.</p>
<p>Each position, as we have established, represents the cost to convert the string of characters down the left side ending in the current row&#8217;s character into the the string of characters along the top ending at the current column&#8217;s character.  Put another way, for any given position let&#8217;s call the current row&#8217;s letter A, and the current column&#8217;s letter B.  If we use a colon (:) to indicate string concatenation then the beginning string, the one along the left of the grid, can be written Prefix1:A.  So for our example word &#8220;sturgeon&#8221; if we look at a position in row e6 then Prefix1 is &#8220;sturg&#8221; and the final letter, which we&#8217;re calling A, is &#8220;e&#8221;.</p>
<p>So, speaking in terms of Prefix1, Prefix2, A, and B, we use the following inputs:</p>
<ul>
<li>The cost to change Prefix1 to Prefix2:<strong>B</strong> (the number above the current position).</li>
<li>The cost to change Prefix1:<strong>A</strong> to Prefix2 (the number to the left).</li>
<li>The cost to change Prefix1 to Prefix2 (the above-left number).</li>
</ul>
<p>If we know the costs of these three conversions we can find the cost to change Prefix1:A to Prefix2:B using this logic:</p>
<ul>
<li>We know that if converting Prefix1 to Prefix2:B has a cost of X, then Prefix1:A can be converted to Prefix2:B for the cost of X plus the cost of deleting A, or X + 1.</li>
<li>We know that if converting Prefix1:A to Prefix2 has a cost of Y, then Prefix1:A can be converted to Prefix2:B for the cost of Y plus the cost of adding B, or Y + 1.</li>
<li>We know that if converting Prefix1 to Prefix2 has a cost of Z, then Prefix1:A can be converted to Prefix2:B for the cost of Z plus the cost of replacing A with B, or Z + (0 or 1 depending on whether A = B).</li>
</ul>
<p>If you understand the above logic, then you understand this really neat algorithm.  It&#8217;s a quintessential example of dynamic programming.  The solution is built up by solving simpler problems.  You start with the trivial case of converting to and from the empty string, and then you build up the solution for the prefixes until you have the complete solution.</p>
<p>In the grid&#8217;s initial configuration there is only one location for which we know all three costs and that is row s1, column u1.  That&#8217;s the only space for which all three neighboring values (above, left, and above-left) are populated.  After we fill in this one, there are two more spaces available to us.  Those are (t2, u1) and (s1, r2).  Ordinarily, though, the spaces are populated line by line.</p>
<h2>A Simple Example</h2>
<p>Let&#8217;s do a quick example by hand.  Then we&#8217;ll take a stab at implementing it in code.  What&#8217;s the string distance from &#8220;hat&#8221; to &#8220;tape&#8221;?  First, our empty grid:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1
a 2
t 3
</pre>
<p>The first space is row h, column t.  The letters are different so our choices are 1 + 1 (above), 1 + 1 (left), or 0 + 1 (above-left).  0 + 1 is the smallest value, so the first space gets populated with 1.  The next space has choices 2 + 1 (above), 1 + 1 (left), or 1 + 1 (above-left).  1 + 1 is the lowest, so we fill in the second space with 2.  Once we finish the row, we have this:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1 1 2 3 4
a 2
t 3
</pre>
<p>The next space is row a, column t.  Our choices are 1 + 1 (above), 2 + 1 (left), or 1 + 1 (above-left).  1 + 1 is the smallest value, so the space gets populated with 2.  The next space has choices 2 + 1 (above), 2 + 1 (left), or 1 + 0 (above-left).  Why 1 + 0?  Because the above-left value is 1 and both letters for this space are &#8220;a&#8221; so we can replace &#8220;a&#8221; with &#8220;a&#8221; for free.  Go ahead and finish the whole grid.  This is the result:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1 1 2 3 4
a 2 2 1 2 3
t 3 2 2 2 3
</pre>
<p>The strings &#8220;hat&#8221; and &#8220;tape&#8221; have a distance of 3.</p>
<h2>Some Code, Finally</h2>
<p>As fascinating as Levenshtein distance is, and as much more as there is to say on the topic, the time has come to write some code.  Here&#8217;s a Scala implementation that is very close to the pencil-and-paper approach that we just performed.</p>
<pre class="brush: scala;">
import scala.Math.min
import scala.Math.max

object StringDistance {
  def stringDistance(s1: String, s2: String): Int = {
    def minimum(i1: Int, i2: Int, i3: Int) = min(min(i1, i2), i3)

    val dist = new Array[Array[Int]](s1.length + 1, s2.length + 1)

    for (idx &#60;- 0 to s1.length) dist(idx)(0) = idx
    for (jdx &#60;- 0 to s2.length) dist(0)(jdx) = jdx

    for (idx &#60;- 1 to s1.length; jdx &#60;- 1 to s2.length)
      dist(idx)(jdx) = minimum (
        dist(idx-1)(jdx  ) + 1,
        dist(idx  )(jdx-1) + 1,
        dist(idx-1)(jdx-1) + (if (s1(idx-1) == s2(jdx-1)) 0 else 1)
      )

    dist(s1.length)(s2.length)
  }
</pre>
<p>Do you see what I mean when I say it&#8217;s close to the pencil-and-paper approach?  We actually construct a two-dimensional Array to represent the grid we drew earlier.  It&#8217;s a very literal implementation.</p>
<p>To explain the code briefly, we declare a singleton StringDistance having a single method called stringDistance.  Within this method we declare a 3-argument minimum method. (I wonder why there&#8217;s no &#8220;def min(params: Int*): Int&#8221; defined in scala.Math.)  Then we create an array called &#8220;dist&#8221; and populate the top row and leftmost column in lines 8-11.  The for loop on line 13 cycles through each array position from left to right then top to bottom, and populates them according to the Levenshtein logic. Finally, once the grid is filled in we return the number in the bottom right position.</p>
<p>The job&#8217;s not done yet, of course.  We haven&#8217;t written our unit tests.  Here&#8217;s the test I wrote:</p>
<pre class="brush: scala;">
import org.scalatest._

class StringDistanceSuite extends FunSuite with PrivateMethodTester {

  test(&#34;stringDistance should work on empty strings&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,    &#34;&#34;) == 0 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,    &#34;&#34;) == 1 )
    assert( StringDistance.stringDistance(   &#34;&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;,    &#34;&#34;) == 3 )
    assert( StringDistance.stringDistance(   &#34;&#34;, &#34;abc&#34;) == 3 )
  }

  test(&#34;stringDistance should work equal strings&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,    &#34;&#34;) == 0 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,   &#34;a&#34;) == 0 )
    assert( StringDistance.stringDistance(&#34;abc&#34;, &#34;abc&#34;) == 0 )
  }

  test(&#34;stringDistance should work where only inserts are needed&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,  &#34;ab&#34;) == 1 )
    assert( StringDistance.stringDistance(  &#34;b&#34;,  &#34;ab&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ac&#34;, &#34;abc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abcdefg&#34;, &#34;xabxcdxxefxgx&#34;) == 6 )
  }

  test(&#34;stringDistance should work where only deletes are needed&#34;) {
    assert( StringDistance.stringDistance(  &#34;a&#34;,    &#34;&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,   &#34;b&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;,  &#34;ac&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;xabxcdxxefxgx&#34;, &#34;abcdefg&#34;) == 6 )
  }

  test(&#34;stringDistance should work where only substitutions are needed&#34;) {
    assert( StringDistance.stringDistance(  &#34;a&#34;,   &#34;b&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,  &#34;ac&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ac&#34;,  &#34;bc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;, &#34;axc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;xabxcdxxefxgx&#34;, &#34;1ab2cd34ef5g6&#34;) == 6 )
  }

  test(&#34;stringDistance should work many operations are needed&#34;) {
    assert( StringDistance.stringDistance(&#34;example&#34;, &#34;samples&#34;) == 3 )
    assert( StringDistance.stringDistance(&#34;sturgeon&#34;, &#34;urgently&#34;) == 6 )
    assert( StringDistance.stringDistance(&#34;levenshtein&#34;, &#34;frankenstein&#34;) == 6 )
    assert( StringDistance.stringDistance(&#34;distance&#34;, &#34;difference&#34;) == 5 )
    assert( StringDistance.stringDistance(&#34;java was neat&#34;, &#34;scala is great&#34;) == 7 )
  }

}
</pre>
<p>It tests several special cases as well as the general case.  All we have to do is compile our StringDistance object and the StringDistanceSuite unit test, fire up the scala interpreter and run the test:</p>
<pre class="brush: scala;">
scala&#62; (new StringDistanceSuite).execute()
Test Starting - StringDistanceSuite: recursiveStringDistance should work on empty strings
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work on empty strings
Test Starting - StringDistanceSuite: recursiveStringDistance should work on equal strings
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work on equal strings
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only inserts are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only inserts are needed
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only deletes are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only deletes are needed
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only substitutions are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only substitutions are needed
Test Starting - StringDistanceSuite: stringDistance should work many operations are needed
Test Succeeded - StringDistanceSuite: stringDistance should work many operations are needed

scala&#62;
</pre>
<h2>Refactoring: Reduced Memory Usage</h2>
<p>The code passes all the tests, so let&#8217;s take things a step further.  One shortcoming of our implementation is that it can require a lot of memory.  That array has to be of size (n+1)*(m+1) where n and m are the lengths of the two strings we&#8217;re comparing.  If you want to apply the method to strings that are a few hundred characters long (or longer) then you&#8217;re starting to talk about some serious memory requirements.  How can we reduce the amount of memory required?  Can you think of a way?</p>
<p>Once we complete one row of the grid, we use it again as an input when we compute the next row.  But after that we&#8217;re done with it.  Why leave it to clutter the heap?  Let&#8217;s tweak our implementation slightly.  Try rewriting the method using only two rows.  Fill the first row with the initial 0, 1, 2, etc.  Then use one to compute the other over and over.  Think about how you would implement this, then have a look at my solution below.</p>
<pre class="brush: scala;">
  def stringDistance(s1: String, s2: String): Int = {
    def minimum(i1: Int, i2: Int, i3: Int) = min(min(i1, i2), i3)

    var dist = ( new Array[Int](s1.length + 1),
                 new Array[Int](s1.length + 1) )

    for (idx &#60;- 0 to s1.length) dist._2(idx) = idx

    for (jdx &#60;- 1 to s2.length) {
      val (newDist, oldDist) = dist
      newDist(0) = jdx
      for (idx &#60;- 1 to s1.length) {
        newDist(idx) = minimum (
          oldDist(idx) + 1,
          newDist(idx-1) + 1,
          oldDist(idx-1) + (if (s1(idx-1) == s2(jdx-1)) 0 else 1)
        )
      }
      dist = dist.swap
    }

    dist._2(s1.length)
  }
</pre>
<p>This one uses a Pair (also called a Tuple2) containing two one-dimensional arrays, instead of a 2*(n+1) array.  Pair happens to have the very handy &#8220;swap&#8221; method which we can use to trade out the rows when we&#8217;ve finished one and are ready to compute the next.</p>
<p>This is where our unit tests really show their worth. No need to wonder whether this new code really does work.  We just recompile, run the tests again, and we can see that the code still gives us the expected results.</p>
<h2>Refactoring: Recursion, Kind Of</h2>
<p>What are some other ways we could write this code?  Can it be improved?  I thought I would try to replace the iteration in the previous implementations with recursion.  Here&#8217;s what that code looks like:</p>
<pre class="brush: scala;">
  def stringDistance(s1: String, s2: String): Int = {
    def newCost(ins: Int, del: Int, subst: Int, c1: Char, c2:Char) =
      Math.min( Math.min( ins+1, del+1 ), subst + (if (c1 == c2) 0 else 1) )

    def getNewCosts(s1: List[Char], c2: Char, delVal: Int, prev: List[Int] ): List[Int] = (s1, prev) match {
      case (c1 :: _ , substVal :: insVal :: _) =&#62;
        delVal :: getNewCosts(s1.tail, c2, newCost(insVal, delVal, substVal, c1, c2), prev.tail)
      case _ =&#62; List(delVal)
    }

    def sd(s1: List[Char], s2: List[Char], prev: List[Int]): Int = s2 match {
      case Nil =&#62; prev.last
      case _ =&#62; sd( s1, s2.tail, getNewCosts(s1, s2.head, prev.head+1, prev) )
    }

    (s1, s2) match {
      case (`s2`, `s1`) =&#62; 0
      case (_, &#34;&#34;) &#124; (&#34;&#34;, _) =&#62; max(s1.length, s2.length)
      case _ =&#62; sd(s1.toList, s2.toList, (0 to s1.length).toList)
    }
  }
</pre>
<p>It&#8217;s a pretty naïve implementation, actually.  It just replaces the the repetition of the two for loops with the repetition of the recursion of the two methods sd and getNewCosts.  The sd method is even tail-recursive, allowing scala to optimize it.  It does the same basic thing as the for loop version, though.  It recurses through the characters of a row in the getNewCosts method, and it recurses through the rows of the grid in the sd method.</p>
<p>It looks more complicated than the previous implementations.  It&#8217;s harder to read.  But it passes our unit tests, so we can be pretty sure it&#8217;s correct.</p>
<h2>Refactoring: List Methods</h2>
<p>After the last implementation, I thought it looked a little sloppy.  I wondered whether I could improve the situation by using some of the many useful methods built into scala&#8217;s List class.  Here is the comparatively brief code that resulted:</p>
<pre class="brush: scala;">
  def stringDistance(s1: String, s2: String): Int = {
    def sd(s1: List[Char], s2: List[Char], costs: List[Int]): Int = s2 match {
      case Nil =&#62; costs.last
      case c2 :: tail =&#62; sd( s1, tail,
          (List(costs.head+1) /: costs.zip(costs.tail).zip(s1))((a,b) =&#62; b match {
            case ((rep,ins), chr) =&#62; Math.min( Math.min( ins+1, a.head+1 ), rep + (if (chr==c2) 0 else 1) ) :: a
          }).reverse
        )
    }
    sd(s1.toList, s2.toList, (0 to s1.length).toList)
  }
</pre>
<p>Like I say, it&#8217;s brief.  Those List methods give you a lot of mileage.</p>
<h2>Refactoring: Real Recursion</h2>
<p>The more I looked at my previous attempt at a recursive solution, the more I realized how hare-brained it was.  It wasn&#8217;t <em>real</em> recursion.  It was just iteration using the stack.  So I went back to the drawing board.  If I want to know the final answer, the value in the bottom right position, how do I get it?  I apply my three rules to the above, left, and above-left positions.  How do I get those positions?  Apply the rules again.  That&#8217;s real recursion.  Here&#8217;s my first stab at it:</p>
<pre class="brush: scala;">
  def stringDistance(s1: String, s2: String): Int = {
    def min(a:Int, b:Int, c:Int) = Math.min( Math.min( a, b ), c)
    def sd(s1: List[Char], s2: List[Char]): Int = (s1, s2) match {
      case (_, Nil) =&#62; s1.length
      case (Nil, _) =&#62; s2.length
      case (c1::t1, c2::t2)  =&#62; min( sd(t1,s2) + 1, sd(s1,t2) + 1,
                                     sd(t1,t2) + (if (c1==c2) 0 else 1) )
    }
    sd( s1.toList, s2.toList )
  }
</pre>
<p>Now, THAT is a nice looking recursive function.  That&#8217;s more like it.  See the pattern match block?  If we try to convert from any string to the empty string or from the empty to a non-empty string then we just use the string length.  You see?  That takes care of the positions along the top and left of the grid.  All the others are determined in the last case.  That last case just applies our three rules.  That is so short and simple.  It&#8217;s a thing of beauty.</p>
<p>The only problem?  It doesn&#8217;t work.</p>
<p>It&#8217;s technically correct.  It will return correct answers &#8230; eventually.  Or, rather, I think it will.  I can&#8217;t be sure because it&#8217;s too slow to complete my unit tests! For anything but very short inputs (4 or 5 characters), the function takes a long time to return.  Why?  Let&#8217;s look at how many recursive calls are made for some inputs.</p>
<p>If we pass use strings &#8220;a&#8221; and &#8220;b&#8221; we pass by the &#8220;(_, Nil)&#8221; and &#8220;(Nil, _)&#8221; cases in the first call to function sd, because both our strings (Lists, actually) are non-empty.  This results in three more calls to sd.  Each of these three calls includes an empty List of characters, so there is no more recursion.  That&#8217;s a total of four calls to sd for strings &#8220;a&#8221; and &#8220;b&#8221;.</p>
<p>What about &#8220;ab&#8221; and &#8220;xy&#8221;?  Think about it for a moment?  Step through the function in your head.  How many calls to sd will there be for &#8220;ab&#8221; and &#8220;xy&#8221;?</p>
<p>Have you done it?  I count 19.  What about &#8220;abc&#8221; and &#8220;xyz&#8221;?  I&#8217;ll save you the trouble.  It&#8217;s 94.  For length 4 strings it&#8217;s 481.  For length 5 it&#8217;s 2524.  Length 6 is 13,483.  Then 73 thousand, then 400 thousand, then 2 million and so forth.  Why so many calls?  Each position in the grid is computed using all the positions to the left and all the positions above the current position.  So a position in the top left will be computed and recomputed many times.</p>
<p>There is a way to get around this, of course.  You probably already have some ideas.  We&#8217;re going to do something called memoization.  When you memoize a function, you make it remember results that it computed previously without having to actually recompute them.  I&#8217;ll do that by caching results in a map.  The map&#8217;s key is a Pair of List[Char]s, the inputs to my inner function sd, and its data is an Int, the return type of sd.  I will modify sd to first check the map to see if the result for the current parameters has already been cached.  If so, we simply return it.  If not, we compute the value, cache it, and return it.</p>
<pre class="brush: scala;">
  def stringDistance(s1: String, s2: String): Int = {
    val memo = scala.collection.mutable.Map[(List[Char],List[Char]),Int]()
    def min(a:Int, b:Int, c:Int) = Math.min( Math.min( a, b ), c)
    def sd(s1: List[Char], s2: List[Char]): Int = {
      if (memo.contains((s1,s2)) == false)
        memo((s1,s2)) = (s1, s2) match {
          case (_, Nil) =&#62; s1.length
          case (Nil, _) =&#62; s2.length
          case (c1::t1, c2::t2)  =&#62; min( sd(t1,s2) + 1, sd(s1,t2) + 1,
                                         sd(t1,t2) + (if (c1==c2) 0 else 1) )
        }
      memo((s1,s2))
    }

    sd( s1.toList, s2.toList )
  }
</pre>
<p>There.  That uglies up my function somewhat, but at least it&#8217;s usable now.  And it passes my unit tests, so I&#8217;m reasonably assured that it&#8217;s right.</p>
<p>Memoization only works if you expect the same result for each identical function call.  If your function takes input from stdin, for example, you can&#8217;t memoize that.  Or if it has a random component.  Or if, for any other reason, its return value is not always the same for the same inputs.  You can memoize functions in different ways.  There&#8217;s a post on <a href="http://michid.wordpress.com/2009/02/23/function_mem/">Michid&#8217;s Weblog</a> about a more general solution, a memoizing class which wraps existing functions to give you a memoized version.</p>
<h2>PHEW!</h2>
<p>Ok, I&#8217;ve tried to keep my rambling to a minimum in this post but it&#8217;s still a doozy.  The things I wanted to get across are:</p>
<ul>
<li>The usefulness of Levenshtein distance in solving a variety of problems.</li>
<li>How to understand the Levenshtein distance algorithm and why it works.</li>
<li>How to use unit tests to improve your code while maintaining some assurance that the new code still has the correct behavior.</li>
<li>Some of the different ways of implementing Levenshtein.</li>
</ul>
<p>In the end, I think I like the second implementation (the one that switches out the two rows) and the last implementation the best.  The second one seems to have good performance.  I did some informal performance tests and it has a good mix of performance and simplicity.  The last one, the memoized recursive one, appeals to me because it is in a more functional style and still has respectable performance.</p>
<p style="text-align:right;font-family:Times;">Don&#8217;t forget to <a href="http://oldfashionedsoftware.com/feed/rss"><img src="http://oldfashionedsoftware.com/files/2008/08/rssbutton.png" alt="" /> subscribe to my RSS feed</a>, or <a href="http://twitter.com/mmofsoftware"><img src="http://oldfashionedsoftware.com/files/2009/08/twitter.png" alt="" /> follow this blog on Twitter</a>.<br />
Copyright © 2009 Matthew Jason Malone</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JS_RUnit Reformulated]]></title>
<link>http://uglyweb.wordpress.com/2009/11/17/js_runit-reformulated/</link>
<pubDate>Tue, 17 Nov 2009 17:23:30 +0000</pubDate>
<dc:creator>gutzofter</dc:creator>
<guid>http://uglyweb.wordpress.com/2009/11/17/js_runit-reformulated/</guid>
<description><![CDATA[js_runit is now a standalone JavaScript testing framework. So if your into a minimalist JavaScript t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://github.com/gutzofter/js_runit">js_runit</a> is now a standalone JavaScript testing framework. So if your into a minimalist JavaScript testing experience, this tool is for you. Two files to download. The html file and the JavaScript file. Included with this is an example of Passive View with unit tests.</p>
<p>To really appreciate this see the <a href="http://jsbin.com/ebuce/edit">passive view example</a>.</p>
<p>The <a href="http://jsbin.com/uhiza/edit">unit tests for the above example can be found here</a>.</p>
<p>Happy unit testing.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Add Adapter Service Reference Not Showing in UnitTest Project]]></title>
<link>http://dgoins.wordpress.com/2009/11/16/add-adapter-service-reference-not-showing-in-unittest-project/</link>
<pubDate>Mon, 16 Nov 2009 21:02:58 +0000</pubDate>
<dc:creator>dngoins</dc:creator>
<guid>http://dgoins.wordpress.com/2009/11/16/add-adapter-service-reference-not-showing-in-unittest-project/</guid>
<description><![CDATA[Quick Hack: Right-click the unit test project in VS.NET -&gt; Unload Right-click the unit test proje]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Quick Hack:
</p>
<p>Right-click the unit test project in VS.NET -&#62; Unload
</p>
<p>Right-click the unit test project in VS.NET -&#62; Edit [project file]
</p>
<p>Navigate to &#60;ProjectTypeGuids&#62;…
</p>
<p>Remove &#8220;{3AC096D0-A1C2-E12C-1390-A8335801FDAB};&#8221; from the listing.
</p>
<p>Save the file. Reopen in VS.NET.
</p>
<p><span style="color:black;"><strong>Finito!!!</strong></span><span style="color:red;"><br />
		</span></p>
<p><span style="color:red;"><strong>Don&#8217;t forget to add this line back to have the project behave like a VS.NET Unit Test project after adding the Adapter reference!!!</strong></span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Code Farming: Sprouting Some Methods]]></title>
<link>http://blog.criticalresults.com/2009/11/16/code-farming-sprouts/</link>
<pubDate>Mon, 16 Nov 2009 05:59:12 +0000</pubDate>
<dc:creator>Mark W. Schumann</dc:creator>
<guid>http://blog.criticalresults.com/2009/11/16/code-farming-sprouts/</guid>
<description><![CDATA[I am trying, with only partial success, to apply what I&#8217;ve learned in Working Effectively With]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I am trying, with only partial success, to apply what I&#8217;ve learned in <a title="Working Effectively With Legacy Code" href="http://www.powells.com/biblio/62-9780131177055-1"><em>Working Effectively With Legacy Code</em></a> by Michael C. Feathers.</p>
<p>Feathers is a huge advocate of test-driven development. He puts it out there on page xvi: &#8220;Code without tests is bad code.&#8221; He defines &#8220;legacy code&#8221; as, strictly speaking, any code that isn&#8217;t already under unit tests. At first it struck me as a funny definition, because obviously lots of code is written today&#8211;even by me&#8211;without unit tests, and how can it be right to refer to software <em>nobody&#8217;s even thought of yet</em> as &#8220;legacy&#8221;? But for purposes of the book it works.</p>
<p><!--more--></p>
<p>The bulk of this text consists of techniques for making changes in existing code, either while bringing into a unit testing regime or while carefully working around the lack of one. Thoughtfully, each of the chapters is titled with a question or complaint, to wit:</p>
<ul>
<li>How Do I Add a Feature?</li>
<li>I Need to Make Change, but I Don&#8217;t Know What Tests to Write</li>
<li>My Test Code Is in the Way</li>
</ul>
<p>and so on.</p>
<p>Within each chapter, Feathers gives one or more coping techniques. The effect is quite a lot like that of <a title="Design Patterns" href="http://www.powells.com/biblio/4-9780201633610-15">Design Patterns</a> by Gamma et al., sort of an indexed glossary of solutions. With names. Throughout the text, solutions are referenced by name and page number, such as when the Sprout Method (59) solution suggests use of Pass Null (111).</p>
<h2>Sprout Farming</h2>
<p>And that&#8217;s the one I want to talk about today: the Sprout Method solution. I&#8217;ve used this a lot recently and it makes sense even if it looks weird at first.</p>
<div style="border:1px solid gray;background:yellow none repeat scroll 0 0;width:30%;float:left;font-size:small;margin:.5em;padding:3px;">Is making non-sucky software your bag? Then get onto <a title="Free stuff! Easy! Fun!" href="http://criticalresults.com/freestuff.html">my eZine mailing list</a>. It has a complete eZine mailing about once a month, with articles and links and special offers that help you do your job, as well a quick note with something funny or interesting every week or so. And vegetarian recipes too! Go. You want to.</div>
<h3>Here&#8217;s the problem.</h3>
<p>You need to add some code to a method, you might need to do it in multiple places in the system, you want the changes to be unit-tested, and you need to do it right away without a lot of refactoring.</p>
<h3>Here&#8217;s the solution.</h3>
<p>You write the added code as a new method and call it where needed, rather than typing the new code in every place it goes.</p>
<p>This can be kind of ugly at first, because your original method might have thirty lines of logic-logic-logic and then there&#8217;s this one crazy method call in the middle of it that does about five lines of stuff and it&#8217;s not obvious why you didn&#8217;t put it in the main method.</p>
<p>But here&#8217;s the thing. The new method can be put under unit test, and then you&#8217;ve gained a little bit more control over the <em>next</em> change and the change after that. Maybe bits and pieces of the big methods migrate into your little new method over time. Maybe your big methods eventually turn into lots of these little methods, and then you realize the big methods are now <em>completely unit tested anyway</em> and you&#8217;ve succeeded!</p>
<h2>What it&#8217;s good for</h2>
<p>If today were endless, we&#8217;d spend it refactoring everything into logical units and placing it all under test with JUnit or NUnit or the like. That would be cool. But alas, the world is not that cool, and we don&#8217;t get to muck around with code that already works just to make it hypothetically easier to change in the future. What we <em>can</em> do is get the most benefit from the changes that we have to make anyway.</p>
<p>So Sprout Method (59) is a good start. Long story short, when you need to add a few (or more) lines of code to an existing method, consider making the new code a testable method of its own.</p>
<p>&#160;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Buch-Rezension zu "The Art of Unit Testing"]]></title>
<link>http://graberj.wordpress.com/2009/11/08/buch-rezension-zu-the-art-of-unit-testing/</link>
<pubDate>Sun, 08 Nov 2009 12:45:32 +0000</pubDate>
<dc:creator>Johnny Graber</dc:creator>
<guid>http://graberj.wordpress.com/2009/11/08/buch-rezension-zu-the-art-of-unit-testing/</guid>
<description><![CDATA[&#8220;The Art of Unit Testing&#8221; von Roy Osherove ist im Mai 2009 bei Manning erschienen. Das B]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.manning.com/osherove/"><img src="http://graberj.wordpress.com/files/2009/10/artunittesting.jpg" alt="The Art of Unit Testing" title="The Art of Unit Testing" width="150" height="186" class="alignleft size-full wp-image-160" /></a>&#8220;The Art of Unit Testing&#8221; von <a href="http://weblogs.asp.net/ROsherove/">Roy Osherove</a> ist im Mai 2009 bei Manning erschienen. Das Buch behandelt Unit Testing in C#. </p>
<p>&#160;<br />
<strong>Zum Inhalt</strong><br />
<strong>Kapitel 1</strong> zeigt die Basis von Unit Tests. Diese umfasst eine Definition der Begriffe, eine kurze Einführung zu Test-Driven Development (TDD) und eine Abgrenzung gegen Integrationstests. Den nicht alles, was sicht Unit Test nennt, ist auch wirklich einer.</p>
<p><strong>Kapitel 2</strong> hilft einem durch den ersten Unit Test. Nach der Auflistung der Vorteile die ein entsprechendes Test-Framework bringen folgt ein Rundgang durch NUnit. Dieser reicht von der Installation über die Einrichtung eines Test-Projekts zu Namenskonventionen bis hin zur Ausführung der Tests.</p>
<p>Wie man mit <a href="http://de.wikipedia.org/wiki/Stub_%28Programmierung%29">Stubs </a>die Abhängigkeiten aufbrechen kann wird in <strong>Kapitel 3</strong> gezeigt. Das Beispielprojekt hat zu beginn eine direkte Abhängigkeit zum Dateisystem. In 2 Schritten wird der Code so umgebaut, dass die Abhängigkeit aufgelöst werden kann. Mit einer kleinen Hilfsklasse, dem Stub, kann man dann genau die Antwort zurück liefern, die man für den Test der Übergeordneten Klasse benötigt. Dies kann in dem Beispiel sowohl ein Boolean sein wie auch eine Exception des Dateisystems.<br />
Es folgt ein Abstecher ins Thema <a href="http://de.wikipedia.org/wiki/Dependency_Injection">Dependency Injection</a>. Denn der Stub, aber auch die konkrete Klasse mit der Logik, muss ja mit der aufrufenden Klasse verbunden werden. Es werden die Vor- und Nachteile der jeweiligen Ansätze dargelegt, damit man selber das zu seinem Problem passende auswählen kann. </p>
<p><strong>Kapitel 4</strong> zeigt wie man mit Mock Objekten die Interaktion mit der zu testenden Klasse prüfen kann. Mit einem selbst geschriebenen Mock wird das Prinzip erklärt, bevor in <strong>Kapitel 5</strong> das Mock-Framework <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a> erklärt wird. Eine Übersicht der anderen verbreiteten Frameworks (wie <a href="http://learn.typemock.com/">TypeMock</a>, <a href="http://www.nmock.org/">NMock </a>und <a href="http://www.nunit.org/index.php">NUnit.Mocks</a>) rundet das Kapitel ab. </p>
<p>Die Organisation von Tests, Test Patterns und Continuous Integration bilden das <strong>Kapitel 6</strong>, während  <strong>Kapitel 7</strong> die Qualität der Tests behandelt. Lesbarkeit und Verständlichkeit sind Dinge, die auch bei Tests bedacht werden müssen. </p>
<p><strong>Kapitel 8</strong> hilft bei der Integration von Unit Tests in die Firma. Hierbei geht es nicht um die technische, sondern um die organisatorische Ebene. Osherove berichtet über seine Erfahrungen und liefert Antworten zu häufig aufkommenden Fragen und Problemen. </p>
<p>Wie man mit Legacy Code arbeiten kann zeigt <strong>Kapitel 9</strong>. Grosse Projekte ohne wirkliche Unit Tests benötigen spezifische Vorgehensweise. Auch hier werden Vor- und Nachteile der Ansätze aufgezeigt. Der Einsatz von Tools kann einem auch hier das Leben erleichtern. Depender oder NDepend können Abhängigkeiten anzuzeigen, was als Ausgangslage für Unit Tests dienen kann. Für Java Entwickler werden die Tools <a href="https://jmockit.dev.java.net/">JMockit </a>(vergleichbar mit TypeMock) und Vise erwähnt. </p>
<p>Design und Testbarkeit werden noch einmal ausführlich im <strong>Anhang A</strong> behandelt. <strong>Anhang B</strong> bietet eine kompakte Auflistung von Tools und Frameworks aus allen Bereichen von Tests.</p>
<p>&#160;<br />
<strong>Fazit</strong><br />
Ein sehr gutes Buch zur Kunst des Unit Testings. Auf rund 300 Seiten erfährt man unzählige Möglichkeiten zum sauberen testen. Das Buch richtet sich eher an Leser mit Erfahrungen im Bereich Unit Testing. Für Anfänger mag sich nicht immer erschliessen, worin die Vorteile der jeweiligen Ansätze liegen. Hat man sich aber mit den Problemen selber herumgeschlagen, braucht es nicht mehr viele Worte. Ich fand das Buch eine ideale Ergänzung zu <a href="http://graberj.wordpress.com/2009/09/15/buch-rezension-zu-test-driven/">Test Driven</a>.<br />
Der Anhang A hätte ein eigenes, „richtiges“ Kapitel verdient und einige Grafiken hätte man nochmals überarbeiten können. Davon abgesehen ist das Buch sehr gut.</p>
<p>&#160;<br />
<strong>Zum Buch</strong><br />
<a href="http://www.manning.com/osherove/">The Art of Unit Testing with Examples in .NET</a> von Roy Osherove, 2009 Manning, ISBN 978-1-933988-27-6, 320 Seiten</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Métodos internal, unit testing y el atributo InternalsVisibleTo]]></title>
<link>http://adeshoras.wordpress.com/2009/11/05/metodos-internal-unit-testing-y-el-atributo-internalsvisibleto/</link>
<pubDate>Thu, 05 Nov 2009 22:12:05 +0000</pubDate>
<dc:creator>César</dc:creator>
<guid>http://adeshoras.wordpress.com/2009/11/05/metodos-internal-unit-testing-y-el-atributo-internalsvisibleto/</guid>
<description><![CDATA[Los miembros y métodos en C#, pueden gozar de varios modificadores de acceso. Amigos míos, no solo d]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Los miembros y métodos en C#, pueden gozar de varios modificadores de acceso. Amigos míos, no solo de públicos y privados vive el hombre.</p>
<p>Hoy vamos a hablar de uno de ellos.</p>
<h2>El modificador de acceso internal.</h2>
<p>El modificador de acceso internal, es aquel que nos va a permitir acceder a la clase, miembro, método etc. desde el propio ensamblado.</p>
<p>Que quiere decir esto, pues implica que dentro de un mismo ensamblado vamos a poder acceder a una clase internal como si de una clase pública se tratara, pero fuera de este ensamblado esta clase no va a ser accesible ya que no la estamos exponiendo.</p>
<p>Trabajar con clases internal, considero que es una buena práctica, ya que en los distintos assemblies que vamos generando, únicamente vamos a exponer lo que consideramos fundamental, de manera que el susodicho assembly, queda mucho más encapsulado. Además si el software que estamos desarrollando va a ser distribuido para que lo usen terceros, todavía tenemos más razones para usar este tipo de modificador de acceso.</p>
<h2>Los métodos internal y las pruebas unitarias (unit test) o como acceder a aquello que no expones.</h2>
<p>Hasta aquí, me encanta el modificador de acceso internal, pero ¿qué ocurre cuando tenemos que crear las pruebas unitarias para métodos internal?</p>
<p>Pues muy sencillo, que como no estamos exponiendo muchas clases y métodos, resulta que no lo podemos probar.</p>
<p>Jajajajaja, bueno, esto no es así exactamente aunque sí que es verdad que es una de las primeras cositas que encuentras (si tu desarrollo es TDD compliance claro).</p>
<p>La realidad es que no estamos exponiendo muchas clases por lo tanto no deberíamos poder probarlas, pero el Framework de ASP.NET precisamente cuenta “un mecanismo” para realizar esto.</p>
<h2>El atributo InternalsVisibleTo.</h2>
<p>Pues si amigos míos, el Framework de ASP.NET cuenta con atributo llamado InternalsVisibleTo que nos va a permitir acceder a clases internal desde assemblies externos.</p>
<p>El código necesario sería el siguiente:<br />
<code>[assembly: InternalsVisibleTo("MiAssemblyName.Test")]</code></p>
<p>Y esto, tenemos que colocarlo en el AssemblyInfo de nuestro proyecto.</p>
<p>Nada más por hoy mis druguitos. Aquí se acaba esta sesión de ultraviolencia. Os dejo con The XX, que además de ser unos chavales que hacen una música que me recuerda a los títulos de crédito de documentos tv, son geniales.</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/Pib8eYDSFEI&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/Pib8eYDSFEI&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Calculating Coverage with NCover]]></title>
<link>http://thegsharp.wordpress.com/2009/10/28/calculating-coverage-with-ncover/</link>
<pubDate>Wed, 28 Oct 2009 13:20:17 +0000</pubDate>
<dc:creator>machadogj</dc:creator>
<guid>http://thegsharp.wordpress.com/2009/10/28/calculating-coverage-with-ncover/</guid>
<description><![CDATA[NCover is an excellent tool that allows you to calculate how much of your code is being hit by your ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>NCover is an excellent tool that allows you to calculate how much of your code is being hit by your unit tests. Basically what it does is a profile of your application. So you can run your tests through any application and NCover will tell you the coverage of your tests. NCover is not an open source free tool, however it does have a Community Edition that will do the work for this tutorial which you can download from <a title="NCover Community Edition" href="http://www.ncover.com/download/community" target="_blank">here</a> after going through the registration.</p>
<p>Since I have already showed how to run <a title="running nunit from the cosole" href="http://thegsharp.wordpress.com/2009/10/27/running-nunit-from-the-console/" target="_blank">NUnit tests from the console</a>, we are going to calculate the  coverage using NCover with NUnit. And taking advantage of the folder structure used we will continue with the following structure:</p>
<div id="attachment_71" class="wp-caption alignnone" style="width: 200px"><img class="size-full wp-image-71" title="ncover folder" src="http://thegsharp.wordpress.com/files/2009/10/ncover1.png" alt="ncover folder" width="190" height="207" /><p class="wp-caption-text">ncover folder</p></div>
<p>In order to make this available to the whole team, we are going to create a batch file (.bat) that will run the command for us (this will be usefull when integrating it with Nant). As I explained earlier, ncover has to execute an application in order to do the profiling. In our case, we want to run the NUnit tests, so this application will be nunit-console that rests in \lib\nunit 2.4.8 folder. We covered the parameters that NUnit needs in order to run our tests in my previous <a title="running nunit from the console" href="http://thegsharp.wordpress.com/2009/10/27/running-nunit-from-the-console/" target="_blank">post</a>, so the only thing left to do is run ncover. The batch file will in the trunk folder, and will contain the following command:</p>
<p>.\NCover\NCover.console.exe  .\nunit\nunit-console.exe /xml=.\build-result\tests.xml .\Concur.Lib.Tests\bin\debug\Concur.Lib.Tests.dll</p>
<p>We can optionally add a parameter in order to store the coverage output file into a different folder, like this: //x .\build-result\coverage.xml, so the batch file would look like this:</p>
<p>.\NCover\NCover.console.exe //x .\build-result\coverage.xml .\nunit\nunit-console.exe /xml=.\build-result\tests.xml .\Concur.Lib.Tests\bin\debug\Concur.Lib.Tests.dll</p>
<p>And finally you can use your favorite xsl in order to visualize the results. There’s a very cool xsl file in the NCover folder called “coverage.xsl” which you can use by editing the xml to add the reference like this:<br />
&#60;?xml version=”1.0″ encoding=”utf-8″ standalone=”no”?&#62;<br />
&#60;?xml-stylesheet type=”text/xsl” href=”coverage.xsl”?&#62;</p>
<p>Adding this file to the build-result folder is a good idea too.</p>
<p>So we have successfully calculated our NCoverage coverage for our project, and left a batch file available to the whole team to run it in their local machine. Simple as it is, this leaves us one step closer to having a pretty decent build mechanism.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Next Generation]]></title>
<link>http://nikhilsidhaye.wordpress.com/2009/10/26/test-next-generation/</link>
<pubDate>Mon, 26 Oct 2009 15:01:33 +0000</pubDate>
<dc:creator>nikhilsidhaye</dc:creator>
<guid>http://nikhilsidhaye.wordpress.com/2009/10/26/test-next-generation/</guid>
<description><![CDATA[Test Next Generation !! Definitely TestNG. TestNG is a testing framework designed to simply a broad ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h1>Test Next Generation !! Definitely <a title="Test Next Generation" href="http://testng.org">TestNG</a>.</h1>
<p>TestNG is a testing framework designed to simply a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers).</p>
<p>TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use, such as:</p>
<ul>
<li>JDK 5 Annotations (JDK 1.4 is also supported with JavaDoc annotations).</li>
<li>Flexible test configuration.</li>
<li>Support for data-driven testing (with @DataProvider).</li>
<li>Support for parameters.</li>
<li>Allows distribution of tests on slave machines.</li>
<li>Powerful execution model (no more TestSuite).</li>
<li>Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc&#8230;).</li>
<li>Embeds BeanShell for further flexibility.</li>
<li>Default JDK functions for runtime and logging (no dependencies).</li>
<li>Dependent methods for application server testing.</li>
</ul>
<p>TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc&#8230;</p>
<p>Writing a test is typically a three-step process:</p>
<ol>
<li>Write the business logic of your test and insert TestNG annotations in your code.</li>
<li>Add the information about your test (e.g. the class name, the groups you wish to run, etc&#8230;) in a testng.xml file or in build.xml</li>
<li>Run TestNG</li>
</ol>
<h2><strong>Requirements:</strong></h2>
<p>TestNG runs on JDK 1.4 and 5.  The examples shown in this documentation assume JDK 5 and therefore, use JDK 5 annotations, but they can easily be translated to JDK 1.4 JavaDoc-type annotations.</p>
<h2><strong>Integration with other tools:</strong></h2>
<p>TestNG can be integrated with Eclipse, IDEA IntelliJ and NetBeans with plugins.<br />
Also by ant &#38; maven you can integrate this TestNG to any Java Project.</p>
<h2><strong>Simple Example:</strong></h2>
<p>I am giving simple example from testng.org site to visualize how easy to configure TestNG to in any project.</p>
<blockquote><p>package example1;</p>
<p>import org.testng.annotations.*;</p>
<p>public class SimpleTest {</p>
<p>@BeforeClass<br />
public void setUp() {<br />
// code that will be invoked when this test is instantiated<br />
}</p>
<p>@Test(groups = { &#8220;fast&#8221; })<br />
public void aFastTest() {<br />
System.out.println(&#8220;Fast test&#8221;);<br />
}</p>
<p>@Test(groups = { &#8220;slow&#8221; })<br />
public void aSlowTest() {<br />
System.out.println(&#8220;Slow test&#8221;);<br />
}</p>
<p>}</p></blockquote>
<p>The method<span style="text-decoration:underline;"> setUp()</span> will be invoked after the test class has been built and before any test method is run.  In this example, we will be running the group fast, so <span style="text-decoration:underline;">aFastTest()</span> will be invoked while <span style="text-decoration:underline;">aSlowTest()</span> will be skipped.</p>
<h2><strong>Things to note:</strong></h2>
<ul>
<li>No need to extend a class or implement an interface.</li>
<li>Even though the example above uses the JUnit conventions, our methods can be called any name you like, it&#8217;s the annotations that tell TestNG what they are.</li>
<li>A test method can belong to one or several groups. These groups will be used at runtime to determine what test methods should be invoked..</li>
</ul>
<p>Once you have compiled your test class into the build directory, you can invoke your test with the command line, an ant task (shown below) or an XML file:</p>
<blockquote><p>&#60;project default=&#8221;test&#8221;&#62;</p>
<p>&#60;path id=&#8221;cp&#8221;&#62;<br />
&#60;pathelement location=&#8221;lib/testng-testng-4.4-jdk15.jar&#8221;/&#62;<br />
&#60;pathelement location=&#8221;build&#8221;/&#62;<br />
&#60;/path&#62;</p>
<p>&#60;taskdef name=&#8221;testng&#8221; classpathref=&#8221;cp&#8221;<br />
classname=&#8221;org.testng.TestNGAntTask&#8221; /&#62;</p>
<p>&#60;target name=&#8221;test&#8221;&#62;<br />
&#60;testng classpathref=&#8221;cp&#8221; groups=&#8221;fast&#8221;&#62;<br />
&#60;classfileset dir=&#8221;build&#8221; includes=&#8221;example1/*.class&#8221;/&#62;<br />
&#60;/testng&#62;<br />
&#60;/target&#62;</p>
<p>&#60;/project&#62;</p></blockquote>
<p>Use ant to invoke it:</p>
<blockquote><p>D:&#62; ant<br />
Buildfile: build.xml</p>
<p>test:<br />
[testng] Fast test<br />
[testng] ===============================================<br />
[testng] Suite for Command line test<br />
[testng] Total tests run: 1, Failures: 0, Skips: 0<br />
[testng] ===============================================</p>
<p>BUILD SUCCESSFUL<br />
Total time: 4 seconds</p></blockquote>
<p>You can view the results from browser for above file test-output\index.html</p>
<h2><strong>Why TestNG:</strong></h2>
<ul>
<li><strong>Parametric Testing Ability: </strong>One of my favorite features of TestNG is its parametric testing ability, which allows you to create generic test cases and then vary the test values– you can use parameters from XML files or even use the Data Provider feature for a richer parameter type. In fact, for awhile, because it’s my bag baby, I’ve been espousing TestNG’s out of the box parametric testing features as a reason to use TestNG as an opposed to JUnit for higher level testing. JUnit 4, however, now supports parametric tests– and you’ll find that its parametric testing is rather similar to TestNG’s Data Provider.</li>
<li><strong>Configurable Test Suite:</strong> Second one should not dirty his/her hands to create test suite. Here you just write xml &#38; you done with your test suite. You can define which test should executed etc.</li>
<li><strong>Logical Groups:</strong> Other feature is grouping. You can create logical groups which may be class level or method level or both by simply annotations. Suppose you have different packages in BO layer so you can define class level group for Business Layer for all classes. &#38; you can run TestNG only for those groups.</li>
<li>Reports: You can generate different reports from email-able reports to deep level reports. You also can generate diff. reports using custom style sheets.</li>
</ul>
<h2><strong>Reports:</strong></h2>
<p>There are different types of Report generated in one go:</p>
<ul>
<li>Chronological Reports: Methods run, sorted chronologically</li>
<li>Alphabetical Reports: Methods run, sorted alphabetically</li>
<li>Groups Report: Groups used for this test run</li>
<li>Not Run Methods: Methods that were not run</li>
<li>Reporter Out: If you used Reporter API provided by TestNG.</li>
<li>Emailable-report: Small &#38; Sweet Report may be useful for client or PM.</li>
</ul>
<p>If possible just try out in your project. It really worth to try.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Run unit tests in Resharper 4.5.1]]></title>
<link>http://robertoschiabel.wordpress.com/2009/10/23/run-unit-tests-in-resharper/</link>
<pubDate>Fri, 23 Oct 2009 12:04:18 +0000</pubDate>
<dc:creator>robertoschiabel</dc:creator>
<guid>http://robertoschiabel.wordpress.com/2009/10/23/run-unit-tests-in-resharper/</guid>
<description><![CDATA[Looking for more info about running unit tests in Resharper, I found this post: MSTest ReSharper 4 P]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Looking for more info about running unit tests in Resharper, I found this post: <a href="http://www.sneal.net/blog/2009/01/24/MSTestReSharper4Plugin.aspx" target="_blank">MSTest ReSharper 4 Plugin</a>.</p>
<p><a href="http://www.jetbrains.com/resharper/index.html" target="_blank">Resharper 4.5</a> support <a href="http://odetocode.com/blogs/scott/archive/2007/07/23/unit-testing-with-visual-studio-2008.aspx" target="_blank">MSTest</a> natively (<a href="http://www.jetbrains.com/resharper/features/newfeatures.html" target="_blank">here</a>), so it&#8217;s obsolete but not useless. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>During my early tests, I found Resharper running slowly my unit tests, but more customizable. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<pre>Technorati tags: <a href="http://technorati.com/tags/Visual+Studio" target="_blank">Visual Studio</a>, <a href="http://technorati.com/tags/Resharper" target="_blank">Resharper</a>, <a href="http://technorati.com/tags/Unit+Test" target="_blank">Unit Test</a></pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Erro MSB6006 em testes unitários numa Team Build]]></title>
<link>http://blog.ricardoserradas.net/2009/10/20/erro-msb6006-em-testes-unitarios-numa-team-build/</link>
<pubDate>Tue, 20 Oct 2009 19:54:55 +0000</pubDate>
<dc:creator>Ricardo Serradas</dc:creator>
<guid>http://blog.ricardoserradas.net/2009/10/20/erro-msb6006-em-testes-unitarios-numa-team-build/</guid>
<description><![CDATA[Olá a todos! Hoje vamos falar de mais um capítulo da série &#8220;Problema e solução&#8221;. Problem]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá a todos! Hoje vamos falar de mais um capítulo da série &#8220;Problema e solução&#8221;.</p>
<p><strong>Problema</strong>:</p>
<p>Ao configurar uma Team Build no VSTS de um projeto que compila e que roda os testes unitários tudo certinho, a build roda, porém o status dela fica como &#8220;<em>Partially Succeeded</em>&#8221; porque os testes unitários falharam e, ao analisar o log, você encontra a seguinte linha no final:</p>
<p><span style="color:#ff0000;">MSBUILD : warning MSB6006: &#8220;MSTest.exe&#8221; exited with code 1.</span></p>
<p>O mais interessante é que se você roda os testes unitários a partir do <em>Test List</em> da Solution, todos funcionam, não é?</p>
<p><strong>Causa</strong>:</p>
<p>Pois bem. Por algum motivo, o erro se dá por conta do usuário TFSSERVICE* não ter permissão na pasta onde o resultado do build foi colocado (ou &#8220;dropado&#8221;).</p>
<p><strong>Solução</strong>:</p>
<p>Basta permitir escrita (tanto NTFS quando de compartilhamento) para pra o usuário TFSSERVICE na pasta de build drop.</p>
<p>*Este nome pode variar de acordo com a instalação realizada.</p>
<p>[]&#8217;s</p>
<p>Ricardo Serradas</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Javascript Complexity]]></title>
<link>http://uglyweb.wordpress.com/2009/10/14/javascript-complexity/</link>
<pubDate>Thu, 15 Oct 2009 00:45:07 +0000</pubDate>
<dc:creator>gutzofter</dc:creator>
<guid>http://uglyweb.wordpress.com/2009/10/14/javascript-complexity/</guid>
<description><![CDATA[Javascript is a language used in web development. I would argue that it is Object Oriented (OO). And]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Javascript is a language used in web development. I would argue that it is Object Oriented (OO). And due to this the <a href="http://mmiika.wordpress.com/oo-design-principles/">principles guiding</a> development in an OO language apply.</p>
<p>When developing software, at its basic level, you have three responsibilities that need to be managed.</p>
<ol>
<li>Input: consist of user actions.</li>
<li>Output: change to the web browser.</li>
<li>Logic: any piece of code where a decision is made.</li>
</ol>
<p>To manage this complexity, you should be Unit Testing if not testing-first.</p>
<p><a href="http://github.com/gutzofter/js_runit">A simple Javascript unit testing framework used for Rails.</a></p>
<p>&#160;</p>
<h2><a href="http://github.com/gutzofter/js_runit">js_runit</a></h2>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[A short tutorial about unit test with Visual Studio]]></title>
<link>http://robertoschiabel.wordpress.com/2009/10/06/a-short-tutorial-about-unit-test-with-visual-studio/</link>
<pubDate>Tue, 06 Oct 2009 07:38:01 +0000</pubDate>
<dc:creator>robertoschiabel</dc:creator>
<guid>http://robertoschiabel.wordpress.com/2009/10/06/a-short-tutorial-about-unit-test-with-visual-studio/</guid>
<description><![CDATA[Visual Studio has a unit test engine, where you can write you unit tests (TDD, Unit Testing, &#8230;]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.microsoft.com/visualstudio/en-gb/default.mspx" target="_blank">Visual Studio</a> has a unit test engine, where you can write you unit tests (TDD, Unit Testing, &#8230;).<br />
If you need a short (but full!) tutorial to start writing your own unit tests, read <a href="http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx" target="_blank">A Unit Testing Walkthrough with Visual Studio Team Test</a> by Mark Michaelis.<br />
It also will cover refactoring and code coverage items. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<blockquote><p>With the latest release of Visual Studio Test System (VSTS) comes a full suite of functionality for Visual Studio Team Test (TT). Team Test is a Visual Studio integrated unit-testing framework that enables:<br />
-Code generation of test method stubs.<br />
-Running tests within the IDE.<br />
-Incorporation of test data loaded from a database.<br />
-Code coverage analysis once the tests have run.<br />
In addition, Team Test includes a suite of testing capabilities not only for the developer, but the test engineer as well.[...]</p></blockquote>
<p>more info about Visual Studio Products, here <a href="http://blogs.msdn.com/robcaron/archive/2008/01/31/7346879.aspx" target="_blank">Updated: Visual Studio 2008 Product Comparison Guide</a> by <a href="http://blogs.msdn.com/robcaron/" target="_blank">Rob Caron</a></p>
<pre>Technorati tags: <a href="http://technorati.com/tags/Visual+Studio" target="_blank">Visual Studio</a>, <a href="http://technorati.com/tags/Agile" target="_blank">Agile</a>, <a href="http://technorati.com/tags/Unit+Testing" target="_blank">Unit Testing</a>, <a href="http://technorati.com/tags/Refactoring" target="_blank">Refactoring</a>, <a href="http://technorati.com/tags/Code+Coverage" target="_blank">Code Coverage</a></pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Mock me to my (inter)face]]></title>
<link>http://blog.criticalresults.com/2009/10/05/mock-me-to-my-interface/</link>
<pubDate>Mon, 05 Oct 2009 17:55:20 +0000</pubDate>
<dc:creator>Mark W. Schumann</dc:creator>
<guid>http://blog.criticalresults.com/2009/10/05/mock-me-to-my-interface/</guid>
<description><![CDATA[I learned an interesting, although in retrospect somewhat obvious, technique from Michael Feathers]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I learned an interesting, although in retrospect somewhat obvious, technique from Michael Feathers&#8217;s great book, <a href="http://www.powells.com/biblio/62-9780131177055-1"><em>Working Effectively With Legacy Code</em></a>.</p>
<p>Suppose you have a class that can&#8217;t be unit-tested in any automated way because it has side effects or requires user input. Or, in the case of my application, it drives hardware that I don&#8217;t actually have readily at hand. <a href="http://www.nunit.org">NUnit</a> and the like provide input to methods and test the resulting output. How can you run tests on something where the &#8220;output&#8221; is the motion of a sensor arm, or the &#8220;input&#8221; is a stream of weather data?</p>
<p>The short answer is that you really can&#8217;t, but that shouldn&#8217;t stop you from setting up unit tests.</p>
<p><!--more-->The long answer is that you can hide the troubling class behind an interface, then implement the interface again with a class that <em>can</em> be tested.</p>
<p>To wit, let&#8217;s say this is your class now. It moves a data collector probe in 3D space, pulls input of some kind from the probe, and sends output now and then.</p>
<p><code><br />
public class RealFoo<br />
{<br />
public RealFoo()<br />
{<br />
...<br />
}<br />
public void MoveDataCollectorProbe(int x, int y, int z)<br />
{<br />
...<br />
}<br />
public string GetInput()<br />
{<br />
...<br />
}<br />
public void SendOutput(string x)<br />
{<br />
}<br />
}<br />
</code></p>
<p>This is going to be hard to test, because NUnit can&#8217;t see the probe moving around. But what you can test is some file I/O, so you can make a similar class thus:</p>
<p><code><br />
using System.Diagnostics;<br />
public class FakeFoo<br />
{<br />
public FakeFoo()<br />
{<br />
// probably doesn't do anything<br />
}<br />
public void MoveDataCollectorProbe(int x, int y, int z)<br />
{</code><code> Trace.WriteLine ("TRACE: Moving data probe to coordinates x = " +x + ", y = " + y + ", z = " + z);<br />
}<br />
public string GetInput()<br />
{<br />
Trace.WriteLine ("TRACE: Getting input from probe.");<br />
return "Typical Input Here.";<br />
}<br />
public void SendOutput(string x)<br />
{<br />
Trace.WriteLine ("TRACE: Sending output \"" + x + "\" to probe.");<br />
}<br />
}<br />
</code></p>
<p>Obviously the two classes have the same interface:</p>
<p><code><br />
interface Foo<br />
{<br />
Foo();<br />
void MoveDataCollectorProbe (int x, int y, int z);<br />
string GetInput();<br />
void SendOutput(string x);<br />
}<br />
</code></p>
<p>Then you&#8217;d declare that both RealFoo and FakeFoo implement the Foo interface.</p>
<p>At this point, your application code can simply pass a Foo reference around all it likes. While under test, the object factory, or perhaps your own hardcoding, instantiates a FakeFoo. In actual use, or when you have hardware available, you instantiate a RealFoo:</p>
<p><code><br />
public class FooFactory<br />
{<br />
public static Foo MakeFoo()<br />
{<br />
#if DEBUG<br />
return new FakeFoo();<br />
#else<br />
return new RealFoo();<br />
}<br />
}</code></p>
<p>You can make the fake object as realistic as you like: randomize output, do intelligent things with the input, perform error checking, or throw exceptions to stress-test the calling code. The main thing is that tools like NUnit will have a fighting chance at picking up the trace stream and interpreting the results as pass or fail. As a bonus, you can do your development when the specialized hardware is unavailable or you&#8217;re not ready to run it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[to RSpec or not to RSpec]]></title>
<link>http://charpcfn.wordpress.com/2009/10/01/to-rspec-or-not-to-rspec/</link>
<pubDate>Fri, 02 Oct 2009 03:04:18 +0000</pubDate>
<dc:creator>ggnextmap</dc:creator>
<guid>http://charpcfn.wordpress.com/2009/10/01/to-rspec-or-not-to-rspec/</guid>
<description><![CDATA[I took another look at RSpec today. I tried to re-write the script using a test driven development m]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I took another look at RSpec today. I tried to re-write the script using a test driven development method but am finding it harder to use than expected. I think I just have to shift my brain into programming TDD style. I really didn&#8217;t come up with any good code, I must have started over at least 10 times. I started with things like it &#8220;should accept a parameter &#8211;operation that takes either &#8216;add&#8217; or &#8217;sub&#8217; as it&#8217;s value&#8221; Then I would read RSpec docs and try to test tha&#8230;needless to say it&#8217;s a good way to learn about RSpec albeit rather slow. Hopefully I can move my brain to this new style of thinking. It seemed so easy at first but once you try it, it&#8217;s actually kind of difficult to do.</p>
<p>Here is the list of requirements I&#8217;m going to be working off of.</p>
<ul>
<li>it &#8220;should accept two parameters, an operation that is either add or sub and a time value formatted at least with one digit. It should also accept two arguments, an in_file and na out_file&#8221;</li>
<li>it &#8220;should add or subtract time based on the set operation&#8221;</li>
<li>it &#8220;should modify the time by the amount passed in as a parameter of &#8211;time&#8221;</li>
<li>it &#8220;should read times and all other lines from the first file&#8221;</li>
<li>it &#8220;should write modified times and unmodified other lines to the second file&#8221;</li>
</ul>
<p>IF you can get these tests to pass, then you&#8217;ve got yourself a working program and RSpec test to go with it as well as some documentation!</p>
<p>Until next time&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Shift Subtitle, RSpec]]></title>
<link>http://charpcfn.wordpress.com/2009/09/29/shift-subtitle-rspec/</link>
<pubDate>Wed, 30 Sep 2009 00:34:24 +0000</pubDate>
<dc:creator>ggnextmap</dc:creator>
<guid>http://charpcfn.wordpress.com/2009/09/29/shift-subtitle-rspec/</guid>
<description><![CDATA[Sometimes it&#8217;s just nice to have everything you need in your apartment and you can just sit ar]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sometimes it&#8217;s just nice to have everything you need in your apartment and you can just sit around and code :]</p>
<p>I decided today to try my hand at some unit testing using RSpec, as was suggested at the end of the challenge. I haven&#8217;t done much testing before so this seems like a good way to get started. The code I submitted includes a class definition as well as some imperative programming all in one. It would have been nice to separate that out, but this was supposed to be one script that works using the standard library. However, since this is beyond the challenge I&#8217;m going to test the class I&#8217;ve made, SubtitleTime. You can see it in the <a href="http://charpcfn.pastebin.com/f594e4212">pastebin</a>. It takes two parameters, a string in the format of HH:MM:SS,mmm and a &#8216;modifier&#8217; that is either add or sub.</p>
<p>So starting off with RSpec first you have to &#8216;describe&#8217; the class. Then you use a function named &#8216;it&#8217; and write what the class should do. For example:</p>
<pre>describe SubtitleTime do
    it "should be able to add another timestamp to itself" do
    end
end</pre>
<p>Once that part of the code is written, then you just have to add some filler lines to actually test the code. This code above could be expanded to look like this:</p>
<pre><span style="text-decoration:line-through;">describe SubtitleTime do
    it "should be able to add another timestamp to itself" do
        subtitletime.should add_time(another_timestamp)
    end
end</span> # note: this has been crossed out as after reading more about RSpec, this just doesn't make sense.</pre>
<p>Well after having written a few test cases and finally understanding what RSpec is all about, I feel like I should do this the right way and see what happens to my class if I built it using TDD (Test Driven Design). It initially seems very difficult to build up a test suite on an already existing piece of code. So let&#8217;s get started with some test cases.</p>
<p>First off we want the class to have a time that, before altered, is equal to the initial time. The code for that would look like this:</p>
<pre>describe SubtitleTime do
    it "should have time equal to the initial time before the class is altered" do
        subtime = Subtitletime.new(:initial)
        subtitle.time.should == :initial
    end
done</pre>
<p>Then When you run this test with the command &#60;spec subtitletime_spec.rb&#62; it will fail saying there is no class SubtitleTime. Simple. The idea behind TDD is that you make a test case, have it break, then fix it. An occasional (or after each iteration) step of refactoring your code should also be included in this process. So now I&#8217;ll make a class SubtitleTime</p>
<pre>class SubtitleTime
end</pre>
<p>This fixes the first error but we still get another error as the test is run. But that&#8217;s all I have time for right now, I was using an <a href="http://www.ibm.com/developerworks/web/library/wa-rspec/">ibm guide to rspec</a>. That should make things fairly clear. There is a lot to go over and a lot to do, but I&#8217;ll get back to this hopefully sooner rather than later and then finish up this challenge&#8217;s extras!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[September 28-October 2]]></title>
<link>http://ibdogs.wordpress.com/2009/09/29/september-28-october-2/</link>
<pubDate>Tue, 29 Sep 2009 16:44:05 +0000</pubDate>
<dc:creator>ibdogs</dc:creator>
<guid>http://ibdogs.wordpress.com/2009/09/29/september-28-october-2/</guid>
<description><![CDATA[Monday:  Recording of WWI War Guilt podcasts for those signed up.  Review for objective test (40 ter]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong><span style="text-decoration:underline;">Monday:</span></strong>  Recording of WWI War Guilt podcasts for those signed up.  Review for objective test (40 terms from unit cover sheet, matching, worth 20 points).  Begin reviewing for unit test.</p>
<p>*Outline / plan your answer.</p>
<p>*Answer the question being asked. Read the questions carefully.</p>
<p>*Use specific supporting evidence to support your stated position.  Be sure to answer why the evidence supports your position/helps answer the question.</p>
<p>*Proper sequencing of events important.</p>
<p>*Historiography used only when appropriate.  Not as filler when you don’t know the material.</p>
<p><strong><span style="text-decoration:underline;">Tuesday:</span></strong>  Objective test.  We will correct in class once students have finished.  Continue reviewing for unit test.</p>
<p><strong><span style="text-decoration:underline;">Wednesday:</span></strong>  Hand out materials for next unit (Mexican Revolution) &#8211; written assignment, <span style="text-decoration:underline;">Underdogs</span>, unit readings.  Notes on defining a revolution.  No unit test for Unit 1 today because it is an Advisory day which means classes are shortened.</p>
<p><strong><span style="text-decoration:underline;">Thursday:</span></strong>  Unit 1 (World War One) unit test. Students have been given 4 possible essay questions to study.  On this day I will randomly select 2 using a deck of cards and students must answer <strong>one</strong> question.</p>
<p><strong><span style="text-decoration:underline;">Friday:</span></strong>  Begin notes on Mexican Revolution covering the rise of Porfirio Diaz.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[The Zune Freezes: More on Unit Testing]]></title>
<link>http://hbfs.wordpress.com/2009/09/22/the-zune-freezes-more-on-unit-testing/</link>
<pubDate>Tue, 22 Sep 2009 10:33:22 +0000</pubDate>
<dc:creator>Steven Pigeon</dc:creator>
<guid>http://hbfs.wordpress.com/2009/09/22/the-zune-freezes-more-on-unit-testing/</guid>
<description><![CDATA[Do you remember the epic fail that bricked the Zune a whole day on the last day of last year, a bise]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Do you remember the <a href="http://en.wikipedia.org/wiki/Failure#Internet_meme" target="_blank">epic fail</a> that <a href="http://en.wikipedia.org/wiki/Brick_(electronics)" target="_blank">bricked</a> the <a href="http://en.wikipedia.org/wiki/Zune" target="_blank">Zune</a> a whole day on the last day of last year, a <a href="http://en.wikipedia.org/wiki/Leap_year" target="_blank">bisextile</a> year? I described <a href="http://hbfs.wordpress.com/2008/12/31/the-zune-freezes-a-stupid-avoidable-bug/" target="_blank">here</a> and <a href="http://hbfs.wordpress.com/2009/01/05/the-zunes-freezes-update/" target="_blank">here</a> how this error could have been entirely avoided using <em>basic</em> <a href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit testing</a>.</p>
<p><a href="http://hbfs.wordpress.com/files/2009/07/brick-small1.jpg"><img src="http://hbfs.wordpress.com/files/2009/07/brick-small1.jpg" alt="brick-small" title="brick-small" width="250" height="250" class="aligncenter size-full wp-image-1467" /></a></p>
<p>You probably remember (if you read the original post) that I first claimed that it&#8217;d take a few seconds to check all possible dates but in fact it ended up taking something like 90 minutes. This week, I come back on unit testing of a very large domain under a time constraint.</p>
<p><!--more--></p>
<p>So in this previous post, I have been testing the values one by one until I&#8212;well, the program&#8212;exhausted all input values. This ensures that all values passed into a given piece of code returns the correct result. But while this exhaustive testing increases the confidence one can have in his own code, it has at least two major shortcomings, at least in the specific form I presented.</p>
<p>First, it is exhaustive. At first, exhaustive sounds good because there&#8217;s no need to identify particular <a href="http://en.wikipedia.org/wiki/Edge_case" target="_blank">edge cases</a> because you&#8217;re going to test them eventually anyway. But that also means that you&#8217;ll test plenty of essentially uninteresting cases as well. Nothing special happened on the Zune until you hit the edge case, that is, the last day of a leap year. So, testing mindlessly all possible cases, while a simple test in this case, is very slow&#8212;not that you&#8217;re the one pushing bits around either; but 90 minutes is quite a lot of computing power to compute a single test on a single function.</p>
<p>Second, it is not readily capable of detecting infinite loops and exit gracefully, that is, by detecting that it is stuck and report an error. One way of constraining run-time (if you&#8217;re using a <a href="http://en.wikipedia.org/wiki/Unix" target="_blank">*nix</a> box of some sort and <a href="http://en.wikipedia.org/wiki/Bash" target="_blank">Bash</a>) is to use the <tt>ulimit</tt> shell built-in to constrain run-time. For example, typing:</p>
<pre class="brush: bash;">
$ (ulimit -t 2  -St 1; date-time-unit-test )
</pre>
<p>You will get:</p>
<pre class="brush: bash;">
CPU time limit exceeded
</pre>
<p>because when the soft time limit (set by <tt>-St 1</tt>) is reached, the OS starts issuing <a href="http://en.wikipedia.org/wiki/SIGXCPU" target="_blank"><tt>SIGXCPU</tt></a> <a href="http://en.wikipedia.org/wiki/Signal_(computing)" target="_blank">signals</a> to the process that traps it and quits with the <tt>CPU time limit exceeded</tt> message. If the process is really locked-up (or explicitly eats the <tt>SIGXCPU</tt> messages) it will terminate with a <tt>killed</tt> message when the hard time limit is reached.</p>
<p>Using <tt>ulimit</tt> devolves the responsibility of setting time limits to the shell script that launches the unit tests. This also allows the script to report whether the unit test succeeded or failed, and in case of failure, report the correct error message (<a href="http://en.wikipedia.org/wiki/SIGSEGV" target="_blank"><tt>SIGSEGV</tt></a>, <tt>SIGXCPU</tt>, etc.) so that it is easier to isolate the bug the next morning.</p>
<p>Another possible technique is to use <a href="http://en.wikipedia.org/wiki/Watchdog_timer" target="_blank">watchdog timers</a> if they are available in your test environment. Watchdog timers are timers that count down a certain amount of time and when they reach zero, a specific event is triggered. It may be that the program is crashed with a verbose error message or that a specific signal is sent to the program. To prevent the program from being killed by a watchdog timer reaching zero, the program resets the timer each time it can.</p>
<p>In out Zune example, that would be that the unit test program resets the watchdog timer each time a pair of encode/decode date function are called. If either function gets stuck in an infinite loop, the timer will reach zero and the program is terminated&#8212;maybe gracefully, giving it time to report a specific error code.</p>
<p>The <a href="http://en.wikipedia.org/wiki/POSIX" target="_blank">POSIX</a> signal <a href="http://en.wikipedia.org/wiki/SIGVTALRM" target="_blank">SIGVTALRM</a> is meant just to do that. On Linux, you can use <tt>signal</tt> (defined in <tt>&#60;signal.h&#62;</tt>) to setup a call back on <tt>SIGVTALRM</tt>. You would do something like:</p>
<pre class="brush: cpp;">
sighandler_t my_handler = signal(SIGVTALRM,my_watchdog_handler);
</pre>
<p>to set the signal handler and <tt>timer_create</tt> to create the timer, and finally <tt>timer_settime</tt> to set its characteristics. The body of the unit test launcher would look something like:</p>
<pre class="brush: cpp;">
#include &#60;stdlib.h&#62;
#include &#60;stdio.h&#62;
#include &#60;signal.h&#62;
#include &#60;time.h&#62;

//////////////////////////////
//
// Handles a signal (in our case,
// SIGVTALRM)
//
void my_sighandler(int this_signal)
 {
  printf(&#34;oh noes! got a SIGVTARLM\n&#34;);

  // Bash-esque return value
  exit(128+this_signal);
 }

//////////////////////////////
//
// Main program that setups
// timers, signal handler and
// would launch unit tests as
// well.
//
int main()
 {
  // set event-handler
  //
  if (signal( SIGVTALRM,
              my_sighandler)!=SIG_ERR)
   {
    timer_t timer_id;
    struct sigevent signal_event;

    // creates a timer for
    // say, 2 seconds.
    //
    signal_event.sigev_notify = SIGEV_SIGNAL;
    signal_event.sigev_signo = SIGVTALRM;
    signal_event.sigev_value.sival_ptr = &#38;timer_id;

    if( timer_create( CLOCK_REALTIME,
                      &#38;signal_event,
                      &#38;timer_id
                      )==0)
     {
      struct itimerspec timer_specs, timer_out_specs;
      // we created a timer!
      // let us set granularity
      // (and make it repeat only
      // once)

      // initial delay
      //
      timer_specs.it_value.tv_sec=2;
      timer_specs.it_value.tv_nsec=0;

      // repeat delay
      // (zero means no repeat)
      //
      timer_specs.it_interval.tv_sec=0;
      timer_specs.it_interval.tv_nsec=0;

      if ( timer_settime( timer_id,0,
                          &#38;timer_specs,
                          &#38;timer_out_specs)==0)
       {

        // ok, timer is set,
        // let's eat the CPU !
        // (let's pretend the
        // unit test is launched)
        // from here
        //
        while(1);

        // would exit normally
        // if reached at the end
        // of the unit test
        return 0;
       }
      else fprintf(stderr,&#34;error setting timer properties!\n&#34;);
     }
    else fprintf(stderr,&#34;could not create timer!\n&#34;);
   }
  else fprintf(stderr,&#34;could not set handler!\n&#34;);

  return 1;
 }
</pre>
<p>What you put in the signal handler is up to you, but I would suggest printing something informative and returning a standard-looking error code (such as those <a href="http://tldp.org/LDP/abs/html/exitcodes.html" target="_blank">here</a>).</p>
<p>When you compile the above code snippet (and use <tt>-lrt</tt> to link the library that contains the timer calls) to <tt>timer-test</tt>, you get the following output:</p>
<pre class="brush: bash;">
$ timer-test ; echo $?
oh noes! got a SIGVTARLM
154
</pre>
<p>and 154 is indeed 128+<tt>SIGVTALRM</tt>. Success!</p>
<p align="center">*<br />*&#8195;*</p>
<p>Exhaustive testing can be very long. With the Zune example, we&#8217;re lucky because the domain isn&#8217;t incredibly vast and computers are quite fast enough nowadays to run <img src='http://l.wordpress.com/latex.php?latex=2%5E%7B32%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2^{32}' title='2^{32}' class='latex' /> calls to a simple function (or a couple of) in a matter of mere hours.</p>
<p>Since you&#8217;re not especially interested in finding all edge cases by hand, you could enumerate the test value in some order that pushes somewhat the bad cases in the front of the list. For example, one could first enumerate timestamps that correspond to elapsed whole days, then hours (even with redundancies) then minutes, and at last seconds. The Zune leap day problem would have been caught very rapidly during the first phases of the unit test and everybody would&#8217;ve been much happier.</p>
<p><a href="http://en.wikipedia.org/wiki/Gare_Montparnasse#1895_derailment" target="_blank"><img src="http://hbfs.wordpress.com/files/2009/07/train_wreck_at_montparnasse_1895.jpg?w=250" alt="Train_wreck_at_Montparnasse_1895" title="Train_wreck_at_Montparnasse_1895" width="250" height="300" class="aligncenter size-medium wp-image-1463" /></a></p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
