Fix tests

This fixes the speed & random failures in the tests cases. The important part is commit 89ad2cd.