Refactor connection setup, and add tests