diff --git a/src/qeval/base_commands/__init__.py b/src/qeval/base_commands/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/qeval/base_commands/benchmark_queries.py b/src/qeval/base_commands/benchmark_queries.py new file mode 100644 index 00000000..adeff742 --- /dev/null +++ b/src/qeval/base_commands/benchmark_queries.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from abc import abstractmethod + +from qeval.base_commands.index_stats import BaseIndexStatsCommand +from qlever.commands.benchmark_queries import ( + BenchmarkQueriesCommand as QleverBenchmarkQueriesCommand, +) + + +class BaseBenchmarkQueriesCommand(QleverBenchmarkQueriesCommand): + """ + Run benchmark queries against the SPARQL endpoint of an engine. + """ + + @abstractmethod + def index_stats_command(self) -> BaseIndexStatsCommand: + """The command that reads the index time and size of the engine.""" + + def can_clear_cache(self, args, engine: str | None) -> bool: + # Clearing the cache before each query only works for QLever. + return False diff --git a/src/qeval/base_commands/index_stats.py b/src/qeval/base_commands/index_stats.py new file mode 100644 index 00000000..614cf2c1 --- /dev/null +++ b/src/qeval/base_commands/index_stats.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from abc import abstractmethod +from pathlib import Path + +from qlever.commands.index_stats import ( + IndexStatsCommand as QleverIndexStatsCommand, +) +from qlever.commands.index_stats import ( + get_size_unit, + get_size_unit_factor, + get_time_unit, + get_time_unit_factor, +) +from qlever.log import log +from qlever.util import get_total_file_size + + +def read_index_log(log_file_name: str | Path) -> str | None: + """ + The text of the index log, or None if it cannot be read, which is + reported as an error. + """ + try: + return Path(log_file_name).read_text(errors="replace") + except OSError as e: + log.error(f"Problem reading index log file {log_file_name}: {e}") + return None + + +class BaseIndexStatsCommand(QleverIndexStatsCommand): + """ + Show how long the index build of an engine took and how much space its + index uses, from the durations in its index log and the size of its + index files. + """ + + @abstractmethod + def index_size_patterns(self, args) -> list[str]: + """The glob patterns of the index files, whose sizes add up.""" + + @abstractmethod + def parse_index_durations(self, log_text: str) -> dict[str, float]: + """ + How long each phase of the build took in seconds, from the text of + the index log, in the order to show them. The result files of + `benchmark-queries` take the index time from the "TOTAL time" entry. + """ + + def index_durations(self, log_file_name: str | Path) -> dict[str, float]: + """ + Read the index log and parse it. Empty if the log cannot be read. + """ + log_text = read_index_log(log_file_name) + if log_text is None: + return {} + return self.parse_index_durations(log_text) + + def execute_time( + self, args, log_file_name: str + ) -> dict[str, tuple[float | None, str]]: + """ + The duration of each phase, all in the same unit, picked to suit + the longest one. + """ + durations = self.index_durations(log_file_name) + if not durations: + return {} + time_unit = get_time_unit(args.time_unit, max(durations.values())) + unit_factor = get_time_unit_factor(time_unit) + return { + heading: (seconds / unit_factor, time_unit) + for heading, seconds in durations.items() + } + + def execute_space(self, args) -> dict[str, tuple[float, str]]: + """The total size of the index files, in a unit that suits it.""" + index_size = get_total_file_size(self.index_size_patterns(args)) + size_unit = get_size_unit(args.size_unit, index_size) + unit_factor = get_size_unit_factor(size_unit) + return {"TOTAL size": (index_size / unit_factor, size_unit)} diff --git a/src/qeval/base_commands/query.py b/src/qeval/base_commands/query.py new file mode 100644 index 00000000..305b2b0c --- /dev/null +++ b/src/qeval/base_commands/query.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from qlever.commands.query import QueryCommand as QleverQueryCommand + + +class BaseQueryCommand(QleverQueryCommand): + """ + Send a query to the SPARQL endpoint of an engine. QLever's option to pin + the result to its cache, and the access token that this needs, are left + out. + """ + + def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: + return {"server": ["host_name", "port"]} + + def accept_header_choices(self) -> list[str]: + return [ + "text/tab-separated-values", + "text/csv", + "application/sparql-results+json", + "application/sparql-results+xml", + ] + + def can_pin_to_cache(self) -> bool: + return False diff --git a/src/qeval/base_commands/setup_config.py b/src/qeval/base_commands/setup_config.py new file mode 100644 index 00000000..91575387 --- /dev/null +++ b/src/qeval/base_commands/setup_config.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from abc import abstractmethod +from pathlib import Path + +from qlever.commands.setup_config import ( + SetupConfigCommand as QleverSetupConfigCommand, +) +from qlever.commands.setup_config import check_qleverfile_exists +from qlever.log import log +from qlever.qleverfile import Qleverfile + + +class BaseSetupConfigCommand(QleverSetupConfigCommand): + """ + Create a Qleverfile for an engine from one of QLever's pre-configured + Qleverfiles: keep only the parts that every engine needs, then add the + engine's image and its own settings. + """ + + def filter_criteria(self) -> dict[str, list[str] | None]: + """ + The sections and options of a pre-configured Qleverfile to keep, by + default those that every engine needs. `None` keeps every option of + the section. An engine that needs more can add to what this returns. + """ + return { + "data": None, + "index": ["INPUT_FILES"], + "server": ["PORT"], + "runtime": ["SYSTEM", "IMAGE"], + "ui": ["UI_CONFIG"], + } + + @abstractmethod + def image(self) -> str: + """The container image of the engine.""" + + @abstractmethod + def engine_settings(self, args) -> dict[str, dict[str, str]]: + """The engine's own Qleverfile values, as {section: {option: value}}.""" + + def execute(self, args) -> bool: + template_path = ( + self.qleverfiles_path / f"Qleverfile.{args.config_name}" + ) + self.show( + f"Create a Qleverfile from {template_path}, keeping only the " + "parts that apply to this graph database", + only_show=args.show, + ) + if args.show: + return True + + if check_qleverfile_exists(args.main_command_name): + return False + + # Each step can override the values of the steps before it. + try: + qleverfile = Qleverfile.filter( + template_path, self.filter_criteria() + ) + qleverfile.set("runtime", "IMAGE", self.image()) + for section, options in self.engine_settings(args).items(): + # Skip sections that the pre-configured Qleverfile lacks. + if qleverfile.has_section(section): + for option, value in options.items(): + qleverfile.set(section, option, value) + for section, arg_name in self.override_args: + if arg_value := getattr(args, arg_name): + qleverfile.set(section, arg_name.upper(), str(arg_value)) + with Path("Qleverfile").open("w") as qleverfile_file: + qleverfile.write(qleverfile_file) + except Exception as e: + log.error(f"Could not create the Qleverfile: {e}") + return False + + log.info( + f'Created Qleverfile for config "{args.config_name}" in the ' + "current directory" + ) + return True diff --git a/src/qeval/base_commands/status.py b/src/qeval/base_commands/status.py new file mode 100644 index 00000000..a4d6eca5 --- /dev/null +++ b/src/qeval/base_commands/status.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from abc import abstractmethod + +from qlever.commands.status import StatusCommand as QleverStatusCommand + + +class BaseStatusCommand(QleverStatusCommand): + """ + Show the processes of an engine. + """ + + @abstractmethod + def default_regex(self) -> str: + """Regex for the command lines of the engine's processes.""" + + def description(self) -> str: + return ( + "Show the processes of this graph database running on this machine" + ) diff --git a/src/qeval/base_commands/stop.py b/src/qeval/base_commands/stop.py new file mode 100644 index 00000000..d89a001d --- /dev/null +++ b/src/qeval/base_commands/stop.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from abc import abstractmethod + +from qeval.base_commands.status import BaseStatusCommand +from qlever.commands.stop import StopCommand as QleverStopCommand + + +class BaseStopCommand(QleverStopCommand): + """ + Stop the server of an engine for a given dataset, like QLever's `stop` + but without systemd: stop its container if there is one, otherwise kill + the processes that match a regex. + """ + + @abstractmethod + def default_regex(self) -> str: + """ + Regex for the command line of the engine's server, where `%%NAME%%` + stands for the dataset name. + """ + + @abstractmethod + def status_command(self) -> BaseStatusCommand: + """The engine's `status` command, shown when no server matches.""" + + @abstractmethod + def status_regex(self) -> str: + """Regex for the command lines of all the engine's servers.""" + + def description(self) -> str: + return "Stop the server of this graph database for a given dataset" + + def systemd_unit(self, name: str) -> str | None: + # Only QLever runs its server as a systemd unit so far. + return None diff --git a/src/qeval/config.py b/src/qeval/config.py index 79678a77..215139ba 100644 --- a/src/qeval/config.py +++ b/src/qeval/config.py @@ -63,7 +63,7 @@ def parse_command_line() -> argparse.Namespace: tool_description = ( f"{SCRIPT_NAME} sets up, indexes, queries, and benchmarks " "graph databases in a uniform way. " - f"Supported engines: {supported_engines}" + f"Supported graph databases: {supported_engines}" ) parser = argparse.ArgumentParser( description=colored(tool_description, attrs=["bold"]) @@ -99,6 +99,7 @@ def parse_command_line() -> argparse.Namespace: script_name=SCRIPT_NAME, engine_short_name=engine, engine_display_name=engine_info.display_name, + endpoint_path=engine_info.endpoint_path, main_command_name=main_command_name, ) subparsers = engine_parser.add_subparsers( diff --git a/src/qeval/engines.py b/src/qeval/engines.py index d9d39cca..83e67a9b 100644 --- a/src/qeval/engines.py +++ b/src/qeval/engines.py @@ -6,16 +6,19 @@ class Engine(NamedTuple): """ - The package with the commands of an engine, and the name of the engine as - shown to the user. + The package with the commands of an engine, the name of the engine as + shown to the user, and the path of its SPARQL endpoint on the server. """ package: str display_name: str + endpoint_path: str ENGINES = { - "qlever": Engine(package="qlever", display_name="QLever"), + "qlever": Engine( + package="qlever", display_name="QLever", endpoint_path="/" + ), } diff --git a/src/qlever/commands/benchmark_queries.py b/src/qlever/commands/benchmark_queries.py index 92652987..e0e0aaaf 100644 --- a/src/qlever/commands/benchmark_queries.py +++ b/src/qlever/commands/benchmark_queries.py @@ -737,6 +737,23 @@ def additional_arguments(self, subparser) -> None: ), ) + def index_stats_command(self) -> IndexStatsCommand: + """The command that reads the index time and size of the engine.""" + return IndexStatsCommand() + + def can_clear_cache(self, args, engine: str | None) -> bool: + """ + Whether the cache can be cleared before each query. Only QLever can + do that, so guess from the endpoint and the result file name. + """ + is_qlever = ( + not args.sparql_endpoint + or args.sparql_endpoint.startswith("https://qlever") + ) + if engine is not None: + is_qlever = is_qlever or "qlever" in engine.lower() + return is_qlever + def execute(self, args) -> bool: # We can't have both `--remove-offset-and-limit` and `--limit`. if args.remove_offset_and_limit and args.limit: @@ -821,14 +838,8 @@ def execute(self, args) -> bool: return False # Clear cache only works for QLever. - is_qlever = ( - not args.sparql_endpoint - or args.sparql_endpoint.startswith("https://qlever") - ) - if engine is not None: - is_qlever = is_qlever or "qlever" in engine.lower() if args.clear_cache == "yes": - if is_qlever: + if self.can_clear_cache(args, engine): log.warning( "Clearing the cache before each query" " (only works for QLever)" @@ -845,7 +856,8 @@ def execute(self, args) -> bool: f"curl -sv https://qlever.dev/api/examples/{args.ui_config}" ) sparql_endpoint = ( - args.sparql_endpoint or f"{args.host_name}:{args.port}" + args.sparql_endpoint + or f"{args.host_name}:{args.port}{args.endpoint_path}" ) self.show( @@ -909,7 +921,9 @@ def execute(self, args) -> bool: if args.result_file: result_yml_query_records["timeout"] = timeout - index_time, index_size = compute_index_stats(IndexStatsCommand()) + index_time, index_size = compute_index_stats( + self.index_stats_command() + ) result_yml_query_records["index_time"] = index_time result_yml_query_records["index_size"] = index_size diff --git a/src/qlever/commands/index_stats.py b/src/qlever/commands/index_stats.py index e6bc9022..1e82e906 100644 --- a/src/qlever/commands/index_stats.py +++ b/src/qlever/commands/index_stats.py @@ -293,9 +293,8 @@ def execute(self, args) -> bool: # that messages about a missing or incomplete log appear below it. if not args.only_space: self.show( - f"Breakdown of the time used for " - f"building the index, based on the timestamps for key " - f'lines in "{log_file_name}"', + "Breakdown of the time used for building the index, " + f'based on key lines in "{log_file_name}"', only_show=args.show, ) diff --git a/src/qlever/commands/query.py b/src/qlever/commands/query.py index a2005ad1..3367c22d 100644 --- a/src/qlever/commands/query.py +++ b/src/qlever/commands/query.py @@ -40,6 +40,21 @@ def should_have_qleverfile(self) -> bool: def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: return {"server": ["host_name", "port", "access_token"]} + def accept_header_choices(self) -> list[str]: + """The media types that `--accept` offers.""" + return [ + "text/tab-separated-values", + "text/csv", + "application/sparql-results+json", + "application/sparql-results+xml", + "application/qlever-results+json", + "application/octet-stream", + ] + + def can_pin_to_cache(self) -> bool: + """Whether `--pin-to-cache` is offered, which needs an access token.""" + return True + def additional_arguments(self, subparser) -> None: subparser.add_argument( "query", @@ -54,26 +69,23 @@ def additional_arguments(self, subparser) -> None: choices=self.predefined_queries.keys(), help="Use a predefined query", ) - subparser.add_argument( - "--pin-to-cache", - action="store_true", - default=False, - help="Pin the query to the cache", - ) + if self.can_pin_to_cache(): + subparser.add_argument( + "--pin-to-cache", + action="store_true", + default=False, + help="Pin the query to the cache", + ) + else: + # `execute` reads this option, so it needs a value. + subparser.set_defaults(pin_to_cache=False) subparser.add_argument( "--sparql-endpoint", type=str, help="URL of the SPARQL endpoint" ) subparser.add_argument( "--accept", type=str, - choices=[ - "text/tab-separated-values", - "text/csv", - "application/sparql-results+json", - "application/sparql-results+xml", - "application/qlever-results+json", - "application/octet-stream", - ], + choices=self.accept_header_choices(), default="text/tab-separated-values", help="Accept header for the SPARQL query", ) @@ -110,7 +122,7 @@ def execute(self, args) -> bool: sparql_endpoint = ( args.sparql_endpoint if args.sparql_endpoint - else f"{args.host_name}:{args.port}" + else f"{args.host_name}:{args.port}{args.endpoint_path}" ) curl_cmd = ( f"curl -s {sparql_endpoint}" diff --git a/src/qlever/commands/status.py b/src/qlever/commands/status.py index e9a89a2c..72b1dd34 100644 --- a/src/qlever/commands/status.py +++ b/src/qlever/commands/status.py @@ -23,14 +23,18 @@ def should_have_qleverfile(self) -> bool: def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: return {} + def default_regex(self) -> str: + """Regex for the command lines of QLever's processes.""" + # A server that runs as a systemd unit (see `start`) has the + # absolute path of its binary in its command line, because + # `systemd-run` resolves it; a server started with `nohup` has + # the name as given in `SERVER_BINARY`. + return r"^(\S*/)?(qlever-server|qlever-index)" + def additional_arguments(self, subparser) -> None: subparser.add_argument( "--cmdline-regex", - # A server that runs as a systemd unit (see `start`) has the - # absolute path of its binary in its command line, because - # `systemd-run` resolves it; a server started with `nohup` has - # the name as given in `SERVER_BINARY`. - default=r"^(\S*/)?(qlever-server|qlever-index)", + default=self.default_regex(), help="Show only processes where the command " "line matches this regex", ) diff --git a/src/qlever/commands/stop.py b/src/qlever/commands/stop.py index 0fb7f4e4..b69df161 100644 --- a/src/qlever/commands/stop.py +++ b/src/qlever/commands/stop.py @@ -50,10 +50,32 @@ def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: "runtime": ["server_container"], } + def default_regex(self) -> str: + """ + Regex for the command line of the server, where `%%NAME%%` stands for + the dataset name. + """ + return "qlever-server.* -i [^ ]*%%NAME%%" + + def systemd_unit(self, name: str) -> str | None: + """ + The systemd unit the server for dataset `name` may run in, or None if + it never does. + """ + return systemd_unit_name(name) + + def status_command(self) -> StatusCommand: + """The `status` command, shown when no server matches.""" + return StatusCommand() + + def status_regex(self) -> str: + """Regex for the command lines of all servers, shown by `status`.""" + return r"^(\S*/)?qlever-server.* -i [^ ]*" + def additional_arguments(self, subparser) -> None: subparser.add_argument( "--cmdline-regex", - default="qlever-server.* -i [^ ]*%%NAME%%", + default=self.default_regex(), help="Show only processes where the command " "line matches this regex", ) @@ -81,15 +103,18 @@ def execute(self, args) -> bool: # be stopped via its unit (otherwise it would just be restarted). A # unit that is not active any more (for example, one that has hit its # start limit) is only cleaned up, and the search for the server - # continues below. - unit = systemd_unit_name(args.name) - unit_was_active = systemd_unit_is_active(unit) - if stop_systemd_unit(unit): - if unit_was_active: - log.info(f'Systemd unit "{unit}" stopped') - return True - log.info(f'Systemd unit "{unit}" was not active any more, removed') - log.info("") + # continues below. An engine that never uses systemd has no unit. + unit = self.systemd_unit(args.name) + if unit is not None: + unit_was_active = systemd_unit_is_active(unit) + if stop_systemd_unit(unit): + if unit_was_active: + log.info(f'Systemd unit "{unit}" stopped') + return True + log.info( + f'Systemd unit "{unit}" was not active any more, removed' + ) + log.info("") # First check if there is container running and if yes, stop and remove # it (unless the user has specified `--no-containers`). @@ -114,7 +139,7 @@ def execute(self, args) -> bool: else "No matching process or container found" ) log.error(message) - args.cmdline_regex = r"^(\S*/)?qlever-server.* -i [^ ]*" + args.cmdline_regex = self.status_regex() log.info("") - StatusCommand().execute(args) + self.status_command().execute(args) return True diff --git a/src/qlever/config.py b/src/qlever/config.py index 802925de..e8f05c2b 100644 --- a/src/qlever/config.py +++ b/src/qlever/config.py @@ -278,14 +278,15 @@ def parse_command_line() -> argparse.Namespace: # The name of the script (the console script from `pyproject.toml`), the # short name of the engine (used for the container names), the name of the - # engine as shown to the user, and the name of the main command (what the - # user types before a command, which for a script that supports several - # engines may consist of more than one word). These are provided to all - # commands via `args`. + # engine as shown to the user, the path of its SPARQL endpoint on the + # server, and the name of the main command (what the user types before a + # command, which for a script that supports several engines may consist + # of more than one word). These are provided to all commands via `args`. parser.set_defaults( script_name="qlever", engine_short_name="qlever", engine_display_name="QLever", + endpoint_path="/", main_command_name="qlever", ) diff --git a/src/qlever/qleverfile.py b/src/qlever/qleverfile.py index 7136487f..46637d0d 100644 --- a/src/qlever/qleverfile.py +++ b/src/qlever/qleverfile.py @@ -776,14 +776,15 @@ def read(qleverfile_path: Path, engine_short_name: str) -> ConfigParser: @staticmethod def filter( - qleverfile_path: Path, options_included: dict[str, list[str]] + qleverfile_path: Path, options_included: dict[str, list[str] | None] ) -> RawConfigParser: """ Given a filter criteria (key: section_header, value: list[options]), return a RawConfigParser object to create a new filtered Qleverfile - with only the specified sections and options (selects all options if - list[options] is empty). Mainly to be used by `qeval` for the - `setup-config` command of non-qlever engines. + with only the specified sections and options (a value of `None` keeps + every option of the section, an empty list keeps the section without + options). Mainly to be used by `qeval` for the `setup-config` command + of non-qlever engines. """ # Read the Qleverfile. config = RawConfigParser() @@ -797,8 +798,8 @@ def filter( if config.has_section(section): filtered_config.add_section(section) - # If the list is empty, copy all fields - if not desired_fields: + # Without a list of fields, copy all of them. + if desired_fields is None: for field, value in config.items(section): filtered_config.set(section, field, value) else: diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 index 00000000..e8919e1c --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,40 @@ +import os +from unittest.mock import MagicMock + +import pytest + + +# A signal to a process id or group of 1 or less goes to the caller's own +# group (0), to every process of the user (-1, which is also what `killpg(1)` +# means), or to a group given as a negative number. No test may do that: on +# 2026-09-13, a `killpg` with the `pid` of a mocked `Popen` (a `MagicMock`, +# which evaluates to 1) killed every process of the user on two machines, +# including the production servers. Such a call now fails the test instead. +@pytest.fixture(autouse=True) +def no_broadcast_signals(monkeypatch): + def guarded(name, original): + def send(target, sig, *rest): + if not isinstance(target, int) or target <= 1: + raise AssertionError( + f"os.{name}({target!r}, {sig!r}) would signal processes " + "that are not children of the test, refused" + ) + return original(target, sig, *rest) + + return send + + monkeypatch.setattr(os, "kill", guarded("kill", os.kill)) + monkeypatch.setattr(os, "killpg", guarded("killpg", os.killpg)) + + +@pytest.fixture +def mock_command(monkeypatch): + def _mock(module_name: str, function_name: str, override=None): + if override: + monkeypatch.setattr(f"{module_name}.{function_name}", override) + return override + mock = MagicMock(name=f"{function_name}_mock") + monkeypatch.setattr(f"{module_name}.{function_name}", mock) + return mock + + return _mock diff --git a/test/qeval/base_commands/conftest.py b/test/qeval/base_commands/conftest.py new file mode 100644 index 00000000..1d7afb9f --- /dev/null +++ b/test/qeval/base_commands/conftest.py @@ -0,0 +1,51 @@ +import argparse + +import pytest + +from qeval.base_commands.index_stats import BaseIndexStatsCommand +from qlever.config import add_subparser_for_command +from qlever.qleverfile import Qleverfile + + +class FakeIndexStatsCommand(BaseIndexStatsCommand): + def index_size_patterns(self, args): + return [f"{args.name}.fake-index.*"] + + def parse_index_durations(self, log_text): + phases = (line.rsplit(maxsplit=1) for line in log_text.splitlines()) + return {heading: float(seconds) for heading, seconds in phases} + + +@pytest.fixture +def fake_index_stats(): + """ + The `index-stats` command of a fake engine. Its index log has one line + per phase, like `TOTAL time 90`, and its index files are the files + `.fake-index.*`. + """ + return FakeIndexStatsCommand() + + +@pytest.fixture +def parse_args(): + """Parse a command line with the real parser of a command.""" + + def parse(command, argv): + parser = argparse.ArgumentParser() + parser.set_defaults( + script_name="qeval", + engine_short_name="fake", + engine_display_name="Fake", + endpoint_path="/sparql", + main_command_name="qeval fake", + ) + subparsers = parser.add_subparsers() + add_subparser_for_command( + subparsers, + "cmd", + command, + Qleverfile.all_arguments("qeval fake"), + ) + return parser.parse_args(["cmd", *argv]) + + return parse diff --git a/test/qeval/base_commands/test_base_benchmark_queries.py b/test/qeval/base_commands/test_base_benchmark_queries.py new file mode 100644 index 00000000..1ab7a5c8 --- /dev/null +++ b/test/qeval/base_commands/test_base_benchmark_queries.py @@ -0,0 +1,104 @@ +from pathlib import Path + +import yaml + +from qeval.base_commands.benchmark_queries import BaseBenchmarkQueriesCommand + +QUERIES_YML = """\ +name: Fake benchmark +description: Two small queries +queries: + - name: q1 + description: All triples + query: SELECT * WHERE { ?s ?p ?o } + - name: q2 + description: All subjects + query: SELECT ?s WHERE { ?s ?p ?o } +""" + + +class FakeBenchmarkQueriesCommand(BaseBenchmarkQueriesCommand): + def __init__(self, index_stats=None): + super().__init__() + self.index_stats = index_stats + + def index_stats_command(self): + return self.index_stats + + +def test_base_benchmark_queries_ignores_clear_cache(parse_args): + command = FakeBenchmarkQueriesCommand() + args = parse_args( + command, + [ + "--queries-tsv", + "queries.tsv", + "--accept", + "text/tab-separated-values", + "--clear-cache", + "yes", + "--show", + ], + ) + + assert command.execute(args) + + assert args.clear_cache == "no" + + +def test_base_benchmark_queries_writes_result_file( + parse_args, fake_index_stats, mock_command, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "queries.yml").write_text(QUERIES_YML) + (tmp_path / "olympics.index-log.txt").write_text("TOTAL time 90\n") + (tmp_path / "olympics.fake-index.data").write_bytes(b"x" * 1000) + + def write_result(url, headers, params, result_file, max_time): + Path(result_file).write_text("?s\n\n\n") + return "200" + + curl = mock_command( + "qlever.commands.benchmark_queries", "run_curl_command" + ) + # Each query gets a result with two rows. + curl.side_effect = write_result + # Pretty-printing runs a container, without it the query is kept as is. + mock_command( + "qlever.commands.benchmark_queries", "pretty_printed_query" + ).return_value = None + + command = FakeBenchmarkQueriesCommand(fake_index_stats) + args = parse_args( + command, + [ + "--queries-yml", + "queries.yml", + "--accept", + "text/tab-separated-values", + "--host-name", + "localhost", + "--port", + "7878", + "--result-file", + "olympics.fake", + ], + ) + + assert command.execute(args) + + assert [call.args[0] for call in curl.call_args_list] == [ + "localhost:7878/sparql", + "localhost:7878/sparql", + ] + results = yaml.safe_load( + (tmp_path / "olympics.fake.results.yaml").read_text() + ) + assert results["name"] == "Fake benchmark" + assert results["description"] == "Two small queries" + assert results["index_time"] == 90.0 + assert results["index_size"] == 1000 + assert [ + (query["name"], query["description"], query["result_size"]) + for query in results["queries"] + ] == [("q1", "All triples", 2), ("q2", "All subjects", 2)] diff --git a/test/qeval/base_commands/test_base_index_stats.py b/test/qeval/base_commands/test_base_index_stats.py new file mode 100644 index 00000000..8527c4cf --- /dev/null +++ b/test/qeval/base_commands/test_base_index_stats.py @@ -0,0 +1,69 @@ +import pytest + +from qlever.commands.benchmark_queries import compute_index_stats + + +@pytest.mark.parametrize( + "time_unit,expected", + [ + # Both phases in hours, picked to suit the longer one. + ("auto", {"Parse": (30 / 3600, "h"), "Build": (2.0, "h")}), + ("min", {"Parse": (0.5, "min"), "Build": (120.0, "min")}), + ], +) +def test_base_index_stats_time_unit_suits_longest_phase( + parse_args, fake_index_stats, tmp_path, time_unit, expected +): + log_path = tmp_path / "olympics.index-log.txt" + log_path.write_text("Parse 30\nBuild 7200\n") + args = parse_args( + fake_index_stats, ["--name", "olympics", "--time-unit", time_unit] + ) + + assert fake_index_stats.execute_time(args, log_path) == expected + + +def test_base_index_stats_adds_up_index_files( + parse_args, fake_index_stats, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.fake-index.data").write_bytes(b"x" * 1000) + (tmp_path / "olympics.fake-index.meta").write_bytes(b"x" * 500) + # Not an index file of the engine, so it does not count. + (tmp_path / "olympics.other").write_bytes(b"x" * 999) + args = parse_args(fake_index_stats, ["--name", "olympics"]) + + assert fake_index_stats.execute_space(args) == {"TOTAL size": (1500, "B")} + + +def test_base_index_stats_succeeds_with_log_and_index_files( + parse_args, fake_index_stats, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.index-log.txt").write_text("Parse 30\n") + (tmp_path / "olympics.fake-index.data").write_bytes(b"x" * 1000) + args = parse_args(fake_index_stats, ["--name", "olympics"]) + + assert fake_index_stats.execute(args) + + +def test_base_index_stats_fails_without_log( + parse_args, fake_index_stats, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.fake-index.data").write_bytes(b"x" * 1000) + args = parse_args(fake_index_stats, ["--name", "olympics"]) + + assert not fake_index_stats.execute(args) + + +def test_base_index_stats_gives_benchmark_total_time_and_size( + fake_index_stats, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.index-log.txt").write_text( + "Load 60\nTOTAL time 90\n" + ) + (tmp_path / "olympics.fake-index.data").write_bytes(b"x" * 1000) + + assert compute_index_stats(fake_index_stats) == (90.0, 1000) diff --git a/test/qeval/base_commands/test_base_query.py b/test/qeval/base_commands/test_base_query.py new file mode 100644 index 00000000..888a39c2 --- /dev/null +++ b/test/qeval/base_commands/test_base_query.py @@ -0,0 +1,37 @@ +import shlex + +import pytest + +from qeval.base_commands.query import BaseQueryCommand + +SERVER_ARGS = ["--host-name", "localhost", "--port", "7878"] + + +# No test may send a real request, so the command that runs `curl` is +# replaced in every test. +@pytest.fixture(autouse=True) +def run_command(mock_command): + return mock_command("qlever.commands.query", "run_command") + + +def test_base_query_sends_query_to_engine_endpoint(parse_args, run_command): + command = BaseQueryCommand() + args = parse_args(command, SERVER_ARGS) + + assert command.execute(args) + + curl_cmd = run_command.call_args.args[0] + assert "localhost:7878/sparql" in shlex.split(curl_cmd) + + +def test_base_query_rejects_pin_to_cache(parse_args): + with pytest.raises(SystemExit): + parse_args(BaseQueryCommand(), ["--pin-to-cache", *SERVER_ARGS]) + + +@pytest.mark.parametrize( + "accept", ["application/qlever-results+json", "application/octet-stream"] +) +def test_base_query_rejects_qlever_only_accept(parse_args, accept): + with pytest.raises(SystemExit): + parse_args(BaseQueryCommand(), ["--accept", accept, *SERVER_ARGS]) diff --git a/test/qeval/base_commands/test_base_setup_config.py b/test/qeval/base_commands/test_base_setup_config.py new file mode 100644 index 00000000..5cd2f231 --- /dev/null +++ b/test/qeval/base_commands/test_base_setup_config.py @@ -0,0 +1,72 @@ +from configparser import RawConfigParser + +from qeval.base_commands.setup_config import BaseSetupConfigCommand + + +class FakeSetupConfigCommand(BaseSetupConfigCommand): + def image(self): + return "docker.io/fake/engine:1.0" + + def engine_settings(self, args): + return { + "server": {"PORT": "8888", "TIMEOUT": "60s"}, + # The olympics Qleverfile has no such section. + "extra": {"OPTION": "value"}, + } + + +def read_qleverfile(path): + """The Qleverfile at `path`, read without resolving `${...}`.""" + qleverfile = RawConfigParser() + qleverfile.read(path) + return qleverfile + + +def test_base_setup_config_writes_filtered_qleverfile( + parse_args, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + command = FakeSetupConfigCommand() + args = parse_args(command, ["olympics"]) + + assert command.execute(args) + + qleverfile = read_qleverfile(tmp_path / "Qleverfile") + assert qleverfile.sections() == [ + "data", + "index", + "server", + "runtime", + "ui", + ] + assert not qleverfile.has_option("server", "ACCESS_TOKEN") + assert qleverfile.get("data", "NAME") == "olympics" + assert qleverfile.get("runtime", "IMAGE") == "docker.io/fake/engine:1.0" + assert qleverfile.get("server", "PORT") == "8888" + assert qleverfile.get("server", "TIMEOUT") == "60s" + + +def test_base_setup_config_port_option_beats_engine_setting( + parse_args, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + command = FakeSetupConfigCommand() + args = parse_args(command, ["olympics", "--port", "9999"]) + + assert command.execute(args) + + qleverfile = read_qleverfile(tmp_path / "Qleverfile") + assert qleverfile.get("server", "PORT") == "9999" + + +def test_base_setup_config_keeps_existing_qleverfile( + parse_args, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "Qleverfile").write_text("[data]\nNAME = mine\n") + command = FakeSetupConfigCommand() + args = parse_args(command, ["olympics"]) + + assert not command.execute(args) + + assert (tmp_path / "Qleverfile").read_text() == "[data]\nNAME = mine\n" diff --git a/test/qeval/base_commands/test_base_status.py b/test/qeval/base_commands/test_base_status.py new file mode 100644 index 00000000..27e4ad80 --- /dev/null +++ b/test/qeval/base_commands/test_base_status.py @@ -0,0 +1,41 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock + +from qeval.base_commands.status import BaseStatusCommand + + +class FakeStatusCommand(BaseStatusCommand): + def default_regex(self): + return "^fake-server" + + +def fake_process(pid, cmdline): + """A process as `psutil.process_iter` returns it.""" + process = MagicMock() + process.as_dict.return_value = { + "pid": pid, + "username": "user", + "create_time": 0, + "memory_info": SimpleNamespace(rss=0), + "cmdline": cmdline, + } + return process + + +def test_base_status_shows_only_engine_processes( + parse_args, monkeypatch, caplog +): + processes = [ + fake_process(4711, ["fake-server", "-i", "olympics"]), + fake_process(4712, ["other-program"]), + ] + monkeypatch.setattr( + "qlever.commands.status.psutil.process_iter", lambda: processes + ) + command = FakeStatusCommand() + args = parse_args(command, []) + + assert command.execute(args) + + assert "fake-server -i olympics" in caplog.text + assert "other-program" not in caplog.text diff --git a/test/qeval/base_commands/test_base_stop.py b/test/qeval/base_commands/test_base_stop.py new file mode 100644 index 00000000..006d219b --- /dev/null +++ b/test/qeval/base_commands/test_base_stop.py @@ -0,0 +1,94 @@ +import pytest + +from qeval.base_commands.status import BaseStatusCommand +from qeval.base_commands.stop import BaseStopCommand + + +class FakeStatusCommand(BaseStatusCommand): + def __init__(self): + super().__init__() + self.executed = False + + def default_regex(self): + # Differs from `status_regex` of the stop command, so that a test can + # tell which regex the fallback used. + return "^fake-" + + def execute(self, args): + self.executed = True + return super().execute(args) + + +class FakeStopCommand(BaseStopCommand): + def __init__(self): + super().__init__() + self.status = FakeStatusCommand() + + def default_regex(self): + return "^fake-server .* %%NAME%%" + + def status_command(self): + return self.status + + def status_regex(self): + return "^fake-server" + + +# The stop functions are replaced in every test, so that no test can stop a +# real systemd unit, container, or process. By default, there is no container +# and one matching process, which is stopped. +@pytest.fixture(autouse=True) +def stop_systemd_unit(mock_command): + mock_command("qlever.commands.stop", "systemd_unit_is_active") + return mock_command("qlever.commands.stop", "stop_systemd_unit") + + +@pytest.fixture(autouse=True) +def stop_container(mock_command): + mock = mock_command("qlever.commands.stop", "stop_container") + mock.return_value = False + return mock + + +@pytest.fixture(autouse=True) +def stop_process_with_regex(mock_command): + mock = mock_command("qlever.commands.stop", "stop_process_with_regex") + mock.return_value = [True] + return mock + + +def test_base_stop_puts_dataset_name_into_regex( + parse_args, stop_process_with_regex +): + command = FakeStopCommand() + args = parse_args(command, ["--name", "olympics"]) + + command.execute(args) + + stop_process_with_regex.assert_called_once_with("^fake-server .* olympics") + + +def test_base_stop_never_touches_systemd(parse_args, stop_systemd_unit): + command = FakeStopCommand() + args = parse_args(command, ["--name", "olympics"]) + + command.execute(args) + + stop_systemd_unit.assert_not_called() + + +def test_base_stop_shows_servers_when_nothing_matches( + parse_args, stop_process_with_regex, monkeypatch, capsys +): + stop_process_with_regex.return_value = [] + monkeypatch.setattr( + "qlever.commands.status.psutil.process_iter", lambda: [] + ) + command = FakeStopCommand() + args = parse_args(command, ["--name", "olympics"]) + + assert command.execute(args) + + assert command.status.executed + assert args.cmdline_regex == "^fake-server" + assert "No processes found" in capsys.readouterr().out diff --git a/test/qlever/conftest.py b/test/qlever/conftest.py index 71607ac7..a96e69d3 100644 --- a/test/qlever/conftest.py +++ b/test/qlever/conftest.py @@ -1,32 +1,6 @@ -import os -from unittest.mock import MagicMock - import pytest -# A signal to a process id or group of 1 or less goes to the caller's own -# group (0), to every process of the user (-1, which is also what `killpg(1)` -# means), or to a group given as a negative number. No test may do that: on -# 2026-09-13, a `killpg` with the `pid` of a mocked `Popen` (a `MagicMock`, -# which evaluates to 1) killed every process of the user on two machines, -# including the production servers. Such a call now fails the test instead. -@pytest.fixture(autouse=True) -def no_broadcast_signals(monkeypatch): - def guarded(name, original): - def send(target, sig, *rest): - if not isinstance(target, int) or target <= 1: - raise AssertionError( - f"os.{name}({target!r}, {sig!r}) would signal processes " - "that are not children of the test, refused" - ) - return original(target, sig, *rest) - - return send - - monkeypatch.setattr(os, "kill", guarded("kill", os.kill)) - monkeypatch.setattr(os, "killpg", guarded("killpg", os.killpg)) - - @pytest.fixture def write_log(tmp_path): """Write bytes to a fresh log file and return its Path.""" @@ -37,16 +11,3 @@ def make(data): return path return make - - -@pytest.fixture -def mock_command(monkeypatch): - def _mock(module_name: str, function_name: str, override=None): - if override: - monkeypatch.setattr(f"{module_name}.{function_name}", override) - return override - mock = MagicMock(name=f"{function_name}_mock") - monkeypatch.setattr(f"{module_name}.{function_name}", mock) - return mock - - return _mock