race conditions fixes

This pull requests fixes race conditions in tests and listener (I've recently created issues in the main repository).
Right, I think the problem here is that this test basically tests a race condition (the changes I proposed didn't correct it). I'll make a pull request if I come up with a solution.