Solving the diamond kata with property-based testing series
- How to get started with Property-based Testing in C#
- Input generators in property-based tests with FsCheck
- First and Last line content
- Height equals Width
- Outside space symmetry
- Symmetry around the vertical axis
- Symmetry around the horizontal axis
- No padding for input letter row
- Letters order
All code samples are available on github
Intro
Last time, we started to explore the properties around the diamond's symmetry and discovered some interesting pattern with the spacing around the diamond.
Symmetry around the vertical axis
If you split the diamond in two with a vertical line right in the middle, you'll discover that it's perfectly symmetric. It feels like a property to me; let's try to model it and write a test.
C# Tests
[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
public Property SymmetricAroundVerticalAxis(char c)
{
return Diamond.Generate(c).ToArray()
.All(row =>
{
var half = row.Length / 2;
var firstHalf = row[..half];
var secondHalf = row[(half + 1)..];
return firstHalf.Reverse().SequenceEqual(secondHalf);
}).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:
- Take the first half of a row
row[..half]
- Take the second half of a row, ignoring the middle character
row[(half + 1)..]
- Reverse one of the halves and compare the two sequence
- Do it for each row
If you are wondering what's
[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
it's probably because you missed my previous post
Wrapping up
Symmetry is an easy pattern to spot in problems as it's very visual. Can you find any other interesting symmetry? We'll find out next time. Until then, don't forget to subscribe.
Solving the diamond kata with property-based testing series
- How to get started with Property-based Testing in C#
- Input generators in property-based tests with FsCheck
- First and Last line content
- Height equals Width
- Outside space symmetry
- Symmetry around the vertical axis
- Symmetry around the horizontal axis
- No padding for input letter row
- Letters order
All code samples are available on github