Add more unit tests and cleanup logic in them