Fixes #23799 squashmigrations optimize conditionally

This commit fixes this issue
https://code.djangoproject.com/ticket/23799

It has tests and implementation
unittest.mock isn't available in Python < 3.3. see ticket #23289