Fix tests

This is a set of commits that ensures that our test suite is solid. Some code is refactored in the process.