Today’s random F# code: Nice test error messages with Unquote and Diffract

When comparing complex data types in unit test assertions, for example, records with nested lists containing discriminated unions, the error messages quickly get hard to understand. How to spot a single difference?

That’s why I mixed Unquote and D-Edge.Diffract together.

An example unit test from our codebase:

A WorkdayTime consists of a time and a workday shift. A workday shift of 0 means that it is on the same workday, -1 means yesterday, 1 means tomorrow and so on. We use this to model scenarios like working over midnight into the next day. E.g. you start at 23:00 on 2022-10-01 and it should count to 2022-10-02 then use Workday = 2022-10-02 Shift = -1.

The above test has a bug – the expectation is wrong because the workday shift of the parsed data should be 1:

On the top, you can see the diff that clearly states what is wrong. We get this from Diffract.

At the bottom, you can see Unquote’s output stating all the steps done when evaluating the passed quotation (aka expression in other languages).

To get this nice output, we use the following test function:

First, we call Unquote, and if the assertion fails, we check whether the quotation/expression is a =. If so, we use Diffract to generate the diff between the actual and expected values and augment the error message; otherwise, we return Unquote’s error message.

By the way: you can write any quotation/expression inside the <@ … @>. E.g: test <@ 1 < 2 @admin My code just handles = specially.

About the author

Urs Enzler


By Urs Enzler

Recent Posts