-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
test_cloud_cli.py
224 lines (171 loc) · 7.35 KB
/
test_cloud_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import enum
import logging
import os
from dataclasses import dataclass
from functools import partial
from unittest import mock
from unittest.mock import ANY, call, MagicMock
import pytest
from click.testing import CliRunner
from lightning_cloud.openapi import (
V1LightningappV2,
V1ListLightningappInstancesResponse,
V1ListLightningappsV2Response,
V1ListMembershipsResponse,
V1Membership,
)
from lightning_cloud.openapi.rest import ApiException
from tests_app import _PROJECT_ROOT
import lightning_app.runners.backends.cloud as cloud_backend
from lightning_app.cli.lightning_cli import run_app
from lightning_app.runners import cloud
from lightning_app.runners.cloud import CloudRuntime
_FILE_PATH = os.path.join(_PROJECT_ROOT, "tests", "tests_app", "core", "scripts", "app_metadata.py")
@dataclass
class AppMetadata:
id: str
@dataclass
class FakeResponse:
lightningapps = [AppMetadata(id="my_app")]
class FakeLightningClient:
def lightningapp_v2_service_list_lightningapps_v2(self, *args, **kwargs):
return V1ListLightningappsV2Response(lightningapps=[])
def lightningapp_instance_service_list_lightningapp_instances(self, *args, **kwargs):
return V1ListLightningappInstancesResponse(lightningapps=[])
def lightningapp_service_delete_lightningapp(self, id: str = None):
assert id == "my_app"
def projects_service_list_memberships(self):
return V1ListMembershipsResponse(memberships=[V1Membership(name="test-project", project_id="test-project-id")])
class CloudRuntimePatch(CloudRuntime):
def __init__(self, *args, **kwargs):
super_init = super().__init__
if hasattr(super_init, "__wrapped__"):
super_init.__wrapped__(self, *args, **kwargs)
else:
super_init(*args, **kwargs)
class V1LightningappInstanceState(enum.Enum):
FAILED = "failed"
SUCCESS = "success"
@dataclass
class FailedStatus:
phase = V1LightningappInstanceState.FAILED
@dataclass
class SuccessStatus:
phase = V1LightningappInstanceState.SUCCESS
@dataclass
class RuntimeErrorResponse:
id = "my_app"
source_upload_url = "something"
status = FailedStatus()
@dataclass
class RuntimeErrorResponse2:
id = "my_app"
source_upload_url = ""
status = SuccessStatus()
@dataclass
class SuccessResponse:
id = "my_app"
source_upload_url = "something"
status = SuccessStatus()
@dataclass
class ExceptionResponse:
status = FailedStatus()
class FakeLightningClientCreate(FakeLightningClient):
def __init__(self, *args, create_response, **kwargs):
super().__init__()
self.create_response = create_response
def lightningapp_v2_service_create_lightningapp_v2(self, *args, **kwargs):
return V1LightningappV2(id="my_app", name="app")
def lightningapp_v2_service_create_lightningapp_release(self, project_id, app_id, body):
assert project_id == "test-project-id"
return self.create_response
def lightningapp_v2_service_create_lightningapp_release_instance(self, project_id, app_id, id, body):
assert project_id == "test-project-id"
return self.create_response
@mock.patch("lightning_app.core.queues.QueuingSystem", MagicMock())
@mock.patch("lightning_app.runners.runtime_type.CloudRuntime", CloudRuntimePatch)
@pytest.mark.parametrize("create_response", [RuntimeErrorResponse(), RuntimeErrorResponse2()])
def test_start_app(create_response, monkeypatch):
monkeypatch.setattr(cloud, "V1LightningappInstanceState", MagicMock())
monkeypatch.setattr(cloud, "Body8", MagicMock())
monkeypatch.setattr(cloud, "V1Flowserver", MagicMock())
monkeypatch.setattr(cloud, "V1LightningappInstanceSpec", MagicMock())
monkeypatch.setattr(
cloud_backend,
"LightningClient",
partial(FakeLightningClientCreate, create_response=create_response),
)
monkeypatch.setattr(cloud, "LocalSourceCodeDir", MagicMock())
monkeypatch.setattr(cloud, "_prepare_lightning_wheels_and_requirements", MagicMock())
runner = CliRunner()
def run():
result = runner.invoke(run_app, [_FILE_PATH, "--cloud", "--open-ui=False"], catch_exceptions=False)
assert result.exit_code == 0
if isinstance(create_response, RuntimeErrorResponse):
cloud.V1LightningappInstanceState.FAILED = V1LightningappInstanceState.FAILED
with pytest.raises(RuntimeError, match="Failed to create the application"):
run()
elif isinstance(create_response, RuntimeErrorResponse2):
with pytest.raises(RuntimeError, match="The source upload url is empty."):
run()
elif isinstance(create_response, RuntimeErrorResponse2):
with pytest.raises(RuntimeError, match="The source upload url is empty."):
run()
else:
run()
mocks_calls = cloud.LocalSourceCodeDir._mock_mock_calls
assert len(mocks_calls) == 5
assert str(mocks_calls[0].kwargs["path"]) == os.path.dirname(_FILE_PATH)
mocks_calls[1].assert_called_once()
mocks_calls[2].assert_called_once(url="url")
assert cloud.V1Flowserver._mock_call_args_list == [call(name="root.flow_b")]
cloud.V1LightningappInstanceSpec._mock_call_args.assert_called_once(
app_entrypoint_file=_FILE_PATH,
enable_app_server=True,
works=ANY,
flow_servers=ANY,
)
cloud.Body8.assert_called_once()
class HttpHeaderDict(dict):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.reason = kwargs["reason"]
self.status = kwargs["status"]
self.data = kwargs["data"]
def getheaders(self):
return {}
class FakeLightningClientException(FakeLightningClient):
def __init__(self, *args, message, **kwargs):
super().__init__()
self.message = message
def lightningapp_v2_service_list_lightningapps_v2(self, *args, **kwargs):
raise ApiException(
http_resp=HttpHeaderDict(
data=self.message,
reason="",
status=500,
)
)
@mock.patch("lightning_app.utilities.network.create_swagger_client", MagicMock())
@mock.patch("lightning_app.runners.runtime_type.CloudRuntime", CloudRuntimePatch)
@pytest.mark.parametrize(
"message",
[
"Cannot create a new app, you have reached the maximum number (10) of apps. Either increase your quota or delete some of the existing apps" # noqa E501
],
)
def test_start_app_exception(message, monkeypatch, caplog):
monkeypatch.setattr(cloud, "V1LightningappInstanceState", MagicMock())
monkeypatch.setattr(cloud, "Body8", MagicMock())
monkeypatch.setattr(cloud, "V1Flowserver", MagicMock())
monkeypatch.setattr(cloud, "V1LightningappInstanceSpec", MagicMock())
monkeypatch.setattr(cloud, "LocalSourceCodeDir", MagicMock())
monkeypatch.setattr(cloud, "_prepare_lightning_wheels_and_requirements", MagicMock())
monkeypatch.setattr(cloud, "logger", logging.getLogger())
runner = CliRunner()
fake_grid_rest_client = partial(FakeLightningClientException, message=message)
with caplog.at_level(logging.ERROR):
with mock.patch("lightning_app.runners.backends.cloud.LightningClient", fake_grid_rest_client):
result = runner.invoke(run_app, [_FILE_PATH, "--cloud", "--open-ui=False"], catch_exceptions=False)
assert result.exit_code == 1
assert caplog.messages == [message]