Testing Go CLI Apps

I recently started using the really great go.cli library to develop a super simple command line server in Go. When testing this server, however, I needed to figure out a way of starting and stopping it on demand. It is very easy to start a CLI app, just call the Run method with a list of arguments.

To stop it, I realized I could use golang.org/x/net/context library, to pass a context into the app and then cancel it after I wanted the test to stop.

First I had to figure out a way create an app dynamically with a context.Context. For some reason, it took me while to figure out I could just wrap making the cli app in a function, that took a context.Context and executed the action using this.

Then to test it, I could pass in a custom context and cancel it later, like this (using GoConvey syntax):

You might also notice the use of the ShouldNotBeRunningGoroutines function, which I just blogged about

I am new to Go, so let me know if I am doing anything stupid.

This post was inspired by Peter Bourgon’s great talk, which asked the Go community to talk more about their approaches to using the context package.