From f3b08b6dfb29c3a77378de17fe70cd9703b16577 Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Thu, 5 Nov 2026 11:59:44 -0500 Subject: [PATCH 1/4] test: cover the TTree and RNTuple reading APIs New tests from #1814, apart from the regression tests of its fixes. Assisted-by: Claude Code:claude-opus-5-5 --- tests/test_1832_cov_api_cache.py | 149 ++++++ tests/test_1832_cov_api_dask.py | 541 +++++++++++++++++++++ tests/test_1832_cov_api_graphed.py | 67 +++ tests/test_1832_cov_api_read_options.py | 409 ++++++++++++++++ tests/test_1832_cov_api_tbranch.py | 617 ++++++++++++++++++++++++ tests/test_1832_cov_rntuple_api.py | 475 ++++++++++++++++++ tests/test_1832_cov_rntuple_lowlevel.py | 367 ++++++++++++++ tests/test_1832_cov_rntuple_numpy.py | 133 +++++ tests/test_1832_cov_rntuple_root.py | 231 +++++++++ tests/test_1832_cov_rntuple_writing.py | 163 +++++++ 10 files changed, 3152 insertions(+) create mode 100644 tests/test_1832_cov_api_cache.py create mode 100644 tests/test_1832_cov_api_dask.py create mode 100644 tests/test_1832_cov_api_graphed.py create mode 100644 tests/test_1832_cov_api_read_options.py create mode 100644 tests/test_1832_cov_api_tbranch.py create mode 100644 tests/test_1832_cov_rntuple_api.py create mode 100644 tests/test_1832_cov_rntuple_lowlevel.py create mode 100644 tests/test_1832_cov_rntuple_numpy.py create mode 100644 tests/test_1832_cov_rntuple_root.py create mode 100644 tests/test_1832_cov_rntuple_writing.py diff --git a/tests/test_1832_cov_api_cache.py b/tests/test_1832_cov_api_cache.py new file mode 100644 index 000000000..081d6d2c4 --- /dev/null +++ b/tests/test_1832_cov_api_cache.py @@ -0,0 +1,149 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import pickle + +import numpy as np +import pytest +import skhep_testdata + +import uproot +from uproot.cache import LRUArrayCache, LRUCache + + +def test_lru_order_and_views(): + cache = LRUCache(3) + assert (cache.limit, cache.current) == (3, 0) + + cache["a"], cache["b"], cache["c"] = 1, 2, 3 + assert cache["a"] == 1 # "a" is now the most recently used + + assert cache.keys() == ["b", "c", "a"] + assert cache.values() == [2, 3, 1] + assert cache.items() == [("b", 2), ("c", 3), ("a", 1)] + assert list(cache) == ["b", "c", "a"] + assert len(cache) == 3 + assert cache.current == 3 + + cache["d"] = 4 # evicts "b", the least recently used + assert cache.items() == [("c", 3), ("a", 1), ("d", 4)] + assert cache.current == 3 + + +def test_lru_replacing_and_deleting_keep_current_in_step(): + cache = LRUCache(2) + cache["a"] = 1 + cache["b"] = 2 + + cache["a"] = 10 # replacing moves "a" to the end without counting it twice + assert cache.items() == [("b", 2), ("a", 10)] + assert cache.current == 2 + + del cache["b"] + assert cache.items() == [("a", 10)] + assert cache.current == 1 + with pytest.raises(KeyError, match="b"): + del cache["b"] + assert cache.current == 1 + + +def test_lru_replacing_a_key_protects_it_from_eviction(): + cache = LRUCache(3) + cache["a"], cache["b"], cache["c"] = 1, 2, 3 + cache["a"] = 99 + cache["d"] = 4 # evicts "b", now the least recently used + assert cache.items() == [("c", 3), ("a", 99), ("d", 4)] + + +def test_lru_without_limit_never_evicts(): + cache = LRUCache(None) + assert cache.limit is None + for i in range(100): + cache[i] = i + assert len(cache) == cache.current == 100 + assert repr(cache).startswith("= 0 + # the tree's file was read + assert report.performance_counters.num_requested_bytes[0] > 0 + + +def test_trivial_form_mapping_is_the_default_read(two_files): + a, b = two_files + files = {a: "t", b: "t"} + mapped = uproot.dask( + files, filter_name=["x", "j"], form_mapping=uproot._dask.TrivialFormMapping() + ) + plain = uproot.dask(files, filter_name=["x", "j"]) + assert ak.to_list(_compute(mapped)) == ak.to_list(_compute(plain)) + + +def test_project_manually_reads_only_what_is_asked(two_files): + a, _ = two_files + lazy = uproot.dask({a: "t"}, filter_name=["x", "j"]) + layer = next( + layer + for layer in lazy.dask.layers.values() + if hasattr(layer, "io_func") and hasattr(layer.io_func, "project_manually") + ) + full = layer.io_func + assert full.common_keys == frozenset({"x", "j"}) + + projected = full.project_manually(frozenset({"x"})) + assert projected.common_keys == frozenset({"x"}) + out = projected((0, 2, 5)) + assert out.layout.form.fields == ["x", "j"] + assert out.x.tolist() == [2, 3, 4] + with pytest.raises(Exception, match="excluded during a pre-run phase"): + ak.to_list(out.j) + + +def test_form_mapping_base_class_has_no_projection(): + with pytest.raises(NotImplementedError): + uproot._dask.UprootReadMixin().project_keys(frozenset()) + + +def test_access_log_must_be_extendable(two_files): + a, _ = two_files + with uproot.open(a) as file: + lazy = file["t"].arrays(filter_name="x", virtual=True, access_log=()) + with pytest.raises(ValueError, match=r"access_log=\(\) needs to implement"): + ak.materialize(lazy.x) + + +class TestDaskArrayFromMap: + @staticmethod + def _add(x, y, offset=0, scale=1): + return np.full(2, (x + y + offset) * scale) + + def test_several_iterables_are_paired(self): + out = uproot._dask._dask_array_from_map( + self._add, [1, 2], (x for x in [10, 20]), chunks=((2, 2),), dtype="i8" + ) + assert _compute(out).tolist() == [11, 11, 22, 22] + + def test_args_and_kwargs_are_passed_through(self): + out = uproot._dask._dask_array_from_map( + self._add, [1, 2], args=(10,), chunks=((2, 2),), dtype="i8", offset=100 + ) + assert _compute(out).tolist() == [111, 111, 112, 112] + + def test_label_and_token_name_the_collection(self): + out = uproot._dask._dask_array_from_map( + self._add, + [1], + args=(10,), + chunks=((2,),), + dtype="i8", + label="mine", + token="abc", + ) + assert out.name == "mine-abc" + + @pytest.mark.parametrize( + ("func", "iterables", "kwargs", "message"), + [ + (None, ([1],), {}, "`func` argument must be `callable`"), + (abs, (1,), {}, "All elements of `iterables` must be Iterable, got "), + (abs, (), {}, "`from_map` requires at least one Iterable input"), + (abs, ([1], [1, 2]), {}, "All `iterables` must have the same length"), + (abs, ([],), {}, "All `iterables` must have a non-zero length"), + ( + abs, + ([1], [2]), + {"produces_tasks": True}, + "Multiple iterables not supported when produces_tasks=True", + ), + ], + ) + def test_bad_inputs(self, func, iterables, kwargs, message): + with pytest.raises(ValueError, match=message): + uproot._dask._dask_array_from_map( + func, *iterables, chunks=((1,),), dtype="i8", **kwargs + ) + + +def test_lazy_inputs_dict(): + lazy = uproot._dask._LazyInputsDict(["a", "b"]) + assert len(lazy) == 2 + assert list(lazy.keys()) == [(0,), (1,)] + assert list(lazy) == ["a", "b"] # as dask's iteration over values expects + assert lazy[(1,)] == "b" + assert (1,) in lazy + assert (2,) not in lazy + assert (-1,) not in lazy + assert "a" not in lazy + assert ("a",) not in lazy + + +def test_packed_arg_callable(): + call = uproot._dask._PackedArgCallable(lambda *args: args, args=[3], packed=True) + assert call((1, 2)) == (1, 2, 3) + unpacked = uproot._dask._PackedArgCallable( + lambda x, **kwargs: (x, kwargs), kwargs={"y": 2} + ) + assert unpacked((1, 2)) == ((1, 2), {"y": 2}) + assert uproot._dask._PackedArgCallable(lambda x: x)(5) == 5 + + +class TestCoerce: + def test_no_expected_dtype_passes_through(self): + array = np.arange(3) + assert uproot._dask._coerce_numpy_chunk(array, None) is array + + def test_same_structured_dtype_passes_through(self): + array = np.zeros(2, dtype=[("a", "i4")]) + assert uproot._dask._coerce_numpy_chunk(array, array.dtype) is array + + def test_structured_fields_are_coerced_one_by_one(self): + array = np.array([(1, 2.5), (3, 4.5)], dtype=[("a", "i4"), ("b", "f8")]) + expected = np.dtype([("a", "i8"), ("b", "O")]) + out = uproot._dask._coerce_numpy_chunk(array, expected) + assert out.dtype == expected + assert out.tolist() == [(1, 2.5), (3, 4.5)] + + def test_plain_dtype(self): + out = uproot._dask._coerce_numpy_chunk(np.arange(2, dtype="i4"), np.dtype("f8")) + assert out.dtype == np.dtype("f8") + assert out.tolist() == [0.0, 1.0] + + def test_same_dtype_passes_through(self): + array = np.arange(2, dtype="i4") + assert uproot._dask._coerce_field(array, np.dtype("i4")) is array + + def test_subarray_of_the_right_shape(self): + array = np.arange(4, dtype="i4").reshape(2, 2) + same = uproot._dask._coerce_field(array, np.dtype(("i4", (2,)))) + assert same is array + wider = uproot._dask._coerce_field(array, np.dtype(("i8", (2,)))) + assert wider.dtype == np.dtype("i8") + assert wider.tolist() == array.tolist() + + def test_to_object_rows(self): + array = np.arange(4).reshape(2, 2) + out = uproot._dask._coerce_field(array, np.dtype("O")) + assert out.shape == (2,) + assert [row.tolist() for row in out] == [[0, 1], [2, 3]] + + def test_masked_to_object_rows(self): + array = np.ma.MaskedArray( + np.arange(6.0).reshape(3, 2), + mask=[[False, False], [True, False], [True, True]], + ) + out = uproot._dask._coerce_field(array, np.dtype("O")) + assert out[0].tolist() == [0.0, 1.0] + assert out[1].dtype == np.dtype("O") + assert out[1].tolist() == [None, 3.0] + assert out[2] is None + + def test_masked_to_object_scalars(self): + array = np.ma.MaskedArray([1, 2, 3], mask=[False, True, False]) + out = uproot._dask._coerce_field(array, np.dtype("O")) + assert out.tolist() == [1, None, 3] + + def test_to_object_scalars(self): + out = uproot._dask._coerce_field(np.arange(2), np.dtype("O")) + assert out.dtype == np.dtype("O") + assert out.tolist() == [0, 1] + assert uproot._dask._coerce_field(out, np.dtype("O")) is out + + +def test_fixed_size_arrays_of_strided_objects(): + """``TLorentzVector[][5]``: a list per entry of arrays of 5 objects.""" + path = skhep_testdata.data_path("uproot-issue513.root") + name = "Jet.TrimmedP4[5]" + lazy = uproot.dask( + f"{path}:Delphes", filter_name=r"/^Jet\.TrimmedP4\[5\]$/", open_files=False + ) + out = _compute(lazy)[name] + assert str(out.type) == ( + "10 * var * 5 * TLorentzVector[fP: TVector3[fX: float64, fY: float64, " + "fZ: float64], fE: float64]" + ) + assert ak.num(out, axis=1).tolist() == [8, 6, 5, 4, 5, 5, 6, 6, 6, 9] + + +def test_rntuple_as_numpy_dtype(): + path = skhep_testdata.data_path("test_int_float_rntuple_v1-0-0-0.root") + with uproot.open(path) as file: + dtype = uproot._dask._branch_or_field_numpy_dtype(file["ntuple"]) + assert dtype == np.dtype([("one_integers", ">``: an option has no size to add.""" + + class Field(uproot._dask.HasFields): + def to_akform(self): + pair = ak.forms.RecordForm([ak.forms.NumpyForm("int32")], ["0"]) + form = ak.forms.RecordForm([ak.forms.IndexedOptionForm("i64", pair)], ["o"]) + return form, ["o", "0"] + + assert uproot._dask._branch_or_field_numpy_dtype(Field()) == np.dtype("int32") + + +def test_rntuple_fields_of_regular_records_as_numpy(tmp_path): + path = str(tmp_path / "regular.root") + records = ak.Array( + [ + [{"x": 1, "y": 2.0}, {"x": 3, "y": 4.0}], + [{"x": 5, "y": 6.0}, {"x": 7, "y": 8.0}], + ] + ) + with uproot.recreate(path) as file: + file.mkrntuple("n", {"regular": ak.to_regular(records)}) + + lazy = uproot.dask({path: "n"}, library="np") + assert set(lazy) == {"regular", "regular.x", "regular.y"} + assert lazy["regular.x"].shape == (2, 2) + assert _compute(lazy["regular.x"]).tolist() == [[1, 3], [5, 7]] + assert _compute(lazy["regular.y"]).tolist() == [[2.0, 4.0], [6.0, 8.0]] + assert _compute(lazy["regular"]).tolist() == [ + [(1, 2.0), (3, 4.0)], + [(5, 6.0), (7, 8.0)], + ] + + +def test_rntuple_union_field_lazy_equals_eager(): + path = skhep_testdata.data_path("test_stl_containers_rntuple_v1-0-0-0.root") + name = "variant_int32_string" + with uproot.open(path) as file: + expected = file["ntuple"].arrays(filter_name=name) + lazy = uproot.dask({path: "ntuple"}, filter_name=name) + assert ak.to_list(_compute(lazy)) == ak.to_list(expected) + + +def test_dask_write_without_a_prefix(two_files, tmp_path): + a, _ = two_files + lazy = uproot.dask( + {a: "t"}, filter_name=["x", "only_a"], steps_per_file=2, open_files=False + ) + with dask.config.set(scheduler="synchronous"): + uproot.dask_write(lazy, str(tmp_path)) + assert sorted(p.name for p in tmp_path.iterdir()) == ["part0.root", "part1.root"] + out = uproot.concatenate( + [str(tmp_path / "part0.root"), str(tmp_path / "part1.root")], + library="np", + ) + assert out["x"].tolist() == list(range(7)) + assert out["only_a"].tolist() == list(range(7)) diff --git a/tests/test_1832_cov_api_graphed.py b/tests/test_1832_cov_api_graphed.py new file mode 100644 index 000000000..ff1410805 --- /dev/null +++ b/tests/test_1832_cov_api_graphed.py @@ -0,0 +1,67 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import os + +import numpy as np +import pytest + +import uproot + +ak = pytest.importorskip("awkward") +graphed = pytest.importorskip("graphed") +pytest.importorskip("graphed.awkward") +pytest.importorskip("graphed_executors.local") + +import graphed.aggregate # noqa: E402 +from graphed.awkward import AwkwardBackend # noqa: E402 + + +def _make_tree(path, n=8): + with uproot.recreate(path) as file: + file.mktree("events", {"x": "f8"}) + file["events"].extend({"x": np.arange(n, dtype="f8")}) + return path + ":events" + + +@pytest.mark.parametrize("backend", [None, AwkwardBackend]) +def test_write_with_a_graphed_without_worker_backend(tmp_path, monkeypatch, backend): + """``graphed`` 0.0.9 has no ``aggregate.worker_backend``: the workers rebuild the session's + backend from its type, unless given one.""" + monkeypatch.delattr(graphed.aggregate, "worker_backend", raising=False) + source = uproot.graphed(_make_tree(os.path.join(tmp_path, "in.root"))) + paths = uproot.graphed_write( + source, + os.path.join(tmp_path, "out"), + steps_per_file=2, + executor="thread", + backend=backend, + ) + assert len(paths) == 2 + pieces = [] + for path in paths: + with uproot.open(path) as file: + pieces.append(file["tree"].arrays()) + back = ak.concatenate(pieces) + assert back.x.tolist() == list(range(8)) + + +@pytest.mark.skipif( + not hasattr(graphed, "current_session"), + reason="graphed has no one-binding-per-name rule", +) +def test_tree_whose_name_reads_as_a_cycle(tmp_path): + """The tree in hand has its key as the only spelling: ``a;3`` would open cycle 3 of ``a``.""" + path = os.path.join(tmp_path, "cycle.root") + with uproot.recreate(path) as file: + file.mktree("a;3", {"x": "i4"}).extend({"x": np.arange(3, dtype="i4")}) + + with uproot.open(path, object_cache=None) as file: + tree = file.values()[0] + assert uproot._graphed._spellings(tree, None, tree).paths == {"a;3;1"} + + session = graphed.Session(AwkwardBackend()) + first = uproot.graphed(tree, session=session, name="events") + second = uproot.graphed(tree, session=session, name="events") + assert first.node_id == second.node_id diff --git a/tests/test_1832_cov_api_read_options.py b/tests/test_1832_cov_api_read_options.py new file mode 100644 index 000000000..0cc69d58c --- /dev/null +++ b/tests/test_1832_cov_api_read_options.py @@ -0,0 +1,409 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import os + +import numpy as np +import pytest +import skhep_testdata + +import uproot + +ak = pytest.importorskip("awkward") + + +@pytest.fixture(scope="module") +def zmumu_path(): + return skhep_testdata.data_path("uproot-Zmumu.root") + + +@pytest.fixture(scope="module") +def zmumu(zmumu_path): + """The known values, as read by the simplest path: one branch at a time.""" + with uproot.open(zmumu_path) as file: + tree = file["events"] + yield {name: tree[name].array(library="np") for name in ("M", "Run", "Q1")} + + +@pytest.fixture +def two_files(tmp_path): + """``a.root`` has ``x`` (0 to 9) and ``y`` (10 times ``x``); ``b.root`` has only ``x`` + (10 to 14).""" + a, b = str(tmp_path / "a.root"), str(tmp_path / "b.root") + with uproot.recreate(a) as file: + x = np.arange(10, dtype=np.int64) + file.mktree("t", {"x": "int64", "y": "int64"}).extend({"x": x, "y": x * 10}) + with uproot.recreate(b) as file: + x = np.arange(10, 15, dtype=np.int64) + file.mktree("t", {"x": "int64"}).extend({"x": x}) + return a, b + + +def _as_numpy_columns(arrays, library, names): + """``{name: numpy array}`` from what ``arrays`` gives by default for ``library``.""" + if library == "np": + return {name: arrays[name] for name in names} + elif library == "ak": + return {name: ak.to_numpy(arrays[name]) for name in names} + return {name: arrays[name].to_numpy() for name in names} + + +ENTRY_RANGES = [(None, None), (100, 2000), (-500, None), (None, -2000), (2000, 100)] + + +def _expected(zmumu, entry_start, entry_stop, cut): + keep = np.zeros(len(zmumu["M"]), dtype=bool) + keep[entry_start:entry_stop] = True + if cut: + keep &= zmumu["M"] > 90 + return { + "M": zmumu["M"][keep], + "double_M": zmumu["M"][keep] * 2, + "Run": zmumu["Run"][keep], + } + + +@pytest.mark.parametrize("library", ["np", "ak", "pd"]) +@pytest.mark.parametrize("cut", [None, "M > 90"]) +@pytest.mark.parametrize(("entry_start", "entry_stop"), ENTRY_RANGES) +def test_arrays_expressions_aliases_cut_and_entries( + zmumu_path, zmumu, library, cut, entry_start, entry_stop +): + if library == "pd": + pytest.importorskip("pandas") + expected = _expected(zmumu, entry_start, entry_stop, cut) + with uproot.open(zmumu_path) as file: + arrays = file["events"].arrays( + ["M", "double_M", "Run"], + cut=cut, + aliases={"double_M": "M * 2"}, + entry_start=entry_start, + entry_stop=entry_stop, + library=library, + ) + columns = _as_numpy_columns(arrays, library, expected) + for name, values in expected.items(): + assert columns[name].tolist() == values.tolist() + + +@pytest.mark.parametrize("library", ["np", "ak", "pd"]) +@pytest.mark.parametrize("cut", [None, "M > 90"]) +@pytest.mark.parametrize(("entry_start", "entry_stop"), ENTRY_RANGES) +@pytest.mark.parametrize("step_size", [1000, "2 kB"]) +def test_iterate_is_arrays_in_steps( + zmumu_path, zmumu, library, cut, entry_start, entry_stop, step_size +): + if library == "pd": + pytest.importorskip("pandas") + expected = _expected(zmumu, entry_start, entry_stop, cut) + start, stop = uproot.behaviors.TBranch._regularize_entries_start_stop( + len(zmumu["M"]), entry_start, entry_stop + ) + with uproot.open(zmumu_path) as file: + steps = list( + file["events"].iterate( + ["M", "double_M", "Run"], + cut=cut, + aliases={"double_M": "M * 2"}, + entry_start=entry_start, + entry_stop=entry_stop, + step_size=step_size, + library=library, + report=True, + ) + ) + # the reports tile the requested range exactly + position = start + for _, report in steps: + assert report.tree_entry_start == report.global_entry_start == position + assert report.start == position + position = report.tree_entry_stop + assert report.stop == report.global_entry_stop == position + assert position == stop + + columns = [_as_numpy_columns(arrays, library, expected) for arrays, _ in steps] + for name, values in expected.items(): + joined = [v for column in columns for v in column[name].tolist()] + assert joined == values.tolist() + + +@pytest.mark.parametrize( + ("library", "how", "expected_type"), + [ + ("np", None, dict), + ("np", dict, dict), + ("np", tuple, tuple), + ("np", list, list), + ("ak", dict, dict), + ("ak", tuple, tuple), + ("ak", list, list), + ("pd", dict, dict), + ("pd", tuple, tuple), + ("pd", list, list), + ], +) +def test_how(zmumu_path, zmumu, library, how, expected_type): + if library == "pd": + pytest.importorskip("pandas") + with uproot.open(zmumu_path) as file: + arrays = file["events"].arrays( + ["Run", "M"], entry_stop=5, library=library, how=how + ) + assert type(arrays) is expected_type + run, mass = arrays.values() if expected_type is dict else arrays + assert list(run) == zmumu["Run"][:5].tolist() + assert list(mass) == zmumu["M"][:5].tolist() + + +@pytest.mark.parametrize( + ("kwargs", "expected"), + [ + ({"filter_name": "Q*"}, {"Q1", "Q2"}), + ({"filter_name": "/^[EM]$|^E1$/"}, {"E1", "M"}), + ({"filter_name": ["Run", "Event"]}, {"Run", "Event"}), + ({"filter_typename": "int32_t"}, {"Run", "Event", "Q1", "Q2"}), + ( + {"filter_branch": lambda branch: branch.name.startswith("px")}, + {"px1", "px2"}, + ), + ], +) +def test_filters_select_the_same_branches_everywhere(zmumu_path, kwargs, expected): + with uproot.open(zmumu_path) as file: + tree = file["events"] + assert set(tree.keys(**kwargs)) == expected + assert set(tree.arrays(entry_stop=1, library="np", **kwargs)) == expected + steps = list(tree.iterate(entry_stop=1, step_size=1, library="np", **kwargs)) + assert [set(step) for step in steps] == [expected] + concatenated = uproot.concatenate( + {zmumu_path: "events"}, entry_stop=1, library="np", **kwargs + ) + assert set(concatenated) == expected + + +def test_iterate_with_a_filter_matching_nothing_yields_nothing(zmumu_path): + with uproot.open(zmumu_path) as file: + assert list(file["events"].iterate(filter_name="nonexistent*")) == [] + + +@pytest.mark.parametrize( + ("entry_start", "entry_stop", "expected"), + [ + (None, None, list(range(15))), + (12, None, [12, 13, 14]), + (None, 3, [0, 1, 2]), + (8, 12, [8, 9, 10, 11]), + (10, 10, []), + (-2, None, [13, 14]), + ], +) +def test_concatenate_entry_range_across_files( + two_files, entry_start, entry_stop, expected +): + a, b = two_files + out = uproot.concatenate( + {a: "t", b: "t"}, + ["x"], + entry_start=entry_start, + entry_stop=entry_stop, + library="np", + ) + assert out["x"].tolist() == expected + + +def test_concatenate_pandas_index_counts_from_the_first_file(two_files): + pytest.importorskip("pandas") + a, b = two_files + out = uproot.concatenate( + {a: "t", b: "t"}, ["x"], cut="x % 5 == 0", library="pd", entry_start=1 + ) + assert out["x"].tolist() == [5, 10] + assert out.index.tolist() == [5, 10] + + +def test_concatenate_ak_with_cut_alias_and_how(two_files): + a, b = two_files + out = uproot.concatenate( + {a: "t", b: "t"}, ["twice"], cut="x > 11", aliases={"twice": "x * 2"}, how=tuple + ) + assert out[0].tolist() == [24, 26, 28] + + +def test_missing_branch_raises_unless_allow_missing(two_files): + a, b = two_files + files = {a: "t", b: "t"} + + with pytest.raises(uproot.KeyInFileError, match="y"): + uproot.concatenate(files, ["y"], library="np") + with pytest.raises(uproot.KeyInFileError, match="y"): + list(uproot.iterate(files, ["y"], library="np")) + + tens = list(range(0, 100, 10)) + out = uproot.concatenate(files, ["y"], library="np", allow_missing=True) + assert out["y"].tolist() == tens + steps = uproot.iterate(files, ["y"], library="np", allow_missing=True) + assert [step["y"].tolist() for step in steps] == [tens] + + +def test_missing_tree_with_allow_missing(two_files): + a, b = two_files + files = {a: "t", b: "not_there"} + with pytest.raises(uproot.KeyInFileError, match="not_there"): + uproot.concatenate(files, ["x"], library="np") + out = uproot.concatenate(files, ["x"], library="np", allow_missing=True) + assert out["x"].tolist() == list(range(10)) + steps = uproot.iterate(files, ["x"], library="np", allow_missing=True) + assert [step["x"].tolist() for step in steps] == [list(range(10))] + + +def test_iterate_function_report_and_global_offset(two_files): + a, b = two_files + steps = list( + uproot.iterate({a: "t", b: "t"}, ["x"], step_size=6, library="np", report=True) + ) + assert [step["x"].tolist() for step, _ in steps] == [ + list(range(6)), + list(range(6, 10)), + list(range(10, 15)), + ] + + reports = [report for _, report in steps] + assert [(r.tree_entry_start, r.tree_entry_stop) for r in reports] == [ + (0, 6), + (6, 10), + (0, 5), + ] + assert [(r.start, r.stop) for r in reports] == [(0, 6), (6, 10), (10, 15)] + assert [r.global_offset for r in reports] == [0, 0, 10] + + last = reports[-1] + assert os.path.basename(last.file_path) == "b.root" + assert last.tree.object_path == "/t;1" + assert last.source is last.tree + assert last.file is last.tree.file + assert last.file.file_path == last.file_path + source = last.file_path + ":/t;1" + assert repr(last) == f"" + + +def test_iterate_method_on_a_leaf_branch(two_files): + a, _ = two_files + with uproot.open(a) as file: + branch = file["t"]["y"] + steps = list(branch.iterate(step_size=4, library="np")) + assert [list(step) for step in steps] == [["y"]] * 3 + assert np.concatenate([step["y"] for step in steps]).tolist() == list( + range(0, 100, 10) + ) + # a filter that rejects the branch itself leaves nothing to iterate over + assert list(branch.iterate(filter_branch=lambda b: False)) == [] + + +def test_expressions_on_a_leaf_branch_look_among_its_subbranches(two_files): + a, _ = two_files + with uproot.open(a) as file, pytest.raises(uproot.KeyInFileError, match="'y'"): + list(file["t"]["y"].iterate("y + 1", library="np")) + + +@pytest.mark.parametrize( + "expressions", + [ + pytest.param(["x", 1], id="not a string"), + pytest.param([("x", None, None)], id="tuple of the wrong length"), + ], +) +def test_iterable_of_bad_expressions(two_files, expressions): + a, _ = two_files + with ( + uproot.open(a) as file, + pytest.raises( + TypeError, match="iterable of expressions must be strings or name, Interp" + ), + ): + file["t"].arrays(expressions) + + +def test_expressions_of_the_wrong_type(two_files): + a, _ = two_files + with ( + uproot.open(a) as file, + pytest.raises(TypeError, match="expressions must be None .* not 5"), + ): + file["t"].arrays(5) + + +def test_expressions_as_name_interpretation_pairs(two_files): + a, _ = two_files + # the bytes of x as big-endian floats + expected = np.arange(10, dtype=">i8").view(">f8").tolist() + with uproot.open(a) as file: + tree = file["t"] + as_dict = tree.arrays({"x": uproot.AsDtype(">f8")}, library="np") + as_pairs = tree.arrays([("x", np.dtype(">f8")), "y"], library="np") + assert as_dict["x"].tolist() == expected + assert as_pairs["x"].tolist() == expected + assert as_pairs["y"].tolist() == list(range(0, 100, 10)) + + +@pytest.mark.parametrize( + ("array_cache", "expected_limit"), + [ + ("1 kB", 1000), + (2048, 2048), + ], +) +def test_array_cache_by_memory_size(two_files, array_cache, expected_limit): + a, _ = two_files + regularized = uproot.behaviors.TBranch._regularize_array_cache(array_cache, None) + assert isinstance(regularized, uproot.cache.LRUArrayCache) + assert regularized.limit == expected_limit + with uproot.open(a) as file: + out = file["t"]["x"].array(array_cache=array_cache, library="np") + assert out.tolist() == list(range(10)) + + +def test_array_cache_of_the_wrong_type(two_files): + a, _ = two_files + with ( + uproot.open(a) as file, + pytest.raises( + TypeError, + match="array_cache must be None, a MutableMapping, or a memory size", + ), + ): + file["t"]["x"].array(array_cache=1.5) + + +def test_concatenate_with_explicit_executors_uses_them(two_files): + a, b = two_files + + class Counting(uproot.source.futures.TrivialExecutor): + submitted = 0 + + def submit(self, task, /, *args, **kwargs): + Counting.submitted += 1 + return super().submit(task, *args, **kwargs) + + out = uproot.concatenate( + {a: "t", b: "t"}, + ["x"], + library="np", + decompression_executor=Counting(), + interpretation_executor=Counting(), + ) + assert out["x"].tolist() == list(range(15)) + # one basket per file, each decompressed then interpreted + assert Counting.submitted == 4 + + +def test_num_entries_for_without_fsspec_source(two_files): + a, _ = two_files + with uproot.open(a) as file: + one_basket = file["t"]["x"].basket_uncompressed_bytes(0) + with uproot.open(a, handler=uproot.source.file.MemmapSource) as file: + tree = file["t"] + assert not isinstance(file.file.source, uproot.source.fsspec.FSSpecSource) + # half of the only TBasket, TKey included, is half of the entries + assert tree.num_entries_for(f"{one_basket / 2} B", ["x"]) == 5 + assert tree.num_entries_for(f"{one_basket} B", ["x"]) == 10 diff --git a/tests/test_1832_cov_api_tbranch.py b/tests/test_1832_cov_api_tbranch.py new file mode 100644 index 000000000..0142f8634 --- /dev/null +++ b/tests/test_1832_cov_api_tbranch.py @@ -0,0 +1,617 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import array +import io +import struct + +import numpy as np +import pytest +import skhep_testdata + +import uproot +from uproot.interpretation.grouped import AsGrouped +from uproot.interpretation.identify import UnknownInterpretation + +ak = pytest.importorskip("awkward") + + +@pytest.fixture +def tree_path(tmp_path): + """``t`` with the 32-bit ``x`` (0 to 9, in 2 TBaskets of 4 and 6 entries) and the long-named + ``a_rather_long_branch_name`` (twice ``x``, as doubles).""" + path = str(tmp_path / "tree.root") + with uproot.recreate(path) as file: + tree = file.mktree("t", {"x": "int32", "a_rather_long_branch_name": "float64"}) + for start, stop in ((0, 4), (4, 10)): + x = np.arange(start, stop, dtype=np.int32) + tree.extend({"x": x, "a_rather_long_branch_name": x * 2.0}) + return path + + +@pytest.fixture +def branch(tree_path): + with uproot.open(tree_path) as file: + yield file["t"]["x"] + + +def test_show_of_a_tree(tree_path): + stream = io.StringIO() + with uproot.open(tree_path) as file: + file["t"].show( + name_width=8, typename_width=7, interpretation_width=20, stream=stream + ) + assert stream.getvalue().split("\n") == [ + "name | typenam | interpretation ", + "---------+---------+---------------------", + "x | int32_t | AsDtype('>i4')", + "a_rat... | double | AsDtype('>f8')", + "", + ] + + +def test_show_of_a_branch_starts_with_the_branch(branch): + stream = io.StringIO() + branch.show(name_width=4, typename_width=8, interpretation_width=15, stream=stream) + assert stream.getvalue().split("\n") == [ + "name | typename | interpretation ", + "-----+----------+----------------", + "x | int32_t | AsDtype('>i4') ", + "", + ] + + +@pytest.mark.parametrize( + "width", ["name_width", "typename_width", "interpretation_width"] +) +def test_show_widths_must_fit_an_ellipsis(tree_path, width): + with ( + uproot.open(tree_path) as file, + pytest.raises(ValueError, match=f"'{width}' must be at least 3"), + ): + file["t"].show(**{width: 2}) + + +def test_mapping_access(tree_path): + with uproot.open(tree_path) as file: + tree = file["t"] + assert tree[0].name == "x" + assert tree[1].name == "a_rather_long_branch_name" + assert tree[np.int64(0)] is tree["x"] + with pytest.raises( + TypeError, match=r"where must be an integer or a string, not 1\.5" + ): + tree[1.5] + assert [name for name, _ in tree.items()] == [ + "x", + "a_rather_long_branch_name", + ] + assert tree.items()[0][1] is tree["x"] + assert list(tree._ipython_key_completions_()) == tree.keys() + + +def test_filter_branch_argument(tree_path): + with uproot.open(tree_path) as file: + tree = file["t"] + assert tree.keys(filter_branch=None) == tree.keys() + with pytest.raises( + TypeError, match="filter_branch must be None or a function: TBranch -> bool" + ): + tree.keys(filter_branch="x") + + +def test_tree_outside_of_its_open_file_has_no_source(tree_path): + with uproot.open(tree_path) as file: + assert file["t"].source is file.file.source + assert file["t"]["x"].source is file.file.source + + # a tree read as part of another object is on a detached file + key = file.key("t") + chunk, cursor = key.get_uncompressed_chunk_cursor() + detached = file.file.class_named("TTree").read( + chunk, + cursor, + {"breadcrumbs": (), "TKey": key}, + file.file, + file.file.detached, + None, + ) + assert detached.name == "t" + assert detached.source is None + + +def test_repr_of_branches(): + path = skhep_testdata.data_path("uproot-small-evnt-tree-fullsplit.root") + with uproot.open(path) as file: + tree = file["tree"] + parent, leaf = tree["evt"], tree["evt/I32"] + assert repr(leaf).startswith("iiq", start + ) + path = tmp_path / "corrupted.root" + path.write_bytes(corrupted) + + with uproot.open(path) as file: + branch = file["t"]["x"] + assert branch.num_entries == 11 + with pytest.raises( + ValueError, + match=r"entries in normal baskets \(10\) plus embedded baskets \(0\) " + r"don't add up to expected number of entries \(11\)", + ): + branch.entry_offsets + + +@pytest.mark.parametrize( + ("entry_start", "entry_stop", "expected"), + [ + (5, 2, []), + (-3, -8, []), + (20, 30, []), + (-100, 2, [0, 1]), + ], +) +def test_entry_ranges_are_clipped(branch, entry_start, entry_stop, expected): + out = branch.array(entry_start=entry_start, entry_stop=entry_stop, library="np") + assert out.tolist() == expected + + +def test_streamer_of_an_object_branch(): + path = skhep_testdata.data_path("uproot-Event.root") + with uproot.open(path) as file: + tree = file["T"] + streamers = file.file.streamers + + event = tree["event"] + assert event.streamer is streamers["Event"][max(streamers["Event"])] + assert event.streamer is event.streamer + + # no member of Track has this name, but fTriggerBits, a TBits, has fNbits + nbits = tree["event/fTracks/fTracks.fTriggerBits.fNbits"] + assert nbits.streamer.name == "fNbits" + assert nbits.streamer.typename == "unsigned int" + + # TBits has no member named TObject, even though it inherits from it + assert tree["event/fTriggerBits/fTriggerBits.TObject"].streamer is None + + +def test_streamer_of_a_member_missing_from_its_parents_class(tmp_path): + """The TTree is moved to the end of the file, uncompressed, with one TBranch renamed.""" + path = skhep_testdata.data_path("uproot-Event.root") + with uproot.open(path) as file: + key = file.key("T") + seek, key_size, size = key.fSeekKey, key.fKeylen, key.fNbytes + chunk, _ = key.get_uncompressed_chunk_cursor() + data = bytes(chunk.raw_data) + with open(path, "rb") as stream: + raw = stream.read() + + old_name, new_name = b"fTracks.fTriggerBits.fNbits", b"fTracks.fTriggerBits.fNbads" + assert new_name not in data + data = data.replace(old_name, new_name, 1) + + header = raw[seek : seek + key_size] + # fNbytes at the start of the header and fSeekKey after the 4 + 2 + 4 + 4 + 2 + 2 bytes + assert struct.unpack(">ihiIhhi", header[:22])[0] == size + assert struct.unpack(">ihiIhhi", header[:22])[6] == seek + moved = struct.pack(">i", key_size + len(data)) + header[4:18] + moved += struct.pack(">i", len(raw)) + header[22:] + # the same bytes are in the directory's list of keys + assert raw.count(header) == 2 + corrupted = tmp_path / "renamed.root" + corrupted.write_bytes(raw.replace(header, moved) + moved + data) + + with uproot.open(corrupted) as file: + tracks = file["T"]["event/fTracks"] + # fTriggerBits is a member of Track, but TBits has no fNbads + assert tracks["fTracks.fTriggerBits.fNbads"].streamer is None + assert tracks["fTracks.fTriggerBits.fAllBits"].streamer.name == "fAllBits" + + +def test_streamer_of_a_tclonesarray_branch(): + path = skhep_testdata.data_path("uproot-delphes-pr442.root") + with uproot.open(path) as file: + branch = file["Delphes"]["CaloJet02"] + assert branch.streamer.name == "Jet" + assert branch._streamer_isTClonesArray + + +def test_streamer_of_a_class_not_in_the_file(): + path = skhep_testdata.data_path("uproot-FCCDelphesOutput.root") + with uproot.open(path) as file: + assert file["events"]["bTags"].streamer is None + + +def test_streamer_of_a_parent_not_in_the_file(cms_events): + name = "uint_bunchSpacingProducer__PAT." + assert cms_events[name][name + "obj"].streamer is None + + +def test_plain_branch_has_no_streamer(): + with uproot.open(skhep_testdata.data_path("uproot-Zmumu.root")) as file: + assert file["events"]["M"].streamer is None + + +def test_virtual_arrays_with_full_paths_keep_grouped_children(nested_groups): + out = nested_groups._virtual_arrays(entry_stop=2) + assert "branch/value" in out.fields + assert out["branch/value"].tolist() == [0, 1] + + +def test_more_normal_baskets_than_basket_entries(tmp_path): + """ROOT can read a ``fBasketEntry`` with no entry after the last TBasket: its size comes + from the TBasket's header. Here, fMaxBaskets = 3 and the third TBasket is that of ``other``, + as uproot always leaves one free.""" + path = str(tmp_path / "full.root") + with uproot.recreate(path) as file: + tree = file.mktree("t", {"x": "int32"}, initial_basket_capacity=3) + tree.extend({"x": np.arange(0, 4, dtype=np.int32)}) + tree.extend({"x": np.arange(4, 10, dtype=np.int32)}) + other = file.mktree("other", {"x": "int32"}) + other.extend({"x": np.arange(100, 106, dtype=np.int32)}) + + with uproot.open(path) as file: + branch = file["t"]["x"] + assert branch.member("fMaxBaskets") == 3 + assert branch.member("fWriteBasket") == 2 + seeks = branch.member("fBasketSeek").tolist() + sizes = branch.member("fBasketBytes").tolist() + extra_seek = int(file["other"]["x"].member("fBasketSeek")[0]) + extra_size = int(file["other"]["x"].member("fBasketBytes")[0]) + start = file.key("t").fSeekKey + + with open(path, "rb") as stream: + raw = stream.read() + + raw = _replaced(raw, (*seeks[:2], 0), (*seeks[:2], extra_seek), ">3q", start) + raw = _replaced(raw, (*sizes[:2], 0), (*sizes[:2], extra_size), ">3i", start) + # fWriteBasket and fEntryNumber + raw = _replaced(raw, (2, 10), (3, 16), ">iq", start) + # fMaxBaskets, fSplitLevel and fEntries + raw = _replaced(raw, (3, 0, 10), (3, 0, 16), ">iiq", start) + # the TTree's fEntries comes before all of the above + raw = _replaced(raw, (10,), (16,), ">q", start) + + corrupted = tmp_path / "corrupted.root" + corrupted.write_bytes(raw) + with uproot.open(corrupted) as file: + branch = file["t"]["x"] + assert branch.num_baskets == 3 + assert branch.embedded_baskets == [] + assert branch.entry_offsets == [0, 4, 10, 16] + expected = [*range(10), *range(100, 106)] + assert branch.array(library="np").tolist() == expected + + +@pytest.fixture(scope="module", params=[True, False], ids=["minimal", "all metadata"]) +def minimal_ttree_metadata(request): + return request.param + + +def _fill(ROOT, tree, stop, start=0): + value = array.array("i", [0]) + tree.SetBranchAddress("x", value) + for i in range(start, stop): + value[0] = i + tree.Fill() + + +def _new_tree(ROOT): + tree = ROOT.TTree("t", "t") + tree.SetAutoFlush(0) + value = array.array("i", [0]) + tree.Branch("x", value, "x/I").SetBasketSize(4096) + return tree + + +@pytest.fixture(scope="module") +def autosaved(tmp_path_factory): + """As left by a ROOT process that died: the last TBasket is still in the TBranch metadata.""" + ROOT = pytest.importorskip("ROOT") + path = str(tmp_path_factory.mktemp("embedded") / "autosaved.root") + file = ROOT.TFile(path, "RECREATE") + tree = _new_tree(ROOT) + _fill(ROOT, tree, 3100) + tree.AutoSave("SaveSelf") + file.Close() + return path + + +@pytest.fixture(scope="module") +def memory_resident(tmp_path_factory): + """A TTree that was never attached to a file has all of its TBaskets in the metadata.""" + ROOT = pytest.importorskip("ROOT") + path = str(tmp_path_factory.mktemp("embedded") / "memory.root") + file = ROOT.TFile(path, "RECREATE") + tree = _new_tree(ROOT) + tree.SetDirectory(ROOT.nullptr) + _fill(ROOT, tree, 5000) + file.WriteObject(tree, "t") + file.Close() + return path + + +def test_embedded_basket_after_normal_baskets(autosaved, minimal_ttree_metadata): + with uproot.open(autosaved, minimal_ttree_metadata=minimal_ttree_metadata) as file: + branch = file["t"]["x"] + normal = branch.num_baskets - 1 + assert normal > 0 + assert len(branch.embedded_baskets) == 1 + embedded = branch.embedded_baskets[0] + + offsets = branch.entry_offsets + assert offsets[-1] == 3100 + assert branch.basket(normal) is embedded + assert embedded.basket_num == normal + assert embedded.num_entries == offsets[-1] - offsets[-2] + assert branch.basket_entry_start_stop(normal) == (offsets[-2], 3100) + assert branch.basket_compressed_bytes(normal) == embedded.compressed_bytes + assert branch.basket_uncompressed_bytes(normal) == embedded.uncompressed_bytes + + with pytest.raises(IndexError, match="only normal baskets have cursors"): + branch.basket_chunk_cursor(normal) + with pytest.raises( + ValueError, match="is an embedded basket, which has no TKey" + ): + branch.basket_key(normal) + + assert branch.array(library="np").tolist() == list(range(3100)) + # across the boundary between normal and embedded baskets + middle = offsets[-2] + assert branch.array( + entry_start=middle - 2, entry_stop=middle + 2, library="np" + ).tolist() == list(range(middle - 2, middle + 2)) + + # all of the baskets count for a step in bytes + total = sum(branch.basket_uncompressed_bytes(i) for i in range(normal + 1)) + assert file["t"].num_entries_for(f"{total} B", ["x"]) == 3100 + + +def test_several_embedded_baskets(memory_resident, minimal_ttree_metadata): + with uproot.open( + memory_resident, minimal_ttree_metadata=minimal_ttree_metadata + ) as file: + branch = file["t"]["x"] + assert branch.num_baskets == len(branch.embedded_baskets) > 1 + assert [b.basket_num for b in branch.embedded_baskets] == list( + range(branch.num_baskets) + ) + + offsets = branch.entry_offsets + assert offsets[0] == 0 + assert offsets[-1] == 5000 + assert [ + branch.basket_entry_start_stop(i) for i in range(branch.num_baskets) + ] == list(zip(offsets[:-1], offsets[1:], strict=True)) + + assert branch.array(library="np").tolist() == list(range(5000)) + steps = list(file["t"].iterate(["x"], step_size=1500, library="np")) + assert [len(step["x"]) for step in steps] == [1500, 1500, 1500, 500] + + +def test_subbranches_with_the_same_name(tmp_path): + ROOT = pytest.importorskip("ROOT") + path = str(tmp_path / "duplicates.root") + + file = ROOT.TFile(path, "RECREATE") + tree = ROOT.TTree("t", "t") + values = [array.array("i", [0]) for _ in range(3)] + parent = tree.Branch("p", values[0], "p/I") + ignore_level = ROOT.gErrorIgnoreLevel + ROOT.gErrorIgnoreLevel = ROOT.kError # ROOT warns about the second "c" + first = tree.Branch("c", values[1], "c/I") + second = tree.Branch("c", values[2], "c/I") + ROOT.gErrorIgnoreLevel = ignore_level + for i in range(3): + values[0][0], values[1][0], values[2][0] = i, i * 10, i * 100 + tree.Fill() + for branch in (first, second): + tree.GetListOfBranches().Remove(branch) + parent.GetListOfBranches().Add(branch) + tree.Write() + file.Close() + + with uproot.open(path) as file: + parent = file["t"]["p"] + assert [branch.name for branch in parent.branches] == ["c", "c"] + # a name finds the first; the second is reachable by its index + assert parent["c"] is parent[0] + assert parent["c"].array(library="np").tolist() == [0, 10, 20] + assert parent[1].array(library="np").tolist() == [0, 100, 200] diff --git a/tests/test_1832_cov_rntuple_api.py b/tests/test_1832_cov_rntuple_api.py new file mode 100644 index 000000000..640c7ed7a --- /dev/null +++ b/tests/test_1832_cov_rntuple_api.py @@ -0,0 +1,475 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import io +import re + +import numpy as np +import pytest + +import uproot +from uproot.behaviors.RNTuple import concatenate, iterate + +ak = pytest.importorskip("awkward") + + +@pytest.fixture +def ntuple_path(tmp_path): + """A small RNTuple with nested records, lists, and documented fields.""" + path = tmp_path / "nested.root" + rec = ak.Array( + [ + {"a": 1, "inner": {"deep": 1.5}}, + {"a": 2, "inner": {"deep": 2.5}}, + {"a": 3, "inner": {"deep": 3.5}}, + ] + ) + vec = ak.Array([[{"p": 1}], [], [{"p": 2}, {"p": 3}]]) + data = ak.with_field(ak.Array({"x": [10, 20, 30]}), rec, "rec") + data = ak.with_field(data, vec, "vec") + data = ak.with_parameter(data, "__doc__", "Some entries") + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", data, description="The description") + return path + + +@pytest.fixture +def ntuple(ntuple_path): + with uproot.open(ntuple_path) as file: + yield file["ntuple"] + + +ALL_KEYS = ["x", "rec", "rec.a", "rec.inner", "rec.inner.deep", "vec", "vec.p"] + + +def _write_x(path, values): + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", {"x": np.asarray(values, dtype=np.int64)}) + return str(path) + + +@pytest.fixture +def three_files(tmp_path): + return [ + _write_x(tmp_path / "first.root", [0, 1, 2]), + _write_x(tmp_path / "second.root", [3, 4, 5, 6]), + _write_x(tmp_path / "third.root", [7, 8]), + ] + + +@pytest.mark.parametrize( + ("entry_start", "entry_stop"), + [ + (None, None), + # spans a whole file in the middle, which is read completely + (1, 8), + # leaves the last files out + (0, 2), + # leaves the first files out + (7, None), + # only in the middle file + (4, 6), + # negative positions count from the end + (-2, None), + ], +) +def test_concatenate_entry_range(three_files, entry_start, entry_stop): + out = concatenate( + {path: "ntuple" for path in three_files}, + entry_start=entry_start, + entry_stop=entry_stop, + ) + assert out.x.to_list() == list(range(9))[entry_start:entry_stop] + + +@pytest.fixture +def one_file_without_ntuple(tmp_path): + with_ntuple = _write_x(tmp_path / "with.root", [1, 2, 3]) + without_ntuple = tmp_path / "without.root" + with uproot.recreate(without_ntuple) as file: + file["other"] = "a TObjString" + return {with_ntuple: "ntuple", str(without_ntuple): "ntuple"} + + +def test_iterate_allow_missing_object(one_file_without_ntuple): + out = list(iterate(one_file_without_ntuple, step_size=2, allow_missing=True)) + assert [chunk.x.to_list() for chunk in out] == [[1, 2], [3]] + + +def test_concatenate_allow_missing_object(one_file_without_ntuple): + out = concatenate(one_file_without_ntuple, allow_missing=True) + assert out.x.to_list() == [1, 2, 3] + + +@pytest.mark.parametrize( + "read", + [ + lambda files: list(iterate(files, step_size=2)), + lambda files: concatenate(files), + ], +) +def test_missing_object_is_an_error_by_default(one_file_without_ntuple, read): + with pytest.raises(uproot.KeyInFileError, match="ntuple"): + read(one_file_without_ntuple) + + +@pytest.fixture +def one_file_without_subfield(tmp_path): + """Both files have a record, but only the first has the subfield ``y``.""" + paths = {} + for name, fields in (("with", ("x", "y")), ("without", ("x",))): + path = str(tmp_path / f"{name}.root") + with uproot.recreate(path) as file: + file.mkrntuple( + "ntuple", {"rec": ak.Array([{field: 1 for field in fields}] * 2)} + ) + paths[path] = "ntuple" + return paths + + +def _select_records_with_y(field): + # a filter on an RField can look at its subfields, which raises if they are missing + return field.name != "rec" or field["y"].typename == "std::int64_t" + + +def test_iterate_allow_missing_field(one_file_without_subfield): + out = list( + iterate( + one_file_without_subfield, + filter_field=_select_records_with_y, + allow_missing=True, + ) + ) + assert [chunk.to_list() for chunk in out] == [[{"rec": {"x": 1, "y": 1}}] * 2] + + +def test_concatenate_allow_missing_field(one_file_without_subfield): + out = concatenate( + one_file_without_subfield, + filter_field=_select_records_with_y, + allow_missing=True, + ) + assert out.to_list() == [{"rec": {"x": 1, "y": 1}}] * 2 + + +@pytest.mark.parametrize( + "read", + [ + lambda files: list(iterate(files, filter_field=_select_records_with_y)), + lambda files: concatenate(files, filter_field=_select_records_with_y), + ], +) +def test_missing_field_is_an_error_by_default(one_file_without_subfield, read): + with pytest.raises(uproot.KeyInFileError, match="not found"): + read(one_file_without_subfield) + + +def test_path_of_an_rntuple_is_a_dot(ntuple): + assert ntuple.path == "." + assert ntuple["rec"]["inner"]["deep"].path == "rec.inner.deep" + + +@pytest.mark.parametrize( + "method", + [ + lambda ntuple, **kwargs: ntuple.arrays("x", **kwargs), + lambda ntuple, **kwargs: list(ntuple.iterate("x", **kwargs)), + lambda ntuple, **kwargs: ntuple.num_entries_for("1 MB", "x", **kwargs), + ], +) +def test_expressions_and_filter_name_are_exclusive(ntuple, method): + with pytest.raises(ValueError, match="Expressions are not supported yet"): + method(ntuple, filter_name="rec") + + +def test_expressions_act_as_filter_name(ntuple): + assert ntuple.arrays("x").fields == ["x"] + assert [chunk.fields for chunk in ntuple.iterate("x")] == [["x"]] + assert ntuple.num_entries_for("1 kB", "x") == ntuple.num_entries_for( + "1 kB", filter_name="x" + ) + # 8 bytes per entry, a 3 entry cluster + assert ntuple.num_entries_for(80, "x") == 10 + + +def test_num_entries_for_nothing_selected(ntuple): + assert ntuple.num_entries_for("1 MB", filter_name="does_not_exist") is None + + +@pytest.mark.parametrize("filter_name", ["x", "vec"]) +def test_num_entries_for_an_empty_entry_range(ntuple, filter_name): + # no clusters are in the range, so there is no size to go by + assert ( + ntuple.num_entries_for( + "1 MB", filter_name=filter_name, entry_start=2, entry_stop=2 + ) + == 1 + ) + + +@pytest.mark.parametrize( + ("interpreter", "message"), + [ + ("gpu", "Backend cpu GDS support not implemented."), + ("unknown", "Backend cpu not implemented."), + ], +) +def test_unsupported_interpreter(ntuple, interpreter, message): + with pytest.raises(NotImplementedError, match=message): + ntuple.arrays(interpreter=interpreter, backend="cpu") + + +def test_array_protocol_of_a_field(ntuple): + out = np.asarray(ntuple["x"]) + assert out.dtype == np.dtype("int64") + assert out.tolist() == [10, 20, 30] + + converted = np.asarray(ntuple["x"], dtype=np.float32) + assert converted.dtype == np.dtype("float32") + assert converted.tolist() == [10.0, 20.0, 30.0] + + +def test_array_protocol_of_an_rntuple(ntuple): + # An RNTuple is a table of fields, not one array + assert ntuple.__array__()["x"].tolist() == [10, 20, 30] + with pytest.raises(ValueError, match="__array__"): + np.asarray(ntuple) + wrapped = ntuple.__array__(dtype=object) + assert wrapped.shape == () + assert wrapped.item()["x"].tolist() == [10, 20, 30] + + +def test_iterate_report(three_files): + out = list( + iterate( + {path: "ntuple" for path in three_files[:2]}, + step_size=2, + report=True, + ) + ) + assert [chunk.x.to_list() for chunk, _ in out] == [[0, 1], [2], [3, 4], [5, 6]] + assert [ + (report.global_entry_start, report.global_entry_stop) for _, report in out + ] == [(0, 2), (2, 3), (3, 5), (5, 7)] + assert [(report.tree_entry_start, report.tree_entry_stop) for _, report in out] == [ + (0, 2), + (2, 3), + (0, 2), + (2, 4), + ] + + +def test_items(ntuple): + assert [ + (name, field.typename) for name, field in ntuple.items(recursive=False) + ] == [ + ("x", "std::int64_t"), + ("rec", ""), + ("vec", ""), + ] + assert ntuple.items(filter_name="deep")[0][1] is ntuple["rec.inner.deep"] + + +def test_values(ntuple): + assert [field.name for field in ntuple.values(recursive=False)] == [ + "x", + "rec", + "vec", + ] + assert [field.name for field in ntuple["rec"].values()] == ["a", "inner", "deep"] + + +def test_filter_branch_is_deprecated(ntuple): + with pytest.warns(DeprecationWarning, match="filter_branch kwarg should not"): + assert ntuple.keys(filter_branch=lambda field: field.name == "x") == ["x"] + + +def test_filter_field_none_selects_everything(ntuple): + assert ntuple.keys(filter_field=None) == ALL_KEYS + + +def test_filter_field_must_be_callable(ntuple): + with pytest.raises(TypeError, match="filter_field must be None or a function"): + ntuple.keys(filter_field="x") + + +def test_typenames(ntuple): + assert ntuple.typenames(filter_name="x") == {"x": "std::int64_t"} + assert ntuple.typenames(filter_typename="double") == {"rec.inner.deep": "double"} + assert dict(ntuple["rec"].itertypenames(recursive=False)) == { + "a": "std::int64_t", + "inner": "", + } + + +def test_ipython_key_completions(ntuple): + assert list(ntuple._ipython_key_completions_()) == ALL_KEYS + + +def test_fields_by_position(ntuple): + assert [field.name for field in ntuple] == ["x", "rec", "vec"] + assert ntuple[1] is ntuple["rec"] + assert ntuple["rec"][0] is ntuple["rec"]["a"] + assert ntuple[-1].name == "vec" + + +@pytest.mark.parametrize( + "where", + ["rec.inner.deep", "rec/inner/deep", "rec\\inner\\deep", "rec..inner.deep", "deep"], +) +def test_fields_by_name(ntuple, where): + assert ntuple[where] is ntuple["rec"]["inner"]["deep"] + + +def test_recursive_lookup_of_a_later_field(ntuple): + # the first fields are searched without success + assert ntuple["p"].path == "vec.p" + # and the result of a search is not confused with a parent's fields + assert ntuple["a"] is ntuple["rec"]["a"] + assert ntuple["rec"]["deep"] is ntuple["rec"]["inner"]["deep"] + + +@pytest.mark.parametrize( + "where", + ["does_not_exist", "rec.does_not_exist", ".deep"], +) +def test_missing_field_lookup(ntuple, ntuple_path, where): + with pytest.raises(uproot.KeyInFileError, match="not found") as excinfo: + ntuple[where] + assert excinfo.value.key == where + assert excinfo.value.file_path.endswith(ntuple_path.name) + + +def test_field_lookup_with_a_bad_type(ntuple): + with pytest.raises(TypeError, match="where must be an integer or a string"): + ntuple[1.5] + + +def test_show(ntuple): + stream = io.StringIO() + ntuple.show(stream=stream) + assert stream.getvalue() == """ntuple (ROOT::RNTuple) +Description: The description +├─ x (std::int64_t) +├─ rec () +│ ├─ a (std::int64_t) +│ └─ inner () +│ └─ deep (double) +└─ vec () + └─ p (std::int64_t) +""" + + +def test_show_not_recursive_and_narrow(ntuple): + stream = io.StringIO() + ntuple.show(stream=stream, recursive=False, max_width=12) + assert stream.getvalue().splitlines() == [ + "ntuple (ROOT", + "Description:", + "├─ x (std::i", + "├─ rec ()", + "└─ vec ()", + ] + + +def test_show_a_field_with_nothing_selected(ntuple): + stream = io.StringIO() + ntuple["rec"].show(stream=stream, filter_name="does_not_exist") + assert stream.getvalue() == "rec ()\n" + + +def test_show_field_descriptions(tmp_path): + form = ak.forms.RecordForm( + [ + ak.forms.NumpyForm("int32", parameters={"__doc__": "the first"}), + ak.forms.RecordForm( + [ak.forms.NumpyForm("int32", parameters={"__doc__": "the inner"})], + ["c"], + parameters={"__doc__": "the second"}, + ), + ak.forms.NumpyForm("int32"), + ], + ["a", "b", "d"], + ) + path = tmp_path / "documented.root" + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", form) + + stream = io.StringIO() + with uproot.open(path) as file: + file["ntuple"].show(stream=stream) + assert stream.getvalue() == """ntuple (ROOT::RNTuple) +├─ a (std::int32_t) +│ Description: the first +├─ b () +│ Description: the second +│ └─ c (std::int32_t) +│ Description: the inner +└─ d (std::int32_t) +""" + + +def test_source(ntuple, ntuple_path): + assert ntuple.source.file_path.endswith(ntuple_path.name) + + +def test_source_of_a_detached_rntuple(ntuple_path): + with uproot.open(ntuple_path) as file: + # an RNTuple read as part of another object is on a detached file + key = file.key("ntuple") + chunk, cursor = key.get_uncompressed_chunk_cursor() + detached = file.file.class_named("ROOT::RNTuple").read( + chunk, + cursor, + {"breadcrumbs": (), "TKey": key}, + file.file, + file.file.detached, + None, + ) + assert detached.source is None + + +def test_reprs(ntuple): + assert re.fullmatch( + r"", repr(ntuple) + ) + assert re.fullmatch( + r"", + repr(ntuple["rec"]), + ) + assert re.fullmatch( + r"", repr(ntuple["x"]) + ) + + +def test_repr_without_fields(tmp_path): + path = tmp_path / "empty.root" + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", ak.forms.RecordForm([], [])) + with uproot.open(path) as file: + assert re.fullmatch( + r"", repr(file["ntuple"]) + ) + + +def test_field_index(ntuple): + assert [field.index for field in ntuple.fields] == [0, 1, 2] + assert ntuple["rec"]["inner"].index == 1 + + +def test_member_that_shadows_an_inherited_member(tmp_path): + # ":_N" is how a base class is stored + path = tmp_path / "file.root" + data = ak.Array([{"member": 1, ":_0": {"member": 2}}] * 2) + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", {"c": data}) + with uproot.open(path) as file: + ntuple = file["ntuple"] + assert ntuple.keys() == ["c", "c.member", "c.::member"] + assert ntuple.arrays().c.to_list() == [{"member": 1, "::member": 2}] * 2 + + +def test_field_names(ntuple): + assert ntuple.field_names is ntuple.field_names + assert ntuple.field_names[:2] == ["x", "rec"] diff --git a/tests/test_1832_cov_rntuple_lowlevel.py b/tests/test_1832_cov_rntuple_lowlevel.py new file mode 100644 index 000000000..429f7e6f9 --- /dev/null +++ b/tests/test_1832_cov_rntuple_lowlevel.py @@ -0,0 +1,367 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import struct +import types + +import numpy as np +import pytest +import xxhash + +import uproot +import uproot.const +import uproot.models.RNTuple as models +from uproot.interpretation.objects import CannotBeForth + +ak = pytest.importorskip("awkward") + + +def _write(path, data): + with uproot.recreate(path, compression=None) as file: + file.mkrntuple("ntuple", data) + return path + + +def _list_frame_items(buffer, position): + """ + Returns the positions of the payloads of a list frame of record frames, and the + position that follows the list frame. + """ + list_size, num_items = struct.unpack_from("H", raw, version)[0] < 0x4000 + raw[version] |= 0x40 + path.write_bytes(raw) + + with uproot.open(path) as file: + with pytest.raises(NotImplementedError, match="memberwise serialization"): + file["ntuple"] + + +def test_big_endian_systems_are_rejected(tmp_path, monkeypatch): + path = _write(tmp_path / "file.root", {"x": np.array([1, 2])}) + monkeypatch.setattr(models, "sys", types.SimpleNamespace(byteorder="big")) + with uproot.open(path) as file: + with pytest.raises(NotImplementedError, match="little-endian"): + file["ntuple"] + + +def test_rntuple_cannot_be_forth(tmp_path): + path = _write(tmp_path / "file.root", {"x": np.array([1, 2])}) + with uproot.open(path) as file: + ntuple = file["ntuple"] + context = {"forth": types.SimpleNamespace(gen=object())} + with pytest.raises(CannotBeForth): + ntuple.read_members(None, None, context, ntuple.file) + + +@pytest.mark.parametrize( + "field", + [ + {"v": ak.Array([[1], [2, 3]])}, + {"u": _union([1], [1.5], tags=[0, 1], index=[0, 0])}, + ], +) +def test_base_col_form_of_columns_without_a_form(tmp_path, field): + # index and switch columns only give their buffers a name + path = _write(tmp_path / "file.root", field) + with uproot.open(path) as file: + ntuple = file["ntuple"] + assert ntuple.base_col_form(ntuple.column_records[0]) == "column-0" + + +def test_cluster_range_skips_negative_clusters(tmp_path): + path = _write(tmp_path / "file.root", {"x": np.array([1, 2, 3])}) + with uproot.open(path) as file: + ntuple = file["ntuple"] + length, starts, _ = ntuple._expected_array_length_starts_dtype(0, -1, 1) + assert (length, starts) == (3, [0]) + assert ntuple.read_cluster_range(0, -1, 1).tolist() == [1, 2, 3] + + +def test_access_log_must_be_extendable(tmp_path): + path = _write(tmp_path / "file.root", {"x": np.array([1, 2, 3])}) + with uproot.open(path) as file: + arrays = file["ntuple"].arrays(virtual=True, access_log=object()) + with pytest.raises(ValueError, match="needs to implement '__iadd__'"): + arrays.x.to_list() + + +def test_read_cluster_pages_without_destination_from_cache(tmp_path): + path = _write(tmp_path / "file.root", {"x": np.array([1, 2, 3])}) + with uproot.open(path) as file: + ntuple = file["ntuple"] + metadata = ntuple.get_field_metadata(0) + cache = {} + out = ntuple.read_cluster_pages(0, 0, metadata, array_cache=cache) + assert out.tolist() == [1, 2, 3] + assert list(cache) == [f"{ntuple.cache_key}:0:0"] + + cached = ntuple.read_cluster_pages(0, 0, metadata, array_cache=cache) + assert cached is cache[f"{ntuple.cache_key}:0:0"] + + +def test_large_locator(): + data = struct.pack(" 1 else content, + ) + record = ak.contents.RecordArray( + [ak.Array([[1], []]).layout, indexed], ["jagged", "indexed"] + ) + out = _rntuple_to_numpy(ak.Array(record)) + assert out.dtype["indexed"] == np.dtype(object) + assert [np.asarray(x).tolist() for x in out["indexed"]] == expected diff --git a/tests/test_1832_cov_rntuple_root.py b/tests/test_1832_cov_rntuple_root.py new file mode 100644 index 000000000..a1cc72dcd --- /dev/null +++ b/tests/test_1832_cov_rntuple_root.py @@ -0,0 +1,231 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import pytest + +import uproot + +ak = pytest.importorskip("awkward") + +_WRITERS = """ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_1832 { + +struct Base { + int member; + float other; +}; +struct Child : Base { + int member; +}; +struct Left { + int shared; +}; +struct Right { + int shared; +}; +struct Both : Left, Right { + int member; +}; + +void write_projections(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + auto pt = model->MakeField("pt"); + auto values = model->MakeField>("values"); + model + ->AddProjectedField(ROOT::RFieldBase::Create("pt_alias", "float").Unwrap(), + [](const std::string &) { return std::string("pt"); }) + .ThrowOnError(); + model + ->AddProjectedField( + ROOT::RFieldBase::Create("num_values", "ROOT::RNTupleCardinality").Unwrap(), + [](const std::string &) { return std::string("values"); }) + .ThrowOnError(); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + for (int i = 0; i < 4; i++) { + *pt = 1.5f * i; + *values = std::vector(i, i); + writer->Fill(); + } +} + +void write_shadowed_members(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + auto child = model->MakeField("child"); + auto both = model->MakeField("both"); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + for (int i = 0; i < 3; i++) { + child->member = i; + child->Base::member = 10 * i; + child->other = 0.5f * i; + both->member = 100 * i; + both->Left::shared = 200 * i; + both->Right::shared = 300 * i; + writer->Fill(); + } +} + +void write_streamer_field(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + model->MakeField("x"); + model->AddField(std::make_unique("streamed", "std::vector")); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + auto entry = writer->CreateEntry(); + auto x = entry->GetPtr("x"); + auto streamed = entry->GetPtr>("streamed"); + for (int i = 0; i < 2; i++) { + *x = i; + streamed->push_back(i); + writer->Fill(*entry); + } +} + +void write_without_fields(const char *path) +{ + auto writer = ROOT::RNTupleWriter::Recreate(ROOT::RNTupleModel::Create(), "ntuple", path); +} + +std::string show(const char *path, int entry) +{ + std::ostringstream stream; + ROOT::RNTupleReader::Open("ntuple", path)->Show(entry, stream); + return stream.str(); +} + +// Show doesn't support variants +std::string show_variant(const char *path, int entry) +{ + auto reader = ROOT::RNTupleReader::Open("ntuple", path); + auto view = reader->GetView>("a"); + auto value = view(entry); + if (value.index() == 0) + return std::to_string(std::get<0>(value)); + return std::get<1>(value); +} + +} // namespace test_1832 +""" + +_ATTRIBUTE_WRITER = """ +#include + +namespace test_1832 { + +void write_attributes(const char *path) +{ + auto file = std::unique_ptr(TFile::Open(path, "RECREATE")); + auto model = ROOT::RNTupleModel::Create(); + auto x = model->MakeField("x"); + auto writer = ROOT::RNTupleWriter::Append(std::move(model), "ntuple", *file); + auto attribute_model = ROOT::RNTupleModel::Create(); + auto note = attribute_model->MakeField("note"); + auto attributes = writer->CreateAttributeSet(std::move(attribute_model), "my_attributes"); + auto range = attributes->BeginRange(); + *note = "a note"; + for (int i = 0; i < 4; i++) { + *x = i; + writer->Fill(); + } + attributes->CommitRange(std::move(range)); + writer.reset(); +} + +} // namespace test_1832 +""" + + +@pytest.fixture(scope="module") +def root(): + ROOT = pytest.importorskip("ROOT") + if ROOT.gROOT.GetVersionInt() < 63800: + pytest.skip("needs the RNTuple interfaces of a recent ROOT") + # ROOT warnings become Python warnings, which are errors in this test suite. The + # classes above have no dictionaries, which ROOT warns about. + ignore_level = ROOT.gErrorIgnoreLevel + ROOT.gErrorIgnoreLevel = ROOT.kError + if not hasattr(ROOT, "test_1832"): + assert ROOT.gInterpreter.Declare(_WRITERS) + if ROOT.gROOT.GetVersionInt() >= 64000: + assert ROOT.gInterpreter.Declare(_ATTRIBUTE_WRITER) + yield ROOT.test_1832 + ROOT.gErrorIgnoreLevel = ignore_level + + +def test_projected_fields(root, tmp_path): + path = tmp_path / "file.root" + root.write_projections(str(path)) + with uproot.open(path) as file: + ntuple = file["ntuple"] + assert ntuple.keys() == ["pt", "values", "pt_alias", "num_values"] + + alias_field = ntuple["pt_alias"].field_id + assert ntuple.field_records[alias_field].source_field_id == 0 + assert [ + (alias.physical_id, alias.field_id) for alias in ntuple.alias_column_records + ] == [(0, alias_field), (1, ntuple["num_values"].field_id)] + assert ntuple.alias_column_records is ntuple.alias_column_records + + # the form of a projected field is the one of its source field + assert ntuple.col_form(alias_field) == ntuple.col_form(0) + + out = ntuple.arrays() + assert out.pt.to_list() == [0.0, 1.5, 3.0, 4.5] + assert out.pt_alias.to_list() == out.pt.to_list() + assert out.values.to_list() == [[], [1], [2, 2], [3, 3, 3]] + assert out.num_values.to_list() == [0, 1, 2, 3] + + +def test_virtual_cardinality_field(root, tmp_path): + path = tmp_path / "file.root" + root.write_projections(str(path)) + with uproot.open(path) as file: + out = file["ntuple"].arrays(filter_name="num_values", virtual=True) + assert ak.to_list(out.num_values) == [0, 1, 2, 3] + + +def test_streamer_field(root, tmp_path): + path = tmp_path / "file.root" + root.write_streamer_field(str(path)) + with uproot.open(path) as file: + ntuple = file["ntuple"] + record = ntuple["streamed"].record + assert record.struct_role == uproot.const.RNTupleFieldRole.STREAMER + assert record.type_name == "std::vector" + assert isinstance(record.checksum, int) + assert ntuple.arrays(filter_name="x").x.to_list() == [0, 1] + with pytest.raises(NotImplementedError, match="Unsplit fields are not"): + ntuple.arrays() + + +def test_rntuple_without_fields(root, tmp_path): + path = tmp_path / "file.root" + root.write_without_fields(str(path)) + with uproot.open(path) as file: + ntuple = file["ntuple"] + assert len(ntuple) == 0 + assert ntuple.keys() == [] + assert ntuple.num_entries == 0 + assert repr(ntuple).startswith(" Date: Fri, 6 Nov 2026 10:54:58 -0500 Subject: [PATCH 2/4] test: declare only the C++ that the RNTuple tests with ROOT use The ROOT fixture also declared classes and writers that only the tests of #1828 use; if any of them didn't compile with some ROOT version, the tests here would fail too. gErrorIgnoreLevel is now restored if something fails while it's lowered. The four LRUCache tests of test_1661 that test_1832_cov_api_cache.py replaces are deleted here. Assisted-by: Claude Code:claude-opus-5-5 --- tests/test_1661_fix_util_dask_cache.py | 53 +--------------- tests/test_1832_cov_api_tbranch.py | 8 ++- tests/test_1832_cov_rntuple_root.py | 84 +++----------------------- 3 files changed, 14 insertions(+), 131 deletions(-) diff --git a/tests/test_1661_fix_util_dask_cache.py b/tests/test_1661_fix_util_dask_cache.py index 417102443..8e28c4bc5 100644 --- a/tests/test_1661_fix_util_dask_cache.py +++ b/tests/test_1661_fix_util_dask_cache.py @@ -7,7 +7,8 @@ Covers: - maybe_steps leakage via uproot._util.regularize_files (finding 1) - damerau_levenshtein distance values (finding 2) -- LRU cache move-to-end behavior (finding 7) +- LRU cache under concurrent use (finding 7); its ordering is in + tests/test_1832_cov_api_cache.py """ import threading @@ -78,48 +79,6 @@ def test_damerau_levenshtein_no_ratio_param(): # --------------------------------------------------------------------------- -def test_lru_cache_eviction_order(): - """LRU evicts the least-recently *used* key, not insertion order.""" - c = LRUCache(3) - c["a"] = 1 - c["b"] = 2 - c["c"] = 3 - # Access "a" to make it most-recently used - _ = c["a"] - # Insert "d"; LRU is "b" → evict "b" - c["d"] = 4 - assert "b" not in c - assert "a" in c - assert "c" in c - assert "d" in c - assert len(c) == 3 - - -def test_lru_cache_setitem_update_moves_to_end(): - """Updating an existing key moves it to most-recently used.""" - c = LRUCache(3) - c["a"] = 1 - c["b"] = 2 - c["c"] = 3 - # Update "a" → it becomes MRU; "b" becomes LRU - c["a"] = 99 - c["d"] = 4 # evicts "b" - assert "b" not in c - assert c["a"] == 99 - - -def test_lru_cache_keys_order(): - """keys() returns list from LRU to MRU.""" - c = LRUCache(4) - c["x"] = 10 - c["y"] = 20 - c["z"] = 30 - _ = c["x"] # x is now MRU - keys = c.keys() - assert keys[-1] == "x", "most-recently used should be last" - assert keys[0] in ("y", "z"), "LRU should be first" - - def test_lru_cache_thread_safety(): """Concurrent gets and sets should neither raise nor lose track of the contents.""" c = LRUCache(50) @@ -148,11 +107,3 @@ def reader(): # all 200 keys were written, so the cache is full, and nothing got mismatched assert len(c) == c.current == 50 assert all(value == key * 2 for key, value in c.items()) - - -def test_lru_cache_no_limit(): - """limit=None means no eviction.""" - c = LRUCache(None) - for i in range(1000): - c[i] = i - assert len(c) == 1000 diff --git a/tests/test_1832_cov_api_tbranch.py b/tests/test_1832_cov_api_tbranch.py index 0142f8634..fd4e4bcef 100644 --- a/tests/test_1832_cov_api_tbranch.py +++ b/tests/test_1832_cov_api_tbranch.py @@ -596,9 +596,11 @@ def test_subbranches_with_the_same_name(tmp_path): parent = tree.Branch("p", values[0], "p/I") ignore_level = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError # ROOT warns about the second "c" - first = tree.Branch("c", values[1], "c/I") - second = tree.Branch("c", values[2], "c/I") - ROOT.gErrorIgnoreLevel = ignore_level + try: + first = tree.Branch("c", values[1], "c/I") + second = tree.Branch("c", values[2], "c/I") + finally: + ROOT.gErrorIgnoreLevel = ignore_level for i in range(3): values[0][0], values[1][0], values[2][0] = i, i * 10, i * 100 tree.Fill() diff --git a/tests/test_1832_cov_rntuple_root.py b/tests/test_1832_cov_rntuple_root.py index a1cc72dcd..fae39c2b5 100644 --- a/tests/test_1832_cov_rntuple_root.py +++ b/tests/test_1832_cov_rntuple_root.py @@ -15,30 +15,12 @@ #include #include #include -#include #include #include #include namespace test_1832 { -struct Base { - int member; - float other; -}; -struct Child : Base { - int member; -}; -struct Left { - int shared; -}; -struct Right { - int shared; -}; -struct Both : Left, Right { - int member; -}; - void write_projections(const char *path) { auto model = ROOT::RNTupleModel::Create(); @@ -61,23 +43,6 @@ } } -void write_shadowed_members(const char *path) -{ - auto model = ROOT::RNTupleModel::Create(); - auto child = model->MakeField("child"); - auto both = model->MakeField("both"); - auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); - for (int i = 0; i < 3; i++) { - child->member = i; - child->Base::member = 10 * i; - child->other = 0.5f * i; - both->member = 100 * i; - both->Left::shared = 200 * i; - both->Right::shared = 300 * i; - writer->Fill(); - } -} - void write_streamer_field(const char *path) { auto model = ROOT::RNTupleModel::Create(); @@ -99,13 +64,6 @@ auto writer = ROOT::RNTupleWriter::Recreate(ROOT::RNTupleModel::Create(), "ntuple", path); } -std::string show(const char *path, int entry) -{ - std::ostringstream stream; - ROOT::RNTupleReader::Open("ntuple", path)->Show(entry, stream); - return stream.str(); -} - // Show doesn't support variants std::string show_variant(const char *path, int entry) { @@ -120,49 +78,21 @@ } // namespace test_1832 """ -_ATTRIBUTE_WRITER = """ -#include - -namespace test_1832 { - -void write_attributes(const char *path) -{ - auto file = std::unique_ptr(TFile::Open(path, "RECREATE")); - auto model = ROOT::RNTupleModel::Create(); - auto x = model->MakeField("x"); - auto writer = ROOT::RNTupleWriter::Append(std::move(model), "ntuple", *file); - auto attribute_model = ROOT::RNTupleModel::Create(); - auto note = attribute_model->MakeField("note"); - auto attributes = writer->CreateAttributeSet(std::move(attribute_model), "my_attributes"); - auto range = attributes->BeginRange(); - *note = "a note"; - for (int i = 0; i < 4; i++) { - *x = i; - writer->Fill(); - } - attributes->CommitRange(std::move(range)); - writer.reset(); -} - -} // namespace test_1832 -""" - @pytest.fixture(scope="module") def root(): ROOT = pytest.importorskip("ROOT") if ROOT.gROOT.GetVersionInt() < 63800: pytest.skip("needs the RNTuple interfaces of a recent ROOT") - # ROOT warnings become Python warnings, which are errors in this test suite. The - # classes above have no dictionaries, which ROOT warns about. + # ROOT warnings become Python warnings, which are errors in this test suite ignore_level = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError - if not hasattr(ROOT, "test_1832"): - assert ROOT.gInterpreter.Declare(_WRITERS) - if ROOT.gROOT.GetVersionInt() >= 64000: - assert ROOT.gInterpreter.Declare(_ATTRIBUTE_WRITER) - yield ROOT.test_1832 - ROOT.gErrorIgnoreLevel = ignore_level + try: + if not hasattr(ROOT, "test_1832"): + assert ROOT.gInterpreter.Declare(_WRITERS) + yield ROOT.test_1832 + finally: + ROOT.gErrorIgnoreLevel = ignore_level def test_projected_fields(root, tmp_path): From e9eeba297dfaec9d214319c3e37810b7955ad479 Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Thu, 12 Nov 2026 11:01:49 -0500 Subject: [PATCH 3/4] test: drop the RNTuple extend test that #1812 replaced Extending an RNTuple with lists that are all empty now works, and test_1812 checks it, including that other mismatched types still fail. Assisted-by: Claude Code:claude-opus-5-5 --- tests/test_1832_cov_rntuple_writing.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/tests/test_1832_cov_rntuple_writing.py b/tests/test_1832_cov_rntuple_writing.py index 81c54eb6a..ec9f45f2d 100644 --- a/tests/test_1832_cov_rntuple_writing.py +++ b/tests/test_1832_cov_rntuple_writing.py @@ -32,13 +32,6 @@ def test_packed_union_does_not_change_the_input(): assert layout.index.data.tolist() == index.tolist() -def test_extend_with_lists_of_unknown_type(tmp_path): - with uproot.recreate(tmp_path / "file.root") as file: - ntuple = file.mkrntuple("ntuple", {"v": ak.Array([[1], [2, 3]])}) - with pytest.raises(ValueError, match="Data is not compatible"): - ntuple.extend({"v": ak.Array([[], []])}) - - def test_packing_an_unknown_form(): with pytest.raises(NotImplementedError, match="Form type .* cannot be written"): cascade._to_packed_form(object()) From 1a8505217bc71364db57c6f9f88f07d796a17e8b Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Thu, 12 Nov 2026 14:59:12 -0500 Subject: [PATCH 4/4] chore: use the new repo name in the links of the new tests Assisted-by: Claude Code:claude-opus-5-5 --- tests/test_1832_cov_api_cache.py | 2 +- tests/test_1832_cov_api_dask.py | 2 +- tests/test_1832_cov_api_graphed.py | 2 +- tests/test_1832_cov_api_read_options.py | 2 +- tests/test_1832_cov_api_tbranch.py | 2 +- tests/test_1832_cov_rntuple_api.py | 2 +- tests/test_1832_cov_rntuple_lowlevel.py | 2 +- tests/test_1832_cov_rntuple_numpy.py | 2 +- tests/test_1832_cov_rntuple_root.py | 2 +- tests/test_1832_cov_rntuple_writing.py | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/test_1832_cov_api_cache.py b/tests/test_1832_cov_api_cache.py index 081d6d2c4..3d8afee1f 100644 --- a/tests/test_1832_cov_api_cache.py +++ b/tests/test_1832_cov_api_cache.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_api_dask.py b/tests/test_1832_cov_api_dask.py index fca6e2aa0..a2b7f826a 100644 --- a/tests/test_1832_cov_api_dask.py +++ b/tests/test_1832_cov_api_dask.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_api_graphed.py b/tests/test_1832_cov_api_graphed.py index ff1410805..c702c522b 100644 --- a/tests/test_1832_cov_api_graphed.py +++ b/tests/test_1832_cov_api_graphed.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_api_read_options.py b/tests/test_1832_cov_api_read_options.py index 0cc69d58c..853f6a812 100644 --- a/tests/test_1832_cov_api_read_options.py +++ b/tests/test_1832_cov_api_read_options.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_api_tbranch.py b/tests/test_1832_cov_api_tbranch.py index fd4e4bcef..8b965a867 100644 --- a/tests/test_1832_cov_api_tbranch.py +++ b/tests/test_1832_cov_api_tbranch.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_rntuple_api.py b/tests/test_1832_cov_rntuple_api.py index 640c7ed7a..fc3547776 100644 --- a/tests/test_1832_cov_rntuple_api.py +++ b/tests/test_1832_cov_rntuple_api.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_rntuple_lowlevel.py b/tests/test_1832_cov_rntuple_lowlevel.py index 429f7e6f9..7b30e9682 100644 --- a/tests/test_1832_cov_rntuple_lowlevel.py +++ b/tests/test_1832_cov_rntuple_lowlevel.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_rntuple_numpy.py b/tests/test_1832_cov_rntuple_numpy.py index 9a48af98e..e358f6ccc 100644 --- a/tests/test_1832_cov_rntuple_numpy.py +++ b/tests/test_1832_cov_rntuple_numpy.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_rntuple_root.py b/tests/test_1832_cov_rntuple_root.py index fae39c2b5..5ee51ab52 100644 --- a/tests/test_1832_cov_rntuple_root.py +++ b/tests/test_1832_cov_rntuple_root.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations diff --git a/tests/test_1832_cov_rntuple_writing.py b/tests/test_1832_cov_rntuple_writing.py index ec9f45f2d..1cc435d18 100644 --- a/tests/test_1832_cov_rntuple_writing.py +++ b/tests/test_1832_cov_rntuple_writing.py @@ -1,4 +1,4 @@ -# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/main/LICENSE from __future__ import annotations