Test bug fixing and refactoring