Test extended builtins available in eval namespace. These builtins are safe (no I/O, no code execution) and commonly needed for typical xarray operations like slicing, type conversion, and iteration.
()
| 194 | |
| 195 | |
| 196 | def test_eval_extended_builtins() -> None: |
| 197 | """Test extended builtins available in eval namespace. |
| 198 | |
| 199 | These builtins are safe (no I/O, no code execution) and commonly needed |
| 200 | for typical xarray operations like slicing, type conversion, and iteration. |
| 201 | """ |
| 202 | ds = Dataset( |
| 203 | {"a": ("x", [1.0, 2.0, 3.0, 4.0, 5.0])}, |
| 204 | coords={"time": pd.date_range("2019-01-01", periods=5)}, |
| 205 | ) |
| 206 | |
| 207 | # slice - essential for .sel() with ranges |
| 208 | result = ds.eval("a.sel(x=slice(1, 3))") |
| 209 | expected = ds["a"].sel(x=slice(1, 3)) |
| 210 | assert_equal(result, expected) |
| 211 | |
| 212 | # str - type constructor |
| 213 | result = ds.eval("str(int(a.mean()))") |
| 214 | assert result == "3" |
| 215 | |
| 216 | # list, tuple - type constructors |
| 217 | result = ds.eval("list(range(3))") |
| 218 | assert result == [0, 1, 2] |
| 219 | |
| 220 | result = ds.eval("tuple(range(3))") |
| 221 | assert result == (0, 1, 2) |
| 222 | |
| 223 | # dict, set - type constructors |
| 224 | result = ds.eval("dict(x=1, y=2)") |
| 225 | assert result == {"x": 1, "y": 2} |
| 226 | |
| 227 | result = ds.eval("set([1, 2, 2, 3])") |
| 228 | assert result == {1, 2, 3} |
| 229 | |
| 230 | # range - iteration |
| 231 | result = ds.eval("list(range(3))") |
| 232 | assert result == [0, 1, 2] |
| 233 | |
| 234 | # zip, enumerate - iteration helpers |
| 235 | result = ds.eval("list(zip([1, 2], [3, 4]))") |
| 236 | assert result == [(1, 3), (2, 4)] |
| 237 | |
| 238 | result = ds.eval("list(enumerate(['a', 'b']))") |
| 239 | assert result == [(0, "a"), (1, "b")] |
| 240 | |
| 241 | # map, filter - functional helpers |
| 242 | result = ds.eval("list(map(abs, [-1, -2, 3]))") |
| 243 | assert result == [1, 2, 3] |
| 244 | |
| 245 | result = ds.eval("list(filter(bool, [0, 1, 0, 2]))") |
| 246 | assert result == [1, 2] |
| 247 | |
| 248 | # any, all - aggregation |
| 249 | result = ds.eval("any([False, True, False])") |
| 250 | assert result is True |
| 251 | |
| 252 | result = ds.eval("all([True, True, True])") |
| 253 | assert result is True |
nothing calls this directly
no test coverage detected
searching dependent graphs…