Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lean/components/cloud/cloud_project_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def get_cloud_project(self, input: str, push: bool) -> QCProject:
if not self._push_manager.push_projects([local_path]):
raise PushFailedError(input)

local_path = self._push_manager.pushed_project_paths[local_path]
cloud_id = self._project_config_manager.get_project_config(local_path).get("cloud-id")
if cloud_id is None:
raise RuntimeError("Something went wrong while pushing the project to the cloud")
Expand Down
12 changes: 8 additions & 4 deletions lean/components/cloud/push_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ def __init__(self,
self._project_config_manager = project_config_manager
self._organization_manager = organization_manager
self._cloud_projects = []
# 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:
"""Pushes the given project from the local drive to the cloud.
Expand Down Expand Up @@ -81,7 +83,8 @@ 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}'")
self._push_project(path, organization_id, encryption_action_value, encryption_key_value, force=force)
self.pushed_project_paths[path] = self._push_project(path, organization_id, encryption_action_value,
encryption_key_value, force=force)
except Exception as ex:
from traceback import format_exc
self._logger.debug(format_exc().strip())
Expand All @@ -103,14 +106,15 @@ 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) -> None:
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:
"""Pushes a single local project to the cloud.

Raises an error with a descriptive message if the project cannot be pushed.

: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.
:return: the path of the pushed project, which differs from project_path when the push renamed it
"""

project_name = project_path.relative_to(Path.cwd()).as_posix()
Expand Down Expand Up @@ -156,8 +160,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")
self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name)
return
return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name)

self._cloud_projects.append(cloud_project)
organization_message_part = f" in organization '{organization_id}'" if organization_id is not None else ""
Expand All @@ -171,6 +174,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act
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)
return project_path

def _get_files(self, project: Path, encryption_action: Optional[ActionType], encryption_key: Optional[Path]) -> List[Dict[str, str]]:
"""Pushes the files of a local project to the cloud.
Expand Down
103 changes: 103 additions & 0 deletions tests/components/cloud/test_cloud_project_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from pathlib import Path
from unittest import mock

import pytest
from pyfakefs.helpers import reset_ids, set_uid

from lean.container import container
from lean.models.errors import PushFailedError
Expand All @@ -34,6 +37,7 @@ def test_get_cloud_project_pushing_new_project():

push_manager = mock.Mock()
push_manager.push_projects = 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)
Expand Down Expand Up @@ -94,3 +98,102 @@ def test_get_cloud_project_raises_when_push_of_project_given_by_id_fails() -> No

push_manager.push_projects.assert_called_once_with([Path.cwd() / "Python Project"])
api_client.projects.get.assert_not_called()


@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:
create_fake_lean_cli_directory()
if local_name != "Python Project":
(Path.cwd() / "Python Project").rename(Path.cwd() / local_name)

cloud_project = create_api_project(20, cloud_name)

api_client = mock.Mock()
api_client.projects.create.return_value = cloud_project
api_client.projects.get.return_value = cloud_project

initialize_container(api_client_to_use=api_client)

returned_cloud_project = container.cloud_project_manager.get_cloud_project(local_name, push=True)

assert returned_cloud_project == cloud_project
assert not (Path.cwd() / local_name).exists()
final_config = container.project_config_manager.get_project_config(Path.cwd() / cloud_name)
assert final_config.get("cloud-id") == cloud_project.projectId
api_client.projects.update.assert_called_once()
api_client.projects.get.assert_called_with(cloud_project.projectId, "abc")


def test_get_cloud_project_leaves_other_project_configs_untouched_when_push_renames_project() -> None:
create_fake_lean_cli_directory()
(Path.cwd() / "Python Project").rename(Path.cwd() / "Unsafe:Project")
other_config_path = Path.cwd() / "Other App" / "config.json"
other_config_content = '{\n// application setting\n"setting": "keep"\n}'
other_config_path.parent.mkdir()
other_config_path.write_text(other_config_content)

cloud_project = create_api_project(20, "Unsafe Project")

api_client = mock.Mock()
api_client.projects.create.return_value = cloud_project
api_client.projects.get.return_value = cloud_project

initialize_container(api_client_to_use=api_client)

assert container.cloud_project_manager.get_cloud_project("Unsafe:Project", push=True) == cloud_project
assert other_config_path.read_text() == other_config_content


def test_get_cloud_project_returns_pushed_copy_sharing_the_local_id_of_its_original() -> None:
create_fake_lean_cli_directory()
original_path = Path.cwd() / "Python Project"
copy_path = Path.cwd() / "Unsafe:Copy"
original_config = container.project_config_manager.get_project_config(original_path)
original_config.set("cloud-id", 10)
original_config.set("local-id", 123456789)
copy_path.mkdir()
for file in original_path.iterdir():
if file.is_file():
(copy_path / file.name).write_text(file.read_text())
container.project_config_manager.get_project_config(copy_path).delete("cloud-id")

original_cloud_project = create_api_project(10, "Python Project")
copy_cloud_project = create_api_project(20, "Unsafe Copy")

api_client = mock.Mock()
api_client.projects.create.return_value = copy_cloud_project
api_client.projects.get.side_effect = lambda project_id, _: {10: original_cloud_project,
20: copy_cloud_project}[project_id]

initialize_container(api_client_to_use=api_client)

assert container.cloud_project_manager.get_cloud_project("Unsafe:Copy", push=True) == copy_cloud_project


def test_get_cloud_project_pushes_read_only_linked_project_without_local_id() -> None:
create_fake_lean_cli_directory()
project_path = Path.cwd() / "Python Project"
config_path = project_path / "config.json"
config = json.loads(config_path.read_text())
config.pop("local-id", None)
config["cloud-id"] = 20
config_path.write_text(json.dumps(config))

cloud_project = create_api_project(20, "Python Project")

api_client = mock.Mock()
api_client.projects.get.return_value = cloud_project

initialize_container(api_client_to_use=api_client)

os.chmod(config_path, 0o444)
os.chmod(project_path, 0o555)
set_uid(1000)
try:
assert container.cloud_project_manager.get_cloud_project("Python Project", push=True) == cloud_project
finally:
reset_ids()

api_client.projects.update.assert_called_once()
assert "local-id" not in json.loads(config_path.read_text())
Loading