[WIP] Backport some more SIP-23 code

This adds some fixes for SIP-23 that @adriaanm introduced recently, as well as some tests. /cc @propensive 

**Note:** please don't merge yet.