Skip to content

Checking the existence of GMTTempFile using "os.path.exists" is invalid #1912

@seisman

Description

@seisman

Description of the problem

In our tests, we usually save the output to a GMTTempFile object and then check if the output temporary file exists using the os.path.exists function.

Here is an example test for grd2xyz:

def test_grd2xyz_file_output(grid):
"""
Test that grd2xyz returns a file output when it is specified.
"""
with GMTTempFile(suffix=".xyz") as tmpfile:
result = grd2xyz(grid=grid, outfile=tmpfile.name, output_type="file")
assert result is None # return value is None
assert os.path.exists(path=tmpfile.name) # check that outfile exists

The problem is, GMTTempFile always creates the 0-byte temporary file when GMTTempFile is called, so the temporary file always exists. It means that we can't use os.path.exists to check if functions like grd2xyz write output to a file or not.

Here is a minimal script to verify it:

import os
from pygmt.helpers import GMTTempFile
with GMTTempFile(suffix="txt") as fp:
    print(fp.name, os.path.exists(fp.name), os.path.getsize(fp.name))

the output is: /tmp/pygmt-mhtfhdmltxt True 0.


Possible solutions:

  • Improve the GMTTempFile class to make sure that the 0-byte temporary file is not created by GMTTempFile
  • Use os.path.getsize to check if the file size is non-zero, rather than using os.path.exists

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions