Files
Nicola Soranzo b86e88720c Drop support for Python 3.10
Python 3.10 reached its end-of-life in October 2026.

Also:
- Run `make pyupgrade` and `make format`
- Fix new ruff and mypy errors
- Run `uv lock` and `sh lib/galaxy/dependencies/update.sh --export-only`
- Run `make update-client-api-schema`
2026-11-17 21:57:50 +00:00

289 lines
8.8 KiB
Python

import errno
import os
import tempfile
from enum import StrEnum
from io import (
BytesIO,
StringIO,
)
from pathlib import Path
import pytest
from galaxy import util
from galaxy.util.json import safe_loads
SECTION_XML = """<?xml version="1.0" ?>
<section id="fasta_fastq_manipulation" name="Fasta Fastq Manipulation" version="">
<tool file="toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/fb1313d79396/seq_filter_by_id/tools/seq_filter_by_id/seq_filter_by_id.xml" guid="toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/seq_filter_by_id/0.2.5">
<tool_shed>
toolshed.g2.bx.psu.edu
</tool_shed>
</tool>
</section>
"""
def test_strip_control_characters():
s = "\x00bla"
assert util.strip_control_characters(s) == "bla"
def test_stream_to_path(tmp_path):
destination = tmp_path / "streamed"
assert util.stream_to_path(BytesIO(b"streamed content"), destination) == destination
assert destination.read_bytes() == b"streamed content"
def test_stream_to_open_named_file_compatibility(tmp_path):
destination = tmp_path / "streamed"
fd = os.open(destination, os.O_WRONLY | os.O_CREAT)
assert util.stream_to_open_named_file(BytesIO(b"streamed content"), fd, destination) == destination
assert destination.read_bytes() == b"streamed content"
with pytest.raises(OSError):
os.fstat(fd)
def test_filesystem_safe_string():
assert util.filesystem_safe_string(".sample/data") == "sample_data"
assert util.filesystem_safe_string("café") == "café"
assert util.filesystem_safe_string("...") == ""
assert util.filesystem_safe_string("...", fallback="_") == "_"
assert util.filesystem_safe_string("a" * 256).endswith("..")
assert len(util.filesystem_safe_string("a" * 256)) == 255
@pytest.mark.parametrize(
("identifier", "expected"),
[
("Plain HDA", "Plain_HDA"),
("../etc/passwd", "_etc_passwd"),
("..\\etc\\passwd", "_etc_passwd"),
(".", "_"),
("..", "_"),
("...", "_"),
("---", "_"),
(".-.", "_"),
("-.hidden", "hidden"),
(".-hidden", "hidden"),
("café", "caf_"),
("NUL", "_NUL"),
("CON.txt", "_CON.txt"),
("name.", "name"),
("x\x00y", "xy"),
("x\ny", "x_y"),
],
)
def test_safe_filename_component(identifier, expected):
assert util.safe_filename_component(identifier) == expected
assert util.safe_filename_component(identifier) == expected
def test_safe_filename_component_is_bounded_but_not_unique():
assert util.safe_filename_component("a/b") == util.safe_filename_component("a:b") == "a_b"
safe_identifier = util.safe_filename_component("a" * 255, max_len=20)
assert safe_identifier == f"{'a' * 18}__"
assert len(safe_identifier) == 20
def test_parse_xml_string():
section = util.parse_xml_string(SECTION_XML)
_verify_section(section)
def test_parse_xml_file():
with tempfile.NamedTemporaryFile(mode="w") as tmp:
tmp.write(SECTION_XML)
tmp.flush()
section = util.parse_xml(tmp.name).getroot()
_verify_section(section)
def _verify_section(section):
tool = next(iter(section))
assert sorted(tool.items()) == [
(
"file",
"toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/fb1313d79396/seq_filter_by_id/tools/seq_filter_by_id/seq_filter_by_id.xml",
),
("guid", "toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/seq_filter_by_id/0.2.5"),
]
assert next(iter(tool)).text == "toolshed.g2.bx.psu.edu"
def test_xml_to_string():
section = util.parse_xml_string(SECTION_XML)
s = util.xml_to_string(section)
assert len(s.split("\n")) == 1
def test_xml_to_string_pretty():
section = util.parse_xml_string(SECTION_XML)
s = util.xml_to_string(section, pretty=True)
PRETTY = """<?xml version="1.0" ?>
<section id="fasta_fastq_manipulation" name="Fasta Fastq Manipulation" version="">
<tool file="toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/fb1313d79396/seq_filter_by_id/tools/seq_filter_by_id/seq_filter_by_id.xml" guid="toolshed.g2.bx.psu.edu/repos/peterjc/seq_filter_by_id/seq_filter_by_id/0.2.5">
<tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
</tool>
</section>"""
assert s == PRETTY
def test_parse_xml_enoent():
with tempfile.NamedTemporaryFile() as temp:
path = temp.name
with pytest.raises(IOError) as excinfo:
util.parse_xml(path)
assert excinfo.value.errno == errno.ENOENT
def test_clean_multiline_string():
x = util.clean_multiline_string("""
a
b
c
""")
assert x == "a\nb\nc\n"
def test_iter_start_of_lines():
assert list(util.iter_start_of_line(StringIO("\n1\n\n12\n123\n1234\n"), 1)) == ["\n", "1", "\n", "1", "1", "1"]
def test_safe_loads():
d: dict[str, str] = {}
rval = safe_loads(d)
assert rval == d
assert rval is not d
rval["foo"] = "bar"
assert "foo" not in d
s = '{"foo": "bar"}'
assert safe_loads(s) == {"foo": "bar"}
def test_in_packages(monkeypatch):
util_path = Path(util.__file__).parent
assert util.in_packages() == (not str(util_path).endswith("lib/galaxy/util"))
def test_galaxy_directory(monkeypatch):
galaxy_dir = util.galaxy_directory()
assert os.path.isabs(galaxy_dir)
assert os.path.isfile(os.path.join(galaxy_dir, "run.sh"))
def test_listify() -> None:
assert util.listify(None) == []
assert util.listify(False) == []
assert util.listify(True) == [True]
assert util.listify("foo") == ["foo"]
assert util.listify("foo, bar") == ["foo", " bar"]
assert util.listify("foo, bar", do_strip=True) == ["foo", "bar"]
list_ = [1, 2, 3]
assert util.listify(list_) is list_
assert util.listify((1, 2, 3)) == [1, 2, 3]
s = {1, 2, 3}
assert util.listify(s) == [s]
d = {"a": 1, "b": 2, "c": 3}
assert util.listify(d) == [d]
o = object()
assert util.listify(o) == [o]
def test_enum_values():
class Stuff(StrEnum):
A = "a"
C = "c"
B = "b"
assert util.enum_values(Stuff) == ["a", "c", "b"]
DOI_VALID_VALUES = [
"https://doi.org/10.1234/42",
"doi.org/10.1234/42",
"doi:10.1234/42",
"doi:10.1234567890/42", # longer prefix
"doi:10.1234/42ab:%&*$//crazy-suffix/%/&/",
"doi:10.1234/aa",
"http://doi.org/10.1234/42",
"stillvalid:10.1234/42",
"dx.doi.org:10.1234/42",
"https://dx.doi.org:10.1234/42",
"httpss://dx.doi.org:10.1234/42",
]
@pytest.mark.parametrize("input", DOI_VALID_VALUES)
def test_validate_doi_pass(input):
assert util.validate_doi(input)
DOI_INVALID_VALUES = [
"doi:11.1234/42",
"doi:101234/42",
"doi:10. 1234/42",
"doi:10.abc/42",
"10.1234 /42/a b",
"doi:10.1234/ 42",
"doi:10.1234/42/a b",
]
@pytest.mark.parametrize("input", DOI_INVALID_VALUES)
def test_validate_doi_fail(input):
assert not util.validate_doi(input)
def test_validate_doi_fail_too_long():
long_suffix = "a" * (util.DOI_MAX_LENGTH - 12)
doi = f"doi:10.1000/{long_suffix}"
assert util.validate_doi(doi)
assert not util.validate_doi(doi + "a") # Increase length by 1 past max limit
@pytest.mark.parametrize(
"input_name,expected_output",
[
# Existing documented behavior
("My Cool Object", "My-Cool-Object"),
("!My Cool Object!", "My-Cool-Object"),
("Hello\u20a9\u25ce\u0491\u029f\u217e", "Hello"),
# Additional edge cases
("simple", "simple"),
("UPPERCASE", "UPPERCASE"), # Note: lowercase applied separately
("with-dash", "with-dash"),
("with spaces", "with-spaces"),
(" multiple spaces ", "-multiple-spaces"),
("trailing!", "trailing"),
("!leading", "leading"),
("special@#$chars", "specialchars"),
("parentheses(test)", "parenthesestest"),
("Rincewind (Ankh-Morpork)", "Rincewind-Ankh-Morpork"),
],
)
def test_ready_name_for_url(input_name, expected_output):
"""Test that ready_name_for_url correctly sanitizes names for URL use."""
assert util.ready_name_for_url(input_name) == expected_output
@pytest.mark.parametrize(
"target,expected_substring",
[
("normal.txt", 'filename="normal.txt"'),
("file.gz ", 'filename="file.gz"'),
(" file.gz", 'filename="file.gz"'),
(" file.gz ", 'filename="file.gz"'),
("Galaxy102-[name].fastqsanger.gz ", 'filename="Galaxy102-[name].fastqsanger.gz"'),
],
)
@pytest.mark.parametrize("disposition", ["attachment", "inline"])
def test_to_content_disposition(target, expected_substring, disposition):
result = util.to_content_disposition(target, disposition=disposition)
assert result.startswith(f"{disposition}; ")
assert expected_substring in result
# Ensure no trailing whitespace in the header value
assert result == result.strip()