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 found that the diamond is symmetric around the vertical axis. Today let's figure out if there's also some symmetry around the horizontal axis.

Symmetry around the horizontal axis

If you split the diamond in two with a horizontal line right in the middle, you'll discover that it's perfectly symmetric. As we already know, symmetry can be modeled as a property that can be expressed as a unit test.

Diamond-kata-Horizontal-Symmetry

C# Tests

[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
public Property SymmetricAroundHorizontalAxis(char c)
{
    var diamond = Diamond.Generate(c).ToArray();
    var half = diamond.Length / 2;
    var topHalf = diamond[..half];
    var bottomHalf = diamond[(half + 1)..];
    return topHalf.Reverse().SequenceEqual(bottomHalf).ToProperty();
}

Here we used some built-in methods of the .NET library, which makes these tests simple to read and short to write. Note the use of the new C# 8.0 range operators .. to select subsections of the array. The method to validate symmetry is simple:

  1. Take the first half of the diamond diamond[..half]
  2. Take the second half of the diamond, ignoring the middle row diamond[(half + 1)..]
  3. Reverse one of the halves and compare the two

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

Wrapping up

So far, all our tests are passing with the first dummy implementation we made. Next time we'll try a new kind of property that will break the dummy implementation and force us to reconsider the implementation and refactor. Until then, don't forget to subscribe.


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