Please assert that this thing doesn't suppress unexpected warnings.

I believe you want this:

if warning_class:
    warning_context = warnings.catch_warnings(warning_class, record=True)
else:
    warning_context = warnings.catch_warnings(record=True)

with warning_context:
   ...


With this in place, I believe you can factor out the "if warning_class" below.