Skip to content

Commit 99258e6

Browse files
committed
refactor code
1 parent b12659a commit 99258e6

File tree

2 files changed

+89
-24
lines changed

2 files changed

+89
-24
lines changed

.generator/cli.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,31 @@ def _write_json_file(path: str, updated_content: Dict):
114114
with open(path, "w") as f:
115115
json.dump(updated_content, f, indent=2)
116116
f.write("\n")
117+
118+
def _get_new_library_config(request_data: Dict) -> Dict:
119+
"""Returns the configuration for a new library.
120+
121+
Args:
122+
request_data(Dict): The request data from which to extract the new
123+
library config.
124+
125+
Returns:
126+
Dict: The configuration of a new library.
127+
"""
128+
new_library_config = {}
129+
for library_config in request_data.get("libraries", []):
130+
all_apis = library_config.get("apis", [])
131+
for api in all_apis:
132+
if api.get("status") == "new":
133+
new_library_config = library_config
134+
break
135+
136+
# remove status key from new library config.
137+
all_apis = new_library_config.get("apis", [])
138+
for api in all_apis:
139+
del api["status"]
140+
141+
return new_library_config
117142

118143

119144
def handle_configure(
@@ -148,22 +173,10 @@ def handle_configure(
148173
try:
149174
# configure-request.json contains the library definitions.
150175
request_data = _read_json_file(f"{librarian}/{CONFIGURE_REQUEST_FILE}")
151-
for library_config in request_data.get("libraries", []):
152-
is_new_library_or_api = False
153-
if "apis" in library_config:
154-
for api in library_config["apis"]:
155-
if api.get("status") == "new":
156-
is_new_library_or_api = True
157-
# Delete the status field since we don't need to include it in `configure-response.json`.
158-
del api["status"]
159-
160-
if is_new_library_or_api:
161-
library_id = _get_library_id(library_config)
162-
# TODO: Add missing information for the configured library.
163-
request_data[library_id] = library_config
176+
new_library_config = _get_new_library_config(request_data)
164177

165178
# Write the new library configuration to configure-response.json.
166-
_write_json_file(f"{librarian}/configure-response.json", request_data[library_id])
179+
_write_json_file(f"{librarian}/configure-response.json", new_library_config)
167180

168181
except Exception as e:
169182
raise ValueError("Configuring a new library failed.") from e

.generator/test_cli.py

Lines changed: 62 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
_get_library_dist_name,
4545
_get_library_id,
4646
_get_libraries_to_prepare_for_release,
47+
_get_new_library_config,
4748
_get_previous_version,
4849
_process_changelog,
4950
_process_version_file,
@@ -162,23 +163,28 @@ def mock_build_request_file(tmp_path, monkeypatch):
162163

163164

164165
@pytest.fixture
165-
def mock_configure_request_file(tmp_path, monkeypatch):
166-
"""Creates the mock request file at the correct path inside a temp dir."""
167-
# Create the path as expected by the script: .librarian/configure-request.json
168-
request_path = f"{LIBRARIAN_DIR}/{CONFIGURE_REQUEST_FILE}"
169-
request_dir = tmp_path / os.path.dirname(request_path)
170-
request_dir.mkdir(parents=True, exist_ok=True)
171-
request_file = request_dir / os.path.basename(request_path)
172-
173-
request_content = {
166+
def mock_configure_request_data():
167+
"""Returns mock data for configure-request.json."""
168+
return {
174169
"libraries": [
175170
{
176171
"id": "google-cloud-language",
177172
"apis": [{"path": "google/cloud/language/v1", "status": "new"}],
178173
}
179174
]
180175
}
181-
request_file.write_text(json.dumps(request_content))
176+
177+
178+
@pytest.fixture
179+
def mock_configure_request_file(tmp_path, monkeypatch, mock_configure_request_data):
180+
"""Creates the mock request file at the correct path inside a temp dir."""
181+
# Create the path as expected by the script: .librarian/configure-request.json
182+
request_path = f"{LIBRARIAN_DIR}/{CONFIGURE_REQUEST_FILE}"
183+
request_dir = tmp_path / os.path.dirname(request_path)
184+
request_dir.mkdir(parents=True, exist_ok=True)
185+
request_file = request_dir / os.path.basename(request_path)
186+
187+
request_file.write_text(json.dumps(mock_configure_request_data))
182188

183189
# Change the current working directory to the temp path for the test.
184190
monkeypatch.chdir(tmp_path)
@@ -261,6 +267,52 @@ def mock_state_file(tmp_path, monkeypatch):
261267
return request_file
262268

263269

270+
def test_handle_configure(mock_configure_request_file, mocker):
271+
"""Tests the successful execution path of handle_configure."""
272+
mock_write_json = mocker.patch("cli._write_json_file")
273+
274+
handle_configure()
275+
276+
# Verify that the correct configuration is written to the response file.
277+
expected_config = {
278+
"id": "google-cloud-language",
279+
"apis": [{"path": "google/cloud/language/v1"}],
280+
}
281+
mock_write_json.assert_called_once_with(
282+
f"{LIBRARIAN_DIR}/configure-response.json", expected_config
283+
)
284+
285+
286+
def test_handle_configure_failure(mocker):
287+
"""Tests that handle_configure raises ValueError on failure."""
288+
with pytest.raises(ValueError, match="Configuring a new library failed."):
289+
handle_configure()
290+
291+
292+
def test_get_new_library_config_new_library_found(mock_configure_request_data):
293+
"""Tests that the new library configuration is returned when found."""
294+
config = _get_new_library_config(mock_configure_request_data)
295+
assert config["id"] == "google-cloud-language"
296+
assert "status" not in config["apis"][0]
297+
298+
299+
def test_get_new_library_config_no_new_library():
300+
"""Tests that an empty dictionary is returned when no new library is found."""
301+
request_data = {
302+
"libraries": [
303+
{"id": "existing-library", "apis": [{"path": "path/v1", "status": "existing"}]},
304+
]
305+
}
306+
config = _get_new_library_config(request_data)
307+
assert config == {}
308+
309+
310+
def test_get_new_library_config_empty_input():
311+
"""Tests that an empty dictionary is returned for empty input."""
312+
config = _get_new_library_config({})
313+
assert config == {}
314+
315+
264316
def test_get_library_id_success():
265317
"""Tests that _get_library_id returns the correct ID when present."""
266318
request_data = {"id": "test-library", "name": "Test Library"}

0 commit comments

Comments
 (0)