import logging import os import pytest from galaxy.tool_util.data import ( DataTableColumnMismatch, tool_data_table_config_sources, ToolDataTableConfigSource, ToolDataTableManager, ) MULTI_TABLE_CONF_XML = """ value, name, path
value, name, path
value, name, path
""" LOC_ALPHA_CONTENTS_V2 = """ data1 data1name ${__HERE__}/data1/entry.txt data2 data2name ${__HERE__}/data2/entry.txt data3 data3name ${__HERE__}/data3/entry.txt """ USER_ACCESSIBLE_TABLE_CONF_XML = """ value, name, path
""" COLUMN_DIVERGENT_TABLE_CONF_XML = """ value, name, path, extra
""" SHED_COLUMN_DIVERGENT_TABLE_CONF_XML = """ value, name, path, extra toolshed.g2.bx.psu.edu data_manager_example iuc abc123
""" def test_data_tables_as_dictionary(tdt_manager): assert "testalpha" in tdt_manager.data_tables assert "testdelta" not in tdt_manager.data_tables def test_to_dict(tdt_manager): as_dict = tdt_manager.to_dict() assert "testalpha" in as_dict assert "testdelta" not in as_dict testalpha_as_dict = as_dict["testalpha"] assert "columns" in testalpha_as_dict def test_index(tdt_manager): index = tdt_manager.index() assert len(index.root) >= 1 entry = index.find_entry("testalpha") assert entry entry = index.find_entry("testomega") assert not entry def test_reload(tdt_manager, tmp_path): assert len(tdt_manager["testalpha"].data) == 2 loc1 = tmp_path / "testalpha.loc" loc1.write_text(LOC_ALPHA_CONTENTS_V2) tdt_manager.reload_tables() assert len(tdt_manager["testalpha"].data) == 3 def test_reload_by_path(tdt_manager, tmp_path): assert len(tdt_manager["testalpha"].data) == 2 loc1 = tmp_path / "testalpha.loc" loc1.write_text(LOC_ALPHA_CONTENTS_V2) tdt_manager.reload_tables(path=str(loc1)) assert len(tdt_manager["testalpha"].data) == 3 def test_reload_by_name(tdt_manager, tmp_path): assert len(tdt_manager["testalpha"].data) == 2 loc1 = tmp_path / "testalpha.loc" loc1.write_text(LOC_ALPHA_CONTENTS_V2) tdt_manager.reload_tables("testalpha") assert len(tdt_manager["testalpha"].data) == 3 def test_merging_tables(merged_tdt_manager): assert len(merged_tdt_manager["testbeta"].data) == 2 def test_get_field_uses_first_entry_for_duplicate_values(tdt_manager): table = tdt_manager["testalpha"] first_entry = table.get_named_fields_list()[0] table.add_entry(["data1", "Another data1", "/other/data1.txt"]) field = table.get_field("data1") assert field is not None assert field.data == first_entry assert table.get_field("unknown") is None def test_merging_tables_preserves_distinct_rows_with_known_value(tmp_path, caplog): (tmp_path / "local.loc").write_text("hg38\tHuman (hg38)\t/local/hg38.fa\nmm10\tMouse (mm10)\t/local/mm10.fa\n") (tmp_path / "idc.loc").write_text( "hg38\tHuman (hg38)\t/idc/hg38.fa\nmm10\tMouse (mm10)\t/local/mm10.fa\ndm6\tFly (dm6)\t/idc/dm6.fa\n" ) confs = [] for name in ("local", "idc"): conf = tmp_path / f"{name}_tool_data_table_conf.xml" conf.write_text(f""" value, name, path
""") confs.append(str(conf)) with caplog.at_level(logging.WARNING, logger="galaxy.tool_util.data"): tdt_manager = ToolDataTableManager(tmp_path, ",".join(confs)) table = tdt_manager["all_fasta"] expected_data = [ ["hg38", "Human (hg38)", "/local/hg38.fa"], ["mm10", "Mouse (mm10)", "/local/mm10.fa"], ["hg38", "Human (hg38)", "/idc/hg38.fa"], ["dm6", "Fly (dm6)", "/idc/dm6.fa"], ] assert table.data == expected_data errors = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR] assert not errors warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] assert len(warnings) == 1 assert "this entry already exists and allow_duplicates is False" in warnings[0] # reloading re-applies the same merge rules table.reload_from_files() assert table.data == expected_data def test_to_json(merged_tdt_manager, tmp_path): json_path = tmp_path / "as_json.json" assert not json_path.exists() merged_tdt_manager.to_json(json_path) assert json_path.exists() def test_assert_data_table_consistency_accepts_new_table(tdt_manager): tdt_manager.assert_data_table_consistency( "brand_new_table", {"value": 0, "name": 1, "path": 2}, ) def test_assert_data_table_consistency_accepts_matching_redefinition(tdt_manager): existing = tdt_manager["testalpha"] tdt_manager.assert_data_table_consistency("testalpha", existing.columns) def test_assert_data_table_consistency_raises_column_mismatch(tdt_manager): with pytest.raises(DataTableColumnMismatch) as exc_info: tdt_manager.assert_data_table_consistency( "testalpha", {"value": 0, "name": 1, "path": 2, "extra": 3}, ) assert exc_info.value.table_name == "testalpha" @pytest.fixture def divergent_conf(tmp_path): loc_path = tmp_path / "divergent.loc" loc_path.write_text("data9\tdata9name\t/data9\textra9\n") conf = tmp_path / "divergent_tool_data_table_conf.xml" conf.write_text(COLUMN_DIVERGENT_TABLE_CONF_XML.format(loc_path=loc_path)) return conf def test_load_from_config_file_raises_column_mismatch(tdt_manager, tmp_path, divergent_conf): with pytest.raises(DataTableColumnMismatch) as exc_info: tdt_manager.load_from_config_file(divergent_conf, tmp_path) assert exc_info.value.table_name == "testalpha" assert exc_info.value.config_filename == divergent_conf assert exc_info.value.repository_info is None assert str(divergent_conf) in str(exc_info.value) def test_load_from_config_file_column_mismatch_names_repository(tdt_manager, tmp_path): loc_path = tmp_path / "divergent.loc" loc_path.write_text("data9\tdata9name\t/data9\textra9\n") conf = tmp_path / "shed_tool_data_table_conf.xml" conf.write_text(SHED_COLUMN_DIVERGENT_TABLE_CONF_XML.format(loc_path=loc_path)) with pytest.raises(DataTableColumnMismatch) as exc_info: tdt_manager.load_from_config_file(conf, tmp_path, from_shed_config=True) assert exc_info.value.repository_info == { "tool_shed": "toolshed.g2.bx.psu.edu", "name": "data_manager_example", "owner": "iuc", "installed_changeset_revision": "abc123", } assert "installed by repository iuc/data_manager_example revision abc123" in str(exc_info.value) assert tdt_manager["testalpha"].columns == {"value": 0, "name": 1, "path": 2} def test_merge_tool_data_table_raises_column_mismatch(tdt_manager, tmp_path, divergent_conf): divergent = ToolDataTableManager(tmp_path, divergent_conf)["testalpha"] table = tdt_manager["testalpha"] original_data = list(table.data) original_filenames = dict(table.filenames) with pytest.raises(DataTableColumnMismatch) as exc_info: table.merge_tool_data_table(divergent) assert exc_info.value.table_name == "testalpha" assert exc_info.value.incoming_columns == divergent.columns assert table.data == original_data assert table.filenames == original_filenames def test_get_filename_for_source_falls_back_to_shared_filename(tdt_manager): table = tdt_manager["testalpha"] [shared_filename] = list(table.filenames) assert table.filenames[shared_filename].get("tool_shed_repository") is None source_with_unknown_repo = { "tool_shed": "tool-shed", "repository_name": "repo", "repository_owner": "owner", "installed_changeset_revision": "abc", } assert table.get_filename_for_source(source_with_unknown_repo) == shared_filename def test_get_filename_for_source_prefers_exact_repo_match_over_shared(tdt_manager): table = tdt_manager["testalpha"] [shared_filename] = list(table.filenames) legacy_info = { "tool_shed": "tool-shed", "repository_name": "legacy", "repository_owner": "owner", "installed_changeset_revision": "deadbeef", } legacy_filename = f"{shared_filename}.legacy" table.filenames[legacy_filename] = dict( found=True, filename=legacy_filename, from_shed_config=True, tool_data_path=None, config_element=None, tool_shed_repository=legacy_info, errors=[], ) assert table.get_filename_for_source(legacy_info) == legacy_filename other_info = dict(legacy_info, repository_name="unknown") assert table.get_filename_for_source(other_info) == shared_filename def test_append_entries_with_attribution_appends_and_dedupes(tdt_manager): table = tdt_manager["testalpha"] [loc_filename] = list(table.filenames) initial_rows = len(table.data) new_entries = [ ["data3", "data3name", "${__HERE__}/data3/entry.txt"], ["data1", "data1name", "${__HERE__}/data1/entry.txt"], # duplicate, must be skipped ] table.append_entries_with_attribution(new_entries, "added by owner/foo@rev1") with open(loc_filename) as fh: contents = fh.read() assert "# added by owner/foo@rev1" in contents assert contents.count("data3\tdata3name") == 1 assert contents.count("data1\tdata1name") == 1 assert len(table.data) == initial_rows + 1 def test_append_entries_with_attribution_noop_when_all_duplicates(tdt_manager): table = tdt_manager["testalpha"] [loc_filename] = list(table.filenames) with open(loc_filename) as fh: before = fh.read() rows_before = list(table.data) table.append_entries_with_attribution( [["data1", "data1name", "${__HERE__}/data1/entry.txt"]], "added by owner/foo@rev1", ) with open(loc_filename) as fh: after = fh.read() assert after == before assert table.data == rows_before class CountingFilesystem: """Real filesystem access that records walk and exists calls. Injected via the ``filesystem`` constructor argument so the "walk once per load pass" invariant can be asserted with an actual implementation instead of monkeypatching ``os``. """ def __init__(self): self.walks = 0 self.exists_lookups = 0 def walk(self, path): self.walks += 1 return os.walk(path) def exists(self, path): self.exists_lookups += 1 return os.path.exists(path) def _write_multi_table_conf(tmp_path): for name in ("t1", "t2", "t3"): (tmp_path / f"{name}.loc").write_text(f"{name}\t{name}name\t/irrelevant\n") conf = tmp_path / "tool_data_table_conf.xml" conf.write_text(MULTI_TABLE_CONF_XML.format(here=str(tmp_path))) return conf def test_directory_walked_once_per_load_pass(tmp_path): # Regression: the tool-data tree must be walked once per load pass, not once # per exists() check. The many exists() calls a pass makes (at least one per # table) must all share a single walk. Guards ToolDataPathFiles.cached() # against the old per-call re-walk. conf = _write_multi_table_conf(tmp_path) fs = CountingFilesystem() manager = ToolDataTableManager(tmp_path, conf, filesystem=fs) assert {"t1", "t2", "t3"}.issubset(manager.data_tables) # One exists() per table (at least), but the tree is walked exactly once. assert fs.exists_lookups >= 3 assert fs.walks == 1, f"expected one walk per load pass, got {fs.walks}" def test_reload_walks_once_regardless_of_table_count(tmp_path): conf = _write_multi_table_conf(tmp_path) fs = CountingFilesystem() manager = ToolDataTableManager(tmp_path, conf, filesystem=fs) fs.walks = 0 manager.reload_tables() assert fs.walks == 1, f"expected one walk per reload pass, got {fs.walks}" def test_exists_outside_load_pass_does_not_walk(tmp_path): # Outside a load pass nothing is cached, so exists() falls back to the # filesystem and never walks -- the listing can't outlive disk state. conf = _write_multi_table_conf(tmp_path) fs = CountingFilesystem() manager = ToolDataTableManager(tmp_path, conf, filesystem=fs) tdpf = manager.tool_data_path_files fs.walks = 0 assert tdpf.exists(str(tmp_path / "t1.loc")) is True assert tdpf.exists(str(tmp_path / "missing.loc")) is False assert fs.walks == 0, f"exists() outside a load pass must not walk, got {fs.walks}" assert tdpf._tool_data_path_files is None def test_config_sources_and_config_filename_are_exclusive(tmp_path): conf = _write_multi_table_conf(tmp_path) with pytest.raises(ValueError, match="not both"): ToolDataTableManager(str(tmp_path), conf, config_sources=[ToolDataTableConfigSource(conf)]) @pytest.mark.parametrize("as_string", [False, True]) def test_config_sources_keep_first_managed_position_across_aliases(tmp_path, as_string): managed = tmp_path / "managed.xml" managed.write_text("") alias = tmp_path / "alias.xml" alias.symlink_to(managed) paths = [str(tmp_path / "local.xml"), str(alias), "", str(tmp_path / "external.xml"), str(managed)] sources = tool_data_table_config_sources( ",".join(p for p in paths if p) if as_string else paths, str(managed), from_shed_config=True, managed_optional=True, ) assert sources == [ ToolDataTableConfigSource(paths[0]), ToolDataTableConfigSource(paths[1], from_shed_config=True, optional=True), ToolDataTableConfigSource(paths[3]), ] @pytest.mark.parametrize("managed_optional", [False, True]) def test_config_sources_append_unlisted_managed_file(tmp_path, managed_optional): managed = str(tmp_path / "missing" / "managed.xml") sources = tool_data_table_config_sources( str(tmp_path / "local.xml"), managed, from_shed_config=False, managed_optional=managed_optional ) assert sources == [ ToolDataTableConfigSource(str(tmp_path / "local.xml")), ToolDataTableConfigSource(managed, optional=managed_optional), ] def _shared_table_conf(tmp_path, name: str, attributes: str) -> str: loc_path = tmp_path / f"{name}.loc" loc_path.write_text("a\tA\t/a\n") conf = tmp_path / f"{name}.xml" conf.write_text(USER_ACCESSIBLE_TABLE_CONF_XML.format(attributes=attributes, loc_path=loc_path)) return str(conf) @pytest.mark.parametrize( "attributes,expected", [("", False), ('user_accessible="false"', False), ('user_accessible="true"', True)], ) def test_tables_are_closed_to_user_tools_unless_opened(tmp_path, attributes, expected): conf = _shared_table_conf(tmp_path, "table", attributes) assert ToolDataTableManager(str(tmp_path), conf)["shared"].user_accessible is expected @pytest.mark.parametrize("first,second", [('user_accessible="true"', ""), ("", 'user_accessible="true"')]) def test_opening_a_table_in_one_config_survives_merging_in_either_order(tmp_path, first, second): configs = [_shared_table_conf(tmp_path, "one", first), _shared_table_conf(tmp_path, "two", second)] manager = ToolDataTableManager(str(tmp_path), config_sources=[ToolDataTableConfigSource(c) for c in configs]) assert manager["shared"].user_accessible is True manager.reload_tables() assert manager["shared"].user_accessible is True def test_tool_shed_repository_cannot_open_a_table(tmp_path): repository_conf = _shared_table_conf(tmp_path, "repository", 'user_accessible="true"') persisted_conf = tmp_path / "shed_tool_data_table_conf.xml" manager = ToolDataTableManager(str(tmp_path)) manager.add_new_entries_from_config_file(repository_conf, str(tmp_path), str(persisted_conf), persist=True) assert manager["shared"].user_accessible is False # The persisted shed config is later loaded like an admin's own. assert ToolDataTableManager(str(tmp_path), str(persisted_conf))["shared"].user_accessible is False