Skip to content

Commit

Permalink
Split netcdf creation from the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lahtinep committed Mar 7, 2024
1 parent e1a6f37 commit c6cd647
Showing 1 changed file with 30 additions and 17 deletions.
47 changes: 30 additions & 17 deletions satpy/tests/reader_tests/test_netcdf_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,43 +302,56 @@ def test_use_h5netcdf_for_file_not_accessible_locally(self):

def test_get_data_as_xarray_netcdf4(tmp_path):
"""Test getting xr.DataArray from netcdf4 variable."""
import netCDF4 as nc
import numpy as np

from satpy.readers.netcdf_utils import get_data_as_xarray

data = np.array([1, 2, 3])

fname = tmp_path / "test.nc"
dset = _write_test_netcdf4(fname, data)

res = get_data_as_xarray(dset["test_data"])
np.testing.assert_equal(res.data, data)
assert res.attrs == NC_ATTRS

Check warning on line 315 in satpy/tests/reader_tests/test_netcdf_utils.py

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (main)

❌ New issue: Code Duplication

The module contains 2 functions with similar structure: test_get_data_as_xarray_h5netcdf,test_get_data_as_xarray_netcdf4. Avoid duplicated, aka copy-pasted, code inside the module. More duplication lowers the code health.


def _write_test_netcdf4(fname, data):
import netCDF4 as nc

dset = nc.Dataset(fname, "w")
dset.createDimension("y", None)
var = dset.createVariable("test_data", "uint8", ("y",))
var[:] = data
var.setncatts(NC_ATTRS)
# Turn off automatic scale factor and offset handling
dset.set_auto_maskandscale(False)
res = get_data_as_xarray(var)
np.testing.assert_equal(res.data, data)
assert res.attrs == NC_ATTRS
dset.close()

return dset


def test_get_data_as_xarray_h5netcdf(tmp_path):
"""Test getting xr.DataArray from h5netcdf variable."""
import h5netcdf
import numpy as np

from satpy.readers.netcdf_utils import get_data_as_xarray

data = np.array([1, 2, 3])

fname = tmp_path / "test.nc"
with h5netcdf.File(fname, "w") as fid:
fid.dimensions = {"y": data.size}
var = fid.create_variable("test_data", ("y",), "uint8")
var[:] = data
for key in NC_ATTRS:
var.attrs[key] = NC_ATTRS[key]
res = get_data_as_xarray(var)
np.testing.assert_equal(res.data, data)
assert res.attrs == NC_ATTRS
fid = _write_test_h5netcdf(fname, data)

res = get_data_as_xarray(fid["test_data"])
np.testing.assert_equal(res.data, data)
assert res.attrs == NC_ATTRS


def _write_test_h5netcdf(fname, data):
import h5netcdf

fid = h5netcdf.File(fname, "w")
fid.dimensions = {"y": data.size}
var = fid.create_variable("test_data", ("y",), "uint8")
var[:] = data
for key in NC_ATTRS:
var.attrs[key] = NC_ATTRS[key]

return fid

0 comments on commit c6cd647

Please sign in to comment.