GenericMappingTools / pygmt

A Python interface for the Generic Mapping Tools.
https://www.pygmt.org
BSD 3-Clause "New" or "Revised" License
749 stars 217 forks source link

check_figures_equal: Initialize fig_ref and fig_test to avoid UnboundLocalError when crashes #3436

Closed seisman closed 2 weeks ago

seisman commented 2 weeks ago

Description of proposed changes

We often see errors like (e.g., https://github.com/GenericMappingTools/pygmt/actions/runs/10801548820/job/29961904337?pr=3434):

>       status = c_call_module(self.session_pointer, module.encode(), mode, argv)
E       OSError: exception: access violation reading 0x0000022883EE60C0

..\pygmt\clib\session.py:654: OSError

During handling of the above exception, another exception occurred:

ext = 'png'
request = <FixtureRequest for <Function test_grdimage_grid_and_shading_with_xarray[png]>>
args = ()
kwargs = {'grid': <xarray.DataArray 'z' (lat: 181, lon: 361)> Size: 523kB
array([[ 2865. ,  2865. ,  2865. , ...,  2865. ,  286...
  * longitude  (longitude) int64 3kB 0 1 2 3 4 5 6 ... 354 355 356 357 358 359
Attributes:
    actual_range:  [-1, 1]}
file_name = 'test_grdimage_grid_and_shading_with_xarray[png]'
...
...
...
        finally:
>           del fig_ref
E           UnboundLocalError: cannot access local variable 'fig_ref' where it is not associated with a value

Here, when calling a GMT module, we have the OSError: exception: access violation reading, thus, making fig_ref/fig_test undefined. Then we see the UnboundLocalError error when we try to delete fig_ref/fig_test. The UnboundLocalError error makes the error log much longer and sometimes is confusing.

The solution here is to initialize fig_ref/fig_test to None, so del fig_ref/del fig_test always works.

For comparison, the error log is much shorter in this branch (https://github.com/GenericMappingTools/pygmt/actions/runs/10802534980/job/29965064177?pr=3436).