extract from testium

This is the logic extracted from testium.