Add a lot more unit tests, improve code testability, remove duplicated integration tests. Change-Id: Id8c9266ae107217047f267296070f26f575889d1