<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by William Martin on Medium]]></title>
        <description><![CDATA[Stories by William Martin on Medium]]></description>
        <link>https://medium.com/@william.la.martin?source=rss-9f1c6126cc40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*muZVkSnPs0mHzidZUOZ3-g.jpeg</url>
            <title>Stories by William Martin on Medium</title>
            <link>https://medium.com/@william.la.martin?source=rss-9f1c6126cc40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 06:27:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@william.la.martin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Ginkgotchas (yeh also Gomega)]]></title>
            <link>https://medium.com/swlh/ginkgotchas-yeh-also-gomega-13e39185ec96?source=rss-9f1c6126cc40------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e39185ec96</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[gomega]]></category>
            <category><![CDATA[ginkgo]]></category>
            <dc:creator><![CDATA[William Martin]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 15:45:27 GMT</pubDate>
            <atom:updated>2020-05-13T07:51:39.864Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post, I wrote about some <a href="https://medium.com/@william.la.martin/effective-ginkgo-gomega-b6c28d476a09">effective Ginkgo and Gomega practices</a>; there were a few more suggestions that came to mind as I was writing but they felt like they were less “effective” and more “where did the last three hours go debugging this crap?” — A fairly arbitrary distinction but it’s my post so…</p><p>Like the previous post, familiarity with Ginkgo and Gomega is expected before reading. With that in mind, here’s some pain-points you might want to take care to avoid when writing tests using Ginkgo and Gomega.</p><h3>Not initialising a variable in the closest BeforeEach</h3><p>This must be the most pervasive gotcha for people new to writing Ginkgo tests, but it definitely catches old hands from time to time. Look at this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86b37e921b07eb900133813dbef61b54/href">https://medium.com/media/86b37e921b07eb900133813dbef61b54/href</a></iframe><p>This looks simple enough right? We declare a variable and initialise it to 10, test that the value is 10, then we have a block that modifies number to 42 and tests it is 42. What could go wrong?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DFEHZwKDwpb_jeaijFY7Q.png" /></figure><p>If you come from a jUnit background, you probably know that each test gets its own instance of the test class to avoid test pollution. In Ginkgo, test lifecycle is bounded by the test processes (1 to n depending on whether you are using the -p parallel flag). If you turn on --randomizeAllSpecs (see my previous post for why you should do this right now) there is no guarantee of the order these examples will run in. As such, for the previous snippet, the first example sets the value of number to 42 and the next example asserts it to be 10 causing the failure.</p><p>The correct way to resolve this is to explicitly set a default value in the BeforeEach closest to variable declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6612210ba48167182e9a664fc8d4b4d9/href">https://medium.com/media/6612210ba48167182e9a664fc8d4b4d9/href</a></iframe><p>This gotcha is particularly frustrating to debug when the -p and --randomizeAllSpecs flags are set (which they should be) because the test pollution can take many forms.</p><p><strong>TIP: </strong>Each ginkgo run prints the seed it uses to shard and order the examples across nodes, and you can pass this with --seed to Ginkgo to replay a previous run!</p><h3>Not passing a function to Eventually or Consistently</h3><p>More like Consistently a pain in my ass. Ok, so the asynchronous matchers in Gomega are pretty nifty to use, they allow you to pass something which will be checked periodically against some particular matcher.</p><p>You can pass a channel:</p><pre>Eventually(ch).Should(Receive())</pre><p>You can pass a structs that satisfies some interface required by the matcher (in the case of Say, something that has a Buffer method:</p><pre>Eventually(session).Should(Say(&quot;something&quot;))</pre><p>You can even pass a function which will be periodically called and asserted against:</p><pre>var i int = 0</pre><pre>func maybe() bool {<br>  if i &gt; 10 {<br>    return true<br>  }</pre><pre>  i++  <br>  return false<br>}</pre><pre>Eventually(maybe).Should(BeTrue())</pre><p>But what you absolutely should not do, is pass the result of an evaluated function:</p><pre>var i int = 0</pre><pre>func maybe() bool {<br>  if i &gt; 10 {<br>    return true<br>  }</pre><pre>  i++<br>  return false<br>}</pre><pre>Eventually(maybe()).Should(BeTrue())</pre><p>The function will be evaluated <strong>once</strong>, eagerly, and you’ll be left wondering where you went wrong in life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*9Z1I8gkH0Tejxqq6mrMffg.gif" /><figcaption>Who designed this thing?</figcaption></figure><h3>Believing Async Should and ShouldNot are opposites</h3><p>This one seems fairly obvious when you take a moment to think about it but it’s caught me and many others in a moment of weakness. When you are writing a standard assertion:</p><pre>Expect(foo).To(Equal(something))</pre><p>and you decide you actually want to assert the opposite, you can simply flip To to NotTo:</p><pre>Expect(foo).NotTo(Equal(something))</pre><p>If you try to do the same thing with async assertions (Eventually and Consistently), you are in for a world of hurt. Let’s reuse the same example from above, assuming that foo is a function that will return some expected value after some amount of time.</p><pre>Eventually(foo).Should(Equal(something))</pre><p>Flipping the intent, that foo should not ever equal something you might reasonably try to say:</p><pre>Eventually(foo).ShouldNot(Equal(something))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*MXJ-5fqTM5a1cYX22mg4Zw.gif" /><figcaption>You made a huge mistake</figcaption></figure><p>This looks like it should work, but remember that the function foo won’t return the unexpected value for some time, Eventually will evaluate the function, see that it passes the matcher and declare success!</p><p>Likely, the intent is better captured by additionally changing Eventually for Consistently:</p><pre>Consistently(foo).ShouldNot(Equal(something))</pre><p>Much better.</p><h3>Leaking a goroutine</h3><p>In the last post, I wrote that you should use goroutines with care because Ginkgo doesn’t really play nice. Consider this snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/684bf2f19d157a1bf5128f5759a60273/href">https://medium.com/media/684bf2f19d157a1bf5128f5759a60273/href</a></iframe><p>You can mostly ignore the sleeps, they exist only to orchestrate an overlap between the examples to demonstrate this failure. Our first example creates a goroutine (it even uses GinkgoRecover() like a good little example), and calls Fail. The second example makes an assertion that cannot possibly fail, that true is equal to true!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROZoxHgro9TzEzx1fWVpWA.png" /><figcaption>You’re gonna have a bad time</figcaption></figure><p>The second example failed! true is no longer equal to true and Pi is exactly 3!</p><p>What happened here is that the goroutine outlived the lifetime of its spec and when Fail was called, Ginkgo determined that the currently running example was the second one. It’s important to make sure your goroutines lifetimes are carefully handled in your examples, typically coordinated via channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*a1dFfhSKqMLC604nw042nQ.gif" /><figcaption>Yeh, it sucks</figcaption></figure><h3>Asserting errors against stdout</h3><p>I’ll keep this one short. If you’ve used the gexec.Say matcher to test stdio of some running process you’ll recognise this:</p><pre>Eventually(session).Should(Say(&quot;something&quot;))</pre><p>This asserts that the string &quot;something&quot; has appeared on some output. More specifically, it asserts that the string has appeared on stdout. If you want to test output on stderr, this mistake will leave you running in circles.</p><p>The Say matcher will call the Buffer method on session to find the contents to assert against. Unfortunately, this returns only the stdout buffer, rather than an amalgamation of both. To test against stderr you need to write:</p><pre>Eventually(session.Err).Should(Say(&quot;something&quot;))</pre><p><strong>TIP: </strong>You may find it more expressive to intentionally use .Out and .Err everywhere to avoid confusion.</p><h3>Accidentally regex testing with Say</h3><p>This gotcha is brought to you by the letters [A-Za-z]. Good joke right. Let’s take the following snippet of code that uses the gbytes package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fe2c9475805a9fa8d41bdb9f9ec29fc/href">https://medium.com/media/0fe2c9475805a9fa8d41bdb9f9ec29fc/href</a></iframe><p>This looks pretty simple right? There’s a buffer containing the string map[string] and then we assert the buffer contains the string map[string]!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71t5wgCdy6RIzZczzfX1iA.png" /><figcaption>Absolute nightmare fuel</figcaption></figure><p>The Say matcher accepts a regular expression as an argument, so the [ and ] characters are tripping it up so we’ll have to escape them with \ characters.</p><p><strong>TIP: </strong>If you use backticks instead of double quotes to surround your argument to Say, this gives a better indicator to your reader that there’s something special about the string.</p><h3>Final thoughts!</h3><p>This list of gotchas is certainly not exhaustive, but they are the most common ones I’ve come across. Despite some of the frustration I’ve experienced over the years at these, in my experience it doesn’t take long for people to recognise these patterns and avoid them. Hopefully this post helps capture some of that tribal knowledge so that others avoid the same issues in the first instance.</p><p>If you’ve got any thoughts on any of these, or have any more to add, let me know.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e39185ec96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/ginkgotchas-yeh-also-gomega-13e39185ec96">Ginkgotchas (yeh also Gomega)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Ginkgo/Gomega]]></title>
            <link>https://medium.com/swlh/effective-ginkgo-gomega-b6c28d476a09?source=rss-9f1c6126cc40------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6c28d476a09</guid>
            <category><![CDATA[ginkgo]]></category>
            <category><![CDATA[gomega]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[William Martin]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 08:58:57 GMT</pubDate>
            <atom:updated>2021-10-19T15:06:36.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kI1fu8tsZf6AE0ws5zYVig.png" /></figure><p>I’ve been writing Go tests using the <a href="https://github.com/onsi/ginkgo">Ginkgo</a> BDD test library, and its preferred matcher library <a href="https://github.com/onsi/gomega">Gomega</a> for almost four years as of writing. In that time I’ve discovered some recurring practices in the projects that I’ve joined, and in those I’ve started, which hopefully may be of use to you. I hesitate to refer to these as “Best Practices”, instead titling this post “Effective”, because although these work for me in most cases, they may not work for everyone in all cases.</p><p>Occasionally I’m going to link to codebases I’ve worked on recently that follows some of these practices, some of the time (hey, I said these weren’t <strong>best</strong> practices <strong>all</strong> the time!) but if there’s anything unclear, please leave a comment!</p><p>It’s expected that you have some familiarity with these libraries (or others like it), to best understand these patterns. So, without further ado:</p><h3>One JustBeforeEach per test hierarchy</h3><p>Consider having one JustBeforeEach at the top level performing some shared action for your test hierarchy (typically bounded to a file, unless you have suite level setup and teardown).</p><p>For example, if you are testing a CLI command, have a JustBeforeEach that runs some set of arguments that can be modified by other BeforeEach blocks. You can find an example of this pattern in the <a href="https://github.com/pivotal-cf/ism/blob/ba9479ac4c9a6aaf892337483d28f6c437a0a0d5/acceptance/service_command_test.go#L38-L44">ism codebase</a> but here’s an inline snippet (pseudocode) demonstrating how you might use this pattern for testing a binary and its arguments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7b3386a69b8c138d239c89b23300e80/href">https://medium.com/media/f7b3386a69b8c138d239c89b23300e80/href</a></iframe><p>Notice how the arguments to the binary are declared at the beginning and then modified throughout the tree structure in BeforeEach blocks. As a result, we only had to run the command once in theJustBeforeEach block. The alternative to this model generally is to run the command in each It as the first line butI prefer JustBeforeEach to reduce the visual noise, and to keep only assertions inside my It blocks.</p><p>Caution: Don’t get clever and keep your hierarchy simple. JustBeforeEaches break the descending tree structure and make reasoning harder so avoid having more than one.</p><h3>BeforeEach should act out the description of its closest Context or Describe</h3><p>Prefer having Context and descriptions immediately being followed by a BeforeEach that takes the relevant action. This allows readers to very easily understand exactly how state is being modified throughout the test hierarchy. Let’s look back at a snippet from the example above and notice how each BeforeEach takes exactly one action that corresponds to the text description above it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bace16af0810475ab6363eba8b41e07a/href">https://medium.com/media/bace16af0810475ab6363eba8b41e07a/href</a></iframe><p>This pattern holds true for more complicated setup as well. Looking into the ism codebase, here is a description stating that a <a href="https://github.com/pivotal-cf/ism/blob/ba9479ac4c9a6aaf892337483d28f6c437a0a0d5/acceptance/service_command_test.go#L87-L90">broker will be registered</a> (don’t worry, you don’t need to understand what a broker is), which is immediately followed by a helper function that takes registers a broker. Such clarity!</p><p>If you find a BeforeEach doing something that isn’t in a description, consider whether the tests should be structured in some other hierarchy.</p><h3>Helper functions over expectations in setup and teardown</h3><p>Instead of setup and teardown directly making assertions, prefer helper functions that use ExpectWithOffset. Take a look again at the <a href="https://github.com/pivotal-cf/ism/blob/ba9479ac4c9a6aaf892337483d28f6c437a0a0d5/acceptance/service_command_test.go#L87-L90">example</a> from the previous section where a broker is being registered, then let’s look at the <a href="https://github.com/pivotal-cf/ism/blob/ba9479ac4c9a6aaf892337483d28f6c437a0a0d5/acceptance/acceptance_suite_test.go#L246-L255">code</a> that function is encapsulating — I definitely don’t want to see that code everywhere we register a broker. In this case, the authors have decided not to use the variant WithOffset which will result in Ginkgo printing a failure stack trace that is off by one (see the tradeoff below for why this might be acceptable).</p><p>The utility of expectations failing in setup and teardown is useful, but the code can get visually busy very quickly. Most of the time when reading a test you want to quickly parse intent through a well chosen name. It can be easy to allow these helper functions to increase in complexity as you just need a little extra behaviour, but this will cause you pain; ensure that your helper functions are extremely narrow in their scope, acting as thin wrappers that assert correctness e.g:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba14d7e96d21e8043b317ff28ec08da1/href">https://medium.com/media/ba14d7e96d21e8043b317ff28ec08da1/href</a></iframe><p>Caution: using ExpectWithOffset couples your code to its calling hierarchy due to the stack frame unwinding. Be very careful if you are going to refactor around the helpers that offsets are correct.</p><h3>Randomise and parallelise from the start</h3><p>Prefer starting your projects with full randomisation and parallelisation on in Ginkgo via the --randomizeAllSpecs and -p flags. The cost of hunting test flakes caused by turning these on later can be huge.</p><p>See Ed King’s great blog post “<a href="https://medium.com/@teddyking/the-night-is-dark-and-full-of-flakes-29c529404c3c">The Night is Dark and Full of Flakes</a>” for our experience on the Cloud Foundry Garden team after not following this advice.</p><h3>Consider the contract Eventually and Consistently place upon your implementation</h3><p>Eventually and Consistently are incredibly useful functions that provide the ability to assert that some state will exist within some timeout (defaulted to one second).</p><p>These utilities are extremely helpful but they are also placing a hidden constraint on your code (that some action should be time bounded) and may hide other issues such as deadlocks. If you find yourself bumping timeouts to appease these functions, consider whether you should be using something else.</p><p>On one project, after experiencing one too many failures that we were unable to debug, we removed the timeout altogether and wrote a tool called slowmobius that watched over all our test runs and notified us of any that were taking an unusually long time to complete. This allowed us to better distinguish environmental slowness from hangs, and gave us the ability to jump in and debug.</p><h3>Use goroutines in tests with care</h3><p>This one is quite simple, be careful with goroutines in your tests, they don’t play well with Ginkgo’s failure model, and if they aren’t carefully managed they can leak between tests.</p><h3>Dot import the testing libraries</h3><p>Dot imports in Go pollute your namespace with public functions and types from the imported package — typically this is a big no-no! I suggest dot importing ginkgo, gomega and its friends gexec, gbytes, and ghttp. However, if you want to see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c246a381800d64bab2f9596538fa112/href">https://medium.com/media/9c246a381800d64bab2f9596538fa112/href</a></iframe><p>Be my guest.</p><h3>Don’t even think about using the Omega symbol</h3><p>When Gomega was first created, you could use Ω instead ofExpect e.g.</p><pre>Ω(foo).To(Equal(bar))</pre><p>This still lurks around in <a href="https://github.com/onsi/ginkgo/blob/4cb744166b80afeec15fd0b4446c640a7688cd51/types/types_test.go#L25">tests we haven’t got round to cleaning up yet</a>. This should be self-explanatory. Don’t do it. Seriously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*ey2mtJZ-xPpaGdRoWqsn_w.gif" /><figcaption>Not a joke</figcaption></figure><h3>What else?</h3><p>Have you got any more effective practices? Do you disagree with any of these? Leave a comment!</p><p>If you’re interested in reading more, check out my next post on <a href="https://medium.com/@william.la.martin/ginkgotchas-yeh-also-gomega-13e39185ec96">common Ginkgo and Gomega gotchas.</a></p><p>Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaPzzHbjyp54GztyfWBEiQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6c28d476a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/effective-ginkgo-gomega-b6c28d476a09">Effective Ginkgo/Gomega</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your first Gomega matcher]]></title>
            <link>https://medium.com/@william.la.martin/your-first-gomega-matcher-29e6350bb933?source=rss-9f1c6126cc40------2</link>
            <guid isPermaLink="false">https://medium.com/p/29e6350bb933</guid>
            <category><![CDATA[gomega]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ginkgo]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[William Martin]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 16:38:36 GMT</pubDate>
            <atom:updated>2019-02-25T16:38:36.526Z</atom:updated>
            <content:encoded><![CDATA[<p>If you write tests in Go, you may have come across the <a href="https://github.com/onsi/gomega">Gomega</a> assertion library, <a href="https://github.com/onsi/ginkgo">Ginkgo’s</a> preferred matcher. I’ve seen a few examples where engineers have written a convoluted series of assertions, when what they really wanted was a custom matcher to express intent.</p><p>I’ve spent the last few years working on the <a href="https://github.com/cloudfoundry/guardian">garden</a> container manager for Cloud Foundry, Concourse and BOSH. Albeit trivial, it’s often useful to check whether a process with a certain pid exists or not, so let’s write a matcher for that!</p><p>Let’s start from a test that doesn’t have a custom pid matcher:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b429ef50f47dd9724facb792c40a73d/href">https://medium.com/media/7b429ef50f47dd9724facb792c40a73d/href</a></iframe><p>Ok so, it’s contrived, but in this test, we start a process that will sleep for 10 seconds, and then wait on it. We can then use the Consistently matcher to assert every second, for 5 seconds, that the process is still running (T<em>he </em>0<em> signal doesn’t actually send a signal but does do existence and permission checks: </em><a href="http://man7.org/linux/man-pages/man2/kill.2.html">http://man7.org/linux/man-pages/man2/kill.2.html</a>).</p><p>Functionally, this works great. However, I think there are two unfortunate issues with this code. Firstly, let’s look at the failure output (when the process doesn’t run for at least 5 seconds):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_Y96v-ZTFkrdv2bsCBgDA.png" /></figure><p>It doesn’t indicate why this test failed at all! Ok, so Gomega provides the ability to annotate assertions with a message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qb4gP3b1uubmVk-YlVfBiQ.png" /></figure><p>and the associated failure output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duebt87r5F-t200DgIlUag.png" /></figure><p>Better, but still a lot of excess information, and the boolean output doesn’t really fit within our domain of pids, so it’s just noise — let’s come back to this later.</p><p>The second issue I have is that a reader must understand the intent of sending the 0signal, it sure would be nice if we could be more expressive by capturing this as an abstraction. In fact, it would be really nice if we could write something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZP4x77zQXnebhnOjyHeW_g.png" /></figure><p>Fortunately, this is super simple, as a custom Gomega matcher only needs to satisfy the GomegaMatcher (go figure!) interface:</p><pre>type GomegaMatcher interface {<br>    Match(actual interface{}) (success bool, err error)<br>    FailureMessage(actual interface{}) (message string)<br>    NegatedFailureMessage(actual interface{}) (message string)<br>}</pre><p>So here’s our desired matcher come to life:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/376dad2783a2fb24159997e97b0cdc4a/href">https://medium.com/media/376dad2783a2fb24159997e97b0cdc4a/href</a></iframe><p>This is super simple, we type assert the actual value to an integer, check it using our aforementioned 0 signal (which a reader no longer needs to understand) and write some error messages to handle To/Should vs NotTo/ShouldNot.</p><p>Let’s see how that failure message looks now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0byOJU1MCpV2kpZjpDzm2g.png" /></figure><p>Ship it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_G51MCfv4zedG4NL.jpg" /></figure><p>As noted at the start, this is a trivial example, but I’ve seen various snippets of code that get lengthy and convoluted that would be far better abstracted as a custom matcher. Can you think of any in your codebases?</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29e6350bb933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Acceptance testing your Go CLI]]></title>
            <link>https://medium.com/@william.la.martin/acceptance-testing-your-go-cli-d992926bcfe5?source=rss-9f1c6126cc40------2</link>
            <guid isPermaLink="false">https://medium.com/p/d992926bcfe5</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[ginkgo]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[gomega]]></category>
            <dc:creator><![CDATA[William Martin]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 11:37:10 GMT</pubDate>
            <atom:updated>2019-02-20T11:37:10.868Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a fan of Acceptance Test Driven Development, or Double-Loop TDD. This involves writing a failing high level end-to-end test that desires some feature, then following the red-green-refactor cycle through layers of unit tests until the acceptance test passes, and then repeating for the next feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*D3969QnidHY2X6YP.jpg" /><figcaption>Double-loop TDD credit: Nat Price and Steve Freeman</figcaption></figure><p>I’m also a fan of Go and CLI tools. No diagram necessary.</p><p>Given these statements, it’s important for me to able to write a test suite that will exercise my CLIs in a black-box manner. Even if you don’t write your tests first, it is still extremely important to have confidence that if you changed the internals (and you <strong>do</strong> refactor don’t you?!), there are no regressions.</p><p>Fortunately, <a href="https://github.com/onsi/ginkgo">Ginkgo</a> and it’s preferred matching library <a href="https://github.com/onsi/gomega">Gomega</a> have our backs. The <a href="https://onsi.github.io/gomega/#gexec-testing-external-processes">gexec</a> library allows us to:</p><blockquote><a href="https://onsi.github.io/gomega/#compiling-external-binaries">compile go binaries</a>, <a href="https://onsi.github.io/gomega/#starting-external-processes">start external processes</a>, <a href="https://onsi.github.io/gomega/#sending-signals-and-waiting-for-the-process-to-exit">send signals and wait for them to exit</a>, make <a href="https://onsi.github.io/gomega/#asserting-against-exit-code">assertions against the exit code</a>, and stream output into<strong>gbytes.Buffer</strong>s to allow you <a href="https://onsi.github.io/gomega/#making-assertions-against-the-process-output">make assertions against output</a>.</blockquote><p>So let’s start testing a simple CLI (we’ll call this scratchpad), that we expect to print “Hello World” on stdout and exit with the status code 0. For our acceptance tests, we will need to:</p><ul><li>Compile the binary</li><li>Run the built binary as a process</li><li>Assert that “Hello World” appears on the stdout stream</li><li>Assert that the process exits with the status code 0</li></ul><p>Here’s an example of how that might look using ginkgo and gomega:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b1a055242b79483a120a56ba9347a9b/href">https://medium.com/media/2b1a055242b79483a120a56ba9347a9b/href</a></iframe><p>Let’s pick this apart. Those who are familiar with tools like rpsec should recognise this Behaviour-Driven testing style, with a top-level Describe outlining the subject under test: our scratchpad CLI!</p><p>Underneath that we have a BeforeEach block, which delegates to functions that will build the CLI, and then execute it. The gexec library provides utility functions to facilitate these steps:</p><p>Build takes the directory containing the main.go we want to build and returns the path of the built binary. This is a costly process, and we probably don’t want it to happen before <strong>every</strong> spec, andginkgo has BeforeSuite and SynchronizedBeforeSuite helpers to reduce overhead here — I’ve just used BeforeEach for simplicity.</p><p>Start takes the path of the built binary, and writers for the stdout and stderr streams. GinkgoWriter is a special buffer that contains all the output for the ginkgo process when tests are running, so any output from our CLI can appear in there (though it will usually only appear if a test fails). Returned is a gexec.Session which is an abstraction over the running process that satisfies interfaces needed by other matchers in our specs — let’s get on to that now.</p><p>Our first spec ensures that the process should exit with the status code 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*8QiE6iwrGvE7TKAYakLdtw.png" /></figure><p>The Eventually assertion ensures that a matcher will pass within some time (defaulting to 1 second), by iteratively checking for a condition to be true. In this case we can take advantage of the Exit function provided, which takes an expected status code as an argument. Usefully, the Session struct satisfies the Exiter interface required by this matcher.</p><p>Our next spec ensures that the process prints “Hello World” to the stdout stream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ILxHv0zXO7W9Q6c_WEixUQ.png" /></figure><p>The Say matcher from the gbytes package requires a buffer, or something that satisfies the BufferProvider interface, and again, the Session struct has us covered.</p><p>Finally, we can use the gexec.CleanupBuildArtifacts() to ensure we don’t leave debris around after each test, easy!</p><p>Alright, so this is a fairly trivial example of acceptance testing a CLI, but these tools can quickly be combined in an extremely expressive manner to cover all number of larger CLI projects for example, the <a href="https://github.com/cloudfoundry/cli">Cloud Foundry CLI</a>, the <a href="https://github.com/pivotal-cf/om">Pivotal OpsManager CLI</a>, and even Ginkgo itself!</p><p>Soon I intend to do a video session on using ginkgo and gomega to ATDD a CLI with more interesting behaviour so if you’re interested, check back soon! For now however, you can find the full code for this in the <a href="https://github.com/williammartin/scratchpad">scratchpad</a> repository on github.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d992926bcfe5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Fear the Subreaper]]></title>
            <link>https://medium.com/@william.la.martin/dont-fear-the-subreaper-19c8127c031e?source=rss-9f1c6126cc40------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c8127c031e</guid>
            <category><![CDATA[zombies]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[subreaper]]></category>
            <dc:creator><![CDATA[William Martin]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 13:21:15 GMT</pubDate>
            <atom:updated>2018-11-02T16:32:28.231Z</atom:updated>
            <content:encoded><![CDATA[<p>Today’s post is brought to you by the letter Z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YvB70UiNRSxl7j1Ri7wJdg.gif" /><figcaption>Z for Zombies</figcaption></figure><p>This post is about Linux subreapers, why they exist, what their behaviour is, and how you can use them, via a practical example in Go. If you are comfortable with how the process table and process states work, you can go ahead and skip the preliminary reading section, otherwise let’s go!</p><p><strong>Preliminary Reading on Process States</strong></p><p>In Linux, a process can progress through various states, however, commonly when you look at ps output, you will only seeR (for running) andS (for interruptible sleep). Below you can see some ps output for a parent and child relationship, they are both in S state with some extra information you can read about on the man7 <a href="http://man7.org/linux/man-pages/man1/ps.1.html">ps</a> page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_2NoacPdPgHEHjamBmqmg.png" /><figcaption>Sleeping Processes</figcaption></figure><p>Less commonly however, you may see processes in Z (for zombie) state; zombie processes are those that have exited but not been reaped by an ancestor via a system call from the <a href="http://man7.org/linux/man-pages/man2/waitpid.2.html">wait</a> family. They are no longer running but have left some state around in the kernel’s process table. They are often seen with the associated &lt;defunct&gt;string, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuS_Js9-mOgKcKcDSaivGQ.png" /><figcaption>Ahhh! Zombies</figcaption></figure><p>Ok so why are we seeing a zombie process here? Why do we ever see them in ps output? Well, ps output is produced by looking at the contents of files found under the/proc/&lt;pid&gt;/ directory. The procfs filesystem is a special beast, a virtual filesystem that can read the process table - you can read more about it in the man7 <a href="http://man7.org/linux/man-pages/man5/proc.5.html">proc</a> page. After a process exits, and transitions toZ state, it still has an entry in the process table until it is reaped, and thus it appears in the ps output. So in this case we can point the finger at the ./main process for not reaping correctly!</p><p>By default, when child processes become orphaned (because their parent process dies :( so sad), they are reparented to the init process (pid 1) in their <a href="http://man7.org/linux/man-pages/man7/pid_namespaces.7.html">pid namespace</a>. The init process is responsible for cleaning up after any debris, and will attempt to reap any zombies that have been reparented under it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*M-ZP7a3qVVylB9FoYYRQOg.gif" /><figcaption>pid 6 putting up a fight</figcaption></figure><p>Sometimes reparenting to init is undesirable behaviour; Sometimes we want a process to be responsible for any and all descendants, even if intermediary processes in the tree have exited. The canonical example here is to support userspace supervisor processes such as <a href="http://man7.org/linux/man-pages/man1/init.1.html">systemd</a>, where services often double-fork to daemonize — based on the behaviour above, this would result in the services being reparented directly to init, bypassing the supervisor process.</p><p>So what mechanism exists to allow supervisor processes to work as intended?</p><p><strong>Don’t Fear The Subreaper</strong></p><p>Since version 3.4, Linux has had the concept of a subreaper. No resource could say it better than the man7 page on <a href="http://man7.org/linux/man-pages/man2/prctl.2.html">prctl</a>:</p><blockquote>A subreaper fulfills the role of init(1) for its descendant processes. When a process becomes orphaned (i.e., its immediate parent terminates) then that process will be reparented to the nearest still living ancestor subreaper. Subsequently, calls to <strong>getppid</strong>() in the orphaned process will now return the PID of the subreaper process, and when the orphan terminates, it is the subreaper process that will receive a <strong>SIGCHLD </strong>signal and will be able to wait(2) on the process to discover its termination status.</blockquote><p>So let’s get to the fun part, and play around with subreapers practically. I created a little library to work from at <a href="https://github.com/williammartin/subreaper">https://github.com/williammartin/subreaper</a>, which provides three functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a02e5730576aa00aafb4e9ca50c263e/href">https://medium.com/media/7a02e5730576aa00aafb4e9ca50c263e/href</a></iframe><p>The Prctl function from the unix library allows interaction with a variety of attributes on a process. Depending on the value passed in the first argument, the following arguments can have different significance. For subreaper attributes, we care about the PR_SET_CHILD_SUBREAPER and PR_GET_CHILD_SUBREAPER values.</p><p>When setting a process as a subreaper, a nonzero second argument sets an attribute, and if it’s zero the attribute is unset. When fetching the subreaper setting of a process, the second value is a pointer into which the value of the subreaper attribute is set (0 or 1).</p><p>Alright, so now we have some utilities that play with the subreaper setting for a process, we can see the impact it has upon the process tree and reaping!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2dd11e8d10732e870e9ff288e88bb87/href">https://medium.com/media/c2dd11e8d10732e870e9ff288e88bb87/href</a></iframe><p>This is a simple demonstration program using the previous library. Let’s break down the runtime structure; This program does a double-fork as discussed earlier when executed with run as the first argument.</p><ol><li>The parent spawns and waits on the child (via cmd.Run()), then sleeps</li><li>The child spawns the grandchild, but does not wait (via cmd.Start())</li><li>The grandchild process goes to sleep</li></ol><p>It should be noted that /proc/self/exe is a special file that links to the currently executing binary. We can use ps to compare the process table with the default reparenting behaviour (by commenting the subreaper.Set() line out), versus setting the parent as a subreaper:</p><p><strong>Default Reparenting Behaviour</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5TzTvp_lKEYUO_HFYyCjg.png" /><figcaption>The grandchild has been reparented to init</figcaption></figure><p>We can see here that the /proc/self/exe grandchild process has been reparented to the init process. If we check again later, it has been reaped and no longer appears in the ps output.</p><p><strong>Subreaper Reparenting Behaviour:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ri8M4ZzdoZLLPwtcdVrJKQ.png" /><figcaption>The grandchild has been reparented to our subreaper!</figcaption></figure><p>Wow! This time when the child exited, the grandchild was reparented to the subreaper rather than init! If we check back 20 seconds later the process will be a zombie…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSXNcnk2nw5hDVYRQ5xuEw.png" /><figcaption>The grandchild has become a zombie!</figcaption></figure><p>Now all our subreaper needs to do is wait on any descendants, and it can act like a real supervisor process!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c661a45702a290479aa288c6c2ddc2c/href">https://medium.com/media/6c661a45702a290479aa288c6c2ddc2c/href</a></iframe><p>The only change we’ve made in here is to listen for SIGCHLD signals and call the Wait4 function with -1 in the first argument to reap any child process that has exited. You can read about the various arguments on the man7 <a href="http://man7.org/linux/man-pages/man2/wait.2.html">wait</a> page. Now our grandchild gets reaped successfully!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*KRuqV-SzDq4BSN7tHstEIQ.png" /><figcaption>The grandchild has been reaped!</figcaption></figure><p>Note that if you were to write this in a non-trivial manner, you would probably want a loop to manage SIGCHLD signals from many descendants, rather than exiting after one. You would probably also want to catch the child process exiting in your loop, rather than via cmd.Run().</p><p><strong>Conclusion</strong></p><p>Hopefully, you now have a good understanding of how the linux model works when it comes to process states, the process tree and reaping. If you have any questions, let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c8127c031e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>