Fixing test failures. Offloading similar loops to a central location. Added test for key expander.