diff --git a/lean/components/cloud/cloud_project_manager.py b/lean/components/cloud/cloud_project_manager.py index 3573ec35..e3d74fbb 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]): + # 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] @@ -111,7 +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(): - if not self._push_manager.push_projects([local_path]): + 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 5c47c7d1..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() @@ -89,17 +98,20 @@ 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()) 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) @@ -127,7 +139,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 +147,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 +211,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 +224,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 +255,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 +318,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 +400,31 @@ 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: + # 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 + + 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) if project is 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 18aeb848..6092822f 100644 --- a/tests/components/cloud/test_cloud_project_manager.py +++ b/tests/components/cloud/test_cloud_project_manager.py @@ -13,13 +13,16 @@ import json import os +from datetime import datetime from pathlib import Path +from typing import Callable, Tuple from unittest import mock import pytest from pyfakefs.helpers import reset_ids, set_uid from lean.container import container +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 @@ -36,11 +39,11 @@ 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() - 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 +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: @@ -67,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) @@ -75,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() @@ -88,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) @@ -96,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() @@ -111,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) @@ -119,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") @@ -249,6 +252,15 @@ def test_get_cloud_project_given_by_id_does_not_push_project_outside_the_working api_client.projects.create.assert_not_called() +@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=()) + + assert container.cloud_project_manager.get_cloud_project(input, push=True).projectId == 1 + + 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"), ("Python Project", "Renamed Project")]) def test_get_cloud_project_follows_project_renamed_by_push(local_name: str, cloud_name: str) -> None: @@ -365,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) @@ -430,3 +442,127 @@ 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(cloud_library_content: Callable[[str], str], + write_denied_project_ids: Tuple[int, ...] = (2,), + 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" + 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 in write_denied_project_ids: + 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=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.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 + + +@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) + + 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") + + 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] + + +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 [call.args[0] for call in api_client.projects.update.call_args_list] == [2, 1]