refactor and fix tests