Round trip
You write data out and read it back: to text, to JSON, to a database row, over the wire. The writer and the reader are two pieces of code that have to agree, and a test that writes one value checks only that one. A round trip checks that reading undoes writing for every value.
The example
Section titled “The example”An app shows amounts of money as people write them, 12.34 for 1,234 cents, and reads them back
the same way:
static String format(int cents) { return cents / 100 + "." + cents % 100;}
static int parse(String text) { return new BigDecimal(text).movePointRight(2).intValueExact();}Whatever amount you start with, formatting it and parsing the text should give it back:
@Testvoid parsingUndoesFormatting() { forAll(integers().atLeast(0).atMost(1_000_000)) .check(cents -> assertEquals(cents, Money.parse(Money.format(cents))));}When it fails
Section titled “When it fails”expected: <1> but was: <10>
parsingUndoesFormatting failed after 1 try (seed 0x401df1df36156c13) shrunk counterexample: cents = 1 pin it: .example(1) rerun: PROPTASTIC_SEED=0x401df1df36156c13 ./gradlew test --tests 'RoundTripTest.parsingUndoesFormatting'One cent formats as 0.1, with no zero before the 1, and 0.1 is ten cents. Any amount that
ends in 1 to 9 cents comes back wrong: 12.05 formats as 12.5, which reads back as 12.50. A test
of 12.34 passes, because 34 has two digits.
Paste the pin it: line after forAll(…) and one cent runs first, every time.
Reach for it when…
Section titled “Reach for it when…”- you have a pair of functions where one undoes the other: encode and decode, serialize and deserialize, format and parse, compress and decompress, save and load;
- you change a format, and want to know every value still survives it;
- you can’t say what the encoded form should be, but you know it must decode to the original.
It won’t catch…
Section titled “It won’t catch…”- A format that’s wrong both ways. If
formatwrites12.34as"twelve"andparsereads"twelve"as 1,234, the round trip holds and nobody else can read it. Pin a few encoded forms with an example-based test too. - Values your domain doesn’t draw. Negative amounts never come up here, so a bug in formatting
-0.05can’t show. Widen the domain to what the code really takes. - The other direction. Text that a person typed, such as
"12.5", isn’t whatformatwrites, so parsing it then formatting it needn’t give it back. That’s a property of its own, and a weaker one.
In the literature
Section titled “In the literature”It’s also called an inverse property, since decoding is the inverse of encoding. One of the first properties in the paper that started property-based testing is a round trip: reversing a list twice gives it back. See Claessen and Hughes, 2000 in further reading.