Some test fixes and refactoring