|
| 1 | +import json |
1 | 2 | from typing import Any
|
2 | 3 |
|
3 | 4 | import numpy as np
|
@@ -32,6 +33,16 @@ def data_array_with_dims_and_coords(
|
32 | 33 | )
|
33 | 34 |
|
34 | 35 |
|
| 36 | +def drop_attrs_log(attrs: dict) -> dict: |
| 37 | + """Drop the log string from attrs to faclitate testing. |
| 38 | + The log string will never exactly match, because datetimes differ. |
| 39 | + """ |
| 40 | + attrs_copy = attrs.copy() |
| 41 | + if "log" in attrs: |
| 42 | + attrs_copy.pop("log", None) |
| 43 | + return attrs_copy |
| 44 | + |
| 45 | + |
35 | 46 | @pytest.fixture
|
36 | 47 | def sample_data_2d() -> xr.DataArray:
|
37 | 48 | """Turn the nparray_0_to_23 into a DataArray."""
|
@@ -103,7 +114,7 @@ def test_scale(
|
103 | 114 | """Test scaling with different factors and space_units."""
|
104 | 115 | scaled_data = scale(sample_data_2d, **optional_arguments)
|
105 | 116 | xr.testing.assert_equal(scaled_data, expected_output)
|
106 |
| - assert scaled_data.attrs == expected_output.attrs |
| 117 | + assert drop_attrs_log(scaled_data.attrs) == expected_output.attrs |
107 | 118 |
|
108 | 119 |
|
109 | 120 | @pytest.mark.parametrize(
|
@@ -180,7 +191,7 @@ def test_scale_twice(
|
180 | 191 | **optional_arguments_2,
|
181 | 192 | )
|
182 | 193 | xr.testing.assert_equal(output_data_array, expected_output)
|
183 |
| - assert output_data_array.attrs == expected_output.attrs |
| 194 | + assert drop_attrs_log(output_data_array.attrs) == expected_output.attrs |
184 | 195 |
|
185 | 196 |
|
186 | 197 | @pytest.mark.parametrize(
|
@@ -241,3 +252,30 @@ def test_scale_invalid_3d_space(factor):
|
241 | 252 | assert str(error.value) == (
|
242 | 253 | "Input data must contain ['z'] in the 'space' coordinates.\n"
|
243 | 254 | )
|
| 255 | + |
| 256 | + |
| 257 | +def test_scale_log(sample_data_2d: xr.DataArray): |
| 258 | + """Test that the log attribute is correctly populated |
| 259 | + in the scaled data array. |
| 260 | + """ |
| 261 | + |
| 262 | + def verify_log_entry(entry, expected_factor, expected_space_unit): |
| 263 | + """Verify each scale log entry.""" |
| 264 | + assert entry["factor"] == expected_factor |
| 265 | + assert entry["space_unit"] == expected_space_unit |
| 266 | + assert entry["operation"] == "scale" |
| 267 | + assert "datetime" in entry |
| 268 | + |
| 269 | + # scale data twice |
| 270 | + scaled_data = scale( |
| 271 | + scale(sample_data_2d, factor=2, space_unit="elephants"), |
| 272 | + factor=[1, 2], |
| 273 | + space_unit="crabs", |
| 274 | + ) |
| 275 | + |
| 276 | + # verify the log attribute |
| 277 | + assert "log" in scaled_data.attrs |
| 278 | + log_entries = json.loads(scaled_data.attrs["log"]) |
| 279 | + assert len(log_entries) == 2 |
| 280 | + verify_log_entry(log_entries[0], "2", "'elephants'") |
| 281 | + verify_log_entry(log_entries[1], "[1, 2]", "'crabs'") |
0 commit comments