Solving the diamond kata with property-based testing series

  1. How to get started with Property-based Testing in C#
  2. Input generators in property-based tests with FsCheck
  3. First and Last line content
  4. Height equals Width
  5. Outside space symmetry
  6. Symmetry around the vertical axis
  7. Symmetry around the horizontal axis
  8. No padding for input letter row
  9. Letters order

All code samples are available on github


Intro

Last time, we discovered some interesting patterns with the first and last line of the diamond. Today, we'll look more globally at the diamond's shape and figure out if there's a property hidden that we could exploit.

Height equals the width

If you look closely at any possible diamond, you'll find that the diamond is quadratic or, in other words, the height is always equal to the width. We cannot see it here because of the font I use on my blog, but if you look at the number of char per line, you'll realize that it's equal to the number of lines.

e.g.

input: E
<---9--->

----A---- ^
---B-B--- |
--C---C-- |
-D-----D- |
E-------E 9
-D-----D- |
--C---C-- |
---B-B--- |
----A---- v

C# Tests

[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
public Property DiamondWidthEqualsHeight(char c)
{
    var diamondLines = Diamond.Generate(c).ToList();
    return diamondLines.All(row => row.Length == diamondLines.Count).ToProperty();
}

Here we used some built-in methods of the .NET library, which makes these tests simple to read and short to write. It almost reads like a sentence.

  1. Diamond.Generate(c) Generates the diamond
  2. All() validates the inner condition for each line
  3. row => row.Length == diamondLines.Count validates that the number of letter per row is equal to the number of rows in the diamond
  4. ToProperty() Transforms a boolean expression to a property

If you are wondering what's [Property(Arbitrary = new[] { typeof(LetterGenerator) })] it's probably because you missed my previous post

Wrapping up

So far, we have three useful tests that are reducing the scope of possible errors in our implementation of the DiamondGenerator. However, there's still some way to go before we can call it a complete suite of tests and be confident that our code is unbreakable.


Solving the diamond kata with property-based testing series

  1. How to get started with Property-based Testing in C#
  2. Input generators in property-based tests with FsCheck
  3. First and Last line content
  4. Height equals Width
  5. Outside space symmetry
  6. Symmetry around the vertical axis
  7. Symmetry around the horizontal axis
  8. No padding for input letter row
  9. Letters order

All code samples are available on github