Fix unstable test and small refactoring