|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import pytest |
| 6 | +import xarray as xr |
| 7 | + |
| 8 | +from mpas_tools.io import write_netcdf |
| 9 | + |
| 10 | +from .util import get_test_data_file |
| 11 | + |
| 12 | +TEST_MESH = get_test_data_file('mesh.QU.1920km.151026.nc') |
| 13 | + |
| 14 | + |
| 15 | +@pytest.mark.skipif( |
| 16 | + not os.path.exists(TEST_MESH), reason='Test mesh not available' |
| 17 | +) |
| 18 | +def test_write_netcdf_basic(tmp_path): |
| 19 | + ds = xr.open_dataset(TEST_MESH) |
| 20 | + out_file = tmp_path / 'test_basic.nc' |
| 21 | + write_netcdf(ds, str(out_file)) |
| 22 | + ds2 = xr.open_dataset(out_file) |
| 23 | + # Should have same dimensions and variables |
| 24 | + assert set(ds.dims) == set(ds2.dims) |
| 25 | + for var in ds.data_vars: |
| 26 | + assert var in ds2.data_vars |
| 27 | + ds2.close() |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.skipif( |
| 31 | + not os.path.exists(TEST_MESH), reason='Test mesh not available' |
| 32 | +) |
| 33 | +def test_write_netcdf_cdf5_format(tmp_path): |
| 34 | + ds = xr.open_dataset(TEST_MESH) |
| 35 | + out_file = tmp_path / 'test_cdf5.nc' |
| 36 | + write_netcdf(ds, str(out_file), format='NETCDF3_64BIT_DATA') |
| 37 | + # Use ncdump -k to check format |
| 38 | + result = subprocess.run( |
| 39 | + ['ncdump', '-k', str(out_file)], |
| 40 | + capture_output=True, |
| 41 | + text=True, |
| 42 | + check=True, |
| 43 | + ) |
| 44 | + # Should be cdf5 for NETCDF3_64BIT_DATA |
| 45 | + assert result.stdout.strip() == 'cdf5' |
| 46 | + |
| 47 | + |
| 48 | +def test_write_netcdf_int64_conversion_and_attr(tmp_path): |
| 49 | + # Create a dataset with int64 variable and an attribute |
| 50 | + arr = np.array([1, 2, 3], dtype=np.int64) |
| 51 | + ds = xr.Dataset({'foo': (('x',), arr)}) |
| 52 | + ds['foo'].attrs['myattr'] = 'testattr' |
| 53 | + out_file = tmp_path / 'test_int64.nc' |
| 54 | + write_netcdf(ds, str(out_file)) |
| 55 | + ds2 = xr.open_dataset(out_file) |
| 56 | + # Should be int32, not int64 |
| 57 | + assert ds2['foo'].dtype == np.int32 |
| 58 | + # Attribute should be preserved |
| 59 | + assert ds2['foo'].attrs['myattr'] == 'testattr' |
| 60 | + ds2.close() |
0 commit comments