- Designing Services API First
- Scaffolding a Microservice
- Building Services Test First
- Deploying and Running in the Cloud
- Summary
Building Services Test First
It’s pretty easy to talk about TDD, but, despite countless blogs and books extolling its virtues, it is still pretty rare to find people who practice it regularly. It is even rarer still to find people who practice it without cutting corners. Cutting corners in TDD is the worst of both worlds—you’re spending the time and effort on TDD but you’re not reaping the benefits of code quality and functional confidence.
In this section of the chapter, we’re going to write a method for our service in test-first fashion. If we’re doing it right, it should feel like we’re spending 95% of our time writing tests, and 5% of our time writing code. The size of our test should be significantly larger than the size of the code we’re testing. Some of this just comes from the fact that it takes more code to exercise all possible paths through a function under test than it does to write the function itself. For more details on this concept, check out the book Continuous Delivery by Jez Humble & David Farley.
Many organizations view the effort to write tests as wasteful, claiming that it does not add value and actually increases time-to-market. There are a number of problems with this myopic claim.
It is true that TDD will, indeed, slow initial development. However, let’s consider a new definition of the term development:
development(n) : The period where the features of the application are being added without the so-called burden of a running version of it in production.
Dan Nemeth
With this definition in mind when we look at the entire life cycle of an application, only for a very small portion of that time is the application ever in this state of “development”.
Investment in testing will pay dividends throughout the entire life cycle of the application, but especially in production where:
Uptime is a must.
Satisfying change/feature requests is urgent.
Debugging is costly, difficult, and oftentimes approaching impossible.
To get started on our own TDD journey of service creation, let’s create a file called handlers_test.go (shown in Listing 5.4). This file is going to test functions written in the handlers.go file. If your favorite text editor has a side-by-side or split-screen mode, this would be a great time to use it.
We’re going to be writing a test for the HTTP handler invoked when someone POSTs a request to start a new match. If we check back with our Apiary documentation, we’ll see that one of the requirements is that this function return an HTTP status code of 201 (Created) when successful.
Let’s write a test for this. We’ll call the function TestCreateMatch and, as with all Go unit tests using the basic unit testing package, it will take as a parameter a pointer to a testing.T struct.
Creating a First, Failing Test
In order to test our server’s ability to create matches, we need to invoke the HTTP handler. We could invoke this manually by fabricating all of the various components of the HTTP pipeline, including the request and response streams, headers, etc. Thankfully, though, Go provides us with a test HTTP server. This doesn’t open up a socket, but it does all the other work we need it to do, which lets us invoke HTTP handlers.
There is a lot going on here, so let’s look at the full listing (Listing 5.4) for the test file in our first iteration, which, in keeping with TDD ideology, is a failing test.
Listing 5.4 handlers_test.go
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/unrolled/render" ) var ( formatter = render.New(render.Options{ IndentJSON: true, }) ) func TestCreateMatch(t *testing.T) { client := &http.Client{} server := httptest.NewServer( http.HandlerFunc(createMatchHandler(formatter))) defer server.Close() body := []byte("{\n \"gridsize\": 19,\n \"players\": [\n {\n \"color\": \"white\",\n \"name\": \"bob\"\n },\n {\n \"color\": \"black\",\n \"name\": \"alfred\"\n }\n ]\n}") req, err := http.NewRequest("POST", server.URL, bytes.NewBuffer(body)) if err != nil { t.Errorf("Error in creating POST request for createMatchHandler: %v", err) } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil { t.Errorf("Error in POST to createMatchHandler: %v", err) } defer res.Body.Close() payload, err := ioutil.ReadAll(res.Body) if err != nil { t.Errorf("Error reading response body: %v", err) } if res.StatusCode != http.StatusCreated { t.Errorf("Expected response status 201, received %s", res.Status) } fmt.Printf("Payload: %s", string(payload)) }
Here’s another reason why we like Apiary so much: if you go to the documentation for the create match functionality and click on that method, you’ll see that it can actually generate sample client code in Go. Much of that generated code is used in the preceding test method in Listing 5.3.
The first thing we do is call httptest.NewServer, which creates an HTTP server listening at a custom URL that will serve up the supplied method. After that, we are using most of Apiary’s sample client code to invoke this method.
We have two main assertions here:
We do not receive any errors when executing the request and reading the response bytes
The response status code is 201 (Created).
If we were to try and run the test above, we would get a compilation failure. This is true TDD, because we haven’t even written the method we’re testing (createMatchHandler doesn’t exist yet). To get the test to compile, we can add a copy of our original scaffold test method to our handlers.go file as shown in Listing 5.5:
Listing 5.5 handlers.go
package main import ( "net/http" "github.com/unrolled/render" ) func createMatchHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { formatter.JSON(w, http.StatusOK, struct{ Test string }{"This is a test"}) } }
Now we can see what happens when we try and test this. First, to test we issue the following command:
$ go test -v $(glide novendor)
We should see the following output:
Expected response status 201, received 200 OK
Now we’ve written our first failing test! At this point, some of you may be starting to doubt these methods. If so, please bear with us; we promise that by the end of the chapter you will have seen the light.
Let’s make this failing test a passing one. To make it pass, all we do is make the HTTP handler return a status of 201. We don’t write the full implementation, we don’t add complex logic. The only thing we do is make the test pass. It is vitally important to the process that we only write the minimum code necessary to make the test pass. If we write code that isn’t necessary for the test to pass, we’re no longer in test-first mode.
To make the test pass, change the formatter line in handlers.go to as follows:
formatter.JSON(w, http.StatusCreated, struct{ Test string }{"This is a test"})
We just changed the second parameter to http.StatusCreated. Now when we run our test, we should see something similar to the following output:
$ go test -v $(glide novendor) === RUN TestCreateMatch --- PASS: TestCreateMatch (0.00s) PASS ok github.com/cloudnativego/gogo-service 0.011s
Testing the Location Header
The next thing that we know our service needs to do in response to a create match request (as stated in our Apiary documentation) is to set the Location header in the HTTP response. By convention, when a RESTful service creates something, the Location header should be set to the URL of the newly created thing.
As usual, we start with a failing test condition and then we make it pass.
Let’s add the following assertion to our test:
if _, ok := res.Header["Location"]; !ok { t.Error("Location header is not set") }
Now if we run our test again, we will fail with the above error message. To make the test pass, modify the createMatchHandler method in handlers.go to look like this:
func createMatchHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { w.Header().Add("Location", "some value") formatter.JSON(w, http.StatusCreated, struct{ Test string }{"This is a test"}) } }
Note that we didn’t add a real value to that location. Instead, we just added some value. Next, we’ll add a failing condition that tests that we get a valid location header that contains the matches resource and is long enough so that we know it also includes the GUID for the newly created match. We’ll modify our previous test for the location header so the code looks like this:
loc, headerOk := res.Header["Location"] if !headerOk { t.Error("Location header is not set") } else { if !strings.Contains(loc[0], "/matches/") { t.Errorf("Location header should contain '/matches/'") } if len(loc[0]) != len(fakeMatchLocationResult) { t.Errorf("Location value does not contain guid of new match") } } }
We’ve also added a constant to the test called fakeMatchLocationResult, which is just a string that we also pulled off of Apiary representing a test value for the location header. We’ll use this for test assertions and fakes. This is defined as follows:
const ( fakeMatchLocationResult = "/matches/5a003b78-409e-4452-b456-a6f0dcee05bd" )
Epic Montage—Test Iterations
Since we have limited space in this book, we don’t want to dump the code for every single change we made during every iteration where we went from red (failing) to green (passing) light in our testing.
Instead, we’ll describe what we did in each TDD pass we made:
Wrote a failing test.
Made the failing test pass.
Checked in the results.
If you want to examine the history so you can sift through the changes we made line-by-line, check out the commit history in GitHub. Look for commits labelled “TDD GoGo service Pass n” where n is the testing iteration number.
We’ve summarized the approaches we took for each failed test and what the resolution was to make the test pass in the following list of steps, so cue up your favorite Hollywood hacker movie montage background music and read on:
TDD Pass 1. We created the initial setup required to host a test HTTP server that invokes our HTTP handler method (the method under test). This test initially failed because of compilation failure—the method being tested did not yet exist. We got the test to pass by dumping the test resource code into the createMatchHandler method.
TDD Pass 2. Added an assertion that the result included a Location header in the HTTP response. This test initially failed, so we added a placeholder value in the location header.
TDD Pass 3. Added an assertion that the Location header was actually a properly formatted URL pointing at a match identified by a GUID. The test initially failed, so we made it pass by generating a new GUID and setting a proper location header.
TDD Pass 4. Added an assertion that the ID of the match in the response payload matched the GUID in the location header. This test initially failed and, to make it pass, we had to add code that un-marshaled the response payload in the test. This meant we actually had to create a struct that represented the response payload on the server. We stopped returning “this is a test” in the handler and now actually return a real response object.
TDD Pass 5. Added an assertion that the repository used by the handler function has been updated to include the newly created match. To do this, we had to create a repository interface and an in-memory repository implementation.
TDD Pass 6. Added an assertion that the grid size in the service response was the same as the grid size in the match added to the repository. This forced us to create a new struct for the response, and to make several updates. We also updated another library, gogo-engine, which contains minimal Go game resolution logic that should remain mostly isolated from the service.
TDD Pass 7. Added assertions to test that the players we submitted in the new match request are the ones we got back in the service JSON reply and they are also reflected accordingly in the repository.
TDD Pass 8. Added assertions to test that if we send something other than JSON, or we fail to send reasonable values for a new match request, the server responds with a Bad Request code. These assertions fail, so we went into the handler and added tests for JSON un-marshaling failures as well as invalid request objects. Go is pretty carefree about JSON de-serialization, so we catch most of our “bad request” inputs by checking for omitted or default values in the de-serialized struct.
Let’s take a breather and look at where things stand after this set of iterations. Listing 5.6 shows the one handler that we have been developing using TDD, iterating through successive test failures which are then made to pass by writing code. To clarify, we never write code unless it is in service of making a test pass. This essentially guarantees us the maximum amount of test coverage and confidence possible.
This is a really hard line for many developers and organizations to take, but we think it’s worth it and have seen the benefits exhibited by real applications deployed in the cloud.
Listing 5.6 handlers.go (after 8 TDD iterations)
package service import ( "encoding/json" "io/ioutil" "net/http" "github.com/cloudnativego/gogo-engine" "github.com/unrolled/render" ) func createMatchHandler(formatter *render.Render, repo matchRepository) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { payload, _ := ioutil.ReadAll(req.Body) var newMatchRequest newMatchRequest err := json.Unmarshal(payload, &newMatchRequest) if err != nil { formatter.Text(w, http.StatusBadRequest, "Failed to parse create match request") return } if !newMatchRequest.isValid() { formatter.Text(w, http.StatusBadRequest, "Invalid new match request") return } newMatch := gogo.NewMatch(newMatchRequest.GridSize, newMatchRequest.PlayerBlack, newMatchRequest.PlayerWhite) repo.addMatch(newMatch) w.Header().Add("Location", "/matches/"+newMatch.ID) formatter.JSON(w, http.StatusCreated, &newMatchResponse{ID: newMatch.ID, GridSize: newMatch.GridSize, PlayerBlack: newMatchRequest.PlayerBlack, PlayerWhite: newMatchRequest.PlayerWhite}) } }
While Go’s formatting guidelines generally call for an 8-character tab, we’ve condensed some of that to make the listing a little more readable here.
We have about 20 lines of code in a single function, and we have about 120 lines of code in the two test methods that exercise that code. This is exactly the type of ratio we want. Before we even open a single HTTP test tool to play with our service, we want to have 100% confidence and know exactly how our service should behave.
Based on the tests that we’ve written thus far, and the code in Listing 5.6, can you spot any testing gaps? Can you see any scenarios or edge cases that might trip up our code that we have not yet accounted for in testing?
There are two glaring gaps that we see:
This service is not stateless. If it goes down, we lose all of our in-progress games. This is a known issue, and we’re willing to let it slide because we have a crystal ball, and we know that Chapter 7 will address data persistence.
There are a number of abuse scenarios against which we are not guarding. Most notably, there is nothing to stop someone from rapidly creating game after game until we exceed our memory capacity and the service crashes. This particular abuse vector is a side-effect of us storing games in memory and us violating a cardinal rule of cloud native: statelessness. We’re not going to write tests for this either because, as mentioned in #1, these conditions are temporary and writing DDoS-guarding code is a rabbit hole we want to avoid in this book.
We’ll correct some of these as we progress throughout the book, but others, like guarding against all of the edge cases, are really going to be your responsibility as you build production-grade services.