Tidy up tests; fix some bugs; fix python 3 compat.