General test code cleanup and optimizations along with other code refactoring.