Tuesday, May 10, 2016

Contract 0.0.4, delivering expressions

This week saw the release of Contract 0.0.4 and the first months stats from maven central. About 30 unique downloads, I'm chuffed if even half of those people who downloaded it actually used it. Ok, on to what we did this week.

Wildcard expressions:

Having to hard code absolutely everything is never going to be very good for testing systems. People don't want to have to fill out contracts in that level of detail. There are also times when people cant predict what will be returned when a request is made to a server. With that in mind, we added the wildcard expression functionality.

We'd dipped our toes into this functionality 2 releases ago with the ${contract.timestamp} in a limited amount. We've expanded on that in our 0.0.4 release to include strings and numbers. We've limited its use to within string fields within JSON bodies for now.

These wildcards can be used to replace parts of the path, query parameters, headers and body. Looking at an example, lets use an online streaming service, and an API endpoint that is used to register new content. Lets write the contract for creating a new TV show.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "request" : {
    "method" : "POST",
    "path" : "/webmovies/library/tvshow",
    "body" : {
     "name" : "Imprisioned Construction",
     "year" : "2005",
     "productionCompany" : "BOX"
    }
  },
  "response" : {
    "status" : 201,
    "body" : {
     "id" : "${contract.anyNumber}",
     "name" : "Imprisioned Construction",
     "year" : "2005",
     "productionCompany" : "BOX",
     "addedOn" : "${contract.timestamp}"
    }
  }
}

This contact specifies that when a POST request is made to the 'webmovies/library/tvshow' url with the body specified. Then the server will respond with the CREATED response code, the same body as was in the request enriched with id and addedOn fields.

We can create a contract for reading a TV show from the service where we know effectively nothing and the test server will fill in the blanks.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
{
  "request" : {
    "method" : "GET",
    "path" : "/webmovies/library/tvshow/${contract.anyString}"
  },
  "response" : {
    "status" : 200,
    "body" : {
     "id" : "${contract.anyNumber}",
     "name" : "${contract.anyString}",
     "year" : "${contract.anyNumber}",
     "productionCompany" : "${contract.anyString}",
     "addedOn" : "${contract.timestamp}"
    }
  }
}

Here any request valid request sent to the server will be given a valid response. 


Want to give it a try? Download our fat runnable jar from here and run it with :

1
java -jar contract-all-0.0.4.jar -s -p 9005 -g https://github.com/harmingcola/webmoviesContracts

Make a GET request to http://localhost:9005/__configure and the contracts loaded into that server will be listed.

Links:
Contract source
Contract docs
Webmovies contracts

No comments: