<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Labix Blog &#187; Test</title>
	<atom:link href="http://blog.labix.org/tag/test/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.labix.org</link>
	<description>by Gustavo Niemeyer</description>
	<lastBuildDate>Mon, 16 Jan 2012 04:02:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Death of goroutines under control</title>
		<link>http://blog.labix.org/2011/10/09/death-of-goroutines-under-control</link>
		<comments>http://blog.labix.org/2011/10/09/death-of-goroutines-under-control#comments</comments>
		<pubDate>Sun, 09 Oct 2011 19:53:47 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Project]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=717</guid>
		<description><![CDATA[Certainly one of the reasons why many people are attracted to the Go language is its first-class concurrency aspects. Features like communication channels, lightweight processes (goroutines), and proper scheduling of these are not only native to the language but are &#8230; <a href="http://blog.labix.org/2011/10/09/death-of-goroutines-under-control">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Certainly one of the reasons why many people are attracted to the <a href="http://golang.org">Go</a> language is its first-class concurrency aspects. Features like communication channels, lightweight processes (<i>goroutines</i>), and proper scheduling of these are not only native to the language but are integrated in a tasteful manner.</p>
<p><span id="more-717"></span>If you stay around listening to community conversations for a few days there&#8217;s a good chance you&#8217;ll hear someone proudly mentioning the tenet:</p>
<blockquote><p>Do not communicate by sharing memory; instead, share memory by communicating.</p></blockquote>
<p>There is a <a href="http://blog.golang.org/2010/07/share-memory-by-communicating.html">blog post</a> on the topic, and also a <a href="http://golang.org/doc/codewalk/sharemem/">code walk</a> covering it.</p>
<p>That model is very sensible, and being able to approach problems this way makes a significant difference when designing algorithms, but that&#8217;s not exactly news. What I address in this post is an open aspect we have today in Go related to this design: the <i>termination</i> of background activity.</p>
<p>As an example, let&#8217;s build a purposefully simplistic goroutine that sends lines across a channel:</p>
<pre>
type LineReader struct {
        Ch chan string
        r *bufio.Reader
}

func NewLineReader(r io.Reader) *LineReader {
        lr := &#038;LineReader{make(chan string), bufio.NewReader(r)}
        go lr.loop()
        return lr
}
</pre>
<p>The type has a channel where the client can consume lines from, and an internal buffer<br />
used to produce the lines efficiently. Then, we have a function that creates an initialized<br />
reader, fires the reading loop, and returns. Nothing surprising there.</p>
<p>Now, let&#8217;s look at the loop itself:</p>
<pre>
func (lr *LineReader) loop() {
        for {
                line, err := lr.r.ReadSlice('\n')
                if err != nil {
                        close(lr.Ch)
                        return
                }
                lr.Ch <- string(line)
        }
}
</pre>
<p>In the loop we'll grab a line from the buffer, close the channel in case of errors and stop, or otherwise send the line to the other side, perhaps blocking while the other side is busy with other activities. Should sound sane and familiar to Go developers.</p>
<p>There are two details related to the termination of this logic, though: first, the error information is being dropped, and then there's no way to interrupt the procedure from outside in a clean way. The error might be easily logged, of course, but what if we wanted to store it in a database, or send it over the wire, or even handle it taking in account its nature? Stopping cleanly is also a valuable feature in many circumstances, like when one is driving the logic from a test runner.</p>
<p>I'm not claiming this is something <i>difficult</i> to do, by any means.  What I'm saying is that there isn't today an <i>idiom</i> for handling these aspects in a simple and consistent way. Or maybe there wasn't. The <i>tomb</i> package for Go is an experiment I'm releasing today in an attempt to address this problem.</p>
<p>The model is simple: a <i>Tomb</i> tracks whether the goroutine is alive, dying, or dead, and the death reason.</p>
<p>To understand that model, let's see the concept being applied to the LineReader example. As a first step, creation is tweaked to introduce Tomb support:</p>
<pre>
type LineReader struct {
        Ch chan string
        r *bufio.Reader
        <span style="color: blue">*tomb.Tomb</span>
}

func NewLineReader(r io.Reader) *LineReader {
        lr := &#038;LineReader{
                make(chan string),
                bufio.NewReader(r),
                <span style="color: blue">tomb.New(),</span>
        }
        go lr.loop()
        return lr
}
</pre>
<p>Looks very similar. Just a new field in the struct and its respective initialization. We've used it as an embedded field just so we can use the Tomb methods directly in the <i>lr</i> variable.</p>
<p>Next, the loop function is modified to support tracking of errors and interruptions:</p>
<pre>
func (lr *LineReader) loop() {
        <span style="color: blue">defer lr.Done()</span>
        for {
                line, err := lr.r.ReadSlice('\n')
                if err != nil {
                        close(lr.Ch)
                        <span style="color: blue">lr.Fatal(err)</span>
                        return
                }
                select {
                case lr.Ch <- string(line):
                <span style="color: blue">case <-lr.Dying:</span>
                        close(lr.Ch)
                        return
                }
        }
}
</pre>
<p>Note a few interesting points here: first, <i>Done</i> is called to track the goroutine termination right before the loop function returns. Then, the previously loose error now goes into the <i>Fatal</i> Tomb method, flagging the goroutine as dying. Finally, the channel send was tweaked so that it doesn't block in case the goroutine is dying for whatever reason.</p>
<p>A Tomb has both <i>Dying</i> and <i>Dead</i> channels, which are closed when the Tomb state changes accordingly. These channels enable explicit blocking until the state changes, and also to selectively unblock select statements in those cases, as done above.</p>
<p>With the loop modified as above, a Stop method can trivially be introduced to request the clean termination of the goroutine synchronously from outside:</p>
<pre>
func (lr *LineReader) Stop() os.Error {
        <span style="color: blue">lr.Fatal(tomb.Stop)</span>
        return <span style="color: blue">lr.Wait()</span>
}
</pre>
<p>In this case the <i>Fatal</i> method will put the goroutine in a dying state from outside, and <i>Wait</i> will block until the goroutine terminates itself and notifies via the <i>Done</i> method as seen before. This procedure behaves correctly even if the goroutine was already dead or in a dying state due to internal errors, because only the first call to Fatal with an actual error is recorded as the cause for the goroutine death. The <i>tomb.Stop</i> value is used as a reason when terminating cleanly without an actual error, and it causes Wait to return nil once the goroutine terminates, flagging a clean stop per common Go idioms.</p>
<p>(<b>UPDATE:</b> there was <a href="http://groups.google.com/group/golang-nuts/browse_thread/thread/383f7cabbb174460">a minor simplification</a> in the API since this post was originally written, and the paragraph above was adapted to cover the new API)</p>
<p>This is pretty much all that there is to it. When I started developing in Go I wondered if coming up with a good convention for this sort of problem would require more support from the language, such as some kind of goroutine state tracking in a similar way to what <a href="http://www.erlang.org/doc/reference_manual/processes.html">Erlang does</a> with its lightweight processes, but it turns out this is mostly a matter of organizing the workflow with existing building blocks.</p>
<p>The tomb package and its Tomb type are a tangible representation of a good convention for goroutine termination, with familiar method names inspired in existing idioms. If you want to make use of it, goinstall the package with:</p>
<pre>
$ goinstall launchpad.net/tomb
</pre>
<p>The API documentation with details is available at:</p>
<p><span style="padding-left: 2em;"><a href="http://goneat.org/lp/tomb">http://goneat.org/lp/tomb</a></span></p>
<p>Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2011/10/09/death-of-goroutines-under-control/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Interfaces and the design of software</title>
		<link>http://blog.labix.org/2010/11/09/interfaces-and-the-design-of-software</link>
		<comments>http://blog.labix.org/2010/11/09/interfaces-and-the-design-of-software#comments</comments>
		<pubDate>Tue, 09 Nov 2010 18:30:29 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Article]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=450</guid>
		<description><![CDATA[A while ago Martin Pool made a very interesting post on the design of interfaces, inspired by a talk from Rusty Russel from 2003. Besides the interesting scale of interface quality explained there, this is a very insightful comment, often &#8230; <a href="http://blog.labix.org/2010/11/09/interfaces-and-the-design-of-software">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A while ago Martin Pool made a <a href="http://sourcefrog.net/weblog/software/aesthetics/interface-levels.html">very interesting post</a> on the design of interfaces, inspired by a <a href="http://www.ozlabs.com/~rusty/ols-2003-keynote/ols-keynote-2003.html">talk from Rusty Russel</a> from 2003.</p>
<p>Besides the interesting scale of interface quality explained there, this is a very insightful comment, often overlooked:</p>
<p><span id="more-450"></span><br />
<blockquote>
Once the code gets too big for one person, it&#8217;s all about damage control. Interfaces make damage control possible&#8230; except when the interfaces themselves are the problem.
</p></blockquote>
<p>Designing a system as a group of people requires splitting tasks up among team members, and/or the community, and perhaps even separate teams. Interfaces are the touch points of that splitting, and is what represents the functionality offered within the module/library/file/command/service/whatever.  Too often, people spend a long time working on the implementation details, thinking really deep about how to obtain the desired behavior, and forget to define clearly what is the <i>interface</i> to that behavior.</p>
<p>Having good interfaces is a key aspect of software development, and getting it correctly offers a number of important benefits:</p>
<p><b>Good encapsulation</b></p>
<p>Having good encapsulation is pretty much a synonym of having good interfaces. Too often, though, people focus on the encapsulation of the small pieces (the functions, the classes, etc), and forget about the encapsulation of the larger blocks (the libraries, modules, packages, commands, etc).</p>
<p>Also, in my experience trying to encourage good architectures, I have found that stating <i>&#8220;We need good encapsulation!&#8221;</i> gives developers no tangible line of action.  It reminds me of a parent telling the child <i>&#8220;You should be responsible!&#8221;</i>.  Sure, encapsulation and responsibility both sound great, but.. what does that <i>really mean</i>?</p>
<p>When inviting developers to think about the <i>interfaces</i> of the system parts they are responsible for, encapsulation becomes a natural outcome. It&#8217;s clear that there must be a line drawn between that part of the system and the rest, and the shape of this line must be considered while (or even better, <i>before</i>) the behavior is implemented.</p>
<p>Given well designed interfaces, the additional requirement of only using other parts of the system through their public interfaces seals the achievement of good encapsulation. Ideally, this barrier would be a natural property of the language used to develop the system (see the interface quality scale in <a href="http://sourcefrog.net/weblog/software/aesthetics/interface-levels.html">Martin&#8217;s post</a>). In other cases, this must be achieved through conventions, agreements, and good documentation.</p>
<p><b>Improved scope and communication</b></p>
<p>By inviting developers to think about the <i>interfaces</i> of the parts they are responsible for, one is basically encouraging the consideration of the interaction between those pieces and the rest of the system.  This process gives an interesting perspective, both in terms of the external expectations (what do I need to offer other people?), as well as the internal goals (what do I need to implement for satisfying what other people need?).</p>
<p>Besides helping people to figure the scope and goal of the piece being developed, this will also give a nice structure to some of the communication which must inevitably happen to integrate correctly the separate parts of the system being developed.</p>
<p><b>Improved testing and experimentation</b></p>
<p>If an interface is well designed and defined, and encapsulates well part of the functionality of the system, it improves significantly the testing and experimentation related to that part of the system.  Again, this has an effect internally and externally to the interface.</p>
<p>Internally in the sense that there&#8217;s a clear boundary between the part in development and the rest of the system, and thus it should be easier to verify that the bits which compose it are working according to plan without dragging the whole system together, and also to verify that the interface itself is behaving as intended (and hopefully as documented).</p>
<p>Externally in the sense that, given that there&#8217;s agreement regarding what is the public interface to the part being considered, one may easily provide a test double (a fake, or dummy, or mock) to simulate that part of the system.  This is well known to be useful in a number of ways:</p>
<ul>
<li>Dependent work may be run in parallel by different people</li>
<li>Real implementation backing the given interface may be postponed, until the idea is proven useful, and the interface feels suitable</li>
<li>External systems which would be hard to run locally may be simulated so that tests run fast and cheap, even without network connections</li>
<li>Faults may be injected in the system via the test doubles to verify behavior in hostile conditions</li>
</ul>
<p>and so on.</p>
<p><b>Quality isolation</b></p>
<p>This point is also my understanding of what Rusty refers to as <i>damage control</i> in his talk.  This property is very useful when designing a system, but even then it&#8217;s often missed when discussing interfaces and encapsulation.</p>
<p>If there&#8217;s a well defined interface to a piece of functionality in the system, and that interface was carefully considered to cover the needs of the system, the implementation of that interface may not start as the most beautiful, or most scalable, or even most reliable piece of software. As any developer responsible for a successful startup will happily point out, a half-baked implementation is often good enough to get things going, prove the concept, and extend the project runway.</p>
<p>Good interfaces play an important role in this kind of situation.  They are, in this sense, a way to be better prepared for success (or, for failure, <a href="http://twitter.com">depending on the perspective</a>).  If the interface implementation suddenly becomes an issue for whatever reason, the implementation itself may be replaced by something which better suits the current reality, while preserving the interaction with the rest of the system.</p>
<p>Of course, it&#8217;s still very hard to predict future system behavior when facing a completely different reality.  Changing the scale requirements for the system a few orders of magnitude, for instance, may easily break existing assumptions, and interfaces designed around these assumptions. Still, even if good interfaces won&#8217;t be enough to avoid modifications in the architecture and integration points in many cases, they will certainly help framing the conversations which will take place when this happens and new interfaces must be developed.</p>
<p><b>Conclusion</b></p>
<p>When developing non-trivial software products, there&#8217;s no other way but to split out the problem solving in several layers and components.  Looking at the points where these layers and components touch each other is a very useful and natural way to organize conversations and structure work which must take place to push the product forward.</p>
<p>It&#8217;s quite revealing to look at the points above, and note that it&#8217;s not simply the existence of interfaces themselves which presents the advantages described, but the process which they encourage around them.  Software architecture is essentially about people.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2010/11/09/interfaces-and-the-design-of-software/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gocheck: A rich testing library for Go</title>
		<link>http://blog.labix.org/2010/11/06/gocheck-a-rich-testing-library-for-go</link>
		<comments>http://blog.labix.org/2010/11/06/gocheck-a-rich-testing-library-for-go#comments</comments>
		<pubDate>Sat, 06 Nov 2010 23:31:59 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Project]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=433</guid>
		<description><![CDATA[It&#8217;s time to release my &#8220;side project&#8221; which has been evolving over the last several months: Gocheck. I&#8217;ve been watching Go for some time, and have been getting more and more interested in the language. My first attempt to write &#8230; <a href="http://blog.labix.org/2010/11/06/gocheck-a-rich-testing-library-for-go">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s time to release my &#8220;side project&#8221; which has been evolving over the last several months: <a href="http://j.mp/dcKGmQ" _href="http://labix.org/gocheck">Gocheck</a>. I&#8217;ve been watching Go for some time, and have been getting more and more interested in the language.  My first attempt to write something interesting in it made it obvious that there would be benefit in having a richer testing platform than what is <a href="http://golang.org/pkg/testing/">available in the standard library</a>.  That said, I do understand why the standard one is slim: it&#8217;s pretty minimalist, because it&#8217;s used by itself to test the rest of the platform.  With Gocheck, though, I don&#8217;t have that requirement.  I&#8217;m able to trust that the standard library works well, and focus on having features which will make me more productive while writing tests, including features such as:</p>
<p><span id="more-433"></span>
<ul>
<li>Better error reporting
<li> Richer test helpers: assertions which interrupt the test immediately, deep multi-type comparisons, string matching, etc
<li> Suite-based grouping of tests
<li> Fixtures: per suite and/or per test set up and tear down
<li> Management of temporary directories
<li> Panic-catching logic, with proper error reporting
<li> Proper counting of successes, failures, panics, missed tests, skips, etc
<li> Support for expected failures
<li> Fully tested (yes, it manages to test itself reliably!)
</ul>
<p>That last point was actually quite fun to get right.  It&#8217;s the first time I wrote a testing framework from the ground up, and of course I wanted to have it fully tested by itself, but I didn&#8217;t want to simply use a foreign testing framework to test it.  So what it does is basically to have a &#8220;bootstrapping&#8221; phase, which ensures that the very basic parts of the library work, without trusting on pretty much any internal functionality (e.g. it verifies the number of executed functions, and works with low-level panics). Then, once the lower layers are trusted, tests for higher functionality was introduced by building on the trusted bits.</p>
<p>Gocheck is actually <i>mostly</i> ready for some time now, but I&#8217;ve been polishing edges with some real world usage before releasing it.  Since both the real world usage and Gocheck itself are side projects, you can imagine that took a bit of time.  Today, though, I&#8217;ve managed to fix the last few things which were bothering me, so it&#8217;s up for world consumption.</p>
<p>I hope you enjoy it, and make some good use of it so that we can all have more reliable software. <img src='http://blog.labix.org/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2010/11/06/gocheck-a-rich-testing-library-for-go/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Mocker 1.0 for Python released!</title>
		<link>http://blog.labix.org/2010/06/20/mocker-1-0-for-python-released</link>
		<comments>http://blog.labix.org/2010/06/20/mocker-1-0-for-python-released#comments</comments>
		<pubDate>Mon, 21 Jun 2010 00:09:02 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Project]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=323</guid>
		<description><![CDATA[After a few years in development, version 1.0 of Mocker is now available! Check out the changes since 0.10.1, the supported features, or go straight to the download page.]]></description>
			<content:encoded><![CDATA[<p>After a few years in development, version 1.0 of <a href="http://bit.ly/dm0GGy" _href="http://labix.org/mocker">Mocker</a> is now <a href="http://bit.ly/dez9jQ" _href="https://launchpad.net/mocker/trunk/1.0">available</a>!  Check out the <a href="http://bit.ly/czhiru " _href="http://bazaar.launchpad.net/~niemeyer/mocker/trunk/annotate/head:/NEWS">changes since 0.10.1</a>, the <a href="http://bit.ly/dm0GGy" _href="http://labix.org/mocker">supported features</a>, or go straight to the <a href="http://bit.ly/9Wszmp" _href="https://launchpad.net/mocker/+download">download page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2010/06/20/mocker-1-0-for-python-released/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The forgotten art of error checking</title>
		<link>http://blog.labix.org/2010/06/17/the-forgotten-art-of-error-checking</link>
		<comments>http://blog.labix.org/2010/06/17/the-forgotten-art-of-error-checking#comments</comments>
		<pubDate>Thu, 17 Jun 2010 15:15:59 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=275</guid>
		<description><![CDATA[I was just rambling randomly yesterday, in the usual microblogging platforms, about how result checking seems to be ignored or done badly. The precise wording was: It&#8217;s really amazing how little attention error handling receives in most software development. Even &#8230; <a href="http://blog.labix.org/2010/06/17/the-forgotten-art-of-error-checking">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was just rambling randomly yesterday, in the usual microblogging platforms, about how result checking seems to be ignored or done badly.  The precise wording was:</p>
<blockquote><p>
It&#8217;s really amazing how little attention error handling receives in most software development. Even *tutorials* often ignore it.
</p></blockquote>
<p>It indeed does amaze me.  It sometimes feels like we write code for theoretical perfect worlds.. <i>&#8220;If the processor executes exactly in this order, and the weather is calm, this program will work.&#8221;</i>.  There are countless examples of bad assumptions.. someday I will come with some statistics of the form <i>&#8220;Every N seconds someone forgets to check the result of write().&#8221;</i>.</p>
<p><span id="more-275"></span></p>
<p>If you are a teacher, or a developer that enjoys writing snippets of code to teach people, please join me in the quest of building a better future.  Do <i>not</i> tell us that you&#8217;re &#8220;avoiding result checking for terseness&#8221;, because that&#8217;s exactly what we people will do (terseness is good, right?).  On the contrary, take this chance to make us feel <i>bad</i> about avoiding result checking.  You might do this by putting a comment like &#8220;If you don&#8217;t do this, you&#8217;re a bad programmer.&#8221; right next to the logic which is handling the result, and might take this chance to teach people how proper result handling is done.</p>
<p>Of course, there&#8217;s another forgotten art related to result checking.  It sits on the other side of the fence.  If you are a library author, do think through about how you plan to make us check conditions which happen inside your library, and try to imagine how to make our lives easier.  If we suck at handling results when there are obvious ways to handle it, you can imagine what happens when you structure your result logic badly.</p>
<p>Here is a clear example of what <i>not</i> to do, coming straight from Python&#8217;s standard library, in the <i>imaplib</i> module:</p>
<pre>
    def login(self, user, password):
        typ, dat = self._simple_command('LOGIN', user, self._quote(password))
        if typ != 'OK':
            raise self.error(dat[-1])
        self.state = 'AUTH'
        return typ, dat
</pre>
<p>You see the problem there?  How do you handle errors from this library?  Should we catch the exception, or should we verify the result code? <i>&#8220;Both!&#8221;</i> is the right answer, unfortunately, because the author decided to do us a little favor and check the error condition himself in some arbitrary cases and raise the error, while letting it go through and end up in the result code in a selection of other arbitrary cases.</p>
<p>I may provide some additional advice on result handling in the future, but for now I&#8217;ll conclude with the following suggestion: please check the results from your actions, and help others to check theirs.  That&#8217;s a good life-encompassing recommendation, actually.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2010/06/17/the-forgotten-art-of-error-checking/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Xpresser &#8211; Python library for GUI automation with image matching</title>
		<link>http://blog.labix.org/2010/05/18/xpresser-python-library-for-gui-automation-with-image-matching</link>
		<comments>http://blog.labix.org/2010/05/18/xpresser-python-library-for-gui-automation-with-image-matching#comments</comments>
		<pubDate>Tue, 18 May 2010 20:43:24 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Project]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/?p=267</guid>
		<description><![CDATA[In a hurry? Go check it out! The context A while ago I found out about Sikuli, a very interesting project which allows people to script actions in GUIs based on screenshot excerpts. The idea is that you basically take &#8230; <a href="http://blog.labix.org/2010/05/18/xpresser-python-library-for-gui-automation-with-image-matching">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><b>In a hurry?</b></p>
<p><a href="http://wiki.ubuntu.com/Xpresser">Go check it out!</a></p>
<p><b>The context</b></p>
<p>A while ago I found out about <a href="http://sikuli.org">Sikuli</a>, a very interesting project which allows people to script actions in GUIs based on screenshot excerpts.  The idea is that you basically take images representing portions of your screen, like a button, or a label, or an icon, and then create a script which can detect a position in the screen which resembles one of these images, and perform actions on them, such as clicking, or hovering.</p>
<p><span id="more-267"></span></p>
<p>I had never imagined something like this, and the idea got me really excited about the possibilities.   Imagine, for instance, what can be done in terms of testing.  Testing of GUIs is unfortunately not yet a trivial task nowadays.  We do have frameworks which are based on accessibility hooks, for instance, but these sometimes can&#8217;t be used because the hook is missing, or is even far off in terms of the context being tested (imagine testing that a browser can open a specific flash site successfully, for instance).</p>
<p>So, Sikuli opened my eyes to the possibility of using image matching technology in a GUI automation context, and I really wanted to play with it.  In the days following the discovery, I fiddled a bit, communicated with the author, and even submitted some changes to make it work well in Ubuntu.</p>
<p>Then, the idea cooled down in my head, and I moved on with life.  Well&#8230; until two weeks ago.</p>
<p>Right before heading to the <a href="http://wiki.ubuntu.com/UDS-M">Ubuntu Developer Summit</a> for the next Ubuntu release, the desire of automating GUIs appeared again in the context of the widely scoped Ubuntu-level testing suite.  Then, over the first few days last week, I was able to catch up with quite a few people which were interested in the concept of automating GUIs, with different purposes (testing, design approval, etc), which of course was all I needed to actually push that old desire forward.</p>
<p>Trying to get Sikuli to work, though, was quite painful.  Even though I had sent patches upstream before, it looks like the build process isn&#8217;t working in Ubuntu again for other reasons (it&#8217;s not a polished build process, honestly), and even if I managed to make it work and contributed that to the upstream, in the end the path to integrate the Java-based tool in the Python-based testing framework which Ubuntu uses (<a href="https://launchpad.net/mago">Mago</a>) wasn&#8217;t entirely straightforward either.</p>
<p><b>Reinventing the wheel</b></p>
<p>So, the the itch was in place, and there was a reason to let the <a href="http://en.wikipedia.org/wiki/Not_Invented_Here">NIH</a> syndrome take over a bit.  Plus, image processing is something I&#8217;d like to get a foot in anyway, so it felt like a good chance to have a closer look and at the same time contribute a small bit to potential quality improvements of Ubuntu.</p>
<p>That&#8217;s when <a href="http://wiki.ubuntu.com/Xpresser">Xpresser</a> was born.  Xpresser is a clean room implementation of the concepts explored by Sikuli, in the form of a Python library which can be used standalone, or embedded into other programs and testing frameworks such as Mago.</p>
<p>The project is sponsored by <a href="http://canonical.com">Canonical</a>, and licensed under the LGPL.</p>
<p>Internally, it makes use of opencv for the image matching, pyatspi for the event generation (mouse clicks, etc), gtk for screen capturing and testing (of itself), and numpy for matrix operations. Clearly, the NIH syndrome, wasn&#8217;t <i>entirely</i> active. <img src='http://blog.labix.org/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   As a side note, I haven&#8217;t played with numpy and gtk for some time, and I&#8217;m always amazed by the quality of these modules.</p>
<p><b>Contribute code and ideas</b></p>
<p>Concluding this post, which is already longer than I expected, the basics of Xpresser are in place, so go ahead and play with it!  That said, there are quite a few low hanging fruits to get it to a point of being a really compelling GUI-driving library, so if you have any interest in the concept, I invite you to play with the code and submit contributions too.  If you want ideas of what else could be done, let&#8217;s have a chat.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2010/05/18/xpresser-python-library-for-gui-automation-with-image-matching/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Mocker 0.10 and trivial patch-mocking of existing objects</title>
		<link>http://blog.labix.org/2007/12/09/mocker-010-and-trivial-patch-mocking-of-existing-objects</link>
		<comments>http://blog.labix.org/2007/12/09/mocker-010-and-trivial-patch-mocking-of-existing-objects#comments</comments>
		<pubDate>Sun, 09 Dec 2007 23:07:13 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Project]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/2007/12/09/mocker-010-and-trivial-patch-mocking-of-existing-objects/</guid>
		<description><![CDATA[Mocker 0.10 is out, with a number of improvements! While we&#8217;re talking about Mocker, here is another interesting use case, exploring a pretty unique feature it offers. Suppose we want to test that a method hello() on an object will &#8230; <a href="http://blog.labix.org/2007/12/09/mocker-010-and-trivial-patch-mocking-of-existing-objects">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://labix.org/mocker">Mocker</a> 0.10 is out, with a <a href="https://launchpad.net/mocker/trunk/0.10">number of improvements</a>!</p>
<p>While we&#8217;re talking about Mocker, here is another interesting use case, exploring a pretty unique feature it offers.</p>
<p>Suppose we want to test that a method <i>hello()</i> on an object will call <i>self.show(&#8220;Hello world!&#8221;)</i> at some point.  Let&#8217;s say that the code we want to test is this:</p>
<pre>
 class Greeting(object):

     def show(self, sentence):
         print sentence

     def hello(self):
         self.show("Hello world!")
</pre>
<p>This is the <i>entire</i> test method:</p>
<pre>
def test_hello(self):
    # Define expectation.
    mock = self.mocker.patch(Greeting)
    mock.show("Hello world!")
    self.mocker.replay()

    # Rock on!
    Greeting().hello()
</pre>
<p>This has helped me in practice a few times already, when testing some involved situations.</p>
<p>Note that you can also <i>passthrough</i> the call.  In other words, the call may actually be made on the real method, and mocker will just assert that the call was really made, whatever the effect is.</p>
<p>One more important point: mocker ensures that the real method <i>exists</i> in the real object, and has a specification compatible with the call made.  If it doesn&#8217;t, and assertion error is raised in the test with a nice error message.</p>
<p><b>UPDATE:</b> <i>The method for doing this is actually mocker.patch() rather than mocker.mock(), as documented. Apologies.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2007/12/09/mocker-010-and-trivial-patch-mocking-of-existing-objects/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Partial stubbing of os.path.isfile() with Mocker</title>
		<link>http://blog.labix.org/2007/11/22/partial-stubbing-of-ospathisfile-with-mocker</link>
		<comments>http://blog.labix.org/2007/11/22/partial-stubbing-of-ospathisfile-with-mocker#comments</comments>
		<pubDate>Thu, 22 Nov 2007 23:27:14 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Project]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/2007/11/22/partial-stubbing-of-ospathisfile-with-mocker/</guid>
		<description><![CDATA[One neat feature which Mocker offers is the ability to very easily implement custom behavior on specific functions or methods. Take for instance the case where you want to pretend to some code that a given file exists, but you &#8230; <a href="http://blog.labix.org/2007/11/22/partial-stubbing-of-ospathisfile-with-mocker">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One neat feature which Mocker offers is the ability to very easily implement custom behavior on specific functions or methods.</p>
<p>Take for instance the case where you want to pretend to some code that a given file exists, but you don&#8217;t want to get on the way of everything else which needs the same function: </p>
<pre>
>>> from mocker import *
>>> mocker = Mocker()
>>> isfile = mocker.replace("os.path.isfile", count=False)
>>> _ = expect(isfile("/non/existent")).result(True)
>>> _ = expect(isfile(ANY)).passthrough()

>>> mocker.replay()

>>> import os
>>> os.path.isfile("/non/existent")
True
>>> os.path.isfile("/etc/passwd")
True
>>> os.path.isfile("/other")
False

>>> mocker.restore()

>>> os.path.isfile("/non/existent")
False
</pre>
<p>Notice that the <i>count=False</i> parameter is available in version 0.9.2.  Without it Mocker will act in a more <i>mocking-strict</i> way and enforce that the given expressions should be executed precisely the given number of times (which defaults to one, and may be modified with the <i>count()</i> method). </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2007/11/22/partial-stubbing-of-ospathisfile-with-mocker/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocker for Python released!</title>
		<link>http://blog.labix.org/2007/11/11/mocker-for-python-released</link>
		<comments>http://blog.labix.org/2007/11/11/mocker-for-python-released#comments</comments>
		<pubDate>Mon, 12 Nov 2007 02:17:00 +0000</pubDate>
		<dc:creator>Gustavo Niemeyer</dc:creator>
				<category><![CDATA[Project]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://blog.labix.org/2007/11/11/mocker-for-python-released/</guid>
		<description><![CDATA[After being bored for a long time for the lack of a better infrastructure for creating test doubles in Python, I decided to give it a go. I&#8217;m actually quite happy with what came out.. it took me about four &#8230; <a href="http://blog.labix.org/2007/11/11/mocker-for-python-released">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>After being bored for a long time for the lack of a better infrastructure for creating <a href="http://martinfowler.com/articles/mocksArentStubs.html">test doubles</a> in Python, I decided to give it a go.</p>
<p>I&#8217;m actually quite happy with what came out.. it took me about four weekends (was developed as a personal project), and I&#8217;ll dare to say that it&#8217;s the best mocking system for Python at the present time.  Not only that, but it has features that I&#8217;ve not seen in any other mocking/stubing infrastructure, independent of language.</p>
<p>Here&#8217;s a feature list to catch your attention:</p>
<ul>
<li> Graceful platform for test doubles in Python (mocks, stubs, fakes, and dummies).
<li> Inspiration from real needs, and also from pmock, jmock, pymock, easymock, etc.
<li> Expectation of expressions defined by actually using mock objects.
<li> Expressions may be replayed in any order by default,
<li> Trivial specification of ordering between expressions when wanted.
<li> Nice parameter matching for defining expectations on method calls.
<li> Good error messages when expectations are broken.
<li> Mocking of many kinds of expressions (getting/setting/deleting attributes, calling, iteration, containment, etc)
<li> Graceful handling of nested expressions (e.g. &#8221;person.details.get_phone().get_prefix()&#8221;)
<li> Mock &#8221;proxies&#8221;, which allow passing through to the real object on specified expressions (e.g. useful with &#8221;os.path.isfile()&#8221;).
<li> Mocking via temporary &#8221;patching&#8221; of existent classes and instances.
<li> Trivial mocking of any external module (e.g. &#8221;time.time()&#8221;) via &#8221;proxy replacement&#8221;.
<li> Mock objects may have method calls checked for conformance with real class/instance to prevent API divergence.
<li> Type simulation for using mocks while still performing certain type-checking operations.
<li> Nice (optional) integration with &#8221;unittest.TestCase&#8221;, including additional assertions (e.g. &#8221;assertIs&#8221;, &#8221;assertIn&#8221;, etc).
<li> More &#8230;
</ul>
<p>Worked?  <a href="http://labix.org/mocker">Check it out!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.labix.org/2007/11/11/mocker-for-python-released/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

