Refactor test code

Extract all shared code between tests into a single place to avoid copying it
around.