Cherry pick of fixed issue #4259 (from maintenance 3.x branch)

Improved assert messages in all tests. Minor code cleanup (still much to do).

The issue itself was already fixed in this branch, but the improvement of assert messages and code cleanup code be ported.