diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index cb22f5c61..9b7e59701 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/platform/common/_bindings.py b/packages/uipath-platform/src/uipath/platform/common/_bindings.py index dc775f862..0301fb8ed 100644 --- a/packages/uipath-platform/src/uipath/platform/common/_bindings.py +++ b/packages/uipath-platform/src/uipath/platform/common/_bindings.py @@ -244,6 +244,10 @@ def folder_identifier(self) -> str: for resource_type in get_args(model.model_fields["resource_type"].annotation) ) +_KNOWN_RESOURCE_TYPES_IN_LOWER_CASE: dict[str, str] = { + resource_type.lower(): resource_type for resource_type in _KNOWN_RESOURCE_TYPES +} + class ResourceOverwriteParser: """Parser for resource overwrite configurations. @@ -267,6 +271,24 @@ def knows(cls, key: str) -> bool: """ return key.split(".")[0] in _KNOWN_RESOURCE_TYPES + @classmethod + def in_this_sdks_spelling(cls, key: str) -> str: + """Spell the resource type of ``key`` the way this SDK looks it up. + + Other runtimes write some types in another case ("Connection" where this + SDK has "connection"), and lookups here match the key exactly. + + Args: + key: The resource key (e.g., "Connection.abc-123"). + + Returns: + The key with its type respelled (e.g., "connection.abc-123"), or the + key unchanged when the type is unknown in any case. + """ + resource_type, separator, name = key.partition(".") + known = _KNOWN_RESOURCE_TYPES_IN_LOWER_CASE.get(resource_type.lower()) + return f"{known}{separator}{name}" if known else key + @classmethod def parse(cls, key: str, value: dict[str, Any]) -> ResourceOverwrite: """Parse a resource overwrite from a key-value pair. diff --git a/packages/uipath-platform/src/uipath/platform/common/_config.py b/packages/uipath-platform/src/uipath/platform/common/_config.py index 8c52135e5..4365ea248 100644 --- a/packages/uipath-platform/src/uipath/platform/common/_config.py +++ b/packages/uipath-platform/src/uipath/platform/common/_config.py @@ -218,6 +218,40 @@ def conversation_id(self) -> str | None: else None ) + @property + def debug_resource_overwrites(self) -> dict[str, Any] | None: + """The resource overwrites a debug job carries, or None when it carries none. + + Studio Web resolves them before it starts a debug and can put them in the + job, so the run has no need to ask Studio for them. They are read from the + ``fpsProperties`` of the config file: the job's own ``debug.executor`` when + that has them, which is how a job started by another job of the debug gets + them, otherwise the entry of this project in ``debug.master``. + """ + fps_properties = self._config_data.get("fpsProperties") + if not isinstance(fps_properties, dict): + return None + + carried = _resource_overwrites_of( + _json_object(fps_properties.get("debug.executor")) + ) + if carried is not None: + return carried + + project_id = self.project_id + master = _json_object(fps_properties.get("debug.master")) + processes = master.get("processes") if master else None + if not project_id or not isinstance(processes, list): + return None + + for process in processes: + if not isinstance(process, dict): + continue + executor_info = _json_object(process.get("executorInfo")) + if executor_info and _same_id(executor_info.get("projectId"), project_id): + return _resource_overwrites_of(executor_info) + return None + @property def is_tracing_enabled(self) -> bool: from uipath.platform.constants import ENV_TRACING_ENABLED @@ -250,6 +284,29 @@ def _config_data(self) -> dict[str, Any]: return data if isinstance(data, dict) else {} +def _json_object(value: Any) -> dict[str, Any] | None: + """The JSON object a job property holds, which a job keeps as text.""" + import json + + if isinstance(value, str): + try: + value = json.loads(value) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def _resource_overwrites_of( + executor_info: dict[str, Any] | None, +) -> dict[str, Any] | None: + overwrites = executor_info.get("resourceOverwrites") if executor_info else None + return overwrites if isinstance(overwrites, dict) and overwrites else None + + +def _same_id(value: Any, project_id: str) -> bool: + return isinstance(value, str) and value.lower() == project_id.lower() + + UiPathConfig = ConfigurationManager() diff --git a/packages/uipath-platform/tests/common/test_config_env_vars.py b/packages/uipath-platform/tests/common/test_config_env_vars.py index 4daa5f51a..c3ab785c3 100644 --- a/packages/uipath-platform/tests/common/test_config_env_vars.py +++ b/packages/uipath-platform/tests/common/test_config_env_vars.py @@ -1,3 +1,4 @@ +import json from pathlib import Path import pytest @@ -316,3 +317,115 @@ def test_internal_arguments_and_conversation_id_come_from_the_same_file( assert UiPathConfig.licensing_context == "ctx" assert UiPathConfig.is_rooted_to_debug_job is True assert UiPathConfig.conversation_id == "conv-1" + + +class TestDebugResourceOverwrites: + _PROJECT_ID = "11111111-1111-1111-1111-111111111111" + _OVERWRITES = {"asset.A": {"name": "B", "folderPath": "F"}} + + @pytest.fixture(autouse=True) + def _isolated_config(self, monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv(ENV_UIPATH_PROJECT_ID, self._PROJECT_ID) + UiPathConfig.reset() + yield + UiPathConfig.reset() + + @staticmethod + def _write_fps_properties(tmp_path: Path, fps_properties: object) -> None: + (tmp_path / UIPATH_CONFIG_FILE).write_text( + json.dumps({"fpsProperties": fps_properties}) + ) + UiPathConfig.reset() + + @staticmethod + def _master(*executor_infos: dict[str, object]) -> str: + return json.dumps( + { + "processes": [ + {"name": "P", "executorInfo": json.dumps(executor_info)} + for executor_info in executor_infos + ] + } + ) + + def test_reads_them_from_the_debug_executor_of_the_job(self, tmp_path): + self._write_fps_properties( + tmp_path, + {"debug.executor": json.dumps({"resourceOverwrites": self._OVERWRITES})}, + ) + assert UiPathConfig.debug_resource_overwrites == self._OVERWRITES + + def test_reads_them_from_the_entry_of_this_project_in_the_debug_master( + self, tmp_path + ): + self._write_fps_properties( + tmp_path, + { + # The job a debug starts itself has an executor info of its own. + "debug.executor": json.dumps( + {"projectId": self._PROJECT_ID, "command": "debug"} + ), + "debug.master": self._master( + { + "projectId": "another-project", + "resourceOverwrites": {"asset.Other": {"name": "Other"}}, + }, + { + "projectId": self._PROJECT_ID.upper(), + "resourceOverwrites": self._OVERWRITES, + }, + ), + }, + ) + assert UiPathConfig.debug_resource_overwrites == self._OVERWRITES + + def test_returns_none_without_config_file(self): + assert UiPathConfig.debug_resource_overwrites is None + + @pytest.mark.parametrize( + "fps_properties", + [ + [], + {}, + {"debug.executor": "not json"}, + {"debug.executor": "[]"}, + {"debug.executor": '{"resourceOverwrites": {}}'}, + {"debug.executor": '{"resourceOverwrites": []}'}, + {"debug.master": "not json"}, + {"debug.master": '{"processes": {}}'}, + {"debug.master": '{"processes": ["x", {"executorInfo": "not json"}]}'}, + ], + ) + def test_returns_none_when_the_job_carries_none(self, tmp_path, fps_properties): + self._write_fps_properties(tmp_path, fps_properties) + assert UiPathConfig.debug_resource_overwrites is None + + def test_ignores_the_entries_of_other_projects_in_the_debug_master(self, tmp_path): + self._write_fps_properties( + tmp_path, + { + "debug.master": self._master( + { + "projectId": "another-project", + "resourceOverwrites": self._OVERWRITES, + } + ) + }, + ) + assert UiPathConfig.debug_resource_overwrites is None + + def test_ignores_the_debug_master_without_a_project_id(self, monkeypatch, tmp_path): + monkeypatch.delenv(ENV_UIPATH_PROJECT_ID) + self._write_fps_properties( + tmp_path, + { + "debug.master": self._master( + { + "projectId": self._PROJECT_ID, + "resourceOverwrites": self._OVERWRITES, + } + ) + }, + ) + assert UiPathConfig.debug_resource_overwrites is None diff --git a/packages/uipath-platform/tests/common/test_resource_override.py b/packages/uipath-platform/tests/common/test_resource_override.py index 284a4bd5e..e19d74788 100644 --- a/packages/uipath-platform/tests/common/test_resource_override.py +++ b/packages/uipath-platform/tests/common/test_resource_override.py @@ -119,3 +119,21 @@ def test_ontology_binding_parses_as_a_generic_name_and_folder_override() -> None assert overwrite.resource_type == "ontology" assert overwrite.resource_identifier == "nxorders" assert overwrite.folder_identifier == "Shared/NxOrdersSolution" + + +@pytest.mark.parametrize( + ("key", "expected"), + [ + ("Connection.abc-123", "connection.abc-123"), + ("connection.abc-123", "connection.abc-123"), + ("MCPSERVER.Name.With.Dots", "mcpServer.Name.With.Dots"), + ("asset", "asset"), + ("Weird.X", "Weird.X"), + ], +) +def test_the_parser_respells_a_known_kind_written_in_another_case( + key: str, expected: str +) -> None: + from uipath.platform.common._bindings import ResourceOverwriteParser + + assert ResourceOverwriteParser.in_this_sdks_spelling(key) == expected diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 6e32115d0..696e14dcb 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index dae9eebae..03ec0a4e4 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,13 +1,13 @@ [project] name = "uipath" -version = "2.15.15" +version = "2.15.16" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" dependencies = [ "uipath-core>=0.5.35, <0.6.0", "uipath-runtime>=0.13.7, <0.14.0", - "uipath-platform>=0.3.20, <0.4.0", + "uipath-platform>=0.3.24, <0.4.0", "uipath-ipc>=2.5.1, <2.6.0", "click>=8.3.3, <9.0.0", "httpx>=0.28.1", diff --git a/packages/uipath/src/uipath/_cli/_utils/_studio_project.py b/packages/uipath/src/uipath/_cli/_utils/_studio_project.py index e85b9076c..c1f6bbfe0 100644 --- a/packages/uipath/src/uipath/_cli/_utils/_studio_project.py +++ b/packages/uipath/src/uipath/_cli/_utils/_studio_project.py @@ -27,6 +27,81 @@ logger = logging.getLogger(__name__) +# Binding types Studio's binding-overwrites endpoint never answers for. +_BINDING_TYPES_WITHOUT_OVERWRITES = frozenset( + {"property", "timetrigger", "appstrigger", "ixp"} +) +# Binding types Studio answers with a connection id instead of a name and a folder path. +_CONNECTION_BINDING_TYPES = frozenset({"connection", "eventtrigger"}) + + +def _is_solution_binding(metadata: Any) -> bool: + """Whether a binding's metadata marks it as one a solution resolves. + + Solution support is stated outright, or implied by bindings version 2.2 + and later. + """ + if not isinstance(metadata, dict): + return False + + by_name = {str(name).lower(): value for name, value in metadata.items()} + if str(by_name.get("solutionssupport")).lower() == "true": + return True + + version = str(by_name.get("bindingsversion", "")).split(".") + if len(version) < 2 or not (version[0].isdigit() and version[1].isdigit()): + return False + return (int(version[0]), int(version[1])) >= (2, 2) + + +def _overwrite_key_of(binding: Any) -> str | None: + """The key Studio answers a binding under, or None for one it resolves nothing for. + + Follows the resource builder's own rule: a solution binding with a key and + a value that is not an expression is answered as ``.``. + """ + if not isinstance(binding, dict): + return None + + resource, key, value = ( + binding.get("resource"), + binding.get("key"), + binding.get("value"), + ) + if not isinstance(resource, str) or not isinstance(key, str): + return None + if not resource or not key: + return None + if resource.lower() in _BINDING_TYPES_WITHOUT_OVERWRITES: + return None + if not _is_solution_binding(binding.get("metadata")): + return None + if not isinstance(value, dict) or all( + isinstance(entry, dict) and entry.get("isExpression") is True + for entry in value.values() + ): + return None + return f"{resource}.{key}" + + +def _is_complete_overwrite(resource: str, overwrite: Any) -> bool: + """Whether an overwrite holds what Studio always answers for its kind of resource. + + A connection is answered with its id, any other resource with its name and + folder path. An entry that lacks them would leave a design-time value in place. + """ + if not isinstance(overwrite, dict): + return False + if resource.lower() in _CONNECTION_BINDING_TYPES: + return any(str(name).lower() == "connectionid" for name in overwrite) + return "name" in overwrite and "folderPath" in overwrite + + +def _in_one_type_case(overwrite_key: str) -> str: + """An overwrite key with its resource type lowercased; the binding key keeps its case.""" + resource, separator, key = overwrite_key.partition(".") + return f"{resource.lower()}{separator}{key}" + class NonCodedAgentProjectException(Exception): """Raised when the targeted project is not a coded agent one.""" @@ -612,9 +687,29 @@ async def get_resource_overwrites(self) -> dict[str, ResourceOverwrite]: a kind added later does not fail a debug or eval run. A malformed entry of a known kind still raises. + A debug job that carries the overwrites of this project's bindings is not + asked of Studio at all: those are what Studio would answer with. + Returns: dict[str, ResourceOverwrite]: Dict of resource overwrites """ + carried = UiPathConfig.debug_resource_overwrites + if carried is not None: + of_bindings = self._carried_of_bindings(carried) + if of_bindings is not None: + logger.info( + "Resource overwrites carried by the debug job (%d entries):\n%s", + len(of_bindings), + json.dumps(of_bindings, indent=2), + ) + return self._parse_resource_overwrites( + self._in_this_sdks_spelling(of_bindings), origin="the debug job" + ) + logger.info( + "The resource overwrites the debug job carries do not cover the " + "project's bindings; asking Studio for them" + ) + if not os.path.exists(UiPathConfig.bindings_file_path): logger.warning( "Bindings file not found at %s, no overwrites to fetch from Studio", @@ -661,12 +756,84 @@ async def get_resource_overwrites(self) -> dict[str, ResourceOverwrite]: json.dumps(data, indent=2), ) + return self._parse_resource_overwrites(data, origin="Studio") + + @staticmethod + def _carried_of_bindings(carried: dict[str, Any]) -> dict[str, Any] | None: + """The carried overwrites of the bindings Studio resolves for this project. + + That is what Studio would answer for the bindings file: entries for + anything else, a resource the project does not bind for one, are left + out, as Studio leaves them out. None when the file cannot be read as a + bindings file, or when one of those bindings has no complete entry, so + Studio is asked. A project with no bindings file binds nothing. + """ + if not os.path.exists(UiPathConfig.bindings_file_path): + return {} + + try: + with open(UiPathConfig.bindings_file_path, encoding="utf-8") as f: + bindings = json.load(f) + except (OSError, ValueError): + return None + + resources = bindings.get("resources") if isinstance(bindings, dict) else None + if not isinstance(resources, list): + return None + + resource_of: dict[str, str] = {} + for binding in resources: + if not isinstance(binding, dict): + return None + key = _overwrite_key_of(binding) + if key is not None: + resource_of[_in_one_type_case(key)] = binding["resource"] + + of_bindings = { + key: overwrite + for key, overwrite in carried.items() + if _in_one_type_case(key) in resource_of + and _is_complete_overwrite(resource_of[_in_one_type_case(key)], overwrite) + } + covered = {_in_one_type_case(key) for key in of_bindings} + return of_bindings if covered == set(resource_of) else None + + @staticmethod + def _in_this_sdks_spelling(carried: dict[str, Any]) -> dict[str, Any]: + """Respell the resource types of the overwrites a debug job carries. + + Studio resolves them for every runtime of the solution, so a type can + come in another runtime's case ("Connection."). An entry already in + this SDK's spelling wins over a respelled one with the same key, and of + two respelled ones the first wins. The entry left out is logged. + """ + respelled: dict[str, Any] = {} + for key, value in carried.items(): + own_spelling = ResourceOverwriteParser.in_this_sdks_spelling(key) + if own_spelling != key and ( + own_spelling in carried or own_spelling in respelled + ): + logger.warning( + "Skipping resource overwrite '%s' from the debug job: " + "'%s' is already there", + key, + own_spelling, + ) + continue + respelled[own_spelling] = value + return respelled + + @staticmethod + def _parse_resource_overwrites( + data: dict[str, Any], origin: str + ) -> dict[str, ResourceOverwrite]: overwrites: dict[str, ResourceOverwrite] = {} for key, value in data.items(): if not ResourceOverwriteParser.knows(key): logger.warning( - "Skipping resource overwrite '%s' from Studio: unknown kind '%s'", + "Skipping resource overwrite '%s' from %s: unknown kind '%s'", key, + origin, key.split(".")[0], ) continue diff --git a/packages/uipath/tests/cli/test_studio_project_overwrites.py b/packages/uipath/tests/cli/test_studio_project_overwrites.py index c27770de4..4a77fb188 100644 --- a/packages/uipath/tests/cli/test_studio_project_overwrites.py +++ b/packages/uipath/tests/cli/test_studio_project_overwrites.py @@ -8,6 +8,7 @@ import json import logging +from collections.abc import Callable, Iterator from pathlib import Path import pytest @@ -15,7 +16,12 @@ from pytest_httpx import HTTPXMock from uipath._cli._utils._studio_project import StudioClient -from uipath.platform.common import GenericResourceOverwrite, UiPathConfig +from uipath.platform.common import ( + ConnectionResourceOverwrite, + GenericResourceOverwrite, + UiPathConfig, +) +from uipath.platform.constants import ENV_UIPATH_CONFIG_PATH _ORG_URL = "https://cloud.uipath.com/organization" _PROJECT_ID = "test-project-id" @@ -104,3 +110,317 @@ async def test_get_resource_overwrites_raises_for_a_malformed_known_kind( with pytest.raises(ValidationError): await studio_client.get_resource_overwrites() + + +@pytest.fixture +def debug_job_config( + tmp_path: Path, studio_client: StudioClient, monkeypatch: pytest.MonkeyPatch +) -> Iterator[Callable[[dict[str, str]], None]]: + """Writes the config file of a debug job, read from the working directory.""" + # Set, it names another file for UiPathConfig to read. + monkeypatch.delenv(ENV_UIPATH_CONFIG_PATH, raising=False) + + def write(fps_properties: dict[str, str]) -> None: + (tmp_path / UiPathConfig.config_file_name).write_text( + json.dumps({"fpsProperties": fps_properties}) + ) + UiPathConfig.reset() + + yield write + UiPathConfig.reset() + + +async def test_get_resource_overwrites_uses_the_ones_the_debug_job_carries( + studio_client: StudioClient, debug_job_config, httpx_mock: HTTPXMock +) -> None: + Path("bindings.json").write_text(_bindings_file(_asset_binding("A"))) + debug_job_config( + { + "debug.executor": json.dumps( + { + "projectId": _PROJECT_ID, + "resourceOverwrites": { + "asset.A": {"name": "B", "folderPath": "F"}, + }, + } + ) + } + ) + + overwrites = await studio_client.get_resource_overwrites() + + asset = overwrites["asset.A"] + assert isinstance(asset, GenericResourceOverwrite) + assert asset.resource_identifier == "B" + assert asset.folder_identifier == "F" + # Studio is not asked: neither for the overwrites nor for the solution id. + assert httpx_mock.get_requests() == [] + + +async def test_get_resource_overwrites_respells_the_kinds_the_debug_job_carries( + studio_client: StudioClient, debug_job_config, httpx_mock: HTTPXMock +) -> None: + Path("bindings.json").write_text( + _bindings_file( + _asset_binding("c-1", resource="Connection"), + _asset_binding("c-2", resource="Connection"), + _asset_binding("A", resource="Asset"), + ) + ) + debug_job_config( + { + "debug.executor": json.dumps( + { + "projectId": _PROJECT_ID, + "resourceOverwrites": { + "Connection.c-1": {"ConnectionId": "robot", "folderKey": "k"}, + "Connection.c-2": {"ConnectionId": "other", "folderKey": "k"}, + "connection.c-2": {"connectionId": "own", "folderKey": "k"}, + "Asset.A": {"name": "B", "folderPath": "F"}, + }, + } + ) + } + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert sorted(overwrites) == ["asset.A", "connection.c-1", "connection.c-2"] + respelled = overwrites["connection.c-1"] + assert isinstance(respelled, ConnectionResourceOverwrite) + assert respelled.resource_identifier == "robot" + # The entry already in this SDK's spelling wins, wherever it sits in the job. + assert overwrites["connection.c-2"].resource_identifier == "own" + assert httpx_mock.get_requests() == [] + + +async def test_get_resource_overwrites_keeps_the_first_of_two_respelled_entries( + studio_client: StudioClient, + debug_job_config, + studio_logs: pytest.LogCaptureFixture, +) -> None: + Path("bindings.json").write_text( + _bindings_file(_asset_binding("c", resource="Connection")) + ) + debug_job_config( + { + "debug.executor": json.dumps( + { + "projectId": _PROJECT_ID, + "resourceOverwrites": { + "Connection.c": {"ConnectionId": "first", "folderKey": "k"}, + "CONNECTION.c": {"ConnectionId": "second", "folderKey": "k"}, + }, + } + ) + } + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert list(overwrites) == ["connection.c"] + assert overwrites["connection.c"].resource_identifier == "first" + assert "'CONNECTION.c'" in studio_logs.text + + +async def test_get_resource_overwrites_skips_unknown_entries_the_debug_job_carries( + studio_client: StudioClient, + debug_job_config, + studio_logs: pytest.LogCaptureFixture, +) -> None: + Path("bindings.json").write_text( + _bindings_file(_asset_binding("A"), _asset_binding("X", resource="weird")) + ) + debug_job_config( + { + "debug.executor": json.dumps( + { + "resourceOverwrites": { + "asset.A": {"name": "B", "folderPath": "F"}, + "weird.X": {"name": "B", "folderPath": "F"}, + } + } + ) + } + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert set(overwrites) == {"asset.A"} + warnings = [ + r.getMessage() for r in studio_logs.records if r.levelno == logging.WARNING + ] + assert [message for message in warnings if "weird.X" in message] == [ + "Skipping resource overwrite 'weird.X' from the debug job: unknown kind 'weird'" + ] + + +def _bindings_file(*bindings: dict[str, object]) -> str: + return json.dumps({"version": "2.0", "resources": list(bindings)}) + + +def _asset_binding( + key: str, metadata: object = None, resource: str = "asset" +) -> dict[str, object]: + return { + "resource": resource, + "key": key, + "value": {"name": {"defaultValue": "MyAsset", "isExpression": False}}, + "metadata": {"SolutionsSupport": "true"} if metadata is None else metadata, + } + + +def _carrying(overwrites: dict[str, object]) -> dict[str, str]: + return { + "debug.executor": json.dumps( + {"projectId": _PROJECT_ID, "resourceOverwrites": overwrites} + ) + } + + +@pytest.mark.parametrize( + "binding", + [ + _asset_binding("MyAsset.Shared"), + # The kind is matched whatever its case; the binding key is not. + _asset_binding("MyAsset.Shared", resource="Asset"), + _asset_binding("MyAsset.Shared", metadata={"BindingsVersion": "2.2"}), + ], +) +async def test_get_resource_overwrites_uses_carried_ones_keyed_as_the_project_binds( + studio_client: StudioClient, + debug_job_config, + httpx_mock: HTTPXMock, + binding: dict[str, object], +) -> None: + Path("bindings.json").write_text(_bindings_file(binding)) + debug_job_config( + _carrying({"asset.MyAsset.Shared": {"name": "B", "folderPath": "F"}}) + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert set(overwrites) == {"asset.MyAsset.Shared"} + assert httpx_mock.get_requests() == [] + + +async def test_get_resource_overwrites_leaves_out_carried_ones_the_project_does_not_bind( + studio_client: StudioClient, debug_job_config, httpx_mock: HTTPXMock +) -> None: + Path("bindings.json").write_text(_bindings_file(_asset_binding("MyAsset.Shared"))) + debug_job_config( + _carrying( + { + "asset.MyAsset.Shared": {"name": "B", "folderPath": "F"}, + "asset.SolutionWide": {"name": "Other", "folderPath": "F"}, + } + ) + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert set(overwrites) == {"asset.MyAsset.Shared"} + assert httpx_mock.get_requests() == [] + + +async def test_get_resource_overwrites_uses_no_carried_ones_without_a_bindings_file( + studio_client: StudioClient, debug_job_config, httpx_mock: HTTPXMock +) -> None: + Path("bindings.json").unlink() + debug_job_config(_carrying({"asset.MyAsset": {"name": "B", "folderPath": "F"}})) + + overwrites = await studio_client.get_resource_overwrites() + + assert overwrites == {} + assert httpx_mock.get_requests() == [] + + +@pytest.mark.parametrize( + "bindings", + [ + # Keyed by resource name, not by the project's binding key. + _bindings_file(_asset_binding("MyAsset.Shared")), + _bindings_file(_asset_binding("myasset")), + _bindings_file(_asset_binding("MyAsset"), _asset_binding("Other")), + # The entry lacks the folder path Studio always answers with. + _bindings_file(_asset_binding("Incomplete")), + "not a bindings file", + json.dumps({"version": "2.0"}), + json.dumps({"version": "2.0", "resources": ["asset"]}), + ], +) +async def test_get_resource_overwrites_asks_studio_when_carried_ones_do_not_cover_the_bindings( + studio_client: StudioClient, + debug_job_config, + httpx_mock: HTTPXMock, + bindings: str, +) -> None: + Path("bindings.json").write_text(bindings) + debug_job_config( + _carrying( + { + "asset.MyAsset": {"name": "B", "folderPath": "F"}, + "asset.Incomplete": {"name": "B"}, + } + ) + ) + UiPathConfig.studio_solution_id = _SOLUTION_ID + httpx_mock.add_response( + method="POST", + url=_OVERWRITES_URL, + json={"asset.FromStudio": {"name": "B", "folderPath": "F"}}, + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert set(overwrites) == {"asset.FromStudio"} + + +@pytest.mark.parametrize( + "binding", + [ + # What Studio resolves nothing for gets no overwrite from the carried list. + _asset_binding("P", resource="Property"), + _asset_binding("Nightly", resource="TimeTrigger"), + _asset_binding("NotInASolution", metadata={"BindingsVersion": "2.1"}), + _asset_binding("NoMetadata", metadata={}), + _asset_binding(""), + { + "resource": "asset", + "key": "OnlyExpressions", + "value": {"name": {"defaultValue": "x", "isExpression": True}}, + "metadata": {"SolutionsSupport": "true"}, + }, + ], +) +async def test_get_resource_overwrites_leaves_out_carried_ones_of_bindings_studio_skips( + studio_client: StudioClient, + debug_job_config, + httpx_mock: HTTPXMock, + binding: dict[str, object], +) -> None: + Path("bindings.json").write_text(_bindings_file(binding)) + key = f"{binding['resource']}.{binding['key']}" + debug_job_config(_carrying({key: {"name": "B", "folderPath": "F"}})) + + overwrites = await studio_client.get_resource_overwrites() + + assert overwrites == {} + assert httpx_mock.get_requests() == [] + + +async def test_get_resource_overwrites_asks_studio_when_the_debug_job_carries_none( + studio_client: StudioClient, debug_job_config, httpx_mock: HTTPXMock +) -> None: + debug_job_config({"debug.executor": json.dumps({"projectId": _PROJECT_ID})}) + # The fixture's reset dropped the cached solution id the client asks under. + UiPathConfig.studio_solution_id = _SOLUTION_ID + httpx_mock.add_response( + method="POST", + url=_OVERWRITES_URL, + json={"asset.A": {"name": "B", "folderPath": "F"}}, + ) + + overwrites = await studio_client.get_resource_overwrites() + + assert set(overwrites) == {"asset.A"} diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ee06f3d06..821e59bcb 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2720,7 +2720,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.15" +version = "2.15.16" source = { editable = "." } dependencies = [ { name = "applicationinsights" }, @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" },