{ |one, step, back| } http://onestepback.org/index.cgi Jim Weirich's Blog en-us { |one, step, back| } http://onestepback.org http://onestepback.org/images/jwface.gif Test Driven Studio in June 2008 http://onestepback.org/index.cgi/Tech/Conferences/TestingInRails/TddStudioJune2008.red <p><em>Joe O&#8217;Brien and I will be leading another Test Driven Studio in Denver, June 9-11.</em></p> <p style="float: right; padding: 0.5em;"><a href="http://pragmaticstudio.com/images/studio/tdd-with-rails-icon.jpg"><img border="0" src="http://onestepback.org/images/pragstudio/studio-medium.gif"/></a></p> <h2>Testing, Colorado, June &#8230; What&#8217;s not to like?</h2> <p>About 8 years ago I come upon a technique that radically changed the way I developed code. I was reading Martin Fowler&#8217;s &#8220;Refactoring&#8221; book and came across this paragraph:</p> <p style="padding-left:3em;"><em>&#8220;Whenever I do refactoring, the first step is always the same. I need to build a solid set of tests for that section of code. The test are essential because even though I follow refactorings structured to avoid most of the opportunities for introducing bugs, I&#8217;m still human and still make mistakes. Thus I need solid tests.&#8221; </em>&#8212;Martin Fowler</p> <p>Chapter 4 of &#8220;Refactoring&#8221; was my first introduction to JUnit and got me interested in &#8220;Test First Design&#8221; (what we now tend to call &#8220;Test Driven Development&#8221;). Although I wrote <em>good</em> code before, the onfidence I had in my code took a dramatic leap forward after I started adopting <span class="caps">TDD</span> practices.</p> <p>On June 9 through 11, <a href="http://objo.com">Joe O&#8217;Brien</a> and I will have the pleasure of leading the next Pragmatic Programmer&#8217;s <a href="http://pragmaticstudio.com/testing-rails">Test-Driven Development with Rails Studio.</a> in Denver. We will have an opportunity to share with you some of our experiences in using <span class="caps">TDD</span> with Ruby and Rails.</p> <p>There are still seats available, so its not too late to sign up. More information is available <a href="http://pragmaticstudio.com/testing-rails">here</a>.</p> Lisp in Ruby http://onestepback.org/index.cgi/Tech/Ruby/LispInRuby.red <p style="padding-left:3em;"><em>I stumbled across <a href="http://bc.tech.coop/blog/080101.html">this</a> and it got me thinking &#8230;</em></p> <h3>Update</h3> <p style="padding-left:3em;"><em>I&#8217;ve updated the Textile formatter on the site and the code for this entry is now displaying correctly. The previous version was swalling the == operators in the code.</em></p> <h2>Lisp 1.5 Programmer&#8217;s Manual</h2> <p>I stumbled across <a href="http://bc.tech.coop/blog/080101.html">this</a> in Bill Clementson&#8217;s blog and remembered using the Lisp 1.5 Prgrammers manual from the college years. I have strong memories of pouring over that particular page in the manual and attempting to understand all the nuances.</p> <p>If you&#8217;ve never read the Lisp 1.5 Programamers Manual, page 13 is the guts of a Lisp Interpreter, the &#8220;eval&#8221; and &#8220;apply&#8221; functions. It is written in Lisp, although the notation used is a bit funky. The entire interpreter (minus two utility functions) is presented on a single page of the book. Talk about a concise language definition!</p> <h2>In Ruby?</h2> <p>I had often thought about implementing a Lisp interpreter, but back in the &#8220;old days&#8221;, the thought of implementing garbage collection and the whole runtime thing was a bit daunting. This was in the day before C, so my implementation language would have been assembler &#8230; yech.</p> <p>But as I was reviewing the page, I realized that with today&#8217;s modern languages, I could problably just convert the funky M-Expressions used on page 13 directly into code. So &#8230; why not?</p> <h2>The Code</h2> <p>Here is the complete Ruby source code for the Lisp interpreter from page 13 of the Lisp Programmers manual:</p> <pre> # Kernel Extensions to support Lisp class Object def lisp_string to_s end end class NilClass def lisp_string "nil" end end class Array # Convert an Array into an S-expression (i.e. linked list). # Subarrays are converted as well. def sexp result = nil reverse.each do |item| item = item.sexp if item.respond_to?(:sexp) result = cons(item, result) end result end end # The Basic Lisp Cons cell data structures. Cons cells consist of a # head and a tail. class Cons attr_reader :head, :tail def initialize(head, tail) @head, @tail = head, tail end def ==(other) return false unless other.class == Cons return true if self.object_id == other.object_id return car(self) == car(other) &#38;&#38; cdr(self) == cdr(other) end # Convert the lisp expression to a string. def lisp_string e = self result = "(" while e if e.class != Cons result &lt;&lt; ". " &lt;&lt; e.lisp_string e = nil else result &lt;&lt; car(e).lisp_string e = cdr(e) result &lt;&lt; " " if e end end result &lt;&lt; ")" result end end # Lisp Primitive Functions. # It is an atom if it is not a cons cell. def atom?(a) a.class != Cons end # Get the head of a list. def car(e) e.head end # Get the tail of a list. def cdr(e) e.tail end # Construct a new list from a head and a tail. def cons(h,t) Cons.new(h,t) end # Here is the guts of the Lisp interpreter. Apply and eval work # together to interpret the S-expression. These definitions are taken # directly from page 13 of the Lisp 1.5 Programmer's Manual. def apply(fn, x, a) if atom?(fn) case fn when :car then caar(x) when :cdr then cdar(x) when :cons then cons(car(x), cadr(x)) when :atom then atom?(car(x)) when :eq then car(x) == cadr(x) else apply(eval(fn,a), x, a) end elsif car(fn) == :lambda eval(caddr(fn), pairlis(cadr(fn), x, a)) elsif car(fn) == :label apply(caddr(fn), x, cons(cons(cadr(fn), caddr(fn)), a)) end end def eval(e,a) if atom?(e) cdr(assoc(e,a)) elsif atom?(car(e)) if car(e) == :quote cadr(e) elsif car(e) == :cond evcon(cdr(e),a) else apply(car(e), evlis(cdr(e), a), a) end else apply(car(e), evlis(cdr(e), a), a) end end # And now some utility functions used by apply and eval. These are # also given in the Lisp 1.5 Programmer's Manual. def evcon(c,a) if eval(caar(c), a) eval(cadar(c), a) else evcon(cdr(c), a) end end def evlis(m, a) if m.nil? nil else cons(eval(car(m),a), evlis(cdr(m), a)) end end def assoc(a, e) if e.nil? fail "#{a.inspect} not bound" elsif a == caar(e) car(e) else assoc(a, cdr(e)) end end def pairlis(vars, vals, a) while vars &#38;&#38; vals a = cons(cons(car(vars), car(vals)), a) vars = cdr(vars) vals = cdr(vals) end a end # Handy lisp utility functions built on car and cdr. def caar(e) car(car(e)) end def cadr(e) car(cdr(e)) end def caddr(e) car(cdr(cdr(e))) end def cdar(e) cdr(car(e)) end def cadar(e) car(cdr(car(e))) end </pre> <h2>An Example</h2> <p>And to prove it, here&#8217;s an example program using Lisp. I didn&#8217;t bother to write a Lisp parser, so I need to express the lists in standard Ruby Array notation (which is converted to a linked list via the &#8220;sexp&#8221; method).</p> <p>Here&#8217;s the ruby program using the lisp interpreter. The Lisp system is very primitive. The only way to define the function needed is to put them in the environment structure, which is simply an association list of keys and values.</p> <pre> require 'lisp' # Create an environment where the reverse, rev_shift and null # functions are bound to an appropriate identifier. env = [ cons(:rev_shift, [:lambda, [:list, :result], [:cond, [[:null, :list], :result], [:t, [:rev_shift, [:cdr, :list], [:cons, [:car, :list], :result]]]]].sexp), cons(:reverse, [:lambda, [:list], [:rev_shift, :list, nil]].sexp), cons(:null, [:lambda, [:e], [:eq, :e, nil]].sexp), cons(:t, true), cons(nil, nil) ].sexp # Evaluate an S-Expression and print the result exp = [:reverse, [:quote, [:a, :b, :c, :d, :e]]].sexp puts "EVAL: #{exp.lisp_string}" puts " =&gt; #{eval(exp,env).lisp_string}" </pre> <p>The program will print:</p> <pre><code>$ ruby reverse.rb EVAL: (reverse (quote (a b c d e))) =&gt; (e d c b a)</code></pre> <p>All I need to do is write a Lisp parser and a <span class="caps">REPL</span>, and I&#8217;m in business!</p> <h2>The Example in Standard Lisp Notation</h2> <p>If you found the Ruby-ized Lisp code hard to read, here is the reverse funtions written in a more Lisp-like manner.</p> <pre> (defun reverse (list) (rev-shift list nil)) (defun rev-shift (list result) (cond ((null list) result) (t (rev-shift (cdr list) (cons (car list) result))) )) </pre> On my wall ... http://onestepback.org/index.cgi/Tech/Programming/DarthTest.red <p><img src="http://onestepback.org/images/rublog/DarthTest.jpg" alt="" /></p> <p>(from <a href="http://www.flickr.com/photos/sebastian_bergmann/2282734669/sizes/o/">here</a>)</p> The Arc Challenge http://onestepback.org/index.cgi/Tech/Ruby/ArcChallenge.red <p style="padding-left:3em;"><em>Paul Graham issues the Arc Challenge &#8230; who could resist?</em></p> <h2>Paul Graham&#8217;s Arc Challenge</h2> <p>You can read about the Arc Challenge here: <a href="http://www.paulgraham.com/arcchallenge.html">The Arc Challenge</a>. Go ahead a read it now, but I will summarize the challenge.</p> <p><strong>Write a web program such that:</strong></p> <ul> <li>The first page of the program displays nothing but a text box and a submit button. You enter some arbitrary text and press the submit button, which takes you to &#8230;</li> </ul> <ul> <li>The second page is nothing but a single link labeled &#8220;click here&#8221;. The <span class="caps">URL</span> linked to must not contain the text entered in the first step (i.e. you are not supposed to pass the text as a parameter on the link). Clicking the link takes you to &#8230;</li> </ul> <ul> <li>The third page which contains &#8220;You said: <span class="caps">XXX</span>&#8221; (where <span class="caps">XXX</span> is the text you entered in the first step).</li> </ul> <p>Here&#8217;s a screen cast demoing my solution to the Arc Challenge. (We will show the code shortly).</p> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="466" height="281"> <param name="movie" value="http://content.screencast.com/bootstrap.swf"></param> <param name="quality" value="high"></param> <param name="bgcolor" value="#FFFFFF"></param> <param name="flashVars" value="thumb=http://content.screencast.com/media/762eebca-fa50-49f8-9b88-dc7652bd3c9a_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/499ec89e-b124-4dcb-bcd0-e74f6fac495f_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000084.swf&#38;width=466&#38;height=281"></param> <param name="allowFullScreen" value="true"></param> <param name="scale" value="showall"></param> <param name="allowScriptAccess" value="always"></param> <embed src="http://content.screencast.com/bootstrap.swf" quality="high" bgcolor="#FFFFFF" width="466" height="281" type="application/x-shockwave-flash" allowScriptAccess="always" flashVars="thumb=http://content.screencast.com/media/762eebca-fa50-49f8-9b88-dc7652bd3c9a_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/499ec89e-b124-4dcb-bcd0-e74f6fac495f_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000084.swf&#38;width=466&#38;height=281" allowFullScreen="true" scale="showall"></embed> </object> <h2>Paul&#8217;s Solution</h2> <p>Paul has been working on designing Arc, his ideal programming language for the future. Given Paul&#8217;s language preferences, it is no surprise that Arc is very Lisp-like. Here is Paul&#8217;s solution written in Arc:</p> <pre class="testcode"> (defop said req (aform [w/link (pr "you said: " (arg _ "foo")) (pr "click here")] (input "foo") (submit))) </pre> <p>Paul points out that the solution is very short and elegant, only 23 nodes in the codetree. I&#8217;m sure I don&#8217;t quite understand exactly what it is doing (I&#8217;d love to see a step by step explanation of the code). He wonders what it would look like in other languages.</p> <p>Several people have responded with solutions in their own languages. I&#8217;ve seen a <a href="http://www.lukas-renggli.ch/blog/take-the-arc-challenge?_s=BXjPNOJFnBmoYxtA&#38;_k=lERhwwWC">Smalltalk Solution</a> as well as a <a href="http://arc-challenge.heroku.com/">Ruby solution</a> (which pretty closely mimics the Arc code from Paul) on the <a href="http://arclanguage.org/item?id=722">Arc Language Forum</a> page that was setup for responses.</p> <h2>Continuation Web Servers</h2> <p>The Arc challenge is a perfect candidate for a continuation based server solution. And I recalled that Chad Fowler and I had written a demo continuation based server for the <a href="http://onestepback.org/articles/callcc/">Continuations Demystified</a> talk we did at RubyConf 2005. (Look for the &#8220;Poor Man&#8217;s Seaside Demo in that presentation.) I wondered how easy it be to code up an Arc challenge solution using that code base.</p> <p>The key to a continuation based server is that it allows the programmer to code in a linear fashion. All the request/response nature of web interaction is completely hidden from you as a programmer.</p> <p>For example, let&#8217;s pretend we wanted to solve the Arc challenge using a terminal and command line rather than a web based solution. How would you write it? Probably something like this:</p> <pre class="rubycode"> text = gets puts "click here" gets puts "You said: #{text}" </pre> <p>Simple, linear programming. (OK, printing &#8220;click here&#8221; is silly in a text program, but you get the idea). You ask a question and read a response. You pause for a click. You then tell the user what the result is.</p> <p>Ask. Pause. Tell.</p> <p>Those are our basic abstract operations for this problem. Lets rewrite our text based solution using these abstractions. We&#8217;ll put this in a file called &#8220;arc_challenge.rb&#8221;.</p> <pre class="rubycode"> Conversation.interact do |io| text = io.ask io.pause("click here") io.tell("You said: #{text}") end </pre> <p>I&#8217;ve introduced three operations (methods) that are provided by an I/O object (let&#8217;s ignore the interact line for now). &#8220;ask&#8221; will ask the user for input, returning the string. &#8220;pause&#8221; will pause until the user indicates he/she is ready to continue (e.g. pressing return in our command line version). &#8220;tell&#8221; sends the given string to the user.</p> <p>So, what does &#8220;Conversation.interact&#8221; do? It creates the environment where the user have a conversation with the program. The interation is controlled through our ask/pause/tell functions provided by the I/O object passed to the interact block.</p> <p>Here is an implementation of a text based conversation.</p> <pre class="rubycode"> class TextBased def interact yield(self) end def ask(prompt=nil) print prompt, " " if prompt gets.chomp end def pause(prompt="") print prompt, " " if prompt gets end def tell(message) puts message end end Conversation = TextBased.new </pre> <p>To run the text based conversation, just require the text. Here&#8217;s a demo:</p> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="465" height="238"> <param name="movie" value="http://content.screencast.com/bootstrap.swf"></param> <param name="quality" value="high"></param> <param name="bgcolor" value="#FFFFFF"></param> <param name="flashVars" value="thumb=http://content.screencast.com/media/1ae5f9ce-5bc5-4360-8cbc-83b165a434ab_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/90dd373a-0352-4710-acb1-6b18620a5609_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000080.swf&#38;width=465&#38;height=238"></param> <param name="allowFullScreen" value="true"></param> <param name="scale" value="showall"></param> <param name="allowScriptAccess" value="always"></param> <embed src="http://content.screencast.com/bootstrap.swf" quality="high" bgcolor="#FFFFFF" width="465" height="238" type="application/x-shockwave-flash" allowScriptAccess="always" flashVars="thumb=http://content.screencast.com/media/1ae5f9ce-5bc5-4360-8cbc-83b165a434ab_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/90dd373a-0352-4710-acb1-6b18620a5609_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000080.swf&#38;width=465&#38;height=238" allowFullScreen="true" scale="showall"></embed> </object> <h2>Arc on the Web</h2> <p>Well, anybody can solve the challenge in text mode. How much work do we have to do to get it on the web.</p> <p>The answer: Zero!</p> <p>The code Chad and I wrote for <a href="http://onestepback.org/articles/callcc/">Continuations Demystified</a> includes a web-based version of the conversation object that is ready to go. All we have to do is plug it in and run it. No changes are required to our basic Arc challenge solution.</p> <p>Again, a screen demo:</p> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="538" height="352"> <param name="movie" value="http://content.screencast.com/bootstrap.swf"></param> <param name="quality" value="high"></param> <param name="bgcolor" value="#FFFFFF"></param> <param name="flashVars" value="thumb=http://content.screencast.com/media/a8773d13-5fe0-46f2-adcf-8ae4830c6e53_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/2918dffc-1f80-401b-8063-d8c8bb908016_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000082.swf&#38;width=538&#38;height=352"></param> <param name="allowFullScreen" value="true"></param> <param name="scale" value="showall"></param> <param name="allowScriptAccess" value="always"></param> <embed src="http://content.screencast.com/bootstrap.swf" quality="high" bgcolor="#FFFFFF" width="538" height="352" type="application/x-shockwave-flash" allowScriptAccess="always" flashVars="thumb=http://content.screencast.com/media/a8773d13-5fe0-46f2-adcf-8ae4830c6e53_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_Thumbnail.gif&#38;content=http://content.screencast.com/media/2918dffc-1f80-401b-8063-d8c8bb908016_e67edb68-7ed6-4b26-9b5e-cd2fd2207a40_static_0_0_00000082.swf&#38;width=538&#38;height=352" allowFullScreen="true" scale="showall"></embed> </object> <p>Yes, we know that although we now have our Arc Challenge on the web, we haven&#8217;t quite conformed to the exact requirements of the challenge. We will handle that next.</p> <h2>The Final Arc Solution</h2> <p>The problem is that the current Web based conversation object makes all kinds of assumptions that are not appropriate for the final Arc solution.</p> <p>In particular, we need to change:</p> <ul> <li>Get rid the head line, restart link and other extraneous <span class="caps">HTML</span> elements.</li> </ul> <ul> <li>Don&#8217;t keep a running log of the conversation. When you move to a new page, you start from scratch.</li> </ul> <ul> <li>The &#8220;click here&#8221; should be a real link, not just a text box where you can press enter.</li> </ul> <p>To get to here, we will have to make some modifications to the conversation web library. It turns out the changes are pretty straight forward. The whole interaction framework is controlled by the Conversation object that implements ask/pause/tell methods. You can see the changes made for the Arc challenge in the &#8220;noecho_web_based.rb&#8221; file (see the end of this post for the availability of the source code).</p> <h2>The Final Conversation Based Solution</h2> <p>In cased you missed it, here is the Arc Challenge Solution:</p> <pre class="rubycode"> Conversation.interact do |io| text = io.ask io.pause("click here") io.tell("You said: #{text}") end </pre> <p>Yep, it&#8217;s the exact same file we used for the text based solution. I don&#8217;t know if it is as elegant as Paul&#8217;s version, but I certainly find it easy to read and understand. (Rerun the <a href="http://www.screencast.com/t/mFoZAA7N">very first screen cast</a> in this posting if you want to see it in action again).</p> <p>If you want to look at the code, there is a <a href="http://onestepback.org/download/conversations.tgz">tarball</a> available that contains all the continuation server demo code from <a href="http://onestepback.org/articles/callcc/">Continuations Demystified</a> talk, as well as the two new files I added for the Arc challenge. &#8220;arc_challenge.rb&#8221; is the actually solution and &#8220;noecho_web_based.rb&#8221; is the conversation library that renders the solution in the style set forth by the challenge.</p> <p>Enjoy.</p> Erlang-like Method Definition in FlexMock http://onestepback.org/index.cgi/Tech/Ruby/FlexMockAndErlang.red <p style="padding-left:3em;"><em>Some fun with Erlang and FlexMock.</em></p> <h2>Erlang Function Definitions</h2> <p>Erlang defines functions by listing a set of possible argument lists and the body of the function to be executed for each argument list. For example, the factorial function might be defined in Erlang as:</p> <pre> factorial(0) -&gt; 1; factorial(N) -&gt; N * fac(N-1). </pre> <p>If factorial is called with a 0 (zero) for an argument, the first argument list will be chosen and the value of the factorial function will be 1. Otherwise, the value returned will be calculated by a recursive call to factorial.</p> <h2>FlexMock and Erlang</h2> <p>While playing around with FlexMock the other day, I realized that it does parameter matching, much like Erlang, when deciding what mock method to call. So I started wondering if you could write Erlang-like function definitions in FlexMock.</p> <p>Here&#8217;s the result.</p> <pre> mock = flexmock('fact') mock.should_receive(:factorial).with(0).and_return(1) mock.should_receive(:factorial).with(Integer). and_return { |n| n * mock.factorial(n-1) } </pre> <p>Ok, that was fun. But let&#8217;s not start building entire systems using nothing but FlexMock.</p> Last Chance (Almost) http://onestepback.org/index.cgi/Tech/Conferences/RubyConf2007/LastChanceAlmost.red <blockquote><em>Time is running out. Get your talk proposals in.</em></blockquote> <h2>RubyConf Talk Proposal: Submitted!</h2> <p>I just sent in my RubyConf talk proposal.</p> <h2>Better Hurry!</h2> <p>If you&#8217;ve got a good idea for a proposal, you can submit it at <a href="http://proposals.rubycentral.org/">http://proposals.rubycentral.org/</a>.</p> <p>The deadline for the proposals is August 20. However, I have it on good authority that the deadline will be extended to Aug 23, 5:00 pm <span class="caps">EST</span>. (Ahh &#8230; I see the announcement made it to <a href="http://www.ruby-forum.com/topic/122035">Ruby-Talk</a>) So you still have some time.</p> <h2>Some Hints</h2> <p>RubyCentral has been having some problems with getting their registration responses delivered (I found my registration confirmation in GMail&#8217;s spam box). I would recommend that you go ahead and register a proposal now, even if you don&#8217;t have all the details ready. By the time you are ready to submit the final version, you won&#8217;t have to worry about any last minite registration hassles.</p> <p>Good luck with your proposals. I hope to see you at RubyConf!</p> My Mac Can't Count http://onestepback.org/index.cgi/Tech/Mac/MyMacCantCount.red <blockquote><em>This one mystifies me.</em></blockquote> <h2>The Raw <span class="caps">HTML</span></h2> <p>This is on my MacBook Pro. How in the world to you go from this <span class="caps">HTML</span>:</p> <p><img src="http://onestepback.org/images/huh/2007-08-19_0727.png" alt="" /></p> <h2>As Rendered in the Browser</h2> <p>To this in the browser?</p> <p><img src="http://onestepback.org/images/huh/2007-08-19_0731.png" alt="" /></p> <p>Look carefully at the sequence of digits for the default font.</p> <p>This happens in both safari and firefox. Javascript is disabled. Disabling <span class="caps">CSS</span> will cause all 7s to look like 9s (because everything is then in the defaualt font).</p> <h2>Huh?</h2> <p>Any clues on how to fix this would be welcome.</p> <h2>Update</h2> <p>Several people have reported they can&#8217;t reproduce it. Here is additional information:</p> <p>Mac <span class="caps">OS 10</span>.4.10<br/> Firefox 2.0.0.6<br/> Safari 3.0.3<br/></p> <p>Also, copying and pasting what looks to be &#8220;0123456979&#8221; into a text editor will give &#8220;0123456789&#8221;. Perhaps a font is corrupted so the &#8220;7&#8221; is displaying as a &#8220;9&#8221; glyph?</p> <h2>Update 2&#8212;Problem Fixed</h2> <p>John Guenin suggests: Try resetting your font caches: http://www.jamapi.com/pr/fn</p> <p>Thanks John. I downloaded FontNuke from the link provided and although the program itself was a bit flaky, I finally got a clean run from it and after rebooting the problem has been fixed. So the verdict is that it was probably a bad font cache that was displaying the &#8220;7&#8221; glyph incorrectly.</p> <p>Whew.</p> <p>Thanks to everyone who made suggestions.</p> FlexMock 0.6.4 Release http://onestepback.org/index.cgi/Tech/Ruby/FlexMock064.red <p style="padding-left:3em;"><em>New Release of FlexMock</em></p> <h2>FlexMock 0.6.4 Release</h2> <p>Just wanted to drop a quick note that a new version of FlexMock is now available.</p> <p>There are two nice enhancements and a minor bug fix in this version.</p> The first enhancement is for mocking ActiveRecord objects. The folks at EdgeCase use a mockmodel() method for the RSpec mock that returns a mock that has some common ActiveRecord methods mocked (stubbed) with some reasonable values. This make is a bit more convenient when mocking Rails models. FlexMock now supports this natively, just say <code>flexmock(:model, YourRailsModel)</code> to create a mock object that mimics a YourRailsModel object. <p>The second enhancement is in regard to the <a href="http://onestepback.org/index.cgi/Tech/Ruby/FlexMockReturns.red">What Should flexmock(real_obj) Return?</a> question I blogged about last May. I asked the question: What should flexmock(real_obj) return, the real object or the mock object? Someone had suggested returning the real object when flexmock() is given a block. There was some positive response to that, so that was included in the FlexMock release.</p> <p>But after several months of using it, I found it difficult to remember which version of flexmock() returned what. At one point I found myself caling flexmock() with an empty block, just to get the real object back. That was madness.</p> <p>So starting with release 0.6.4, flexmock will always return the real object. This is the best of both worlds, but it comes with a small price. Real objects partially mocked by FlexMode will now be enhanced with some extra methods, just enough methods so that addition mock behavior can be added to it. For example, <code>should_receive</code> is added to the partially mocked real object. This pollutes the method namespace for an object, but the result is much simplier for the programmer to use. If you <strong>really</strong> want to avoid method namespace pollution, there is a :safe mode offered. Read the docs for all the gory details.</p> <h2>By The Way, If You Grabbed Version 0.6.3 &#8230;</h2> <p>If you are one of the handful of people that downloaded verion 0.6.3 yesterday, then go ahead and grab 0.6.4. The only difference is in the <span class="caps">API</span> for mocking ActiveRecord models. After using it for a bit, I realized that the <span class="caps">API</span> could be improved, hence version 0.6.4. Sorry about that.</p> A New Pragmatic Studio http://onestepback.org/index.cgi/Tech/Conferences/TestingInRails/AnnounceTestDrivenDevInRails.red <p><em>Joe O&#8217;Brien and I will be hosting the Test-Driven Developement in Rails Pragmatic Studio in Columbus.</em></p> <p style="float: right; padding: 0.5em;"><a href="http://pragmaticstudio.com"><img border="0" src="http://onestepback.org/images/pragstudio/studio-medium.gif"/></a></p> <h2>Test Driven Developement in Rails</h2> <p>Mark your calendars. It is official! Joe O&#8217;Brien and I will be teaching a new Pragmatic Studio: <a href="http://pragmaticstudio.com/testing-rails/index.html">Test Driven Development in Rails</a>. The first offering of this studio will be in Columbus on October 17th through the 19th.</p> <p>To quote from the <a href="http://pragmaticstudio.com/testing-rails/index.html">web site</a>:</p> <p style="padding-left:3em;"><em>In this Studio, you&#8217;ll learn how to do test-driven development by actually doing it. We&#8217;ll teach you how to get started with a solid foundation of testing practices, and then quickly build on those with advanced techniques and tools. You&#8217;ll experience a powerful synergy between testing and design that helps you write better software, faster!</em></p> <p>If you ever wanted to improve your testing skills in Ruby and Rails, then this wil be the place for you. I&#8217;m really excited about this opportunity. I hope to see a lot of you there.</p> Using FlexMock to Test Computational Fluid Dynamics Code http://onestepback.org/index.cgi/Tech/Ruby/FlexMockAndFluidDynamics.red <p style="padding-left:3em;"><em>This is a fun example of using FlexMock</em></p> <h2>Andrew Sweeney Asks:</h2> <p>Andrew Sweeney emailed me with the following question:</p> <p style="padding-left:3em;"><em>I am currently working on a ruby project in which I think flexmock would be a good fit for unit testing. I have read the documentation and gone over the examples however fail to wrap my head around how to apply flexmock to my own app. I was hoping that you could give me some guidence and get me started or point me in the right direction. </em></p> <p>You can find his original source code <a href="http://wikis.onestepback.org/OSB/page/show/OriginalF3DQueueCode">here</a>.</p> <p>I thought his problem was interesting enough to write it up as an example of using FlexMock. Andrew and his mentor, <a href="http://www.workingwithrails.com/person/6007-bil-kleb">Bil Kleb</a> gave permission for me to reproduce the code in my blog. The F3DQueue class is part of a <a href="http://fun3d.larc.nasa.gov">Computational Fluid Dynamics</a> project (<a href="http://fun3d.larc.nasa.gov">http://fun3d.larc.nasa.gov</a>) at <span class="caps">NASA</span>.</p> <h2>Quick Code Review</h2> <p>The F3DQueue class is small, so there&#8217;s not a lot of code we need to wade through. We see it uses a second class named AutoF3D, but the only clues we have to what AutoF3D might do are the four method calls on the &#8220;job&#8221; object in the <ins>run</ins> method.</p> <p>It looks like the main interface to the queue object is the <ins>add_to_queue</ins> method. There is a thread started that pulls jobs (i.e. AutoF3D objects) from the queue and processes them in turn. There is some server delays built into the system. I presume that Computational Fluid Dynamics is, ummm, computationally complex and the delays are just there to make sure the workload does eat up <em>all</em> the <span class="caps">CPU</span> time on the server.</p> <h2>Starting Testing</h2> <p>When writing new code, I always like to approach it in a Test-First manner. Because I won&#8217;t write solution code without a test that forces me to write it, I have a high confidence that the code is well covered with tests.</p> <p>Unfortunately, dealing with legacy code means that the code is already written and the test-first approach won&#8217;t work. That&#8217;s ok, I have a little trick that I use. Just comment out the bodies of all the methods in the class you are about to test. Then write the tests that force you to <em>uncomment</em> the code. Just uncomment only enought to get the tests to pass, don&#8217;t uncomment anything you don&#8217;t have to. You have enough tests when all the code has been uncommented. The technique is <em>almost</em> as good as doing real test-first.</p> <h2>The Commented Out Version</h2> <p><a href="http://wikis.onestepback.org/OSB/page/show/CommentedF3DQueueCode">Here</a> is the code base as I started the test.</p> <h2>An Existence Test</h2> <p>I almost always start out with an existence test. Existence tests basically prove the proper files are included and the object can be created. Normally I delete these after a few tests have been written. But I left this one in for an example.</p> <pre class="testcode"> def test_initial_conditions q = F3DQueue.new assert_not_nil q end </pre> <p>Nothing really exciting here. Let&#8217;s move on &#8230;</p> <h2>Proving <span class="caps">FIFO</span> Queue Order</h2> <p>The first thing I want to prove is that items put into the queue are removed in <span class="caps">FIFO</span> order. Since <ins>add_to_queue</ins> creates a AutoF3D object, I mock out the <ins>new</ins> method on the class object and tell FlexMock to expect <ins>new</ins> to be called twice. Once with :a, :b, and :c as parameters, then again with :x, :y, :z paramters. Each invocation of <ins>new</ins> will return a different symbol (:first and :second) so we can easily test the items are pulled off the queue in <span class="caps">FIFO</span> order.</p> <p>Notice that I pass in simple symbols for the arguments to <ins>add_to_queue</ins>. Our code doesn&#8217;t interpret the values of the arguments, they are merely passed directly to the AutoF3D constructor. All we do is verify that the AutoF3D (mocked) constructor does indeed receive the arguments we pass in.</p> <p>Here&#8217;s the test:</p> <pre class="testcode"> def test_adding_to_queue_is_removed_in_fifo_order flexmock(AutoF3D).should_receive(:new).once.with(:a, :b, :c).and_return(:first).ordered flexmock(AutoF3D).should_receive(:new).once.with(:x, :y, :z).and_return(:second).ordered q = F3DQueue.new q.add_to_queue(:a, :b, :c) q.add_to_queue(:x, :y, :z) assert_equal :first, q.remove_from_queue assert_equal :second, q.remove_from_queue end </pre> <p>This test caused three changes. First, the <ins>add_to_queue</ins> method needed lines uncommented:</p> <pre class="rubycode"> def add_to_queue(modelLoc, params, gridFile) autoF3D = AutoF3D.new(modelLoc, params, gridFile) @queue.push autoF3D # $log.info 'Request added to queue' end </pre> <p>(Notice I didn&#8217;t uncomment the log. The logger is not needed to pass the test, and doesn&#8217;t contribute to the actual functionality of the method. I will not be testing the logger in the for the purposes of this article.)</p> <p>Also the <ins>remove_from_queue</ins> needed its body uncommented:</p> <pre class="rubycode"> def remove_from_queue @queue.pop end </pre> <p>And finally, the initializer code needed to create the queue array:</p> <pre class="rubycode"> def initialize @queue = [] # Thread.new{ process } end </pre> <p>Notice that the <ins>Thread.new</ins> line is left commented. We will deal with that in a bit.</p> <p>So now we run the test:</p> <pre class="shell"> $ ruby test_f3dqueue.rb Started F. Finished in 0.010184 seconds. 1) Failure: test_adding_to_queue_is_removed_in_fifo_order(TestF3DQueue) [test_f3dqueue.rb:23]: &lt;:first&gt; expected but was &lt;:second&gt;. 2 tests, 2 assertions, 1 failures, 0 errors </pre> <p>Oops! This test uncovered the first bug. The code as written has stack behavior (i.e. <span class="caps">LIFO</span>). The naming seems to indicate that we want <span class="caps">FIFO</span>.</p> <p>No problem. That&#8217;s an easy fix.</p> <pre class="rubycode"> def remove_from_queue @queue.shift end </pre> <p>Now the tests run clean:</p> <pre class="shell"> $ ruby test_f3dqueue.rb Started .. Finished in 0.001925 seconds. 2 tests, 3 assertions, 0 failures, 0 errors </pre> <h2>Proving that Running a Job Works</h2> <p>Now when I run a job, I need to show that the proper four methods are called once each and in the proper order. This is very straight forward using FlexMock.</p> <pre class="testcode"> def test_running_a_job_will_call_the_right_stuff_in_the_right_order job = flexmock("job") job.should_receive(:generate_geometry_and_grid).once.ordered job.should_receive(:partition_grid_and_initialize_flow).once.ordered job.should_receive(:run_flow_solver).once.ordered job.should_receive(:post_process_solution).once.ordered q = F3DQueue.new q.run(job) end </pre> <p>Uncommenting the body of <ins>run</ins> is all that is needed here:</p> <pre class="rubycode"> def run( job ) # $log.info 'Request being processed' job.generate_geometry_and_grid # $log.info 'Created Geometry' job.partition_grid_and_initialize_flow # $log.info 'Partitioned Grid' job.run_flow_solver # $log.info 'Flow Solver Completed' job.post_process_solution # $log.info 'Post process Completed' # $log.info 'Request completed' end </pre> <p>Test are now showing:</p> <pre class="shell"> 3 tests, 3 assertions, 0 failures, 0 errors </pre> <h2>Processing an Empty Queue</h2> <p>Ok, now it gets interesting. I want to show that attempting to process a job when the queue is empty will cause the process to sleep for the check queue interval.</p> <p>This is one spot where I changed the code to make it easier to test. It is difficult to test endless loops in unit tests (it tends to make the tests run a <em>bit</em> long), so I broke out the logic for a single pass through the loop into a method called <ins>process_one_job</ins>. We can then test this logic without dealing with the looping at the same time.</p> <p>Note: It is possible to test endless loops and an example will be given below. But it is slightly tricky and this allows us to concentrate on proving the logic.</p> <p>If there are no jobs to be processed, then all the code should do is sleep for a particular amount of time. We will locally mock out the <ins>sleep</ins> method on the queue object and insist that it will be called exactly once with the expected interval.</p> <pre class="testcode"> def test_processing_with_no_jobs_will_sleep_the_check_interval q = F3DQueue.new flexmock(q).should_receive(:sleep).once.with(F3DQueue::CHECK_QUEUE_INTERVAL) q.process_one_job end </pre> <p>Here is <ins>process_one_job</ins> with just two lines uncommented so that the test will pass.</p> <pre class="rubycode"> def process_one_job # execution_attempts = 0 job = remove_from_queue # begin # if job # run job # execution_attempts = 0 # sleep SERVER_RECOVERY_TIME # else sleep CHECK_QUEUE_INTERVAL # end # rescue # $log.warn 'An error occurred during execution' # $log.warn $ERROR_INFO # $log.debug $ERROR_POSITION # sleep SERVER_RECOVERY_TIME # if execution_attempts &gt; MAX_EXECUTION_ATTEMPTS # $log.error 'Too many failed execution_attempts: aborting' # raise # else # execution_attempts += 1 # retry # end # end end </pre> <p>There&#8217;s a lot of code still left commented in that method. Now we need a test to force us to uncomment more code.</p> <h2>Handling a Single Job</h2> <p>Ok, now what happens when a single job is in the queue. We will assume the happy path (i.e. no exceptions) so we expect <ins>run</ins> to be called with the queued object, and then a sleep with the recovery interval.</p> <p>A couple of things to note. First, we mock out AutoF3D again so that when we request something added to the queue, we control what kind of object is returned. We <em>could</em> return a mock object and then mock out the four methods that <ins>run</ins> will be calling.</p> <p>However, I chose a slightly different approach. AutoF3D is mocked so that it returns a simple symbol. Then I mock out the <ins>run</ins> method to do nothing (but it is expected to be called once). This is slightly controversial because I am actually mocking a method on the object under test. But the run method is fairly simple, and we know that <ins>run</ins> works because of our previous test, so in the end we get clearer and simpler code.</p> <p>Also note that the <ins>run</ins> and <ins>sleep</ins> methods mocks are ordered. This means <ins>run</ins> will be called first, then <ins>sleep</ins>.</p> <pre class="testcode"> def test_processing_with_a_single_job_will_run_the_job_and_pause_for_recovery q = F3DQueue.new flexmock(AutoF3D).should_receive(:new).once.and_return(:job) flexmock(q).should_receive(:run).once.with(:job).ordered flexmock(q).should_receive(:sleep).once.with(F3DQueue::SERVER_RECOVERY_TIME).ordered q.add_to_queue(:a, :b, :c) q.process_one_job end </pre> <p>Now we get to uncomment even more lines in <ins>process_one_job</ins>.</p> <pre class="rubycode"> def process_one_job # execution_attempts = 0 job = remove_from_queue # begin if job run job # execution_attempts = 0 sleep SERVER_RECOVERY_TIME else sleep CHECK_QUEUE_INTERVAL end # rescue # $log.warn 'An error occurred during execution' # $log.warn $ERROR_INFO # $log.debug $ERROR_POSITION # sleep SERVER_RECOVERY_TIME # if execution_attempts &gt; MAX_EXECUTION_ATTEMPTS # $log.error 'Too many failed execution_attempts: aborting' # raise # else # execution_attempts += 1 # retry # end # end end </pre> <p>That just leaves the error handling code to be uncommented. So that will be next.</p> <h2> Handling a Job With Errors</h2> <p>Now we want to test the case where processing a job will return an exception. This test exercise the exception recovery code in the original code base. The technique is similar to the last test, but this time we specify two mock calls for <ins>run</ins>. The first time <ins>run</ins> will return an exception. The second time it is called, it will complete normally.</p> <p>Notice that we have ordered <ins>run</ins> and <ins>sleep</ins> so that they interleave execution with each other.</p> <pre class="testcode"> def test_if_a_job_fails_retry_after_recovery_time q = F3DQueue.new flexmock(AutoF3D).should_receive(:new).once.and_return(:job) flexmock(q).should_receive(:run).once.with(:job).and_raise(RuntimeError).ordered flexmock(q).should_receive(:sleep).once.with(F3DQueue::SERVER_RECOVERY_TIME).ordered flexmock(q).should_receive(:run).once.with(:job).ordered flexmock(q).should_receive(:sleep).once.with(F3DQueue::SERVER_RECOVERY_TIME).ordered q.add_to_queue(:a, :b, :c) q.process_one_job end </pre> <p>I was showing this test code to one of my coworkers and they were a little surprised that the second expectation on <ins>run</ins> didn&#8217;t override the first expectation. FlexMock is explicitly designed to allow you to stack expectations like this. When searching for an expectation during mocking, FlexMock will use the first one matching one if finds. When an expectation has been used its designated number of times (in the above test, the <ins>once</ins> method designates that the expectation should only be used once), FlexMock will begin to use matching expectations that are defined later.</p> <p>The upshot is this is that it is easy to define mock behavior for multiple calls to the same method.</p> <p>Here&#8217;s the latest <ins>process_one_job</ins> method with some more lines uncommented. We are getting close to the end with this one.</p> <pre class="rubycode"> def process_one_job # execution_attempts = 0 job = remove_from_queue begin if job run job # execution_attempts = 0 sleep SERVER_RECOVERY_TIME else sleep CHECK_QUEUE_INTERVAL end rescue # $log.warn 'An error occurred during execution' # $log.warn $ERROR_INFO # $log.debug $ERROR_POSITION sleep SERVER_RECOVERY_TIME # if execution_attempts &gt; MAX_EXECUTION_ATTEMPTS # $log.error 'Too many failed execution_attempts: aborting' # raise # else # execution_attempts += 1 retry # end end end </pre> <h2>Processing Jobs that Continually Fail</h2> <p>Finally we test the case where the job will continually raise an exception until the error recovery code gives up and passes the exception on to the caller. I didn&#8217;t bother ordering the run/sleep calls here, making it easy to just specify that each are called four times. I believe that the previous test adequately specified interleaving.</p> <p>I used a RuntimeError for my testing. If you have a specific error in mind, you might want to test explicitly for it. Generally raising the most general error you intend to handle is a good way of testing the boundry conditions on your rescue clause.</p> <pre class="testcode"> def test_too_many_failures_will_pass_along_exception q = F3DQueue.new flexmock(AutoF3D).should_receive(:new).once.and_return(:job) flexmock(q).should_receive(:run).with(:job).and_raise(RuntimeError.new("XYZZY")).times(4) flexmock(q).should_receive(:sleep).with(F3DQueue::SERVER_RECOVERY_TIME).times(4) q.add_to_queue(:a, :b, :c) ex = assert_raise RuntimeError do q.process_one_job end assert_equal "XYZZY", ex.message end </pre> <p>Note that the exception needs to be raised four times. I suspect this is a bug in the error handling logic. I left the logic as is and just made sure the test will pass. The code base specifies a retry count of &#8220;2&#8221;. This seems to imply that we try <ins>run</ins> twice, or perhaps three times (if the initail attempt doesn&#8217;t count as a retry). In any case, four times seems too much.</p> <p>So, here is the code for <ins>process_one_job</ins> with most of its lines uncommented.</p> <pre class="rubycode"> def process_one_job execution_attempts = 0 job = remove_from_queue begin if job run job # execution_attempts = 0 sleep SERVER_RECOVERY_TIME else sleep CHECK_QUEUE_INTERVAL end rescue # $log.warn 'An error occurred during execution' # $log.warn $ERROR_INFO # $log.debug $ERROR_POSITION sleep SERVER_RECOVERY_TIME if execution_attempts &gt; MAX_EXECUTION_ATTEMPTS # $log.error 'Too many failed execution_attempts: aborting' raise else execution_attempts += 1 retry end end end </pre> <p>Again note that this test surfaced a (rather minor) bug. There is an extra assignment that clears the execution attempt counter after a successful run of <ins>job</ins>. Since a successful run will exit the loop, clearing it has no effect (unless it is the sleep command that fails, that would be an interesting test scenario).</p> <p>Since we haven&#8217;t shown the test results for a while, here&#8217;s how we stand at this point:</p> <pre class="shell"> 7 tests, 5 assertions, 0 failures, 0 errors </pre> <h2>Processing Multiple Jobs</h2> <p>Now we know that we can handle a single job successfully. Now let&#8217;s make sure that we can handle multiple jobs. Remember that we broke <ins>process</ins> into two methods: <ins>process_one_job</ins> and a much shorter <ins>process</ins> that will call <ins>process_one_job</ins> in a loop.</p> <p>Here&#8217;s what the original <ins>process</ins> method is looking like at the moment:</p> <pre class="rubycode"> def process # loop do # end end </pre> <p>We pulled out its guts and left the still commented loop there. We haven&#8217;t even bothered to have it call <ins>process_one_job</ins> yet. So let&#8217;s write a test that will force us to fix that.</p> <p>We will just mock out process_one_job so that it must be called 10 times. On the eleventh call it throws a symbol that we catch in the test. Throwing a symbol is the trick that breaks us out of the infinite loop. By throwing a symbol (rather than raising an error), we don&#8217;t interact with the error handling logic of the code under test.</p> <p>This is actually the trick refereced earlier. By breaking the body of the loop into a separate method, we only have to use this trick once rather than on each of the process job tests.</p> <pre class="testcode"> def test_process_calls_process_one_job_in_a_loop q = F3DQueue.new flexmock(q).should_receive(:process_one_job).times(10) flexmock(q).should_receive(:process_one_job).and_return { throw :done } assert_throws(:done) do q.process end end </pre> <p>To get this to pass, we implement the <ins>process</ins> method as follows:</p> <pre class="rubycode"> def process loop do process_one_job end end </pre> <h2>Threading Issues</h2> <p>Finally we need to make sure a thread is started. Here is another place I changed the code to make testing easier. The original code base started a thread in the initializer of the object. This means that <strong>every</strong> F3DQueue object ran in its own thread. This would means every test would have to deal with multithread issues. Yuck!</p> <p>I changed the code so that a thread is started only when explicitly calling the start method. I like this better for real object anyways. Although it is an extra step, it gives you more control about when the threads are started. If you really want to start a thread at object creation, you can just say:</p> <pre><code>queue = F3DQueue.new.start</code></pre> <p>Since I really don&#8217;t want to start a Thread in the test (I just want to make sure that the Thread.new method is called), I mock out Thread.new so that it must be called once and when called will execute the given block.</p> <p>I then mock out the process method to that it must be called once. The combination of these two mocks will ensure that <ins>start</ins> will start a new thread that calls <ins>process</ins>.</p> <p>And finally, I ensure that the return value of <ins>start</ins> will be the queue object. This makes sure that the F3DQueue.new.start idiom works.</p> <pre class="testcode"> def test_start_will_start_a_process_thread q = F3DQueue.new flexmock("thread", Thread).should_receive(:new).with(Proc).once. and_return { |block| block.call } flexmock(q).should_receive(:process).once return_value = q.start assert_equal q, return_value end </pre> <p>And is is the little <ins>start</ins> method that needed to be written for the test. The Thread.new line is moved from the <ins>initialize</ins> method to here.</p> <pre class="rubycode"> def start Thread.new do process end self end </pre> <p>Here&#8217;s our final test run:</p> <pre class="shell"> 9 tests, 7 assertions, 0 failures, 0 errors </pre> <h2>Code Coverage</h2> <p>We know that <span class="caps">TDD</span> gives pretty code code coverage stats out of the box. How did our &#8220;Comment-out First&#8221; approach do with regards to code coverage?</p> <p>Here is the RCov report:</p> <pre class="shell"> +----------------------------------------------------+-------+-------+--------+ | File | Lines | LOC | COV | +----------------------------------------------------+-------+-------+--------+ |AutoF3D.rb | 5 | 2 | 100.0% | |f3dqueue.rb | 82 | 53 | 100.0% | |test_f3dqueue.rb | 100 | 76 | 100.0% | +----------------------------------------------------+-------+-------+--------+ |Total | 187 | 131 | 100.0% | +----------------------------------------------------+-------+-------+--------+ 100.0% 3 file(s) 187 Lines 131 LOC </pre> <p>Wow! 100% on the first try.</p> <h2>Final Code Samples</h2> <p>You can find the final versions of the F3DQueue object and its tests here:</p> <ul> <li><a href="http://wikis.onestepback.org/OSB/page/show/FinalF3DQueueCode">F3DQueue Code</a></li> <li><a href="http://wikis.onestepback.org/OSB/page/show/FinalF3DQueueTestCode">F3DQueue Test Code</a></li> </ul> <h2>Future Directions</h2> <p>Now that the F3DQueue object is well testing, it is time to take a step back and think about the overall design of the class. There are a couple of things that stick out in my mind about this code.</p> <h3>(1) First Item</h3> <p>We did a lot of mocking on the F3DQueue object itself while it was being testing. Although a valid technique, you must be careful so that you don&#8217;t end up just testing your own mocks. What it <em>does</em> indicate is that the object you are testing might be trying to do too many things. Perhaps the class needs to be broken up into small classes, or perhaps some functionality needs to move into other classes.</p> <p>With this in mind, the <ins>run</ins> method seems to know an awful lot about the workings of an Auto3D job object. It seems a bit out of place. Why don&#8217;t we move the <ins>run</ins> method to the job itself. Moving <ins>run</ins> into the Auto3D job object would allow us to write the following code fragment (in the <ins>process_one_job</ins> method):</p> <pre class="rubycode"> ... job = remove_from_queue begin if job job.run # was: run job sleep SERVER_RECOVERY_TIME ... </pre> <p>Now, our queue class is one method shorter and is just concerned with the scheduling of the jobs and not the details of running the job itself. This is good &#8230;</p> <p>Except for the following little piece of code, which leads us into the second thing that bothered me:</p> <pre class="rubycode"> def add_to_queue(modelLoc, params, gridFile) autoF3D = AutoF3D.new(modelLoc, params, gridFile) @queue.push autoF3D end </pre> <h3>(2) Second Item</h3> <p>Here we have direct knowledge of the AutoF3D class. If we remove the reference to AutoF3D, then our queue will suddenly become much more general, and usable in situations where we might want to process a different kind of job.</p> <p>I would recommend changing the above code to:</p> <pre class="rubycode"> def add_to_queue(job) @queue.push job end </pre> <p>This does mean that adding a job to the queue would now have to create the job object explicitly. So, instead of:</p> <pre> queue.add_to_queue(loc, param, grid) </pre> <p>you would have to write:</p> <pre> queue.add_to_queue(new AutoF3D.new(loc, param, grid)) </pre> <p>If you don&#8217;t like to manually create an AutoF3D object all the time (and I don&#8217;t), then the following solution is an easy fix to that:</p> <pre class="rubycode"> queue = F3DQueue.new def queue.add_job(loc, params, grid) add_to_queue(AutoF3D.new(loc, params, grid)) end </pre> <p>The more traditionally minded of us might want to just subclass the F3DQueue class and add the <ins>add_job</ins> method in the subclass rather than in the singleton class. That works too. Either way, it is easy to do.</p> <h2>Recap</h2> <p>I hope this was useful for you. Here is a recap of some of the important ideas from this exercise:</p> <ul> <li>Comment-First is not a bad way to handle legacy code.</li> </ul> <ul> <li>Test scenarios, not methods. Note that I didn&#8217;t just pick a method in F3DQueue and write a single test for it. I choose scenarios that would exercise different sections of the code base. Start with the simple (e.g. a Job that Doesn&#8217;t Fail). Then pick increasing harder scenarios (e.g. &#8220;a Job that Fails Once&#8221;, &#8220;a Job that Fails Multiple Times&#8221;).</li> </ul> <ul> <li>Don&#8217;t be afraid to refactor to make testing easier. Breaking out <ins>process_one_job</ins> was a great idea that not only made testing much easier, but made the code easier to read.</li> </ul> <ul> <li>The &#8220;Use Symbols as Cheap Mocks&#8221; is an idea I stole from Stu Halloway in his &#8220;Refactoring of the Week&#8221; presentation. If a method takes arguments that you don&#8217;t want to deal with, try passing in symbols. If the arguments aren&#8217;t used, the symbols work great. If an argument is actually used, the error message will identify the symbol at fault. At that point, just replace the symbol with the appropriate mock. This technique save you lots of time and makes the tests easier to read.</li> </ul> <ul> <li>If you want to break out of an infinite loop in the code under test, throw a symbol from your mocks and catch it in your test. This generally doesn&#8217;t interfere with any exception handling code in your code under test.</li> </ul> <ul> <li>Always take a step back and look for ways of improving the code. A well tested module is fairly easy to change with confidence. Don&#8217;t be afraid to improve things.</li> </ul> <h2>More Samples</h2> <p>Do you have a bit of code that you are having trouble testing? If so, go ahead and send it to me. If your code is interesting enough, I&#8217;ll take a look at it and post the results here (so don&#8217;t send anything you aren&#8217;t willing to see published in this blog). I can&#8217;t look at everything, but I&#8217;ll try to find some interesting examples.</p>