Fix random test, and add unit tests