Property-based testing is one of the powerful technique to unit test the code. Unlike the example-based testing (where we Arrange a set of example inputs to Assert the system under test), Property based testing enable us to focus on what we wanted to test and liberate us from doing mundane work on coming up with sample inputs.
In this blog post, you are going to learn how Property-based testing has helped me and why you need to consider using(or learning) it
Let me start with the use case that I wanted to test. The library that I am working is an adapter between two HTTP protocol abstractions, System.Net.Http and Suave.Http
The first task is to map HttpStatusCode of System.Net to the HttpCode of Suave.Http and the next task is doing the vice-versa.
HttpStatusCode is an enum type and HttpCode is a discriminated union type. Refer this blog post to know more about this difference.
Identifying the Property
The first step is Property-based testing is identifying the property. In other words, it forces to think about the relationship between the input and the output.
I believe this thinking will make a huge difference in the quality of the software that we deliver.
In the first task that we are about to implement, the relationship is the integer representation of the HTTP status code is both HttpStatusCode and HttpCode.
Programmatically, this can be asserted like
// boolean condition// In F# (=) operator represents the equality checkingLanguagePrimitives.EnumToValuehttpStatusCode=httpCode.code
The EnumToValue returns the integer value associated with the enum, which is nothing but the integer representation of the HTTP status code it represents. The code is a member ofHttpCode that represents the same integer.
If this property holds true for given set of inputs, then we can assert that the function that does the transformation is working correctly.
Implementing the mapping function httpStatusCode
The initial implementation that I had in my mind was
If I haven’t choosen to use Property based testing, I might have ended up with this line by line mapping for all the HTTP status codes. As a matter of fact, in my last blog post on using Suave in Azure Functions, I’ve used this same approach.
While thinking regarding properties to assert the transformation, for the first time I came to know about the Language Primitives module in F# and the EnumToValue function.
There should be an another function EnumOfValue right?
Let’s use this in the httpStatusCode function implementation
The reason for this failure is Suave (up to v1.1.3) doesn’t have the HTTP status code 306 (UnUsed). The unit test that we wrote was exercised by the FsCheck for the all possible values of the HttpStatusCode enum till it encountered this failure case.
In this blog post, you are going to experience a scaled up version of Azure Functions in F# using Suave
What’s in the Function Signatures?
In a functional programming language, we define small functions that do one thing well and then we compose them together to represent the solution. To compose functions, we need to be thoughtful while designing the signature of a function.
The Run function takes a HttpRequestMessage and returns the HttpResponseMessage. This signature is simple, but it has a limitation. The limitation has been showcased in the templates directory of Azure Webjobs SDK
My each C, R, U, D are in different functions. Well, there is nothing wrong here. These templates are suitable for getting started in Azure Functions. But what will you do if you have a requirement to expose CRUD of a resource as an Azure Functions?
One option is to define each part of the CRUD as separate Azure Functions (as defined by the templates). If you choose to go by this, you will have four different endpoints and I am sure your client code will have a hard time to consume these endpoints. In addition to this, you will also need to manage four things to satisfy your one requirement.
The other option is putting the CRUD inside a single function.
The Async represents that the WebPart function is a non-blocking asynchronous function and option type models the WebPart which doesn’t handle the HTTP request
The real power of Suave is its set of combinators to manipulate route flow and task composition. You can define an API in Suave that only handles HTTP POST requests and returns Hello as text without typing too much.
If you notice the binding app itself is a WebPart (which in turn a function) with the signature HttpContext -> Async<HttpContext option>. So, you can call this function in your application code and project the output of the function to any output medium that you wish.
The Azure Functions do an incredible job in helping you to define a part of your system as a function. Suave takes it to the next level by helping you to define your system as function.
In nutshell, Suave complements Azure Functions and helps you to define your system as a Serverless Function
Creating a Suave Adapter
So, to scale up Azure Functions using Suave, all we need is an adapter.
The adapter does the following
Transforms HttpRequestMessage from System.Net.Http to HttpRequest of Suave.Http
Then create an empty Suave’s HttpContext with the above HttpRequest and call the WebPart (that represents your system).
The final step is converting the HttpResult of Suave.Http to HttpResponseMessage of System.Net.Http.
This blog post is a proof of concept to use Suave in Azure Functions. There are a lot of improvements to be made to make it production ready. I am planning to publish this as a NuGet package based on the feedback from the community.
I’m delighted to share that I’m running a tutorial at Progressive F# Tutorials 2016, London on Dec 5, 2016. I’m excited to share my experiences with Suave and help developers to understand this wonderful F# library.
The Progressive F# Tutorials offer hands-on learning for every skill set and is led by some of the best experts in F# and functional programming
Checking the state of the system and performing a requested action only if certain conditions met, is an indispensable requirement in most of the software we write. Though it is a straightforward thing to do, things will get complex/messier when we need to check multiple conditions.
Recently I encountered such a situation while developing a sample application for my fsharp book. Initially, I solved it with a typical nested if else and then I improved it by applying fsharp’s Partial Active Patterns.
In this blog post , I will be sharing what exactly I did and how it can help you to write an elegant code in fsharp.
Let’s start with a description of the problem domain that we are going to solve.
When an individual visits a restaurant, he can place an order, specifying the list of foods he wants. The foods he ordered will be prepared by the chef and then it will be served.
Preparing a food should satisfy the following conditions
The Food should be a part of the order
It should not be prepared already
It should not be served already
Serving a food should satisfy the following conditions
The Food should be a part of the order
It should be prepared already
It should not be served already
If serving a food completes the order, we should tell that the order is served otherwise we should tell that there are some other foods to be served.
The names of the types and its properties clearly describe what they represent, so let’s get to the crux of the problem straight
letprepareFoodfoodipo=ifList.containsfoodipo.PlacedOrder.Foodsthenifnot(List.containsfoodipo.PreparedFoods)thenifnot(List.containsfoodipo.ServedFoods)thenprintfn"Prepare Food"elseprintfn"Can not prepare already served food"elseprintfn"Can not prepare already prepared food"elseprintfn"Can not prepare non ordered food"
The if else conditions represent the criteria mentioned in the business domain and for the sake of simplicity we are just writing the action in the console.
Let’s move on to serving food
letisServingFoodCompletesOrderfoodipo=letnonServedFoods=List.exceptipo.ServedFoodsipo.PlacedOrder.FoodsnonServedFoods=[food]letserveFoodfoodipo=ifList.containsfoodipo.PlacedOrder.FoodsthenifList.containsfoodipo.PreparedFoodsthenifnot(List.containsfoodipo.ServedFoods)thenifisServingFoodCompletesOrderfoodipothenprintfn"Order Served"elseprintfn"Still some food(s) to serve"elseprintfn"Can not serve already served food"elseprintfn"Can not serve unprepared food"elseprintfn"Can not serve non ordered food"
This is called Arrow Anti Pattern and it is obvious that this code is hard to understand and maintain.
Though the specification pattern solves the problem, it has a lot of code! No offense here but it can be done in a better way.
F# Active Patterns
Active Patterns allow programmers to wrap arbitrary values in a union-like data structure for easy pattern matching. For example, its possible wrap objects with an active pattern, so that you can use objects in pattern matching as easily as any other union type. - F# Programming Wiki
Let’s begin by defining a partial active pattern for NonOrderedFood and UnPreparedFood
With this in place we can rewrite serveFood function as
letserveFoodfoodipo=matchfoodwith|NonOrderedFoodipo.PlacedOrder_->printfn"Can not serve non ordered food"|UnPreparedFoodipo_->printfn"Can not serve unprepared food"|AlreadyServedFoodipo_->printfn"Can not serve already served food"|CompletesOrderipo_->printfn"Order Served"|_->printfn"Still some food(s) to serve"
The goal is to have code that scrolls vertically a lot… but not so much horizontally. - Jeff Atwood
Now the code expressing the business logic more clearly
To refactor prepareFood to use the parial active patterns we need one more. So, let’s define it
Now we all set to refactor prepareFood and here we go
letprepareFoodfoodipo=matchfoodwith|NonOrderedFoodipo.PlacedOrder_->printfn"Can not prepare non ordered food"|PreparedFoodipo_->printfn"Can not prepare already prepared food"|AlreadyServedFoodipo_->printfn"Can not prepare already served food"|_->printfn"Prepare Food"