Port Perl unit tests to Python and fix relevant bugs