Archive

Monthly Archives: March 2016

I regret my declaration to write a new blog post every day. Hence, I made this ridiculous declaration to challenge myself until I secure my next contract. There has been benefits though. Hence, writing everyday has reinforced my understanding of what I have been attempting to share with my community. However, I find myself struggling to maintain a journal entry every day due to a lack of motivation and technical content. As I have stuck to my declaration, I’ve made significant progress in learning F# and using my blog to document my understanding of it. However, I am just not confident that I can sustain this writing pace. It’s like I have writer’s block. Except in my case, it’s on a grander scale. I just don’t think I can write at the same pace that I learn. I really do hope I secure a contract soon because I’m going to eventually renig on my declaration.

Intro

Today, I attempted to dig deeper into Property-based Testing. Specifically, I wanted to understand which technique for filtering values of a property-based test was most advantageous. Specifically, I wanted to understand the difference between a precondition expression and a custom generator in regards to their value.

The Difference between Them

Mark Seemann provided an answer here. In summary, he stated that when using a precondition expression for a property-based test, the tester risks reducing the actual number of tests (i.e. coverage) being executed. For example, having a precondition that eliminates negative numbers will only generate 50 test scenarios instead of 100 (the default). Instead, Mark stated that leveraging a custom generator will preserve the number of scenarios to be tested.

I then attempted to integrate a custom generator into a property-based test for a FizzBuzz implementation that I saw. Unfortunately, the test that I wrote always passed and I didn’t understand why.

The code looked like this:

[<Fact>]
let ``FizzBuzz.transform returns FizzBuzz`` () =
    let fiveAndThrees = Arb.generate<int> |> Gen.map ((*) (3 * 5))
                                          |> Arb.fromGen

    Prop.forAll fiveAndThrees <| fun number ->

        let actual = transform number

        let expected = "jbdhjsdhjdsjhsdglsdjlljh"
        expected = actual</pre>

I then received some help that resolved my issue. It turns out that I didn’t assign the prop.forAll expression to a property value. Thus I could then do a check that the property held up based on the range of values.

The working test looks like this:

[<Fact>]
let ``FizzBuzz.transform returns FizzBuzz`` () =
    let fiveAndThrees = Arb.generate<int> |> Gen.map ((*) (3 * 5))
                                          |> Arb.fromGen

    let property = Prop.forAll fiveAndThrees <| fun number ->

        let actual = transform number

        let expected = "FizzBuzz"
        expected = actual

    Check.QuickThrowOnFailure property

Conclusion

In conclusion, I attempted to dig deeper into Property-based Testing. Specifically, I wanted to understand which technique for filtering values of a property-based test was most advantageous. Specifically, I wanted to understand the difference between a precondition expression and a custom generator in regards to their value.

Intro

In the last article, I discussed property-based testing. What I did not discuss was setting up the preconditions necessary for a function to be tested.

Test Conditions

Consider the following function:

let createGrid rowCount = 

    [for x in 0..rowCount-1 do
        for y in 0..rowCount-1 do
            yield { X=x; Y=y; State=Dead }
    ]|> List.map (fun c -> (c.X, c.Y), { X=c.X; Y=c.Y; State=Dead })
     |> Map.ofList

The above function generates a grid from the rowCount argument provided by a client. If we wanted to provide a property-based test for this function, we could write it such that the number of cells generated from the function equals the rowCount that we passed in as input, squared.

The following code is a property-based test:

[<Fact>]
let ``number of cells in grid equals rowcount squared`` () =
    Check.QuickThrowOnFailure <| fun rowCount -> rowCount |> createGrid
                                                          |> Map.toList
                                                          |> List.length = rowCount * rowCount

If we run the above test, we will observe the following failure.

System.Exception : Falsifiable, after 3 tests (1 shrink) (StdGen (199136793,296133941)):
Original:
-2
Shrunk:
-1

Setting Preconditions

For the above test to pass, we need to setup some conditions for the range of inputs. For example, this function probably shouldn’t accept negative values for the number of rows. Therefore, to specify the conditions for the valid range of inputs to our function under test, we can rewrite the test and specify the conditions for a valid range of inputs.

The following test includes conditions for valid inputs:

[<Fact>]
let ``number of cells in grid equals rowcount squared`` () =
    Check.QuickThrowOnFailure <| fun rowCount -> rowCount >= 0 ==> (rowCount |> createGrid
                                                                             |> Map.toList
                                                                             |> List.length = rowCount * rowCount)

Observe the precondition that we provided:

rowCount >= 0

We then feed that precondition into our test with the following operator:

==>

If we run the test now, the test will pass.

Conclusion

In conclusion, I discussed setting up conditions for valid inputs in regards to property-based testing.

Intro

I have been on a journey to learn F# via implementing the Game of Life. Thus, I have decided to dig into Property-based Testing.

Property-based Testing

Property-based testing is another technique used within test automation. Unlike unit tests, which test specific examples on a case-by-case basis, property-based tests target the properties or principles of the function itself. Thus, I now view unit tests (aka: example-based tests) as a design tool for building systems. Furthermore, I view property-based tests as regression tests for each property of a function.

In the Game of Life, I wrote a function called getNeighbors:

let getNeighbors (coordinate:int*int) =
        
    let x,y = coordinate
    let west = x-1, y
    let northWest = x-1, y+1
    let north = x, y+1
    let northEast = x+1, y+1
    let east = x+1, y
    let southEast = x+1, y-1
    let south = x, y-1
    let southWest = x-1, y-1

    [west; northWest; north; northEast; east; southEast; south; southWest]

In the above code, a client passes in a coordinate in which the function will return a list of neighbors for that particular coordinate.

One property that I identified for the getNeighbors function is that a coordinate can have no more than eight neighbors.

To test this, I wrote the following property-based test:

[<Fact>]
let ``cell can't have more than eight neighbors`` () = 
    Check.QuickThrowOnFailure <| fun xy -> xy |> getNeighbors
                                              |> List.length < 9

QuickThrowOnFailure will throw an exception if any argument used within the expression triggers a false result.
The “<|" operator forwards the result of an expression on the right-hand side to a function on the left-hand side.

The test, by default, will pass in a range of values to this function. By default, the range consists of 100 values. However, the range is configurable with a little extra code.

The Nuget dependencies required to setup this test were XUnit, xunit.runner.visualstudio, and FsCheck.

There's also another function that's a good candidate for a property-based test. That function is the createGrid function. The createGrid function takes a rowCount as an argument.

I first attempted to write the test as the following:

[<Fact>]
let “number of cells in grid equals rowcount squared“ () =
Check.QuickThrowOnFailure <|
fun rowCount -> rowCount >= 0 ==>
fun rowCount -> rowCount |> createGrid
|> Map.toList
|> List.length = rowCount * rowCount

However, the test failed as a result of using -1 as an argument for the number of rows. I'm still not sure how -1 got included as an argument though. Hence, I provided the precondition for the row count to be greater than zero. Unfortunately, I need help in identifying my misunderstanding. Thus, I hope to share the correct implementation for this property-based test in my next post.

Conclusion

In conclusion, I have been on a journey to learn F# via implementing the Game of Life. Thus, I have decided to dig into Property-based Testing.

Intro

I decided to learn about Active Patterns within F# and find opportunities to apply them within my Game of Life implementation.

Active Patterns

I interpret Active Patterns as a feature within F# that enables a programmer to use labels as an alias to an expression when performing pattern matching.

Example 1

Here’s the first example:

let isValueNeighbor v1 v2 =
    match v1 >= 0
      &&  v2 >= 0 with
    | true  -> isAbsNeighbor v1 v2
    | _     -> isAbsNeighbor v2 v1

With Active Patterns, we can arguably enhance readability and rewrite the code like this:

let isValueNeighbor v1 v2 =
    match v1, v2 with
    | BothPositive    -> isAbsNeighbor v1 v2
    | NotBothPositive -> isAbsNeighbor v2 v1

To support this rewrite we had to implement the following Active Pattern:

let (|BothPositive|NotBothPositive|) (v1, v2) =

    if v1 >= 0 && v2 >= 0 
    then BothPositive
    else NotBothPositive

If you’ve noticed, we took the original code that I highlighted earlier:

match v1 >= 0
  &&  v2 >= 0 with

And lifted it into an Active Pattern:

    if v1 >= 0 && v2 >= 0 
    then BothPositive
    else NotBothPositive

Example 2

Here’s another example:

match cell1.X <> cell2.X
  ||  cell1.Y <> cell2.Y with
| true ->   isValueNeighbor cell1.X cell2.X
         && isValueNeighbor cell1.Y cell2.Y
| _    -> false

Applying Active Patterns to this code could result in the following:

 match (cell1,cell2) with
 | Different -> isValueNeighbor cell1.X cell2.X
             && isValueNeighbor cell1.Y cell2.Y
 | Same      -> false

Here’s the definition of the Active Pattern that we use for the above code:

let (|Same|Different|) (cell1, cell2) =

    if cell1.X <> cell2.X || cell1.Y <> cell2.Y 
    then Different
    else Same

Domain Logic

Here’s the domain logic:

module Model

type State = Alive | Dead
type Cell = { X:int; Y:int; State:State }

type Response = | Die
                | Survive
                | Resurect

let (|Same|Different|) (cell1, cell2) =

    if cell1.X <> cell2.X || cell1.Y <> cell2.Y 
    then Different
    else Same

let (|BothPositive|NotBothPositive|) (v1, v2) =

    if v1 >= 0 && v2 >= 0 
    then BothPositive
    else NotBothPositive
    
let isNeighbor cell1 cell2 =

    let isAbsNeighbor v1 v2 =
        match abs (v1 - v2) with
        | 0 | 1 -> true
        | _     -> false

    let isValueNeighbor v1 v2 =
        match v1, v2 with
        | BothPositive    -> isAbsNeighbor v1 v2
        | NotBothPositive -> isAbsNeighbor v2 v1

    match (cell1,cell2) with
    | Different -> isValueNeighbor cell1.X cell2.X
                && isValueNeighbor cell1.Y cell2.Y
    | Same      -> false

let createGrid rowCount = 

    [for x in 0..rowCount-1 do
        for y in 0..rowCount-1 do
            yield { X=x; Y=y; State=Dead } 
    ]|> List.map (fun c -> (c.X, c.Y), { X=c.X; Y=c.Y; State=Dead })
     |> Map.ofList

let setCell cell (grid:Map<(int * int), Cell>) =

    grid |> Map.map (fun k v -> match k with
                                | c when c = (cell.X, cell.Y) -> { v with State=cell.State }
                                | _ -> v)

let getStatus coordinate (grid:Map<(int * int), Cell>) =

    match grid.TryFind coordinate with
    | Some cell -> cell.State
    | None      -> Dead

let getNeighbors (coordinate:int*int) =
        
    let x,y = coordinate
    let west = x-1, y
    let northWest = x-1, y+1
    let north = x, y+1
    let northEast = x+1, y+1
    let east = x+1, y
    let southEast = x+1, y-1
    let south = x, y-1
    let southWest = x-1, y-1

    [west; northWest; north; northEast; east; southEast; south; southWest]

let createTimer timerInterval eventHandler =

    let timer = new System.Timers.Timer(float timerInterval)
    timer.AutoReset <- true
    timer.Elapsed.Add eventHandler

    async { timer.Start()
            do! Async.Sleep 500
            timer.Stop() }

let setReaction coordinate grid:Map<(int * int), Cell> = 

    let x,y = coordinate
    let count = coordinate |> getNeighbors
                           |> List.filter (fun coordinate -> grid |> getStatus coordinate = Alive)
                           |> List.length
    match count with
    | count when count < 2 
             ||  count > 3 -> grid |> setCell { X=x; Y=y; State=Dead }
    | 3                    -> match grid.TryFind coordinate with
                              | Some cell -> match cell.State with
                                             | Dead -> grid |> setCell { cell with State=Alive }
                                             | _    -> grid
                              | None      -> failwith "Cell doesn't exists"
    | _ -> grid

let cycleThroughCells (grid:Map<(int * int), Cell>) =

    grid |> Map.toSeq
         |> Seq.map snd
         |> Seq.fold (fun grid c -> grid |> setReaction (c.X, c.Y)) grid

Unit Tests

Here’s the tests:

module Tests

open FsUnit
open NUnit.Framework
open Model

[<Test>]
let ``cells sharing x-coordinate are neighbors``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=0; Y=1 ; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cells sharing y-coordinate are neighbors``() =
   // Setup
   let cell1 = { X=0; Y=1; State=Dead }
   let cell2 = { X=1; Y=1; State=Dead }

   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's right 1 and down 1 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=1; Y=(-1); State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's right 1 and down-0 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=1; Y=0; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's right 1 and up 1 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=1; Y=1 ; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's up 1 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=0; Y=1 ; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's down 1 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0;    State=Dead }
   let cell2 = { X=0; Y=(-1); State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's left 1 and up 1 is neighbor``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=(-1); Y=1 ; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``cell that's left 1 and down 1 is neighbor``() =
   // Setup
   let cell1 = { X=0;    Y=0;    State=Dead }
   let cell2 = { X=(-1); Y=(-1); State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal true

[<Test>]
let ``far away x-coordinates are not neighbors``() =
   // Setup
   let cell1 = { X=(-1); Y=0; State=Dead }
   let cell2 = { X=(+1); Y=0; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal false

[<Test>]
let ``far away y-coordinates are not neighbors``() =
   // Setup
   let cell1 = { X=0; Y=(+1); State=Dead }
   let cell2 = { X=0; Y=(-1); State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal false

[<Test>]
let ``far away x,y-coordinates are not neighbors``() =
   // Setup
   let cell1 = { X=(+1); Y=(+1); State=Dead }
   let cell2 = { X=(+1); Y=(-1); State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal false

[<Test>]
let ``cells with same coordinates cannot be neighbors``() =
   // Setup
   let cell1 = { X=0; Y=0; State=Dead }
   let cell2 = { X=0; Y=0; State=Dead }

   // Verify
   cell1 |> isNeighbor cell2 
         |> should equal false

[<Test>]
let ``create grid``() =
    // Test
    let rowCount = 3
    let grid = rowCount |> createGrid
    
    // Verify
    grid.Count |> should equal 9

[<Test>]
let ``find center``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid

    let getCoordinate coordinate =
        match grid.TryFind coordinate with
        | Some coordinate -> true
        | None            -> false

    // Test
    let found = getCoordinate (1,1)

    // Verify
    found |> should equal true

[<Test>]
let ``get status``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid

    // Test
    let center = grid |> getStatus (1,1)

    // Verify
    center |> should equal Dead

[<Test>]
let ``set cell to alive``() =
    // Setup
    let rowCount = 3
    let target = { X=1; Y=1; State=Alive }

    let grid = rowCount |> createGrid
                        |> setCell target
    // Test
    let result = grid |> getStatus (1,1)

    // Verify
    result |> should equal Alive

[<Test>]
let ``get neighbors``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid

    let center = 2,2
    let count = center |> getNeighbors
                       |> List.length
    // Verify
    count |> should equal 8

[<Test>]
let ``Any live cell with fewer than two live neighbors dies, as if caused by under-population``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid
                        |> setCell { X=1; Y=1; State=Alive }
                        |> setReaction (1,1)
    // Verify
    grid |> getStatus (1,1) |> should equal Dead

[<Test>]
let ``Any live cell with two or three live neighbours lives on to the next generation``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid
                        |> setCell { X=0; Y=0; State=Alive }
                        |> setCell { X=1; Y=1; State=Alive }
                        |> setCell { X=2; Y=1; State=Alive }
                        |> setReaction (1,1)
    // Verify
    grid |> getStatus (1,1) |> should equal Alive

[<Test>]
let ``Any live cell with more than three live neighbours dies, as if by over-population``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid
                        |> setCell { X=0; Y=0; State=Alive }
                        |> setCell { X=1; Y=1; State=Alive }
                        |> setCell { X=0; Y=1; State=Alive }
                        |> setCell { X=1; Y=0; State=Alive }
                        |> setCell { X=2; Y=1; State=Alive }
                        |> setReaction (1,1)
    // Verify
    grid |> getStatus (1,1) |> should equal Dead

[<Test>]
let ``Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction``() =
    // Setup
    let rowCount = 3
    let grid = rowCount |> createGrid
                        |> setCell { X=0; Y=1; State=Alive }
                        |> setCell { X=1; Y=1; State=Dead }
                        |> setCell { X=0; Y=2; State=Alive }
                        |> setCell { X=1; Y=2; State=Alive }
                        |> setReaction (1,1)
    // Verify
    grid |> getStatus (1,1) |> should equal Alive

Conclusion

In conclusion, I decided to learn about Active Patterns within F# and find opportunities to apply them within my Game of Life implementation.

Intro

This post will provide insight on how to implement the DelegateCommand in F#.

The Delegate Command

The DelegateCommand implements the ICommand interface. This command implementation provides two delegates, Execute and CanExecute.

The following is an implementation of the DelegateCommand:

open System
open System.Windows
open System.Windows.Input
open System.ComponentModel

type DelegateCommand (action:(obj -> unit), canExecute:(obj -> bool)) =
    let event = new DelegateEvent<EventHandler>()
    interface ICommand with
        [<CLIEvent>]
        member this.CanExecuteChanged = event.Publish
        member this.CanExecute arg = canExecute(arg)
        member this.Execute arg = action(arg)

The following code is an example implementation of how the DelegateCommand is used:

member self.Play =
    DelegateCommand ((fun _ -> printf "Hello World"), fun _ -> true) :> ICommand

If you’ve noticed, in order to expose the Execute and CanExecute methods for a client to call, we cast the command to the interface type as shown below:

:> ICommand

Without the cast to ICommand, a client cannot invoke the command because it’s just not exposed within F# at the concrete implementation level.

The XAML would look something like this:

<Button Grid.Row="6" Grid.Column="1" Content="Go!" Command="{Binding Play}" />

Conclusion

In conclusion, I have provided insight on how to implement the DelegateCommand in F#. It is essential to cast an implementation of a DelegateCommand to an ICommand for callers to invoke it.