From 4145ab25b77b7ffc0767fc513735e437cbc522fd Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 13 Nov 2026 18:54:15 -0400 Subject: [PATCH 1/4] fix(cloud): push project libraries when using --push in cloud commands --- .../components/cloud/cloud_project_manager.py | 6 ++-- .../cloud/test_cloud_project_manager.py | 34 ++++++++++++++++--- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/lean/components/cloud/cloud_project_manager.py b/lean/components/cloud/cloud_project_manager.py index 3573ec35..20131a44 100644 --- a/lean/components/cloud/cloud_project_manager.py +++ b/lean/components/cloud/cloud_project_manager.py @@ -79,7 +79,8 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr local_path = Path.cwd() / input if self._project_config_manager.try_get_project_config(local_path): if push: - if not self._push_manager.push_projects([local_path]): + libraries = self._project_manager.get_project_libraries(local_path) + if not self._push_manager.push_projects([local_path], libraries): raise PushFailedError(input) local_path = self._push_manager.pushed_project_paths[local_path] @@ -111,7 +112,8 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr if renamed_path and Path.cwd() in renamed_path.parents: local_path = renamed_path if local_path.exists(): - if not self._push_manager.push_projects([local_path]): + libraries = self._project_manager.get_project_libraries(local_path) + if not self._push_manager.push_projects([local_path], libraries): raise PushFailedError(input) return (self._api_client.projects.get(cloud_project.projectId, organization_id), self._push_manager.pushed_project_paths[local_path]) diff --git a/tests/components/cloud/test_cloud_project_manager.py b/tests/components/cloud/test_cloud_project_manager.py index 18aeb848..234951b3 100644 --- a/tests/components/cloud/test_cloud_project_manager.py +++ b/tests/components/cloud/test_cloud_project_manager.py @@ -40,7 +40,7 @@ def test_get_cloud_project_pushing_new_project(): push_manager.pushed_project_paths = {Path.cwd() / "Python Project": Path.cwd() / "Python Project"} project_config = mock.Mock() - project_config.get = mock.MagicMock(return_value=cloud_project.projectId) + project_config.get = mock.MagicMock(side_effect=lambda key, default=None: cloud_project.projectId if key == "cloud-id" else default) project_config.is_empty = mock.MagicMock(return_value=False) project_config_manager = mock.Mock() project_config_manager.try_get_project_config = mock.MagicMock(return_value=None) @@ -55,7 +55,7 @@ def test_get_cloud_project_pushing_new_project(): assert created_cloud_project == cloud_project api_client.projects.get.assert_called_with(cloud_project.projectId, "abc") - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"]) + push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) def test_get_cloud_project_raises_when_push_of_project_with_cloud_id_fails() -> None: @@ -75,7 +75,7 @@ def test_get_cloud_project_raises_when_push_of_project_with_cloud_id_fails() -> with pytest.raises(PushFailedError): container.cloud_project_manager.get_cloud_project("Python Project", push=True) - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"]) + push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) api_client.projects.get.assert_not_called() @@ -96,7 +96,7 @@ def test_get_cloud_project_raises_when_push_of_project_given_by_id_fails() -> No with pytest.raises(PushFailedError): container.cloud_project_manager.get_cloud_project(str(cloud_project.projectId), push=True) - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"]) + push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) api_client.projects.get.assert_not_called() @@ -119,7 +119,7 @@ def test_get_cloud_project_pushes_project_given_by_id_after_its_directory_was_re assert container.cloud_project_manager.get_cloud_project(str(cloud_project.projectId), push=True) == cloud_project - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Renamed Project"]) + push_manager.push_projects.assert_called_once_with([Path.cwd() / "Renamed Project"], []) api_client.projects.get.assert_called_once_with(cloud_project.projectId, "abc") @@ -249,6 +249,30 @@ def test_get_cloud_project_given_by_id_does_not_push_project_outside_the_working api_client.projects.create.assert_not_called() +def test_get_cloud_project_pushing_project_also_pushes_its_libraries() -> None: + create_fake_lean_cli_directory() + + cloud_project = create_api_project(1, "Python Project") + api_client = mock.Mock() + api_client.projects.get_all.return_value = [cloud_project] + api_client.projects.get.return_value = cloud_project + + push_manager = mock.Mock() + push_manager.push_projects = mock.Mock(return_value=True) + push_manager.pushed_project_paths = {Path.cwd() / "Python Project": Path.cwd() / "Python Project"} + + initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) + + library_path = Path.cwd() / "Library" / "Python Library" + container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set("cloud-id", cloud_project.projectId) + container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set( + "libraries", [{"name": "Python Library", "path": str(library_path)}]) + + container.cloud_project_manager.get_cloud_project("Python Project", push=True) + + push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], [library_path.resolve()]) + + @pytest.mark.parametrize("local_name,cloud_name", [("Unsafe:Project", "Unsafe Project"), ("Python Project", "Renamed Project")]) def test_get_cloud_project_follows_project_renamed_by_push(local_name: str, cloud_name: str) -> None: From b2852f6d4133ab63d4ccf1d62a4a4266684501da Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Thu, 19 Nov 2026 00:43:43 -0400 Subject: [PATCH 2/4] fix(cloud): skip pushing referenced libraries that already match the cloud copy A library the user can only read rejects every projects.update, so --push on cloud backtest/optimize/live deploy failed for projects referencing one even when the library had no local changes. Libraries whose files and metadata already match the cloud copy are now left alone; a changed library that fails to upload still stops the command. --- lean/components/cloud/push_manager.py | 35 +++++++++-- .../cloud/test_cloud_project_manager.py | 59 +++++++++++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 5c47c7d1..ec911f8c 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -89,8 +89,11 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu relative_path = path.relative_to(Path.cwd()) try: self._logger.info(f"[{index}/{len(all_projects_to_push)}] Pushing '{relative_path}'") + # A library whose cloud copy already matches the local one needs no update, so it is not + # rejected when the user can only read it. self.pushed_project_paths[path] = self._push_project(path, organization_id, encryption_action_value, - encryption_key_value, force=force) + encryption_key_value, force=force, + skip_if_unchanged=path in associated_libraries_to_push) except Exception as ex: from traceback import format_exc self._logger.debug(format_exc().strip()) @@ -127,7 +130,7 @@ def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: return local_libraries_cloud_ids - def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None) -> Path: + def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None, skip_if_unchanged: bool = False) -> Path: """Pushes a single local project to the cloud. Raises an error with a descriptive message if the project cannot be pushed. @@ -135,6 +138,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act :param project_path: the local project to push :param organization_id: the id of the organization to push the project to :param suggested_rename_path: the path to move the project to. + :param skip_if_unchanged: don't update the cloud project when it already matches the local one :return: the path of the pushed project, which differs from project_path when the push renamed it """ @@ -198,7 +202,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act if cloud_project.name != project_name: # cloud project name was changed. Repeat steps to validate the new name locally. self._logger.info(f"Received new name '{cloud_project.name}' for project '{project_name}' from QuantConnect.com") - return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name) + return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name, skip_if_unchanged) self._cloud_projects.append(cloud_project) organization_message_part = f" in organization '{organization_id}'" if organization_id is not None else "" @@ -211,7 +215,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act encryption_key = local_encryption_key encryption_action = ActionType.ENCRYPT if local_encryption_state else ActionType.DECRYPT # Finalize pushing by updating locally modified metadata, files and libraries - self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force) + self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force, skip_if_unchanged) return project_path def _get_files(self, project: Path, encryption_action: Optional[ActionType], encryption_key: Optional[Path]) -> List[Dict[str, str]]: @@ -242,13 +246,14 @@ def _get_files(self, project: Path, encryption_action: Optional[ActionType], enc return files - def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool]) -> None: + def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], skip_if_unchanged: bool = False) -> None: """Pushes local project description and parameters to the cloud. Does nothing if the cloud is already up-to-date. :param project: the local project to push the parameters of :param cloud_project: the cloud project to push the parameters to + :param skip_if_unchanged: return without updating when the cloud project already matches the local one """ project_config = self._project_config_manager.get_project_config(project) @@ -304,6 +309,10 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act encryption_key_id = get_project_key_hash(encryption_key) update_args["encryption_key"] = encryption_key_id + if skip_if_unchanged and self._is_cloud_project_up_to_date(cloud_project, update_args, expected_correct_project_name): + self._logger.debug(f"'{cloud_project.name}' is already up to date in the cloud, not pushing it") + return + if not force: update_args["code_source_id"] = "cli" if update_args != {}: @@ -382,6 +391,22 @@ def _push_one_by_one(self, cloud_project: QCProject, update_args: Dict[str, Any] f"cloud project now mixes old and new code. Fix the problem and push again. " f"Error: {error}") from error + def _is_cloud_project_up_to_date(self, cloud_project: QCProject, update_args: Dict, expected_name: str) -> bool: + """Checks whether pushing update_args would leave the cloud project unchanged.""" + changed_metadata = set(update_args) - {"name", "files", "libraries", "encryption_key"} + if changed_metadata or cloud_project.name != expected_name or update_args["encryption_key"] != '': + return False + + if set(update_args["libraries"]) != {library.projectId for library in cloud_project.libraries}: + return False + + try: + cloud_files = {file.name: file.content for file in self._api_client.files.get_all(cloud_project.projectId)} + except Exception: + return False + + return cloud_files == {file["name"]: file["content"] for file in update_args["files"]} + def _get_cloud_project(self, project_id: int, organization_id: str) -> QCProject: project = next(iter(p for p in self._cloud_projects if p.projectId == project_id), None) if project is None: diff --git a/tests/components/cloud/test_cloud_project_manager.py b/tests/components/cloud/test_cloud_project_manager.py index 234951b3..b201c0e8 100644 --- a/tests/components/cloud/test_cloud_project_manager.py +++ b/tests/components/cloud/test_cloud_project_manager.py @@ -13,6 +13,7 @@ import json import os +from datetime import datetime from pathlib import Path from unittest import mock @@ -20,6 +21,7 @@ from pyfakefs.helpers import reset_ids, set_uid from lean.container import container +from lean.models.api import QCFullFile, QCProjectLibrary from lean.models.errors import PushFailedError from tests.test_helpers import create_api_project, create_fake_lean_cli_directory from tests.conftest import initialize_container @@ -454,3 +456,60 @@ def test_get_cloud_project_and_local_path_returns_no_directory_for_a_project_wit assert container.cloud_project_manager.get_cloud_project_and_local_path("20", push=False) == (cloud_project, None) if config_content is not None: assert config_path.read_text() == config_content + + +def _setup_project_with_library(library_files_match_cloud: bool, library_write_denied: bool = True): + create_fake_lean_cli_directory() + project_path = Path.cwd() / "Python Project" + library_path = Path.cwd() / "Library" / "Python Library" + + library_cloud_project = create_api_project(2, "Library/Python Library") + library_cloud_project.description = "" + project_cloud_project = create_api_project(1, "Python Project") + project_cloud_project.libraries = [QCProjectLibrary(projectId=2, libraryName="Python Library", + ownerName="owner", access=True)] + + api_client = mock.Mock() + api_client.projects.get_all.return_value = [project_cloud_project, library_cloud_project] + api_client.projects.get.side_effect = lambda project_id, _: {1: project_cloud_project, + 2: library_cloud_project}[project_id] + + def update(project_id: int, **kwargs): + if project_id == 2 and library_write_denied: + raise RuntimeError("You do not have write permission on this project.") + + api_client.projects.update.side_effect = update + + initialize_container(api_client_to_use=api_client) + + container.project_config_manager.get_project_config(project_path).set("cloud-id", 1) + container.project_config_manager.get_project_config(project_path).set( + "libraries", [{"name": "Python Library", "path": str(library_path)}]) + container.project_config_manager.get_project_config(library_path).set("cloud-id", 2) + + library_files = [QCFullFile(name=path.relative_to(library_path).as_posix(), + content=path.read_text(encoding="utf-8") + if library_files_match_cloud else "# changed in the cloud", + modified=datetime.now(), isLibrary=True) + for path in container.project_manager.get_source_files(library_path)] + api_client.files.get_all.return_value = library_files + + return api_client + + +def test_get_cloud_project_push_skips_library_that_matches_its_cloud_copy() -> None: + api_client = _setup_project_with_library(library_files_match_cloud=True) + + container.cloud_project_manager.get_cloud_project("Python Project", push=True) + + updated_ids = [call.args[0] for call in api_client.projects.update.call_args_list] + assert updated_ids == [1] + + +def test_get_cloud_project_push_does_not_skip_library_that_differs_from_its_cloud_copy() -> None: + api_client = _setup_project_with_library(library_files_match_cloud=False) + + with pytest.raises(PushFailedError): + container.cloud_project_manager.get_cloud_project("Python Project", push=True) + + assert 2 in [call.args[0] for call in api_client.projects.update.call_args_list] From 7b53b7165ad186a7e05bf2a84f41c95758e8f2c5 Mon Sep 17 00:00:00 2001 From: Martin Molinero Date: Fri, 27 Nov 2026 18:48:19 -0300 Subject: [PATCH 3/4] fix(cloud): only stop --push when the project itself fails, like cloud push The cloud commands now push through PushManager.push_project, the same path as `lean cloud push`: a referenced library that cannot be pushed only gets a warning, and only a failed push of the project itself stops the command. push_project returns whether the project was pushed. The check that skips libraries already matching their cloud copy now leaves out the files of the library's own libraries, which files/read lists with the library's files, and accepts a local file that is what `lean cloud pull` wrote for the cloud copy (unix line endings and a final newline). Pull's conversion moves into get_pulled_file_content so both use the same code. Co-Authored-By: Claude Opus 5.5 --- .../components/cloud/cloud_project_manager.py | 7 +- lean/components/cloud/pull_manager.py | 22 ++-- lean/components/cloud/push_manager.py | 36 +++++-- .../cloud/live/test_cloud_live_commands.py | 8 +- tests/commands/cloud/test_backtest.py | 2 +- tests/commands/cloud/test_optimize.py | 2 +- .../cloud/test_cloud_project_manager.py | 102 ++++++++++-------- 7 files changed, 112 insertions(+), 67 deletions(-) diff --git a/lean/components/cloud/cloud_project_manager.py b/lean/components/cloud/cloud_project_manager.py index 20131a44..e3d74fbb 100644 --- a/lean/components/cloud/cloud_project_manager.py +++ b/lean/components/cloud/cloud_project_manager.py @@ -79,8 +79,8 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr local_path = Path.cwd() / input if self._project_config_manager.try_get_project_config(local_path): if push: - libraries = self._project_manager.get_project_libraries(local_path) - if not self._push_manager.push_projects([local_path], libraries): + # Like `lean cloud push`, a library that cannot be pushed is only a warning + if not self._push_manager.push_project(local_path): raise PushFailedError(input) local_path = self._push_manager.pushed_project_paths[local_path] @@ -112,8 +112,7 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr if renamed_path and Path.cwd() in renamed_path.parents: local_path = renamed_path if local_path.exists(): - libraries = self._project_manager.get_project_libraries(local_path) - if not self._push_manager.push_projects([local_path], libraries): + if not self._push_manager.push_project(local_path): raise PushFailedError(input) return (self._api_client.projects.get(cloud_project.projectId, organization_id), self._push_manager.pushed_project_paths[local_path]) diff --git a/lean/components/cloud/pull_manager.py b/lean/components/cloud/pull_manager.py index cb812458..549605a6 100644 --- a/lean/components/cloud/pull_manager.py +++ b/lean/components/cloud/pull_manager.py @@ -26,6 +26,21 @@ from lean.models.encryption import ActionType from lean.components.config.storage import safe_save + +def get_pulled_file_content(cloud_file_content: str) -> str: + """Returns the content a pull writes to the local drive for a cloud file's content. + + :param cloud_file_content: the content of the file in the cloud + :return: the content with unix line endings, ending with a newline unless it is empty + """ + # Make sure we always work with unix line endings in memory, + # so they can be properly translated to the local OS line endings when writing to disk. + content = cloud_file_content.replace("\r\n", "\n") + if content != "" and not content.endswith("\n"): + content += "\n" + return content + + class PullManager: """The PullManager class is responsible for synchronizing cloud projects to the local drive.""" @@ -239,12 +254,7 @@ def _pull_files(self, project: QCProject, local_project_path: Path, encryption_a local_file_path.parent.mkdir(parents=True, exist_ok=True) - # Make sure we always work with unix line endings in memory, - # so they can be properly translated to the local OS line endings when writing to disk. - content = cloud_file.content.replace("\r\n", "\n") - if content != "" and not content.endswith("\n"): - content += "\n" - safe_save(content, local_file_path) + safe_save(get_pulled_file_content(cloud_file.content), local_file_path) self._project_manager.update_last_modified_time(local_file_path, cloud_file.modified) self._logger.info(f"Successfully pulled '{project.name}/{cloud_file.name}'") diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index ec911f8c..17e0a478 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -54,15 +54,17 @@ def __init__(self, # Where each pushed project is after its push, which renames directories whose name is not valid locally or in the cloud self.pushed_project_paths: Dict[Path, Path] = {} - def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> None: + def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> bool: """Pushes the given project from the local drive to the cloud. It will also push every library referenced by the project and add or remove references. + A library that cannot be pushed only gets a warning, the project is pushed anyway. :param project: path to the directory containing the local project that needs to be pushed + :return: True if the project was pushed, even when some of its libraries could not be """ libraries = self._project_manager.get_project_libraries(project) - self.push_projects([project], libraries, encryption_action, encryption_key, force) + return project not in self._push_projects([project], libraries, encryption_action, encryption_key, force) def push_projects(self, projects_to_push: List[Path], associated_libraries_to_push: Optional[List[Path]]=[], encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> bool: """Pushes the given projects from the local drive to the cloud. @@ -72,12 +74,19 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu :param projects_to_push: a list of directories containing the local projects that need to be pushed :return: True if every project and library was pushed, False if any of them could not be pushed """ + return len(self._push_projects(projects_to_push, associated_libraries_to_push, encryption_action, + encryption_key, force)) == 0 + + def _push_projects(self, projects_to_push: List[Path], associated_libraries_to_push: List[Path], encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool]) -> List[Path]: + """Pushes the given projects and libraries, with a warning for each one that cannot be pushed. + + :return: the directories of the projects and libraries that could not be pushed + """ all_projects_to_push = associated_libraries_to_push + projects_to_push + failed_paths = [] if len(all_projects_to_push) == 0: - return True - - all_pushed = True + return failed_paths organization_id = self._organization_manager.try_get_working_organization_id() @@ -100,9 +109,9 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu self._logger.warn(f"Cannot push '{relative_path}': {ex}") if "write permission" in str(ex).lower(): self._logger.info("Please pull any required changes and push with --force") - all_pushed = False + failed_paths.append(path) - return all_pushed + return failed_paths def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: project_config = self._project_config_manager.get_project_config(project_dir) @@ -401,11 +410,20 @@ def _is_cloud_project_up_to_date(self, cloud_project: QCProject, update_args: Di return False try: - cloud_files = {file.name: file.content for file in self._api_client.files.get_all(cloud_project.projectId)} + # Library files come with their own names, and belong to the project's libraries, not to the project + cloud_files = {file.name: file.content for file in self._api_client.files.get_all(cloud_project.projectId) + if not file.isLibrary} except Exception: return False - return cloud_files == {file["name"]: file["content"] for file in update_args["files"]} + local_files = {file["name"]: file["content"] for file in update_args["files"]} + if local_files.keys() != cloud_files.keys(): + return False + + # A file is unchanged when it is the one pushed, or the one a pull of the cloud copy wrote + from lean.components.cloud.pull_manager import get_pulled_file_content + return all(content in (cloud_files[name], get_pulled_file_content(cloud_files[name])) + for name, content in local_files.items()) def _get_cloud_project(self, project_id: int, organization_id: str) -> QCProject: project = next(iter(p for p in self._cloud_projects if p.projectId == project_id), None) diff --git a/tests/commands/cloud/live/test_cloud_live_commands.py b/tests/commands/cloud/live/test_cloud_live_commands.py index 7f9b5df2..4d52b24f 100644 --- a/tests/commands/cloud/live/test_cloud_live_commands.py +++ b/tests/commands/cloud/live/test_cloud_live_commands.py @@ -206,15 +206,15 @@ def test_cloud_live_deploy_offers_local_cash_for_resolved_project(project: str, container.api_client.nodes.get_all.return_value = create_qc_nodes() container.api_client.get.return_value = {"success": True, "status": "Undefined"} - def push_and_rename(paths): - paths[0].rename(resolved_path) - container.push_manager.pushed_project_paths[paths[0]] = resolved_path + def push_and_rename(path): + path.rename(resolved_path) + container.push_manager.pushed_project_paths[path] = resolved_path return True options = ["--push"] if push else [] # patch by module object: the dotted path resolves to the `cloud` click group on Python < 3.11 deploy_module = import_module("lean.commands.cloud.live.deploy") - with mock.patch.object(container.push_manager, "push_projects", side_effect=push_and_rename), \ + with mock.patch.object(container.push_manager, "push_project", side_effect=push_and_rename), \ mock.patch.object(deploy_module, "configure_initial_cash_balance", return_value=[]) as configure_cash: result = CliRunner().invoke(lean, ["cloud", "live", "deploy", project, *options, "--brokerage", "Paper Trading", "--node", "live", "--auto-restart", "yes", "--notify-order-events", "no", diff --git a/tests/commands/cloud/test_backtest.py b/tests/commands/cloud/test_backtest.py index 4831fbb8..03c37824 100644 --- a/tests/commands/cloud/test_backtest.py +++ b/tests/commands/cloud/test_backtest.py @@ -200,7 +200,7 @@ def test_cloud_backtest_pushes_nothing_when_project_does_not_exist_locally() -> assert result.exit_code == 0 - push_manager.push_projects.assert_not_called() + push_manager.push_project.assert_not_called() def test_cloud_backtest_aborts_when_push_of_project_with_cloud_id_fails() -> None: diff --git a/tests/commands/cloud/test_optimize.py b/tests/commands/cloud/test_optimize.py index 9c0437ec..c5575454 100644 --- a/tests/commands/cloud/test_optimize.py +++ b/tests/commands/cloud/test_optimize.py @@ -191,7 +191,7 @@ def test_cloud_optimize_pushes_nothing_when_project_does_not_exist_locally() -> assert result.exit_code == 0 - push_manager.push_projects.assert_not_called() + push_manager.push_project.assert_not_called() def test_cloud_optimize_passes_given_config_to_cloud_runner() -> None: diff --git a/tests/components/cloud/test_cloud_project_manager.py b/tests/components/cloud/test_cloud_project_manager.py index b201c0e8..d21f00e6 100644 --- a/tests/components/cloud/test_cloud_project_manager.py +++ b/tests/components/cloud/test_cloud_project_manager.py @@ -15,6 +15,7 @@ import os from datetime import datetime from pathlib import Path +from typing import Callable, Tuple from unittest import mock import pytest @@ -38,7 +39,7 @@ def test_get_cloud_project_pushing_new_project(): api_client.projects.get.return_value = cloud_project push_manager = mock.Mock() - push_manager.push_projects = mock.Mock() + push_manager.push_project = mock.Mock() push_manager.pushed_project_paths = {Path.cwd() / "Python Project": Path.cwd() / "Python Project"} project_config = mock.Mock() @@ -57,7 +58,7 @@ def test_get_cloud_project_pushing_new_project(): assert created_cloud_project == cloud_project api_client.projects.get.assert_called_with(cloud_project.projectId, "abc") - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) + push_manager.push_project.assert_called_once_with(Path.cwd() / "Python Project") def test_get_cloud_project_raises_when_push_of_project_with_cloud_id_fails() -> None: @@ -69,7 +70,7 @@ def test_get_cloud_project_raises_when_push_of_project_with_cloud_id_fails() -> api_client.projects.get.return_value = cloud_project push_manager = mock.Mock() - push_manager.push_projects = mock.Mock(return_value=False) + push_manager.push_project = mock.Mock(return_value=False) initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set("cloud-id", cloud_project.projectId) @@ -77,7 +78,7 @@ def test_get_cloud_project_raises_when_push_of_project_with_cloud_id_fails() -> with pytest.raises(PushFailedError): container.cloud_project_manager.get_cloud_project("Python Project", push=True) - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) + push_manager.push_project.assert_called_once_with(Path.cwd() / "Python Project") api_client.projects.get.assert_not_called() @@ -90,7 +91,7 @@ def test_get_cloud_project_raises_when_push_of_project_given_by_id_fails() -> No api_client.projects.get_all.return_value = [cloud_project] push_manager = mock.Mock() - push_manager.push_projects = mock.Mock(return_value=False) + push_manager.push_project = mock.Mock(return_value=False) initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set("cloud-id", cloud_project.projectId) @@ -98,7 +99,7 @@ def test_get_cloud_project_raises_when_push_of_project_given_by_id_fails() -> No with pytest.raises(PushFailedError): container.cloud_project_manager.get_cloud_project(str(cloud_project.projectId), push=True) - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], []) + push_manager.push_project.assert_called_once_with(Path.cwd() / "Python Project") api_client.projects.get.assert_not_called() @@ -113,7 +114,7 @@ def test_get_cloud_project_pushes_project_given_by_id_after_its_directory_was_re api_client.projects.get.return_value = cloud_project push_manager = mock.Mock() - push_manager.push_projects = mock.Mock(return_value=True) + push_manager.push_project = mock.Mock(return_value=True) push_manager.pushed_project_paths = {Path.cwd() / "Renamed Project": Path.cwd() / "Renamed Project"} initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) @@ -121,7 +122,7 @@ def test_get_cloud_project_pushes_project_given_by_id_after_its_directory_was_re assert container.cloud_project_manager.get_cloud_project(str(cloud_project.projectId), push=True) == cloud_project - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Renamed Project"], []) + push_manager.push_project.assert_called_once_with(Path.cwd() / "Renamed Project") api_client.projects.get.assert_called_once_with(cloud_project.projectId, "abc") @@ -251,28 +252,13 @@ def test_get_cloud_project_given_by_id_does_not_push_project_outside_the_working api_client.projects.create.assert_not_called() -def test_get_cloud_project_pushing_project_also_pushes_its_libraries() -> None: - create_fake_lean_cli_directory() +@pytest.mark.parametrize("input", ["Python Project", "1"]) +def test_get_cloud_project_pushing_project_also_pushes_its_changed_libraries(input: str) -> None: + api_client = _setup_project_with_library(lambda content: "# changed in the cloud", write_denied_project_ids=()) - cloud_project = create_api_project(1, "Python Project") - api_client = mock.Mock() - api_client.projects.get_all.return_value = [cloud_project] - api_client.projects.get.return_value = cloud_project + assert container.cloud_project_manager.get_cloud_project(input, push=True).projectId == 1 - push_manager = mock.Mock() - push_manager.push_projects = mock.Mock(return_value=True) - push_manager.pushed_project_paths = {Path.cwd() / "Python Project": Path.cwd() / "Python Project"} - - initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) - - library_path = Path.cwd() / "Library" / "Python Library" - container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set("cloud-id", cloud_project.projectId) - container.project_config_manager.get_project_config(Path.cwd() / "Python Project").set( - "libraries", [{"name": "Python Library", "path": str(library_path)}]) - - container.cloud_project_manager.get_cloud_project("Python Project", push=True) - - push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"], [library_path.resolve()]) + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1] @pytest.mark.parametrize("local_name,cloud_name", [("Unsafe:Project", "Unsafe Project"), @@ -391,7 +377,7 @@ def test_get_cloud_project_and_local_path_returns_the_local_project_directory(in api_client.projects.get.return_value = cloud_project push_manager = mock.Mock() - push_manager.push_projects = mock.Mock(return_value=True) + push_manager.push_project = mock.Mock(return_value=True) push_manager.pushed_project_paths = {project_path: project_path} initialize_container(api_client_to_use=api_client, push_manager_to_use=push_manager) @@ -458,7 +444,15 @@ def test_get_cloud_project_and_local_path_returns_no_directory_for_a_project_wit assert config_path.read_text() == config_content -def _setup_project_with_library(library_files_match_cloud: bool, library_write_denied: bool = True): +def _setup_project_with_library(cloud_library_content: Callable[[str], str], + write_denied_project_ids: Tuple[int, ...] = (2,), + cloud_files_of_library_libraries: Tuple[QCFullFile, ...] = ()) -> mock.Mock: + """Sets up project 1 referencing library 2, with library 2's cloud files derived from its local files. + + :param cloud_library_content: returns the cloud content of a library file given its local content + :param write_denied_project_ids: the projects whose update the cloud refuses, like for a read-only library + :param cloud_files_of_library_libraries: files the cloud lists for the library's own libraries + """ create_fake_lean_cli_directory() project_path = Path.cwd() / "Python Project" library_path = Path.cwd() / "Library" / "Python Library" @@ -475,7 +469,7 @@ def _setup_project_with_library(library_files_match_cloud: bool, library_write_d 2: library_cloud_project}[project_id] def update(project_id: int, **kwargs): - if project_id == 2 and library_write_denied: + if project_id in write_denied_project_ids: raise RuntimeError("You do not have write permission on this project.") api_client.projects.update.side_effect = update @@ -488,28 +482,52 @@ def update(project_id: int, **kwargs): container.project_config_manager.get_project_config(library_path).set("cloud-id", 2) library_files = [QCFullFile(name=path.relative_to(library_path).as_posix(), - content=path.read_text(encoding="utf-8") - if library_files_match_cloud else "# changed in the cloud", - modified=datetime.now(), isLibrary=True) + content=cloud_library_content(path.read_text(encoding="utf-8")), + modified=datetime.now(), isLibrary=False) for path in container.project_manager.get_source_files(library_path)] - api_client.files.get_all.return_value = library_files + api_client.files.get_all.side_effect = lambda project_id: library_files + list(cloud_files_of_library_libraries) \ + if project_id == 2 else [] return api_client -def test_get_cloud_project_push_skips_library_that_matches_its_cloud_copy() -> None: - api_client = _setup_project_with_library(library_files_match_cloud=True) +@pytest.mark.parametrize("cloud_library_content", [ + lambda content: content, + # What a pull turns into the local file: no final newline and Windows line endings + lambda content: content[:-1].replace("\n", "\r\n"), +]) +def test_get_cloud_project_push_skips_library_that_matches_its_cloud_copy( + cloud_library_content: Callable[[str], str]) -> None: + api_client = _setup_project_with_library(cloud_library_content) + + container.cloud_project_manager.get_cloud_project("Python Project", push=True) + + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [1] + + +def test_get_cloud_project_push_skips_library_whose_own_libraries_are_listed_with_its_files() -> None: + library_library_file = QCFullFile(name="main.py", content="# the library's own library", modified=datetime.now(), + isLibrary=True) + api_client = _setup_project_with_library(lambda content: content, + cloud_files_of_library_libraries=(library_library_file,)) container.cloud_project_manager.get_cloud_project("Python Project", push=True) - updated_ids = [call.args[0] for call in api_client.projects.update.call_args_list] - assert updated_ids == [1] + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [1] + + +def test_get_cloud_project_push_warns_and_continues_when_changed_library_cannot_be_pushed() -> None: + api_client = _setup_project_with_library(lambda content: "# changed in the cloud") + + assert container.cloud_project_manager.get_cloud_project("Python Project", push=True).projectId == 1 + + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1] -def test_get_cloud_project_push_does_not_skip_library_that_differs_from_its_cloud_copy() -> None: - api_client = _setup_project_with_library(library_files_match_cloud=False) +def test_get_cloud_project_push_raises_when_project_cannot_be_pushed_after_its_libraries() -> None: + api_client = _setup_project_with_library(lambda content: "# changed in the cloud", write_denied_project_ids=(1,)) with pytest.raises(PushFailedError): container.cloud_project_manager.get_cloud_project("Python Project", push=True) - assert 2 in [call.args[0] for call in api_client.projects.update.call_args_list] + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1] From 5c106f1c2f8f86f79fe15b7f3fb85e57091cdc14 Mon Sep 17 00:00:00 2001 From: Martin Molinero Date: Fri, 27 Nov 2026 19:36:32 -0300 Subject: [PATCH 4/4] test(cloud): push a library whose files match when something else changed Covers each check that must force a library push even though its files match the cloud copy: a local file added or deleted, a library reference removed, and a changed description or parameters. The warning test now asserts the warning for the library that could not be pushed. Co-Authored-By: Claude Opus 5.5 --- .../cloud/test_cloud_project_manager.py | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/tests/components/cloud/test_cloud_project_manager.py b/tests/components/cloud/test_cloud_project_manager.py index d21f00e6..6092822f 100644 --- a/tests/components/cloud/test_cloud_project_manager.py +++ b/tests/components/cloud/test_cloud_project_manager.py @@ -22,7 +22,7 @@ from pyfakefs.helpers import reset_ids, set_uid from lean.container import container -from lean.models.api import QCFullFile, QCProjectLibrary +from lean.models.api import QCFullFile, QCProject, QCProjectLibrary from lean.models.errors import PushFailedError from tests.test_helpers import create_api_project, create_fake_lean_cli_directory from tests.conftest import initialize_container @@ -446,12 +446,15 @@ def test_get_cloud_project_and_local_path_returns_no_directory_for_a_project_wit def _setup_project_with_library(cloud_library_content: Callable[[str], str], write_denied_project_ids: Tuple[int, ...] = (2,), - cloud_files_of_library_libraries: Tuple[QCFullFile, ...] = ()) -> mock.Mock: + cloud_files_of_library_libraries: Tuple[QCFullFile, ...] = (), + change_library: Callable[[Path, QCProject], None] = lambda path, cloud: None + ) -> mock.Mock: """Sets up project 1 referencing library 2, with library 2's cloud files derived from its local files. :param cloud_library_content: returns the cloud content of a library file given its local content :param write_denied_project_ids: the projects whose update the cloud refuses, like for a read-only library :param cloud_files_of_library_libraries: files the cloud lists for the library's own libraries + :param change_library: changes the local library or its cloud copy once its cloud files are set up """ create_fake_lean_cli_directory() project_path = Path.cwd() / "Python Project" @@ -488,6 +491,8 @@ def update(project_id: int, **kwargs): api_client.files.get_all.side_effect = lambda project_id: library_files + list(cloud_files_of_library_libraries) \ if project_id == 2 else [] + change_library(library_path, library_cloud_project) + return api_client @@ -516,11 +521,41 @@ def test_get_cloud_project_push_skips_library_whose_own_libraries_are_listed_wit assert [call.args[0] for call in api_client.projects.update.call_args_list] == [1] +def _set_library_config(library_path: Path, key: str, value) -> None: + container.project_config_manager.get_project_config(library_path).set(key, value) + + +@pytest.mark.parametrize("change_library", [ + # a local file added + lambda path, cloud: (path / "helpers.py").write_text("def helper():\n return 1\n", encoding="utf-8"), + # a local file deleted + lambda path, cloud: (path / "research.ipynb").unlink(), + # a library reference removed locally + lambda path, cloud: setattr(cloud, "libraries", [QCProjectLibrary(projectId=3, libraryName="Other Library", + ownerName="owner", access=True)]), + # a changed description + lambda path, cloud: _set_library_config(path, "description", "A changed description"), + # changed parameters + lambda path, cloud: _set_library_config(path, "parameters", {"period": "10"}), +], ids=["file added", "file deleted", "library reference removed", "description changed", "parameters changed"]) +def test_get_cloud_project_push_pushes_library_whose_files_match_when_something_else_changed( + change_library: Callable[[Path, QCProject], None]) -> None: + api_client = _setup_project_with_library(lambda content: content, write_denied_project_ids=(), + change_library=change_library) + + container.cloud_project_manager.get_cloud_project("Python Project", push=True) + + assert [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1] + + def test_get_cloud_project_push_warns_and_continues_when_changed_library_cannot_be_pushed() -> None: api_client = _setup_project_with_library(lambda content: "# changed in the cloud") - assert container.cloud_project_manager.get_cloud_project("Python Project", push=True).projectId == 1 + with mock.patch.object(container.logger, "warn") as warn: + assert container.cloud_project_manager.get_cloud_project("Python Project", push=True).projectId == 1 + warn.assert_called_once_with(f"Cannot push '{Path('Library') / 'Python Library'}': " + f"You do not have write permission on this project.") assert [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1]