diff --git a/README.md b/README.md index 2c00216..f3d6e01 100644 --- a/README.md +++ b/README.md @@ -10,35 +10,43 @@ Also see the [main RLBot wiki](https://wiki.rlbot.org/) (make sure to avoid info ## Dev setup -The following is how to setup a development environment for this project, NOT how to create a bot using this interface! - -- Ensure Python 3.11+ is installed -- Create a virtual Python environment - - `python3 -m venv venv` -- Activate the virtual environment - - Windows: `venv\Scripts\activate.bat` - - Linux: `source venv/bin/activate` -- Install the package - - `pip install --editable .` - - This will install the package in editable mode, - meaning you can make changes to the code, and they - will be reflected in the installed package without - having to run the command again -- If you are making changes involving the flatbuffer schema and +The following is how to set up a development environment for this project, not how to create a bot using this interface. + +- Ensure Python 3.11+ is installed. +- Install [uv](https://docs.astral.sh/uv/). +- Create the environment and install the package with development dependencies: + - `uv sync --dev` +- Activate the virtual environment when needed: + - Windows: `.venv\Scripts\activate` + - Linux: `source .venv/bin/activate` +- Run commands without activating the environment with `uv run`. +- If you are making changes involving the FlatBuffer schema and [flatbuffers_python](https://github.com/RLBot/flatbuffers-python), also install your local copy of that package in editable mode: - - `pip uninstall rlbot_flatbuffers` - - `pip install --editable ` + - `uv pip uninstall rlbot_flatbuffers` + - `uv pip install --editable ` This project is formatted using [Ruff](https://docs.astral.sh/ruff/formatter/). -- Install: `pip install ruff`. -- Sort imports: `ruff check --select I --fix` -- Format code: `ruff format` +- Check code: `uv run ruff check .` +- Sort imports: `uv run ruff check --select I --fix` +- Format code: `uv run ruff format` + +## Updating dependencies + +Use uv to change dependencies and update the lock file. + +- Add a runtime dependency: `uv add `. +- Add a development dependency: `uv add --dev `. +- Remove a dependency: `uv remove `. +- Update one dependency: `uv lock --upgrade-package `. +- Update all dependencies: `uv lock --upgrade`. +- Install the locked dependencies: `uv sync --dev`. ## Testing -- You can test launching a match with `python tests/runner.py` +- Run all pytest tests with `uv run pytest`. +- Test launching a match with `uv run python tests/runner.py`. ## Building diff --git a/pyproject.toml b/pyproject.toml index 0ffdf1d..91edb5e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ Repository = "https://github.com/RLBot/python-interface" [dependency-groups] dev = [ + "pytest>=9.1.1", "ruff>=0.16.0", "toml>=0.10.2", ] @@ -27,6 +28,8 @@ build-backend = "setuptools.build_meta" [tool.basedpyright] typeCheckingMode = "standard" +venvPath = "." +venv = ".venv" [tool.ruff.format] docstring-code-format = true diff --git a/rlbot/config.py b/rlbot/config.py index 771aa0e..fc078f2 100644 --- a/rlbot/config.py +++ b/rlbot/config.py @@ -1,8 +1,10 @@ +import os +import re import tomllib from pathlib import Path from typing import Any, Literal -import rlbot.flat as flat +from rlbot import flat from rlbot.utils.os_detector import CURRENT_OS, OS @@ -13,66 +15,190 @@ class ConfigParsingException(Exception): def __enum(table: dict[str, str | Any], key: str, enum: Any, default: int = 0) -> Any: if key not in table: return enum(default) - try: - for i in range(100000): - if str(enum(i)).split(".")[-1].lower() == table[key].lower(): - return enum(i) - except ValueError: - raise ConfigParsingException( - f"Invalid value {repr(table[key])} for key '{key}'." - ) + v = table[key] + if not isinstance(v, str): + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected a string.") + stripped = v.strip() + if stripped != "" and stripped.lstrip("+-").isdigit(): + try: + return enum(int(stripped)) + except (ValueError, OverflowError) as exc: + raise ConfigParsingException( + f"Invalid value {v!r} for key '{key}'." + ) from exc + lowered = stripped.lower() + for name in dir(enum): + if name.startswith("_"): + continue + member = getattr(enum, name) + if callable(member): + continue + if name.lower() == lowered: + return member + raise ConfigParsingException(f"Invalid value {v!r} for key '{key}'.") def __str(table: dict[str, str | Any], key: str, default: str = "") -> str: v = table.get(key, default) if isinstance(v, str): return v - raise ConfigParsingException(f"'{key}' has value {repr(v)}. Expected a string.") + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected a string.") + + +def __opt_str(table: dict[str, str | Any], key: str) -> str | None: + if key not in table: + return None + v = table[key] + if isinstance(v, str): + return v + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected a string.") def __bool(table: dict[str, bool | Any], key: str, default: bool = False) -> bool: v = table.get(key, default) if isinstance(v, bool): return v - raise ConfigParsingException(f"'{key}' has value {repr(v)}. Expected a bool.") + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected a bool.") def __int(table: dict[str, int | Any], key: str, default: int = 0) -> int: v = table.get(key, default) - if isinstance(v, int): - return v - raise ConfigParsingException(f"'{key}' has value {repr(v)}. Expected an int.") + if isinstance(v, bool) or not isinstance(v, int): + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected an int.") + if not 0 <= v <= 0xFFFFFFFF: + raise ConfigParsingException( + f"'{key}' has value {v!r}. Expected an unsigned 32-bit int." + ) + return v def __table(table: dict[str, dict[str, Any] | Any], key: str) -> dict[str, Any]: - v = table.get(key, dict()) + v = table.get(key, {}) if isinstance(v, dict): return v # type: ignore - raise ConfigParsingException(f"'{key}' has value {repr(v)}. Expected a table.") + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected a table.") + + +def __list(table: dict[str, list[Any] | Any], key: str) -> list[Any]: + v = table.get(key, []) + if isinstance(v, list): + return v + raise ConfigParsingException(f"'{key}' has value {v!r}. Expected an array.") def __team(table: dict[str, Literal["blue", "orange", 0, 1] | Any]) -> int: if "team" not in table: return 0 v = table["team"] + if isinstance(v, bool): + raise ConfigParsingException( + f'\'team\' has value {v!r}. Expected a 0, 1, "blue", or "orange".' + ) if isinstance(v, str): if v.lower() == "blue": return 0 if v.lower() == "orange": return 1 - if isinstance(v, int): + elif isinstance(v, int): if 0 <= v <= 1: return v raise ConfigParsingException( - f'\'team\' has value {repr(v)}. Expected a 0, 1, "blue", or "orange".' + f'\'team\' has value {v!r}. Expected a 0, 1, "blue", or "orange".' + ) + + +def __run_command(settings: dict[str, Any]) -> str: + run_command = __str(settings, "run_command") + if CURRENT_OS != OS.WINDOWS: + run_command_linux = __str(settings, "run_command_linux") + if run_command_linux != "": + return run_command_linux + # No Linux run command is set. Run the Windows command via Wine. + if run_command != "": + return f"wine {run_command}" + return "" + return run_command + + +__environment_pattern = re.compile( + r"%([^%]+)%|\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))" +) + + +def __expand_environment(value: str) -> str: + # Use one pass so variable references inside replacement values stay literal. + return __environment_pattern.sub( + lambda m: os.environ.get(m.group(1) or m.group(2) or m.group(3), m.group(0)), + value, + ) + + +def __environment(settings: dict[str, Any]) -> list[flat.EnvironmentVariable]: + env_table = __table(settings, "environment") + values: dict[str, str] = {} + + for key, raw in env_table.items(): + if key == "windows" or key == "linux": + continue + if not isinstance(raw, str): + raise ConfigParsingException( + f"'{key}' has value {raw!r}. Expected a string." + ) + values[key] = raw + + platform = ( + "windows" + if CURRENT_OS == OS.WINDOWS + else "linux" + if CURRENT_OS == OS.LINUX + else None ) + if platform is not None and platform in env_table: + platform_table = env_table[platform] + if not isinstance(platform_table, dict): + raise ConfigParsingException( + f"'{platform}' has value {platform_table!r}. Expected a table." + ) + for key, raw in platform_table.items(): + if not isinstance(raw, str): + raise ConfigParsingException( + f"'{key}' has value {raw!r}. Expected a string." + ) + values[key] = __expand_environment(raw) + + return [flat.EnvironmentVariable(name=k, value=v) for k, v in values.items()] + + +def __abspath(path: Path | str) -> Path: + # os.path.abspath normalizes ".." without resolving symlinks, + # matching C# Path.GetFullPath. + return Path(os.path.abspath(path)) + + +def __match_loadout_override( + car_table: dict[str, Any], match_dir: Path +) -> Path | str | None: + raw = __opt_str(car_table, "loadout_file") + if raw is None: + return None + if raw == "": + # Empty string suppresses the loadout. + return "" + return match_dir / raw + + +def __auto_save_replay(match_table: dict[str, Any]) -> bool: + # Both spellings are accepted. The plural C# reference key wins. + if "auto_save_replays" in match_table: + return __bool(match_table, "auto_save_replays") + return __bool(match_table, "auto_save_replay") def load_match_config(config_path: Path | str) -> flat.MatchConfiguration: """ Reads the match toml file at the provided path and creates the corresponding MatchConfiguration. """ - config_path = Path(config_path) + config_path = __abspath(config_path) with open(config_path, "rb") as f: config = tomllib.load(f) @@ -81,132 +207,359 @@ def load_match_config(config_path: Path | str) -> flat.MatchConfiguration: mutator_table = __table(config, "mutators") players: list[flat.PlayerConfiguration] = [] - for car_table in config.get("cars", []): - car_config = __str(car_table, "config_file") - name = __str(car_table, "name") + cars = __list(config, "cars") + for i, car_table in enumerate(cars): + if not isinstance(car_table, dict): + raise ConfigParsingException( + f"'cars[{i}]' has value {car_table!r}. Expected a table." + ) team = __team(car_table) - loadout_file = __str(car_table, "loadout_file") or None - skill = __enum( - car_table, "skill", flat.PsyonixSkill, int(flat.PsyonixSkill.AllStar) - ) variant = __str(car_table, "type", "rlbot").lower() + name_override = __opt_str(car_table, "name") + loadout_override = __match_loadout_override(car_table, config_path.parent) + + if variant == "human": + players.append(get_human(team)) + continue + + car_config = __str(car_table, "config_file") - match variant: - case "rlbot": - abs_config_path = (config_path.parent / car_config).resolve() + if car_config != "": + abs_config_path = __abspath(config_path.parent / car_config) + if variant == "rlbot": + auto_start = __bool(car_table, "auto_start", True) players.append( - load_player_config(abs_config_path, team, name, loadout_file) - ) - case "psyonix": - abs_config_path = ( - (config_path.parent / car_config).resolve() if car_config else None + load_player_config( + abs_config_path, + team, + name_override, + loadout_override, + auto_start, + ) ) + elif variant == "psyonix": + # Skill comes from the linked toml file. The passed + # skill is only a fallback and is not used here. players.append( load_psyonix_config( team, - skill, - name, - loadout_file, + flat.PsyonixSkill.AllStar, + name_override, + loadout_override, abs_config_path, ) ) - case "human": - players.append(get_human(team)) - case t: + else: raise ConfigParsingException( - f"Invalid player type {repr(t)} for player {len(players)}." + f"Invalid player type {variant!r} for player {len(players)}." ) + elif variant in ("rlbot", "psyonix"): + # Core uses a Psyonix bot when an RLBot car has no config file. + skill = __enum( + car_table, + "skill", + flat.PsyonixSkill, + int(flat.PsyonixSkill.AllStar), + ) + players.append( + load_psyonix_config(team, skill, name_override, loadout_override) + ) + else: + raise ConfigParsingException( + f"Invalid player type {variant!r} for player {len(players)}." + ) scripts: list[flat.ScriptConfiguration] = [] - for script_table in config.get("scripts", []): - if script_config := __str(script_table, "config_file"): - abs_config_path = (config_path.parent / script_config).resolve() - scripts.append(load_script_config(abs_config_path)) - else: - scripts.append(flat.ScriptConfiguration()) + scripts_list = __list(config, "scripts") + for i, script_table in enumerate(scripts_list): + if not isinstance(script_table, dict): + raise ConfigParsingException( + f"'scripts[{i}]' has value {script_table!r}. Expected a table." + ) + script_config = __str(script_table, "config_file") + if script_config == "": + raise ConfigParsingException( + f"'scripts[{i}].config_file' is empty. Scripts must specify a config file." + ) + abs_config_path = __abspath(config_path.parent / script_config) + auto_start = __bool(script_table, "auto_start", True) + scripts.append(load_script_config(abs_config_path, auto_start)) mutators = flat.MutatorSettings( - match_length=__enum(mutator_table, "match_length", flat.MatchLengthMutator), - max_score=__enum(mutator_table, "max_score", flat.MaxScoreMutator), - multi_ball=__enum(mutator_table, "multi_ball", flat.MultiBallMutator), - overtime=__enum(mutator_table, "overtime", flat.OvertimeMutator), - series_length=__enum(mutator_table, "series_length", flat.SeriesLengthMutator), - game_speed=__enum(mutator_table, "game_speed", flat.GameSpeedMutator), + match_length=__enum( + mutator_table, + "match_length", + flat.MatchLengthMutator, + int(flat.MatchLengthMutator.FiveMinutes), + ), + max_score=__enum( + mutator_table, + "max_score", + flat.MaxScoreMutator, + int(flat.MaxScoreMutator.Unlimited), + ), + multi_ball=__enum( + mutator_table, + "multi_ball", + flat.MultiBallMutator, + int(flat.MultiBallMutator.One), + ), + overtime=__enum( + mutator_table, + "overtime", + flat.OvertimeMutator, + int(flat.OvertimeMutator.Unlimited), + ), + series_length=__enum( + mutator_table, + "series_length", + flat.SeriesLengthMutator, + int(flat.SeriesLengthMutator.Unlimited), + ), + game_speed=__enum( + mutator_table, + "game_speed", + flat.GameSpeedMutator, + int(flat.GameSpeedMutator.Default), + ), ball_max_speed=__enum( - mutator_table, "ball_max_speed", flat.BallMaxSpeedMutator + mutator_table, + "ball_max_speed", + flat.BallMaxSpeedMutator, + int(flat.BallMaxSpeedMutator.Default), + ), + ball_type=__enum( + mutator_table, + "ball_type", + flat.BallTypeMutator, + int(flat.BallTypeMutator.Default), + ), + ball_weight=__enum( + mutator_table, + "ball_weight", + flat.BallWeightMutator, + int(flat.BallWeightMutator.Default), + ), + ball_size=__enum( + mutator_table, + "ball_size", + flat.BallSizeMutator, + int(flat.BallSizeMutator.Default), ), - ball_type=__enum(mutator_table, "ball_type", flat.BallTypeMutator), - ball_weight=__enum(mutator_table, "ball_weight", flat.BallWeightMutator), - ball_size=__enum(mutator_table, "ball_size", flat.BallSizeMutator), ball_bounciness=__enum( - mutator_table, "ball_bounciness", flat.BallBouncinessMutator + mutator_table, + "ball_bounciness", + flat.BallBouncinessMutator, + int(flat.BallBouncinessMutator.Default), + ), + boost_amount=__enum( + mutator_table, + "boost_amount", + flat.BoostAmountMutator, + int(flat.BoostAmountMutator.NormalBoost), + ), + rumble=__enum( + mutator_table, + "rumble", + flat.RumbleMutator, + int(flat.RumbleMutator.Off), ), - boost_amount=__enum(mutator_table, "boost_amount", flat.BoostAmountMutator), - rumble=__enum(mutator_table, "rumble", flat.RumbleMutator), boost_strength=__enum( - mutator_table, "boost_strength", flat.BoostStrengthMutator - ), - gravity=__enum(mutator_table, "gravity", flat.GravityMutator), - demolish=__enum(mutator_table, "demolish", flat.DemolishMutator), - respawn_time=__enum(mutator_table, "respawn_time", flat.RespawnTimeMutator), - max_time=__enum(mutator_table, "max_time", flat.MaxTimeMutator), - game_event=__enum(mutator_table, "game_event", flat.GameEventMutator), - audio=__enum(mutator_table, "audio", flat.AudioMutator), + mutator_table, + "boost_strength", + flat.BoostStrengthMutator, + int(flat.BoostStrengthMutator.One), + ), + gravity=__enum( + mutator_table, + "gravity", + flat.GravityMutator, + int(flat.GravityMutator.Default), + ), + demolish=__enum( + mutator_table, + "demolish", + flat.DemolishMutator, + int(flat.DemolishMutator.Default), + ), + respawn_time=__enum( + mutator_table, + "respawn_time", + flat.RespawnTimeMutator, + int(flat.RespawnTimeMutator.ThreeSeconds), + ), + max_time=__enum( + mutator_table, + "max_time", + flat.MaxTimeMutator, + int(flat.MaxTimeMutator.Unlimited), + ), + game_event=__enum( + mutator_table, + "game_event", + flat.GameEventMutator, + int(flat.GameEventMutator.Default), + ), + audio=__enum( + mutator_table, + "audio", + flat.AudioMutator, + int(flat.AudioMutator.Default), + ), + ball_gravity=__enum( + mutator_table, + "ball_gravity", + flat.BallGravityMutator, + int(flat.BallGravityMutator.Default), + ), + territory=__enum( + mutator_table, + "territory", + flat.TerritoryMutator, + int(flat.TerritoryMutator.Off), + ), + stale_ball=__enum( + mutator_table, + "stale_ball", + flat.StaleBallMutator, + int(flat.StaleBallMutator.Unlimited), + ), + jump=__enum( + mutator_table, + "jump", + flat.JumpMutator, + int(flat.JumpMutator.Default), + ), + dodge_timer=__enum( + mutator_table, + "dodge_timer", + flat.DodgeTimerMutator, + int(flat.DodgeTimerMutator.OnePointTwentyFiveSeconds), + ), + possession_score=__enum( + mutator_table, + "possession_score", + flat.PossessionScoreMutator, + int(flat.PossessionScoreMutator.Off), + ), + demolish_score=__enum( + mutator_table, + "demolish_score", + flat.DemolishScoreMutator, + int(flat.DemolishScoreMutator.Zero), + ), + normal_goal_score=__enum( + mutator_table, + "normal_goal_score", + flat.NormalGoalScoreMutator, + int(flat.NormalGoalScoreMutator.One), + ), + aerial_goal_score=__enum( + mutator_table, + "aerial_goal_score", + flat.AerialGoalScoreMutator, + int(flat.AerialGoalScoreMutator.One), + ), + assist_goal_score=__enum( + mutator_table, + "assist_goal_score", + flat.AssistGoalScoreMutator, + int(flat.AssistGoalScoreMutator.Zero), + ), + input_restriction=__enum( + mutator_table, + "input_restriction", + flat.InputRestrictionMutator, + int(flat.InputRestrictionMutator.Default), + ), ) - try: - enable_rendering = ( - flat.DebugRendering.OnByDefault - if __bool(match_table, "enable_rendering") - else flat.DebugRendering.OffByDefault - ) - except ConfigParsingException: - enable_rendering = __enum( - match_table, "enable_rendering", flat.DebugRendering.AlwaysOff - ) + # "soccer" is an alias of "Soccar". + game_mode_table = dict(match_table) + game_mode_raw = game_mode_table.get("game_mode") + if isinstance(game_mode_raw, str) and game_mode_raw.lower() == "soccer": + game_mode_table["game_mode"] = "Soccar" + game_mode = __enum( + game_mode_table, "game_mode", flat.GameMode, int(flat.GameMode.Soccar) + ) + + if "enable_rendering" in match_table: + raw_rendering = match_table["enable_rendering"] + if isinstance(raw_rendering, bool): + enable_rendering = ( + flat.DebugRendering.OnByDefault + if raw_rendering + else flat.DebugRendering.AlwaysOff + ) + else: + enable_rendering = __enum( + match_table, + "enable_rendering", + flat.DebugRendering, + int(flat.DebugRendering.OffByDefault), + ) + else: + enable_rendering = flat.DebugRendering.OffByDefault return flat.MatchConfiguration( - launcher=__enum(rlbot_table, "launcher", flat.Launcher), + launcher=__enum( + rlbot_table, "launcher", flat.Launcher, int(flat.Launcher.Steam) + ), launcher_arg=__str(rlbot_table, "launcher_arg"), auto_start_agents=__bool(rlbot_table, "auto_start_agents", True), wait_for_agents=__bool(rlbot_table, "wait_for_agents", True), - game_map_upk=__str(match_table, "game_map_upk"), + performance_monitor=__enum( + rlbot_table, + "performance_monitor", + flat.PerformanceMonitor, + int(flat.PerformanceMonitor.ShowWhenSuboptimal), + ), + game_map_upk=__str(match_table, "game_map_upk", "Stadium_P"), player_configurations=players, script_configurations=scripts, - game_mode=__enum(match_table, "game_mode", flat.GameMode), + game_mode=game_mode, skip_replays=__bool(match_table, "skip_replays"), - instant_start=__bool(match_table, "instant_start"), + instant_start=__bool(match_table, "start_without_countdown"), mutators=mutators, existing_match_behavior=__enum( - match_table, "existing_match_behavior", flat.ExistingMatchBehavior + match_table, + "existing_match_behavior", + flat.ExistingMatchBehavior, + int(flat.ExistingMatchBehavior.Restart), ), enable_rendering=enable_rendering, - enable_state_setting=__bool(match_table, "enable_state_setting"), + enable_state_setting=__bool(match_table, "enable_state_setting", True), + auto_save_replay=__auto_save_replay(match_table), freeplay=__bool(match_table, "freeplay"), ) def load_player_loadout(path: Path | str, team: int) -> flat.PlayerLoadout: """ - Reads the loadout toml file at the provided path and extracts the `PlayerLoadout` for the given team. + Reads the loadout TOML for the blue team (0) or the orange team (1). """ + if not isinstance(team, int) or isinstance(team, bool) or team not in (0, 1): + raise ConfigParsingException( + f"Invalid team {team!r}. Use 0 (blue) or 1 (orange)." + ) + + path = __abspath(path) with open(path, "rb") as f: config = tomllib.load(f) table_name = "blue_loadout" if team == 0 else "orange_loadout" loadout = __table(config, table_name) - paint = None - if paint_table := __table(loadout, "paint"): - paint = flat.LoadoutPaint( - car_paint_id=__int(paint_table, "car_paint_id"), - decal_paint_id=__int(paint_table, "decal_paint_id"), - wheels_paint_id=__int(paint_table, "wheels_paint_id"), - boost_paint_id=__int(paint_table, "boost_paint_id"), - antenna_paint_id=__int(paint_table, "antenna_paint_id"), - hat_paint_id=__int(paint_table, "hat_paint_id"), - trails_paint_id=__int(paint_table, "trails_paint_id"), - goal_explosion_paint_id=__int(paint_table, "goal_explosion_paint_id"), - ) + paint_table = __table(loadout, "paint") + paint = flat.LoadoutPaint( + car_paint_id=__int(paint_table, "car_paint_id"), + decal_paint_id=__int(paint_table, "decal_paint_id"), + wheels_paint_id=__int(paint_table, "wheels_paint_id"), + boost_paint_id=__int(paint_table, "boost_paint_id"), + antenna_paint_id=__int(paint_table, "antenna_paint_id"), + hat_paint_id=__int(paint_table, "hat_paint_id"), + trails_paint_id=__int(paint_table, "trails_paint_id"), + goal_explosion_paint_id=__int(paint_table, "goal_explosion_paint_id"), + ) return flat.PlayerLoadout( team_color_id=__int(loadout, "team_color_id"), @@ -231,43 +584,48 @@ def load_player_config( team: int, name_override: str | None = None, loadout_override: Path | str | None = None, + auto_start: bool = True, ) -> flat.PlayerConfiguration: """ Reads the bot toml file at the provided path and creates a `PlayerConfiguration` of the given type for the given team. """ - path = Path(path) + path = __abspath(path) with open(path, "rb") as f: config = tomllib.load(f) settings = __table(config, "settings") - root_dir = path.parent.absolute() + root_dir = path.parent if "root_dir" in settings: root_dir /= Path(__str(settings, "root_dir")) - run_command = __str(settings, "run_command") - if CURRENT_OS == OS.LINUX and "run_command_linux" in settings: - run_command = __str(settings, "run_command_linux") + run_command = __run_command(settings) if auto_start else "" - loadout_path = ( - path.parent / Path(__str(settings, "loadout_file")) - if "loadout_file" in settings - else None - ) - loadout_path = loadout_override or loadout_path + if loadout_override is None: + settings_loadout = __opt_str(settings, "loadout_file") + if settings_loadout is None or settings_loadout == "": + loadout_path = None + else: + loadout_path = path.parent / settings_loadout + elif loadout_override == "": + # Empty string suppresses the loadout. + loadout_path = None + else: + loadout_path = loadout_override loadout = ( load_player_loadout(loadout_path, team) if loadout_path is not None else None ) return flat.PlayerConfiguration( flat.CustomBot( - name_override or __str(settings, "name"), + name_override if name_override is not None else __str(settings, "name"), str(root_dir), run_command, loadout, __str(settings, "agent_id"), __bool(settings, "hivemind"), + environment=__environment(settings), ), team, 0, @@ -283,29 +641,39 @@ def load_psyonix_config( ) -> flat.PlayerConfiguration: """ Creates a `PlayerConfiguration` for a Psyonix bot of the given team and skill. - If a path is provided, it will be used override the default name and loadout. + If a path is provided, the skill is read from the linked toml file, + which also supplies the default name and loadout unless overridden here. + Without a path, `skill_level` is used directly. """ - name = name_override - loadout_path = loadout_override - - # Don't parse the toml file if we have no data we need to extract, - # even if a path to a toml file is provided. - if path is not None and (name is None or loadout_path is None): - path = Path(path) + if path is None: + name = name_override + if loadout_override is None or loadout_override == "": + loadout_path = None + else: + loadout_path = loadout_override + else: + path = __abspath(path) with open(path, "rb") as f: config = tomllib.load(f) - settings = __table(config, "settings") - - if name is None: - name = __str(settings, "name") - - if loadout_path is None: - loadout_path = ( - path.parent / Path(__str(settings, "loadout_file")) - if "loadout_file" in settings - else None - ) + skill_level = __enum( + config, "skill", flat.PsyonixSkill, int(flat.PsyonixSkill.AllStar) + ) + settings = __table(config, "settings") + + name = name_override if name_override is not None else __str(settings, "name") + + if loadout_override is None: + settings_loadout = __opt_str(settings, "loadout_file") + if settings_loadout is None or settings_loadout == "": + loadout_path = None + else: + loadout_path = path.parent / settings_loadout + elif loadout_override == "": + # Empty string suppresses the loadout. + loadout_path = None + else: + loadout_path = loadout_override loadout = ( load_player_loadout(loadout_path, team) if loadout_path is not None else None @@ -313,7 +681,7 @@ def load_psyonix_config( return flat.PlayerConfiguration( flat.PsyonixBot( - name or "", + name if name is not None else "", loadout, skill_level, ), @@ -329,23 +697,25 @@ def get_human(team: int) -> flat.PlayerConfiguration: return flat.PlayerConfiguration(flat.Human(), team) -def load_script_config(path: Path | str) -> flat.ScriptConfiguration: +def load_script_config( + path: Path | str, auto_start: bool = True +) -> flat.ScriptConfiguration: """ Reads the script toml file at the provided path and creates a `ScriptConfiguration` from it. """ - path = Path(path) + path = __abspath(path) with open(path, "rb") as f: config = tomllib.load(f) - settings: dict[str, Any] = config["settings"] + settings = __table(config, "settings") root_dir = path.parent if "root_dir" in settings: root_dir /= Path(__str(settings, "root_dir")) - run_command = __str(settings, "run_command") - if CURRENT_OS == OS.LINUX and "run_command_linux" in settings: - run_command = __str(settings, "run_command_linux") + run_command = __run_command(settings) + if not auto_start: + run_command = "" return flat.ScriptConfiguration( __str(settings, "name"), @@ -353,4 +723,5 @@ def load_script_config(path: Path | str) -> flat.ScriptConfiguration: run_command, 0, __str(settings, "agent_id"), + environment=__environment(settings), ) diff --git a/rlbot/interface.py b/rlbot/interface.py index 0ed4a9b..f239ad2 100644 --- a/rlbot/interface.py +++ b/rlbot/interface.py @@ -39,17 +39,6 @@ class SocketRelay: _running = False """Indicates whether a messages are being handled by the `run` loop (potentially in a background thread)""" - on_connect_handlers: list[Callable[[], None]] = [] - packet_handlers: list[Callable[[flat.GamePacket], None]] = [] - field_info_handlers: list[Callable[[flat.FieldInfo], None]] = [] - match_config_handlers: list[Callable[[flat.MatchConfiguration], None]] = [] - match_comm_handlers: list[Callable[[flat.MatchComm], None]] = [] - ball_prediction_handlers: list[Callable[[flat.BallPrediction], None]] = [] - controllable_team_info_handlers: list[ - Callable[[flat.ControllableTeamInfo], None] - ] = [] - raw_handlers: list[Callable[[flat.CorePacket], None]] = [] - socket: sock | None = None def __init__( @@ -61,6 +50,16 @@ def __init__( self.agent_id = agent_id self.connection_timeout = connection_timeout self.logger = get_logger("interface") if logger is None else logger + self.on_connect_handlers: list[Callable[[], None]] = [] + self.packet_handlers: list[Callable[[flat.GamePacket], None]] = [] + self.field_info_handlers: list[Callable[[flat.FieldInfo], None]] = [] + self.match_config_handlers: list[Callable[[flat.MatchConfiguration], None]] = [] + self.match_comm_handlers: list[Callable[[flat.MatchComm], None]] = [] + self.ball_prediction_handlers: list[Callable[[flat.BallPrediction], None]] = [] + self.controllable_team_info_handlers: list[ + Callable[[flat.ControllableTeamInfo], None] + ] = [] + self.raw_handlers: list[Callable[[flat.CorePacket], None]] = [] def __del__(self): if self.socket is not None: @@ -266,7 +265,7 @@ def handle_incoming_messages(self, blocking: bool = False) -> MsgHandlingResult: except BlockingIOError: # No incoming messages and blocking==False return MsgHandlingResult.NO_INCOMING_MSGS - except: + except (EOFError, OSError): self.logger.error("SocketRelay disconnected unexpectedly!") return MsgHandlingResult.TERMINATED @@ -279,7 +278,7 @@ def handle_incoming_messages(self, blocking: bool = False) -> MsgHandlingResult: e, ) return MsgHandlingResult.TERMINATED - except Exception as e: + except Exception as e: # noqa: BLE001 - user handlers can raise anything; keep boundary log-and-terminate behavior self.logger.error( "Unexpected error while handling message of type: %s", e, @@ -327,7 +326,7 @@ def handle_incoming_message(self, incoming_message: bytes) -> MsgHandlingResult: case _: self.logger.warning( "Received unknown message type: %s", - type(flatbuffer.item).__name__, + type(flatbuffer.message).__name__, ) return MsgHandlingResult.MORE_MSGS_QUEUED diff --git a/rlbot/managers/bot.py b/rlbot/managers/bot.py index 13d9f5f..fcf5b9b 100644 --- a/rlbot/managers/bot.py +++ b/rlbot/managers/bot.py @@ -1,4 +1,5 @@ import os +import sys from traceback import print_exc from rlbot import flat @@ -61,7 +62,7 @@ def __init__(self, default_agent_id: str | None = None): "the constructor of the bot. If you are starting your bot manually, please set it " "manually, e.g. `RLBOT_AGENT_ID= python yourbot.py`" ) - exit(1) + sys.exit(1) self._game_interface = SocketRelay(agent_id, logger=self.logger) self._game_interface.match_config_handlers.append(self._handle_match_config) @@ -104,12 +105,12 @@ def _try_initialize(self): try: self.initialize() - except Exception as e: + except Exception as e: # noqa: BLE001 - user initialize may raise anything; log and exit self.logger.critical( "Bot %s failed to initialize due the following error: %s", self.name, e ) print_exc() - exit() + sys.exit(1) self._initialized_bot = True self._game_interface.send_msg(flat.InitComplete()) @@ -150,7 +151,7 @@ def _packet_processor(self, packet: flat.GamePacket): try: controller = self.get_output(packet) - except Exception as e: + except Exception as e: # noqa: BLE001 - user get_output may raise anything; keep bot alive self.logger.error( "Bot %s encountered an error while processing game packet: %s", self.name, @@ -206,7 +207,7 @@ def run( ) self._run() - except Exception as e: + except Exception as e: # noqa: BLE001 - ensure unexpected errors are logged before retire self.logger.error("Unexpected error: %s", e) finally: self.retire() @@ -283,8 +284,8 @@ def set_game_state(self, game_state: flat.DesiredGameState): def set_game_state_parts( self, - balls: dict[int, flat.DesiredBallState] = {}, - cars: dict[int, flat.DesiredCarState] = {}, + balls: dict[int, flat.DesiredBallState] | None = None, + cars: dict[int, flat.DesiredCarState] | None = None, match_info: flat.DesiredMatchInfo | None = None, ): """ diff --git a/rlbot/managers/hivemind.py b/rlbot/managers/hivemind.py index 6b11b63..12082f2 100644 --- a/rlbot/managers/hivemind.py +++ b/rlbot/managers/hivemind.py @@ -1,4 +1,5 @@ import os +import sys from logging import Logger from traceback import print_exc @@ -24,12 +25,8 @@ class Hivemind: """ _logger = DEFAULT_LOGGER - loggers: list[Logger] = [] team: int = -1 - indices: list[int] = [] - names: list[str] = [] - player_ids: list[int] = [] match_config = flat.MatchConfiguration() """ @@ -55,6 +52,11 @@ class Hivemind: _latest_prediction = flat.BallPrediction() def __init__(self, default_agent_id: str | None = None): + self.loggers: list[Logger] = [] + self.indices: list[int] = [] + self.names: list[str] = [] + self.player_ids: list[int] = [] + agent_id = os.environ.get("RLBOT_AGENT_ID") or default_agent_id if agent_id is None: @@ -63,7 +65,7 @@ def __init__(self, default_agent_id: str | None = None): "the constructor of the bot. If you are starting your bot manually, please set it " "manually, e.g. `RLBOT_AGENT_ID= python yourbot.py`" ) - exit(1) + sys.exit(1) self._game_interface = SocketRelay(agent_id, logger=self._logger) self._game_interface.match_config_handlers.append(self._handle_match_config) @@ -108,14 +110,14 @@ def _try_initialize(self): try: self.initialize() - except Exception as e: + except Exception as e: # noqa: BLE001 - user initialize may raise anything; log and exit self._logger.critical( "Hivemind (of %s) failed to initialize due the following error: %s", "Unknown_Bots" if len(self.names) == 0 else ", ".join(self.names), e, ) print_exc() - exit() + sys.exit(1) self._initialized_bot = True self._game_interface.send_msg(flat.InitComplete()) @@ -155,8 +157,8 @@ def _packet_processor(self, packet: flat.GamePacket): self.ball_prediction = self._latest_prediction try: - controller = self.get_outputs(packet) - except Exception as e: + controllers = self.get_outputs(packet) + except Exception as e: # noqa: BLE001 - user get_outputs may raise anything; keep hivemind alive self._logger.error( "Hivemind (of %s) encountered an error while processing game packet: %s", ", ".join(self.names), @@ -165,7 +167,7 @@ def _packet_processor(self, packet: flat.GamePacket): print_exc() return - for index, controller in controller.items(): + for index, controller in controllers.items(): if index not in self.indices: self._logger.warning( "Hivemind produced controller state for a bot index that is does not" @@ -299,8 +301,8 @@ def set_game_state(self, game_state: flat.DesiredGameState): def set_game_state_parts( self, - balls: dict[int, flat.DesiredBallState] = {}, - cars: dict[int, flat.DesiredCarState] = {}, + balls: dict[int, flat.DesiredBallState] | None = None, + cars: dict[int, flat.DesiredCarState] | None = None, match_info: flat.DesiredMatchInfo | None = None, ): """ diff --git a/rlbot/managers/match.py b/rlbot/managers/match.py index 0fa0a68..2e0e9a4 100644 --- a/rlbot/managers/match.py +++ b/rlbot/managers/match.py @@ -2,6 +2,7 @@ import stat from pathlib import Path from time import sleep +from typing import Self import psutil @@ -37,7 +38,7 @@ def __init__(self, rlbot_server_path: Path | None = None): self.rlbot_interface: SocketRelay = SocketRelay("") self.rlbot_interface.packet_handlers.append(self._packet_reporter) - def __enter__(self) -> "MatchManager": + def __enter__(self) -> Self: return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: @@ -46,7 +47,7 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> None: @property def _rlbot_server_name(self) -> str: return ( - self.rlbot_server_path.stem + self.rlbot_server_path.name if self.rlbot_server_path is not None and self.rlbot_server_path.is_file() else RLBOT_SERVER_NAME ) @@ -74,12 +75,12 @@ def ensure_server_started(self): self.logger.debug( f"Could not find RLBotServer in cwd ('{path.parent}'), trying %localappdata% instead." ) - path = ( - Path(os.environ.get("LOCALAPPDATA")) - / "RLBot5" - / "bin" - / RLBOT_SERVER_NAME - ) + local_appdata = os.environ.get("LOCALAPPDATA") + if local_appdata is None: + raise FileNotFoundError( + "LOCALAPPDATA is not set, so the default RLBotServer location cannot be checked." + ) + path = Path(local_appdata) / "RLBot5" / "bin" / RLBOT_SERVER_NAME if not path.exists(): raise FileNotFoundError( "Unable to find RLBotServer in the current working directory " @@ -246,8 +247,8 @@ def set_game_state(self, game_state: flat.DesiredGameState): def set_game_state_parts( self, - balls: dict[int, flat.DesiredBallState] = {}, - cars: dict[int, flat.DesiredCarState] = {}, + balls: dict[int, flat.DesiredBallState] | None = None, + cars: dict[int, flat.DesiredCarState] | None = None, match_info: flat.DesiredMatchInfo | None = None, ): """ diff --git a/rlbot/managers/rendering.py b/rlbot/managers/rendering.py index aec3978..36ea8cc 100644 --- a/rlbot/managers/rendering.py +++ b/rlbot/managers/rendering.py @@ -47,16 +47,15 @@ class Renderer: _logger = get_logger("renderer") - _used_group_ids: set[int] = set() - _group_id: int | None = None - _current_renders: list[flat.RenderMessage] = [] - _default_color = white _screen_width_factor = 1.0 _screen_height_factor = 1.0 def __init__(self, game_interface: SocketRelay): + self._used_group_ids: set[int] = set() + self._group_id: int | None = None + self._current_renders: list[flat.RenderMessage] = [] self._send_msg: Callable[[flat.RenderGroup | flat.RemoveRenderGroup], None] = ( game_interface.send_msg ) @@ -93,6 +92,8 @@ def create_color_hsv(hue: float, saturation: float, value: float) -> flat.Color: q = value * (1 - f * saturation) t = value * (1 - (1 - f) * saturation) + r = g = b = 0.0 + match i % 6: case 0: r, g, b = value, t, p @@ -256,7 +257,7 @@ def draw_string_3d( anchor: flat.RenderAnchor | flat.BallAnchor | flat.CarAnchor | flat.Vector3, scale: float, foreground: flat.Color | None = None, - background: flat.Color = flat.Color(a=0), + background: flat.Color | None = None, h_align: flat.TextHAlign = flat.TextHAlign.Left, v_align: flat.TextVAlign = flat.TextVAlign.Top, ): @@ -264,6 +265,8 @@ def draw_string_3d( Draws text anchored in 3d space. Characters of the font are 20 pixels tall and 10 pixels wide when `scale == 1.0`. """ + if background is None: + background = flat.Color(a=0) self.draw( flat.String3D( text, @@ -283,7 +286,7 @@ def draw_string_2d( y: float, scale: float, foreground: flat.Color | None = None, - background: flat.Color = flat.Color(a=0), + background: flat.Color | None = None, h_align: flat.TextHAlign = flat.TextHAlign.Left, v_align: flat.TextVAlign = flat.TextVAlign.Top, ): @@ -293,6 +296,8 @@ def draw_string_2d( Use `set_resolution` to change to pixel coordinates. Characters of the font are 20 pixels tall and 10 pixels wide when `scale == 1.0`. """ + if background is None: + background = flat.Color(a=0) self.draw( flat.String2D( text, diff --git a/rlbot/managers/script.py b/rlbot/managers/script.py index ae4c925..4893999 100644 --- a/rlbot/managers/script.py +++ b/rlbot/managers/script.py @@ -1,4 +1,5 @@ import os +import sys from traceback import print_exc from rlbot import flat @@ -46,7 +47,7 @@ def __init__(self, default_agent_id: str | None = None): "the constructor of the script. If you are starting your script manually, please set " "it manually, e.g. `RLBOT_AGENT_ID= python yourscript.py`" ) - exit(1) + sys.exit(1) self._game_interface = SocketRelay(agent_id, logger=self.logger) self._game_interface.match_config_handlers.append(self._handle_match_config) @@ -84,14 +85,14 @@ def _try_initialize(self): try: self.initialize() - except Exception as e: + except Exception as e: # noqa: BLE001 - user initialize may raise anything; log and exit self.logger.critical( "Script %s failed to initialize due the following error: %s", self.name, e, ) print_exc() - exit() + sys.exit(1) self._initialized_script = True self._game_interface.send_msg(flat.InitComplete()) @@ -118,7 +119,7 @@ def _packet_processor(self, packet: flat.GamePacket): try: self.handle_packet(packet) - except Exception as e: + except Exception as e: # noqa: BLE001 - user handle_packet may raise anything; keep script alive self.logger.error( "Script %s encountered an error to RLBot: %s", self.name, e ) @@ -243,8 +244,8 @@ def set_game_state(self, game_state: flat.DesiredGameState): def set_game_state_parts( self, - balls: dict[int, flat.DesiredBallState] = {}, - cars: dict[int, flat.DesiredCarState] = {}, + balls: dict[int, flat.DesiredBallState] | None = None, + cars: dict[int, flat.DesiredCarState] | None = None, match_info: flat.DesiredMatchInfo | None = None, ): """ diff --git a/rlbot/utils/__init__.py b/rlbot/utils/__init__.py index 21aaf55..b4be9d7 100644 --- a/rlbot/utils/__init__.py +++ b/rlbot/utils/__init__.py @@ -2,8 +2,8 @@ def fill_desired_game_state( - balls: dict[int, flat.DesiredBallState] = {}, - cars: dict[int, flat.DesiredCarState] = {}, + balls: dict[int, flat.DesiredBallState] | None = None, + cars: dict[int, flat.DesiredCarState] | None = None, match_info: flat.DesiredMatchInfo | None = None, ) -> flat.DesiredGameState: """ diff --git a/rlbot/utils/gateway.py b/rlbot/utils/gateway.py index 0565d32..050e1f2 100644 --- a/rlbot/utils/gateway.py +++ b/rlbot/utils/gateway.py @@ -1,3 +1,4 @@ +import shlex import socket import subprocess from pathlib import Path @@ -6,10 +7,7 @@ from rlbot.interface import RLBOT_SERVER_PORT from rlbot.utils.logging import DEFAULT_LOGGER -from rlbot.utils.os_detector import CURRENT_OS - -if CURRENT_OS != "Windows": - import shlex +from rlbot.utils.os_detector import CURRENT_OS, OS def find_file(base_dir: Path, file_name: str) -> Path | None: @@ -34,7 +32,7 @@ def is_port_accessible(port: int): try: sock.bind(("127.0.0.1", port)) return True - except: + except OSError: return False @@ -52,7 +50,7 @@ def find_open_server_port() -> int: def launch(exe_path: Path) -> tuple[subprocess.Popen[bytes], int]: port = find_open_server_port() - if CURRENT_OS == "Windows": + if CURRENT_OS == OS.WINDOWS: args = [str(exe_path), str(port)] else: args = f"{shlex.quote(exe_path.as_posix())} {port}" # on Unix, when shell=True, args must be a string for flags to reach the executable @@ -71,19 +69,17 @@ def find_server_process( continue args = proc.cmdline() - - if len(args) < 2: - # server has no specified port, return default - return proc, RLBOT_SERVER_PORT - - # read the port - port = int(proc.cmdline()[-1]) - return proc, port - except Exception as e: + except (psutil.NoSuchProcess, psutil.AccessDenied) as e: logger.error( - "Failed to read the name of a process while hunting for %s: %s", - exe_name, - e, + "Failed to inspect a process while looking for %s: %s", exe_name, e ) + continue + + # The socket port comes before the optional game port. + try: + port = int(args[1]) + except (IndexError, ValueError): + port = RLBOT_SERVER_PORT + return proc, port if 0 <= port <= 65535 else RLBOT_SERVER_PORT return None, RLBOT_SERVER_PORT diff --git a/rlbot/utils/logging.py b/rlbot/utils/logging.py index 90311c8..f405ee2 100644 --- a/rlbot/utils/logging.py +++ b/rlbot/utils/logging.py @@ -1,86 +1,87 @@ -import logging -import os -import sys - -DEFAULT_LOGGER_NAME = "rlbot" -DEFAULT_LOGGER = None # Set later - -match os.environ.get("RLBOT_LOG_LEVEL"): - case "debug": - LOGGING_LEVEL = logging.DEBUG - case "info": - LOGGING_LEVEL = logging.INFO - case "warn": - LOGGING_LEVEL = logging.WARNING - case "error": - LOGGING_LEVEL = logging.ERROR - case "critical": - LOGGING_LEVEL = logging.CRITICAL - case _: - LOGGING_LEVEL = logging.INFO - -logging.getLogger().setLevel(logging.NOTSET) - - -class CustomFormatter(logging.Formatter): - GREY = "\x1b[38;20m" - LIGHT_BLUE = "\x1b[94;20m" - YELLOW = "\x1b[33;20m" - GREEN = "\x1b[32;20m" - RED = "\x1b[31;20m" - BOLD_RED = "\x1b[31;1m" - RESET = "\x1b[0m" - SECTIONS = [ - "%(asctime)s " + RESET, - "%(levelname)8s:" + RESET + GREEN + "%(name)12s" + RESET, - "[%(filename)16s:%(lineno)3s - %(funcName)25s() ]" + RESET + " ", - "%(message)s" + RESET, - ] - - FORMATS = { - logging.DEBUG: [GREY, GREY, GREY, GREY], - logging.INFO: [GREY, LIGHT_BLUE, GREY, LIGHT_BLUE], - logging.WARNING: [YELLOW, YELLOW, YELLOW, YELLOW], - logging.ERROR: [RED, RED, RED, RED], - logging.CRITICAL: [RED, BOLD_RED, RED, BOLD_RED], - } - - def format(self, record: logging.LogRecord) -> str: - colors = self.FORMATS[record.levelno] - - log_fmt = "" - for color, section in zip(colors, self.SECTIONS): - log_fmt += color + section - - formatter = logging.Formatter(log_fmt, datefmt="%H:%M:%S") - return formatter.format(record) - - -def check_color(): - from rlbot.utils.os_detector import CURRENT_OS, OS - - if CURRENT_OS == OS.WINDOWS: - import os - - os.system("color") - - -def get_logger(logger_name: str) -> logging.Logger: - if logger_name == DEFAULT_LOGGER_NAME: - if DEFAULT_LOGGER is not None: - return DEFAULT_LOGGER - check_color() - - logger = logging.getLogger(logger_name) - if not logger.handlers: - ch = logging.StreamHandler() - ch.setFormatter(CustomFormatter()) - ch.setLevel(LOGGING_LEVEL) - logger.addHandler(ch) - logging.getLogger().handlers = [] - - logger.debug("creating logger for %s", sys._getframe().f_back) - return logger - - -DEFAULT_LOGGER = get_logger(DEFAULT_LOGGER_NAME) +import logging +import os +import sys +from typing import ClassVar + +DEFAULT_LOGGER_NAME = "rlbot" +DEFAULT_LOGGER = None # Set later + +match os.environ.get("RLBOT_LOG_LEVEL"): + case "debug": + LOGGING_LEVEL = logging.DEBUG + case "info": + LOGGING_LEVEL = logging.INFO + case "warn": + LOGGING_LEVEL = logging.WARNING + case "error": + LOGGING_LEVEL = logging.ERROR + case "critical": + LOGGING_LEVEL = logging.CRITICAL + case _: + LOGGING_LEVEL = logging.INFO + +logging.getLogger().setLevel(logging.NOTSET) + + +class CustomFormatter(logging.Formatter): + GREY = "\x1b[38;20m" + LIGHT_BLUE = "\x1b[94;20m" + YELLOW = "\x1b[33;20m" + GREEN = "\x1b[32;20m" + RED = "\x1b[31;20m" + BOLD_RED = "\x1b[31;1m" + RESET = "\x1b[0m" + SECTIONS: ClassVar[list[str]] = [ + "%(asctime)s " + RESET, + "%(levelname)8s:" + RESET + GREEN + "%(name)12s" + RESET, + "[%(filename)16s:%(lineno)3s - %(funcName)25s() ]" + RESET + " ", + "%(message)s" + RESET, + ] + + FORMATS: ClassVar[dict[int, list[str]]] = { + logging.DEBUG: [GREY, GREY, GREY, GREY], + logging.INFO: [GREY, LIGHT_BLUE, GREY, LIGHT_BLUE], + logging.WARNING: [YELLOW, YELLOW, YELLOW, YELLOW], + logging.ERROR: [RED, RED, RED, RED], + logging.CRITICAL: [RED, BOLD_RED, RED, BOLD_RED], + } + + def format(self, record: logging.LogRecord) -> str: + colors = self.FORMATS[record.levelno] + + log_fmt = "" + for color, section in zip(colors, self.SECTIONS): + log_fmt += color + section + + formatter = logging.Formatter(log_fmt, datefmt="%H:%M:%S") + return formatter.format(record) + + +def check_color(): + from rlbot.utils.os_detector import CURRENT_OS, OS + + if CURRENT_OS == OS.WINDOWS: + import os + + os.system("color") + + +def get_logger(logger_name: str) -> logging.Logger: + if logger_name == DEFAULT_LOGGER_NAME: + if DEFAULT_LOGGER is not None: + return DEFAULT_LOGGER + check_color() + + logger = logging.getLogger(logger_name) + if not logger.handlers: + ch = logging.StreamHandler() + ch.setFormatter(CustomFormatter()) + ch.setLevel(LOGGING_LEVEL) + logger.addHandler(ch) + logging.getLogger().handlers = [] + + logger.debug("creating logger for %s", sys._getframe().f_back) + return logger + + +DEFAULT_LOGGER = get_logger(DEFAULT_LOGGER_NAME) diff --git a/rlbot/version.py b/rlbot/version.py index 6e93f11..f6c1a08 100644 --- a/rlbot/version.py +++ b/rlbot/version.py @@ -1 +1 @@ -__version__ = "2.0.0-beta.57" +__version__ = "2.0.0-beta.58" diff --git a/tests/test_config_parity.py b/tests/test_config_parity.py new file mode 100644 index 0000000..5b4c9f4 --- /dev/null +++ b/tests/test_config_parity.py @@ -0,0 +1,953 @@ +"""Regression tests for match parser parity with core. + +Use only file operations and the parser API. +Run with: pytest tests/test_config_parity.py -v +""" + +from collections.abc import Sequence +from pathlib import Path + +import pytest + +import rlbot.config as config_mod +from rlbot import flat +from rlbot.config import ( + ConfigParsingException, + load_match_config, + load_player_config, + load_player_loadout, + load_psyonix_config, + load_script_config, +) +from rlbot.utils.os_detector import OS + +DIR = Path(__file__).parent + + +def write(path: Path, text: str) -> Path: + """Write text to path. Create parent folders as needed.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + return path + + +def make_bot(tmp: Path, name: str = "bot.toml", with_loadout: bool = True) -> Path: + """Create a minimal bot file. Return its path.""" + lines = [ + "[settings]", + 'agent_id = "test/bot"', + 'name = "Test Bot"', + 'run_command = "python bot.py"', + 'run_command_linux = "python3 bot.py"', + ] + if with_loadout: + lines.append('loadout_file = "loadout.toml"') + write( + tmp / "loadout.toml", + "[blue_loadout]\nteam_color_id = 1\n[orange_loadout]\nteam_color_id = 2\n", + ) + write(tmp / name, "\n".join(lines) + "\n") + return tmp / name + + +def make_script(tmp: Path, name: str = "script.toml") -> Path: + """Create a minimal script file. Return its path.""" + write( + tmp / name, + "[settings]\n" + 'agent_id = "test/script"\n' + 'name = "Test Script"\n' + 'run_command = "python script.py"\n' + 'run_command_linux = "python3 script.py"\n', + ) + return tmp / name + + +def make_linked(tmp: Path) -> Path: + """Create a linked bot file and its loadout. Return the bot path.""" + write( + tmp / "linked.toml", + "[settings]\n" + 'agent_id = "test/linked"\n' + 'name = "Linked Name"\n' + 'run_command = "python bot.py"\n' + 'loadout_file = "loadout.toml"\n', + ) + write( + tmp / "loadout.toml", + "[blue_loadout]\nteam_color_id = 33\n[orange_loadout]\nteam_color_id = 34\n", + ) + return tmp / "linked.toml" + + +def _mutators(m: flat.MatchConfiguration) -> flat.MutatorSettings: + """Return mutators. Fail if missing.""" + mut = m.mutators + assert mut is not None + return mut + + +def _custom(variety: flat.CustomBot | flat.Human | flat.PsyonixBot) -> flat.CustomBot: + """Return custom bot variety. Fail if wrong type.""" + assert isinstance(variety, flat.CustomBot) + return variety + + +def _psyonix(variety: flat.CustomBot | flat.Human | flat.PsyonixBot) -> flat.PsyonixBot: + """Return Psyonix bot variety. Fail if wrong type.""" + assert isinstance(variety, flat.PsyonixBot) + return variety + + +def _custom_env( + variety: flat.CustomBot | flat.Human | flat.PsyonixBot, +) -> Sequence[flat.EnvironmentVariable]: + """Return bot environment list. Fail if missing.""" + bot = _custom(variety) + assert bot.environment is not None + return bot.environment + + +def _script_env(cfg: flat.ScriptConfiguration) -> Sequence[flat.EnvironmentVariable]: + """Return script environment list. Fail if missing.""" + assert cfg.environment is not None + return cfg.environment + + +def _loadout(loadout: flat.PlayerLoadout | None) -> flat.PlayerLoadout: + """Return loadout. Fail if missing.""" + assert loadout is not None + return loadout + + +class TestMatchDefaultsKeysRendering: + """Check match defaults and key names.""" + + def test_empty_file_uses_documented_defaults(self, tmp_path: Path): + p = write(tmp_path / "empty.toml", "") + m = load_match_config(p) + assert m.launcher == flat.Launcher.Steam + assert m.launcher_arg == "" + assert m.auto_start_agents + assert m.wait_for_agents + assert m.game_map_upk == "Stadium_P" + assert m.game_mode == flat.GameMode.Soccar + assert not m.skip_replays + assert not m.instant_start + assert m.existing_match_behavior == flat.ExistingMatchBehavior.Restart + assert m.enable_rendering == flat.DebugRendering.OffByDefault + assert m.enable_state_setting + assert not m.auto_save_replay + assert not m.freeplay + assert m.performance_monitor == flat.PerformanceMonitor.ShowWhenSuboptimal + assert m.player_configurations == [] + assert m.script_configurations == [] + + def test_start_without_countdown_key_maps_to_instant_start(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + "[match]\nstart_without_countdown = true\n", + ) + m = load_match_config(p) + assert m.instant_start + + def test_soccer_alias_maps_to_soccar(self, tmp_path: Path): + p = write(tmp_path / "m.toml", '[match]\ngame_mode = "soccer"\n') + m = load_match_config(p) + assert m.game_mode == flat.GameMode.Soccar + + def test_rendering_false_maps_to_always_off(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[match]\nenable_rendering = false\n") + m = load_match_config(p) + assert m.enable_rendering == flat.DebugRendering.AlwaysOff + + def test_rendering_true_maps_to_on_by_default(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[match]\nenable_rendering = true\n") + m = load_match_config(p) + assert m.enable_rendering == flat.DebugRendering.OnByDefault + + def test_rendering_string_off_by_default(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[match]\nenable_rendering = "OffByDefault"\n', + ) + m = load_match_config(p) + assert m.enable_rendering == flat.DebugRendering.OffByDefault + + def test_rendering_string_always_off(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[match]\nenable_rendering = "AlwaysOff"\n', + ) + m = load_match_config(p) + assert m.enable_rendering == flat.DebugRendering.AlwaysOff + + def test_launcher_arg_and_freeplay_and_autosave(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[rlbot]\nlauncher = "Steam"\nlauncher_arg = "legendary"\n' + "[match]\nfreeplay = true\nauto_save_replay = true\n", + ) + m = load_match_config(p) + assert m.launcher_arg == "legendary" + assert m.freeplay + assert m.auto_save_replay + + def test_plural_auto_save_replays_enables_saving(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[match]\nauto_save_replays = true\n") + m = load_match_config(p) + assert m.auto_save_replay + + def test_plural_auto_save_replays_wins_over_singular(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + "[match]\nauto_save_replay = true\nauto_save_replays = false\n", + ) + m = load_match_config(p) + assert not m.auto_save_replay + + +class TestMutatorParity: + """Check all mutators from core are parsed.""" + + def test_extended_mutators(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + "[mutators]\n" + 'ball_gravity = "High"\n' + 'territory = "Territory"\n' + 'stale_ball = "ThirtySeconds"\n' + 'jump = "NoJumps"\n' + 'dodge_timer = "ThreeSeconds"\n' + 'possession_score = "ThreeSeconds"\n' + 'demolish_score = "Three"\n' + 'normal_goal_score = "Five"\n' + 'aerial_goal_score = "Ten"\n' + 'assist_goal_score = "Three"\n' + 'input_restriction = "Backwards"\n', + ) + m = load_match_config(p) + mut = _mutators(m) + assert mut.ball_gravity == flat.BallGravityMutator.High + assert mut.territory == flat.TerritoryMutator.Territory + assert mut.stale_ball == flat.StaleBallMutator.ThirtySeconds + assert mut.jump == flat.JumpMutator.NoJumps + assert mut.dodge_timer == flat.DodgeTimerMutator.ThreeSeconds + assert mut.possession_score == flat.PossessionScoreMutator.ThreeSeconds + assert mut.demolish_score == flat.DemolishScoreMutator.Three + assert mut.normal_goal_score == flat.NormalGoalScoreMutator.Five + assert mut.aerial_goal_score == flat.AerialGoalScoreMutator.Ten + assert mut.assist_goal_score == flat.AssistGoalScoreMutator.Three + assert mut.input_restriction == flat.InputRestrictionMutator.Backwards + + def test_core_mutators_case_insensitive(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[mutators]\nmatch_length = "TenMinutes"\ngravity = "rEvErsE"\n', + ) + m = load_match_config(p) + mut = _mutators(m) + assert mut.match_length == flat.MatchLengthMutator.TenMinutes + assert mut.gravity == flat.GravityMutator.Reverse + + def test_mutator_defaults_match_core(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "") + m = load_match_config(p) + mut = _mutators(m) + assert mut.match_length == flat.MatchLengthMutator.FiveMinutes + assert mut.max_score == flat.MaxScoreMutator.Unlimited + assert mut.boost_amount == flat.BoostAmountMutator.NormalBoost + assert mut.rumble == flat.RumbleMutator.Off + assert mut.gravity == flat.GravityMutator.Default + assert mut.respawn_time == flat.RespawnTimeMutator.ThreeSeconds + assert mut.ball_gravity == flat.BallGravityMutator.Default + assert mut.territory == flat.TerritoryMutator.Off + + +class TestAutoStart: + """Check per-agent auto_start handling.""" + + def test_car_auto_start_false_clears_run_command(self, tmp_path: Path): + make_bot(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bot.toml"\nteam = 0\nauto_start = false\n', + ) + m = load_match_config(p) + variety = m.player_configurations[0].variety + assert isinstance(variety, flat.CustomBot) + assert _custom(variety).run_command == "" + + def test_car_auto_start_true_keeps_run_command(self, tmp_path: Path): + make_bot(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bot.toml"\nteam = 0\nauto_start = true\n', + ) + m = load_match_config(p) + variety = m.player_configurations[0].variety + assert _custom(variety).run_command != "" + + def test_script_auto_start_false_clears_run_command(self, tmp_path: Path): + make_script(tmp_path) + p = write( + tmp_path / "m.toml", + '[[scripts]]\nconfig_file = "script.toml"\nauto_start = false\n', + ) + m = load_match_config(p) + assert m.script_configurations[0].run_command == "" + + def test_disabled_custom_bot_bad_run_command_type_loads_empty(self, tmp_path: Path): + write( + tmp_path / "bot.toml", + '[settings]\nagent_id = "test/bot"\nname = "Test Bot"\nrun_command = 123\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0, auto_start=False) + assert _custom(cfg.variety).run_command == "" + + +class TestWineFallback: + """Check Linux run command fallback through Wine.""" + + def test_linux_command_preferred_when_present(self, tmp_path: Path): + bot = make_bot(tmp_path) + cfg = load_player_config(bot, 0) + # atba-style bot has run_command_linux set, so Linux build uses it. + # Our helper sets run_command_linux to python3. + assert "python3" in _custom(cfg.variety).run_command + + def test_wine_fallback_when_linux_command_missing( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Wine Bot"\n' + 'run_command = "bot.exe"\n', + ) + bot = tmp_path / "bot.toml" + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + cfg = load_player_config(bot, 0) + assert _custom(cfg.variety).run_command == "wine bot.exe" + + def test_script_wine_fallback_when_linux_command_missing( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + write( + tmp_path / "script.toml", + "[settings]\n" + 'agent_id = "test/script"\n' + 'name = "Wine Script"\n' + 'run_command = "run.exe"\n', + ) + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + cfg = load_script_config(tmp_path / "script.toml") + assert cfg.run_command == "wine run.exe" + + +class TestEnvironment: + """Check environment tables.""" + + def test_common_values_remain_literal( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("RLBOT_TEST_COMMON", "expanded-value") + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + 'LITERAL = "$RLBOT_TEST_COMMON/x"\n' + 'BRACED = "${RLBOT_TEST_COMMON}/y"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("LITERAL") == "$RLBOT_TEST_COMMON/x" + assert values.get("BRACED") == "${RLBOT_TEST_COMMON}/y" + + def test_linux_values_expand_and_override_common( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("RLBOT_TEST_EXPAND", "expanded-value") + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + 'BOT_ENV = "bot-value"\n' + 'SHARED_ENV = "common"\n' + "[settings.environment.linux]\n" + 'SHARED_ENV = "$RLBOT_TEST_EXPAND"\n' + 'PLATFORM_ENV = "$RLBOT_TEST_EXPAND/x"\n' + 'BRACED_ENV = "${RLBOT_TEST_EXPAND}/y"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("BOT_ENV") == "bot-value" + assert values.get("SHARED_ENV") == "expanded-value" + assert values.get("PLATFORM_ENV") == "expanded-value/x" + assert values.get("BRACED_ENV") == "expanded-value/y" + + def test_inactive_platform_is_ignored( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + 'SHARED_ENV = "common"\n' + "[settings.environment.windows]\n" + 'SHARED_ENV = "windows-value"\n' + 'WIN_ONLY = "win"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("SHARED_ENV") == "common" + assert "WIN_ONLY" not in values + + def test_unknown_vars_remain_unchanged( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment.linux]\n" + 'UNKNOWN = "$RLBOT_DEFINITELY_MISSING_XYZ/x"\n' + 'BRACED = "${RLBOT_DEFINITELY_MISSING_XYZ}/y"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("UNKNOWN") == "$RLBOT_DEFINITELY_MISSING_XYZ/x" + assert values.get("BRACED") == "${RLBOT_DEFINITELY_MISSING_XYZ}/y" + + def test_windows_values_expand_percent( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("RLBOT_TEST_WIN", "win-value") + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.WINDOWS) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + 'COMMON = "common"\n' + "[settings.environment.windows]\n" + 'SHARED = "%RLBOT_TEST_WIN%"\n' + 'WIN_ONLY = "%RLBOT_TEST_WIN%/x"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("COMMON") == "common" + assert values.get("SHARED") == "win-value" + assert values.get("WIN_ONLY") == "win-value/x" + + def test_linux_cross_syntax_percent_and_dollar_expand( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("RLBOT_TEST_CROSS", "cross-value") + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment.linux]\n" + 'PCT = "%RLBOT_TEST_CROSS%/x"\n' + 'DOLLAR = "$RLBOT_TEST_CROSS/x"\n' + 'BRACED = "${RLBOT_TEST_CROSS}/y"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("PCT") == "cross-value/x" + assert values.get("DOLLAR") == "cross-value/x" + assert values.get("BRACED") == "cross-value/y" + + def test_platform_expansion_does_not_rescan_replacements( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + monkeypatch.setenv("RLBOT_OUTER", "$RLBOT_INNER") + monkeypatch.setenv("RLBOT_INNER", "value") + monkeypatch.setenv("RLBOT_TEST_DIR(X86)", "test-dir") + path = write( + tmp_path / "bot.toml", + "[settings.environment.linux]\n" + 'VALUE = "%RLBOT_OUTER%|$RLBOT_INNER|%RLBOT_TEST_DIR(X86)%"\n', + ) + bot = load_player_config(path, 0).variety + assert {e.name: e.value for e in _custom_env(bot)} == { + "VALUE": "$RLBOT_INNER|value|test-dir" + } + + def test_inactive_linux_values_stay_absent_and_common_stays_literal( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.WINDOWS) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + 'SHARED = "common"\n' + 'LITERAL = "$SHOULD_STAY_LITERAL/x"\n' + "[settings.environment.linux]\n" + 'SHARED = "linux-value"\n' + 'LINUX_ONLY = "linux"\n', + ) + cfg = load_player_config(tmp_path / "bot.toml", 0) + values = {e.name: e.value for e in _custom_env(cfg.variety)} + assert values.get("SHARED") == "common" + assert values.get("LITERAL") == "$SHOULD_STAY_LITERAL/x" + assert "LINUX_ONLY" not in values + + def test_script_environment_transports_values( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("RLBOT_TEST_SCRIPT", "expanded-value") + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "script.toml", + "[settings]\n" + 'agent_id = "test/script"\n' + 'name = "Env Script"\n' + 'run_command = "python script.py"\n' + "[settings.environment]\n" + 'SCRIPT_ENV = "script-value"\n' + "[settings.environment.linux]\n" + 'LINUX_ENV = "$RLBOT_TEST_SCRIPT/x"\n', + ) + cfg = load_script_config(tmp_path / "script.toml") + values = {e.name: e.value for e in _script_env(cfg)} + assert values.get("SCRIPT_ENV") == "script-value" + assert values.get("LINUX_ENV") == "expanded-value/x" + + def test_non_string_common_environment_raises(self, tmp_path: Path): + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment]\n" + "NUM = 123\n", + ) + with pytest.raises(ConfigParsingException): + load_player_config(tmp_path / "bot.toml", 0) + + def test_non_string_platform_environment_raises( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(config_mod, "CURRENT_OS", OS.LINUX) + write( + tmp_path / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Env Bot"\n' + 'run_command = "python bot.py"\n' + "[settings.environment.linux]\n" + "NUM = 123\n", + ) + with pytest.raises(ConfigParsingException): + load_player_config(tmp_path / "bot.toml", 0) + + +class TestLoadoutOverrideAndPathAnchoring: + """Check loadout override rules and path anchoring.""" + + def test_empty_override_suppresses_loadout(self, tmp_path: Path): + make_bot(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bot.toml"\nteam = 0\nloadout_file = ""\n', + ) + m = load_match_config(p) + variety = m.player_configurations[0].variety + assert _custom(variety).loadout is None + + def test_override_anchored_at_match_dir(self, tmp_path: Path): + bot_dir = tmp_path / "bots" + bot_dir.mkdir() + write( + bot_dir / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Bot"\n' + 'run_command = "python bot.py"\n' + 'loadout_file = "bot_loadout.toml"\n', + ) + write( + bot_dir / "bot_loadout.toml", + "[blue_loadout]\nteam_color_id = 11\n" + "[orange_loadout]\nteam_color_id = 12\n", + ) + override_dir = tmp_path / "overrides" + override_dir.mkdir() + write( + override_dir / "override.toml", + "[blue_loadout]\nteam_color_id = 99\n" + "[orange_loadout]\nteam_color_id = 100\n", + ) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bots/bot.toml"\n' + 'team = 0\nloadout_file = "overrides/override.toml"\n', + ) + m = load_match_config(p) + assert ( + _loadout(_custom(m.player_configurations[0].variety).loadout).team_color_id + == 99 + ) + + def test_bot_relative_loadout_anchored_at_bot_dir(self, tmp_path: Path): + bot_dir = tmp_path / "deep" / "bots" + bot_dir.mkdir(parents=True) + write( + bot_dir / "bot.toml", + "[settings]\n" + 'agent_id = "test/bot"\n' + 'name = "Bot"\n' + 'run_command = "python bot.py"\n' + 'loadout_file = "loadout.toml"\n', + ) + write( + bot_dir / "loadout.toml", + "[blue_loadout]\nteam_color_id = 21\n" + "[orange_loadout]\nteam_color_id = 22\n", + ) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "deep/bots/bot.toml"\nteam = 0\n', + ) + m = load_match_config(p) + assert ( + _loadout(_custom(m.player_configurations[0].variety).loadout).team_color_id + == 21 + ) + + +class TestPsyonixLinkedValues: + """Check Psyonix bots with linked config files.""" + + def test_psyonix_inherits_name_and_loadout(self, tmp_path: Path): + make_linked(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "linked.toml"\nteam = 0\ntype = "Psyonix"\n', + ) + m = load_match_config(p) + variety = m.player_configurations[0].variety + assert isinstance(variety, flat.PsyonixBot) + bot = _psyonix(variety) + assert bot.name == "Linked Name" + assert bot.loadout is not None + assert _loadout(bot.loadout).team_color_id == 33 + + def test_psyonix_explicit_name_wins(self, tmp_path: Path): + make_linked(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "linked.toml"\nteam = 0\n' + 'type = "Psyonix"\nname = "Override"\n', + ) + m = load_match_config(p) + assert _psyonix(m.player_configurations[0].variety).name == "Override" + + def test_psyonix_explicit_loadout_wins(self, tmp_path: Path): + make_linked(tmp_path) + write( + tmp_path / "other.toml", + "[blue_loadout]\nteam_color_id = 77\n" + "[orange_loadout]\nteam_color_id = 78\n", + ) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "linked.toml"\nteam = 0\n' + 'type = "Psyonix"\nloadout_file = "other.toml"\n', + ) + m = load_match_config(p) + assert ( + _loadout(_psyonix(m.player_configurations[0].variety).loadout).team_color_id + == 77 + ) + + def test_psyonix_skill_from_car_table(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[[cars]]\nteam = 0\ntype = "Psyonix"\nskill = "Pro"\n', + ) + m = load_match_config(p) + assert ( + _psyonix(m.player_configurations[0].variety).bot_skill + == flat.PsyonixSkill.Pro + ) + + @pytest.mark.parametrize("car_fields", ["", 'type = "RLBot"\nconfig_file = ""\n']) + def test_rlbot_without_config_uses_psyonix(self, tmp_path: Path, car_fields: str): + write(tmp_path / "loadout.toml", "[orange_loadout]\ncar_id = 23\n") + path = write( + tmp_path / "m.toml", + f"[[cars]]\n{car_fields}" + 'team = "Orange"\nskill = "Pro"\nname = "Boomer"\n' + 'loadout_file = "loadout.toml"\n', + ) + car = load_match_config(path).player_configurations[0] + bot = _psyonix(car.variety) + assert car.team == 1 + assert bot.name == "Boomer" + assert bot.bot_skill == flat.PsyonixSkill.Pro + assert _loadout(bot.loadout).car_id == 23 + + def test_psyonix_default_skill_is_allstar(self, tmp_path: Path): + p = write(tmp_path / "m.toml", '[[cars]]\nteam = 1\ntype = "Psyonix"\n') + m = load_match_config(p) + assert ( + _psyonix(m.player_configurations[0].variety).bot_skill + == flat.PsyonixSkill.AllStar + ) + + def test_direct_psyonix_helper_inherits_linked_values(self, tmp_path: Path): + linked = make_linked(tmp_path) + cfg = load_psyonix_config(0, flat.PsyonixSkill.Pro, None, None, linked) + bot = _psyonix(cfg.variety) + assert bot.name == "Linked Name" + assert _loadout(bot.loadout).team_color_id == 33 + + def test_psyonix_skill_from_linked_root_wins_over_overrides(self, tmp_path: Path): + write( + tmp_path / "linked.toml", + 'skill = "Pro"\n' + "[settings]\n" + 'agent_id = "test/linked"\n' + 'name = "Linked Name"\n' + 'run_command = "python bot.py"\n' + 'loadout_file = "loadout.toml"\n', + ) + write( + tmp_path / "loadout.toml", + "[blue_loadout]\nteam_color_id = 33\n" + "[orange_loadout]\nteam_color_id = 34\n", + ) + write( + tmp_path / "other.toml", + "[blue_loadout]\nteam_color_id = 77\n" + "[orange_loadout]\nteam_color_id = 78\n", + ) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "linked.toml"\nteam = 0\n' + 'type = "Psyonix"\nskill = "Rookie"\n' + 'name = "Override"\nloadout_file = "other.toml"\n', + ) + m = load_match_config(p) + variety = m.player_configurations[0].variety + assert isinstance(variety, flat.PsyonixBot) + bot = _psyonix(variety) + assert bot.bot_skill == flat.PsyonixSkill.Pro + assert bot.name == "Override" + assert _loadout(bot.loadout).team_color_id == 77 + + +class TestInvalidSkillIgnored: + """Check invalid skill is ignored for some entries.""" + + def test_invalid_skill_on_human_is_ignored(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[[cars]]\nteam = 0\ntype = "Human"\nskill = "NotASkill"\n', + ) + m = load_match_config(p) + assert isinstance(m.player_configurations[0].variety, flat.Human) + + def test_invalid_skill_on_custom_file_backed_is_ignored(self, tmp_path: Path): + make_bot(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bot.toml"\nteam = 0\nskill = "NotASkill"\n', + ) + m = load_match_config(p) + assert isinstance(m.player_configurations[0].variety, flat.CustomBot) + + +class TestScriptValidation: + """Check script entries need a config file.""" + + def test_script_without_config_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[[scripts]]\n") + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_script_without_config_but_auto_start_still_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[[scripts]]\nauto_start = false\n") + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_script_with_config_loads_fields(self, tmp_path: Path): + make_script(tmp_path) + p = write(tmp_path / "m.toml", '[[scripts]]\nconfig_file = "script.toml"\n') + m = load_match_config(p) + s = m.script_configurations[0] + assert s.name == "Test Script" + assert s.agent_id == "test/script" + assert s.run_command != "" + assert s.root_dir != "" + + +class TestTypeValidation: + """Check wrong types raise ConfigParsingException.""" + + def test_string_for_bool_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", '[match]\nenable_rendering = "false"\n') + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_bad_launcher_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", '[rlbot]\nlauncher = "NonExistent"\n') + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_bad_team_raises(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[[cars]]\nteam = 42\ntype = "Psyonix"\n', + ) + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_bad_player_type_raises(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[[cars]]\nteam = 0\ntype = "NotARobot"\n', + ) + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_script_missing_settings_returns_defaults(self, tmp_path: Path): + p = write(tmp_path / "empty.toml", "") + cfg = load_script_config(p) + assert cfg.name == "" + assert cfg.agent_id == "" + assert cfg.run_command == "" + assert list(_script_env(cfg)) == [] + + def test_loadout_int_type_error_raises(self, tmp_path: Path): + p = write( + tmp_path / "loadout.toml", + '[blue_loadout]\nteam_color_id = "red"\n' + "[orange_loadout]\nteam_color_id = 1\n", + ) + with pytest.raises(ConfigParsingException): + load_player_loadout(p, 0) + + def test_team_bool_raises(self, tmp_path: Path): + p = write( + tmp_path / "m.toml", + '[[cars]]\nteam = true\ntype = "Human"\n', + ) + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_integer_enum_value_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "[match]\ngame_mode = 1\n") + with pytest.raises(ConfigParsingException): + load_match_config(p) + + @pytest.mark.parametrize("value", ["-1", "999"]) + def test_out_of_range_numeric_enum_raises(self, tmp_path: Path, value: str): + path = write(tmp_path / "m.toml", f'[mutators]\nseries_length = "{value}"\n') + with pytest.raises(ConfigParsingException, match="series_length"): + load_match_config(path) + + def test_non_list_cars_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", 'cars = "nope"\n') + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_non_table_car_entry_raises(self, tmp_path: Path): + p = write(tmp_path / "m.toml", "cars = [42]\n") + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_wrong_type_auto_start_raises(self, tmp_path: Path): + make_bot(tmp_path) + p = write( + tmp_path / "m.toml", + '[[cars]]\nconfig_file = "bot.toml"\nteam = 0\nauto_start = "true"\n', + ) + with pytest.raises(ConfigParsingException): + load_match_config(p) + + def test_loadout_unsigned_id_range_raises(self, tmp_path: Path): + p = write( + tmp_path / "loadout.toml", + "[blue_loadout]\nteam_color_id = -1\n[orange_loadout]\nteam_color_id = 1\n", + ) + with pytest.raises(ConfigParsingException): + load_player_loadout(p, 0) + + p = write( + tmp_path / "loadout.toml", + "[blue_loadout]\nteam_color_id = 4294967296\n" + "[orange_loadout]\nteam_color_id = 1\n", + ) + with pytest.raises(ConfigParsingException): + load_player_loadout(p, 0) + + +class TestPaintBehavior: + """Check paint defaults and values.""" + + def test_missing_paint_gives_zeroed_paint(self, tmp_path: Path): + p = write( + tmp_path / "loadout.toml", + "[blue_loadout]\nteam_color_id = 5\n[orange_loadout]\nteam_color_id = 6\n", + ) + blue = load_player_loadout(p, 0) + orange = load_player_loadout(p, 1) + assert blue.loadout_paint is not None + assert orange.loadout_paint is not None + assert blue.loadout_paint.car_paint_id == 0 + assert orange.loadout_paint.car_paint_id == 0 + assert blue.loadout_paint.trails_paint_id == 0 + + def test_present_paint_values_preserved(self): + blue = load_player_loadout(DIR / "atba" / "loadout.toml", 0) + orange = load_player_loadout(DIR / "atba" / "loadout.toml", 1) + assert blue.loadout_paint is not None + assert orange.loadout_paint is not None + assert blue.loadout_paint.car_paint_id == 9 + assert orange.loadout_paint.car_paint_id == 1 + assert blue.loadout_paint.boost_paint_id == 5 + assert orange.loadout_paint.goal_explosion_paint_id == 10 + + def test_team_selects_correct_loadout_table(self, tmp_path: Path): + p = write( + tmp_path / "loadout.toml", + "[blue_loadout]\nteam_color_id = 31\n" + "[orange_loadout]\nteam_color_id = 32\n", + ) + assert load_player_loadout(p, 0).team_color_id == 31 + assert load_player_loadout(p, 1).team_color_id == 32 + + def test_invalid_team_does_not_select_orange_loadout(self, tmp_path: Path): + path = write(tmp_path / "loadout.toml", "[orange_loadout]\ncar_id = 23\n") + with pytest.raises(ConfigParsingException, match="team"): + load_player_loadout(path, 2) diff --git a/tests/test_gateway.py b/tests/test_gateway.py new file mode 100644 index 0000000..e5b4806 --- /dev/null +++ b/tests/test_gateway.py @@ -0,0 +1,52 @@ +from pathlib import Path +from unittest.mock import Mock + +import psutil +import pytest + +from rlbot.interface import RLBOT_SERVER_PORT +from rlbot.managers.match import MatchManager +from rlbot.utils import gateway + + +@pytest.mark.parametrize( + ("args", "expected_port"), + [ + ([], RLBOT_SERVER_PORT), + (["23235"], 23235), + (["23235", "23233"], 23235), + (["23235", "--flag"], 23235), + (["--flag"], RLBOT_SERVER_PORT), + (["65536"], RLBOT_SERVER_PORT), + ], +) +def test_find_server_process_uses_first_argument( + monkeypatch: pytest.MonkeyPatch, args: list[str], expected_port: int +): + server = Mock(spec=psutil.Process) + server.name.return_value = "RLBotServer.exe" + server.cmdline.return_value = ["RLBotServer.exe", *args] + monkeypatch.setattr(gateway.psutil, "process_iter", lambda: iter([server])) + + assert gateway.find_server_process("RLBotServer.exe") == (server, expected_port) + server.cmdline.assert_called_once_with() + + +def test_match_manager_matches_explicit_executable_name( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + exe = tmp_path / "RLBotServer.exe" + exe.touch() + server = Mock(spec=psutil.Process) + server.name.return_value = exe.name + server.cmdline.return_value = [str(exe), "23235", "23233"] + monkeypatch.setattr(gateway.psutil, "process_iter", lambda: iter([server])) + launch = Mock(side_effect=AssertionError("Server should not be launched twice")) + monkeypatch.setattr(gateway, "launch", launch) + + manager = MatchManager(exe) + manager.ensure_server_started() + + assert manager.rlbot_server_process is server + assert manager.rlbot_server_port == 23235 + launch.assert_not_called()