Add tests for SD-357 and refactor the code