forked from googleapis/google-cloud-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
456 lines (360 loc) · 15.1 KB
/
Copy pathtest_cli.py
File metadata and controls
456 lines (360 loc) · 15.1 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import os
import subprocess
from unittest.mock import MagicMock, mock_open
import pytest
from cli import (
GENERATE_REQUEST_FILE,
BUILD_REQUEST_FILE,
LIBRARIAN_DIR,
REPO_DIR,
_build_bazel_target,
_clean_up_files_after_post_processing,
_copy_files_needed_for_post_processing,
_determine_bazel_rule,
_get_library_id,
_locate_and_extract_artifact,
_read_json_file,
_run_individual_session,
_run_nox_sessions,
_run_post_processor,
handle_build,
handle_configure,
handle_generate,
)
@pytest.fixture
def mock_generate_request_file(tmp_path, monkeypatch):
"""Creates the mock request file at the correct path inside a temp dir."""
# Create the path as expected by the script: .librarian/generate-request.json
request_path = f"{LIBRARIAN_DIR}/{GENERATE_REQUEST_FILE}"
request_dir = tmp_path / os.path.dirname(request_path)
request_dir.mkdir()
request_file = request_dir / os.path.basename(request_path)
request_content = {
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1"}],
}
request_file.write_text(json.dumps(request_content))
# Change the current working directory to the temp path for the test.
monkeypatch.chdir(tmp_path)
return request_file
@pytest.fixture
def mock_build_request_file(tmp_path, monkeypatch):
"""Creates the mock request file at the correct path inside a temp dir."""
# Create the path as expected by the script: .librarian/build-request.json
request_path = f"{LIBRARIAN_DIR}/{BUILD_REQUEST_FILE}"
request_dir = tmp_path / os.path.dirname(request_path)
request_dir.mkdir()
request_file = request_dir / os.path.basename(request_path)
request_content = {
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1"}],
}
request_file.write_text(json.dumps(request_content))
# Change the current working directory to the temp path for the test.
monkeypatch.chdir(tmp_path)
return request_file
@pytest.fixture
def mock_generate_request_data_for_nox():
"""Returns mock data for generate-request.json for nox tests."""
return {
"id": "mock-library",
"apis": [
{"path": "google/mock/v1"},
],
}
def test_get_library_id_success():
"""Tests that _get_library_id returns the correct ID when present."""
request_data = {"id": "test-library", "name": "Test Library"}
library_id = _get_library_id(request_data)
assert library_id == "test-library"
def test_get_library_id_missing_id():
"""Tests that _get_library_id raises ValueError when 'id' is missing."""
request_data = {"name": "Test Library"}
with pytest.raises(
ValueError, match="Request file is missing required 'id' field."
):
_get_library_id(request_data)
def test_get_library_id_empty_id():
"""Tests that _get_library_id raises ValueError when 'id' is an empty string."""
request_data = {"id": "", "name": "Test Library"}
with pytest.raises(
ValueError, match="Request file is missing required 'id' field."
):
_get_library_id(request_data)
def test_handle_configure_success(caplog, mock_generate_request_file):
"""
Tests the successful execution path of handle_configure.
"""
caplog.set_level(logging.INFO)
handle_configure()
assert "'configure' command executed." in caplog.text
def test_determine_bazel_rule_success(mocker, caplog):
"""
Tests the happy path of _determine_bazel_rule.
"""
caplog.set_level(logging.INFO)
mock_content = 'name = "google-cloud-language-v1-py",\n'
mocker.patch("cli.open", mock_open(read_data=mock_content))
rule = _determine_bazel_rule("google/cloud/language/v1", "source")
assert rule == "//google/cloud/language/v1:google-cloud-language-v1-py"
assert "Found Bazel rule" in caplog.text
def test_build_bazel_target_success(mocker, caplog):
"""
Tests that the build helper logs success when the command runs correctly.
"""
caplog.set_level(logging.INFO)
mocker.patch("cli.subprocess.run", return_value=MagicMock(returncode=0))
_build_bazel_target("mock/bazel:rule", "source")
assert "Bazel build for mock/bazel:rule rule completed successfully" in caplog.text
def test_build_bazel_target_fails_to_find_rule_match(mocker, caplog):
"""
Tests that ValueError is raised if the subprocess command fails.
"""
caplog.set_level(logging.ERROR)
mock_content = '"google-cloud-language-v1-py",\n'
mocker.patch("cli.open", mock_open(read_data=mock_content))
with pytest.raises(ValueError):
_build_bazel_target("mock/bazel:rule", "source")
def test_build_bazel_target_fails_to_determine_rule(caplog):
"""
Tests that ValueError is raised if the subprocess command fails.
"""
caplog.set_level(logging.ERROR)
with pytest.raises(ValueError):
_build_bazel_target("mock/bazel:rule", "source")
def test_build_bazel_target_fails(mocker, caplog):
"""
Tests that ValueError is raised if the subprocess command fails.
"""
caplog.set_level(logging.ERROR)
mock_content = '"google-cloud-language-v1-py",\n'
mocker.patch("cli.open", mock_open(read_data=mock_content))
with pytest.raises(ValueError):
_build_bazel_target("mock/bazel:rule", "source")
def test_determine_bazel_rule_command_fails(mocker, caplog):
"""
Tests that an exception is raised if the subprocess command fails.
"""
caplog.set_level(logging.INFO)
mocker.patch(
"cli.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "cmd", stderr="Bazel error"),
)
with pytest.raises(ValueError):
_determine_bazel_rule("google/cloud/language/v1", "source")
assert "Found Bazel rule" not in caplog.text
def test_locate_and_extract_artifact_success(mocker, caplog):
"""
Tests that the artifact helper calls the correct sequence of commands.
"""
caplog.set_level(logging.INFO)
mock_info_result = MagicMock(stdout="/path/to/bazel-bin\n")
mock_tar_result = MagicMock(returncode=0)
mocker.patch("cli.subprocess.run", side_effect=[mock_info_result, mock_tar_result])
mock_makedirs = mocker.patch("cli.os.makedirs")
_locate_and_extract_artifact(
"//google/cloud/language/v1:rule-py",
"google-cloud-language",
"source",
"output",
"google/cloud/language/v1",
)
assert (
"Found artifact at: /path/to/bazel-bin/google/cloud/language/v1/rule-py.tar.gz"
in caplog.text
)
assert (
"Preparing staging directory: output/owl-bot-staging/google-cloud-language"
in caplog.text
)
assert (
"Artifact /path/to/bazel-bin/google/cloud/language/v1/rule-py.tar.gz extracted successfully"
in caplog.text
)
mock_makedirs.assert_called_once()
def test_locate_and_extract_artifact_fails(mocker, caplog):
"""
Tests that an exception is raised if the subprocess command fails.
"""
caplog.set_level(logging.INFO)
mocker.patch(
"cli.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "cmd", stderr="Bazel error"),
)
with pytest.raises(ValueError):
_locate_and_extract_artifact(
"//google/cloud/language/v1:rule-py",
"google-cloud-language",
"source",
"output",
"google/cloud/language/v1",
)
def test_run_post_processor_success(mocker, caplog):
"""
Tests that the post-processor helper calls the correct command.
"""
caplog.set_level(logging.INFO)
mocker.patch("cli.SYNTHTOOL_INSTALLED", return_value=True)
mock_chdir = mocker.patch("cli.os.chdir")
mock_owlbot_main = mocker.patch(
"cli.synthtool.languages.python_mono_repo.owlbot_main"
)
_run_post_processor("output", "google-cloud-language")
mock_chdir.assert_called_once()
mock_owlbot_main.assert_called_once_with("packages/google-cloud-language")
assert "Python post-processor ran successfully." in caplog.text
def test_handle_generate_success(caplog, mock_generate_request_file, mocker):
"""
Tests the successful execution path of handle_generate.
"""
caplog.set_level(logging.INFO)
mock_determine_rule = mocker.patch(
"cli._determine_bazel_rule", return_value="mock-rule"
)
mock_build_target = mocker.patch("cli._build_bazel_target")
mock_locate_and_extract_artifact = mocker.patch("cli._locate_and_extract_artifact")
mock_run_post_processor = mocker.patch("cli._run_post_processor")
mock_copy_files_needed_for_post_processing = mocker.patch(
"cli._copy_files_needed_for_post_processing"
)
mock_clean_up_files_after_post_processing = mocker.patch(
"cli._clean_up_files_after_post_processing"
)
handle_generate()
mock_determine_rule.assert_called_once_with("google/cloud/language/v1", "source")
mock_run_post_processor.assert_called_once_with("output", "google-cloud-language")
mock_copy_files_needed_for_post_processing.assert_called_once_with(
"output", "input", "google-cloud-language"
)
mock_clean_up_files_after_post_processing.assert_called_once_with(
"output", "google-cloud-language"
)
def test_handle_generate_fail(caplog):
"""
Tests the failed to read `librarian/generate-request.json` file in handle_generates.
"""
with pytest.raises(ValueError):
handle_generate()
def test_run_individual_session_success(mocker, caplog):
"""Tests that _run_individual_session calls nox with correct arguments and logs success."""
caplog.set_level(logging.INFO)
mock_subprocess_run = mocker.patch(
"cli.subprocess.run", return_value=MagicMock(returncode=0)
)
test_session = "unit-3.9"
test_library_id = "test-library"
repo = "repo"
_run_individual_session(test_session, test_library_id, repo)
expected_command = [
"nox",
"-s",
test_session,
"-f",
f"{REPO_DIR}/packages/{test_library_id}/noxfile.py",
]
mock_subprocess_run.assert_called_once_with(expected_command, text=True, check=True)
def test_run_individual_session_failure(mocker):
"""Tests that _run_individual_session raises CalledProcessError if nox command fails."""
mocker.patch(
"cli.subprocess.run",
side_effect=subprocess.CalledProcessError(
1, "nox", stderr="Nox session failed"
),
)
with pytest.raises(subprocess.CalledProcessError):
_run_individual_session("lint", "another-library", "repo")
def test_run_nox_sessions_success(
mocker, mock_generate_request_data_for_nox, mock_build_request_file
):
"""Tests that _run_nox_sessions successfully runs all specified sessions."""
mocker.patch("cli._read_json_file", return_value=mock_generate_request_data_for_nox)
mocker.patch("cli._get_library_id", return_value="mock-library")
mock_run_individual_session = mocker.patch("cli._run_individual_session")
sessions_to_run = ["unit-3.9", "lint"]
_run_nox_sessions(sessions_to_run, "librarian", "repo")
assert mock_run_individual_session.call_count == len(sessions_to_run)
mock_run_individual_session.assert_has_calls(
[
mocker.call("unit-3.9", "mock-library", "repo"),
mocker.call("lint", "mock-library", "repo"),
]
)
def test_run_nox_sessions_read_file_failure(mocker):
"""Tests that _run_nox_sessions raises ValueError if _read_json_file fails."""
mocker.patch("cli._read_json_file", side_effect=FileNotFoundError("file not found"))
with pytest.raises(ValueError, match="Failed to run the nox session"):
_run_nox_sessions(["unit-3.9"], "librarian", "repo")
def test_run_nox_sessions_get_library_id_failure(mocker):
"""Tests that _run_nox_sessions raises ValueError if _get_library_id fails."""
mocker.patch("cli._read_json_file", return_value={"apis": []}) # Missing 'id'
mocker.patch(
"cli._get_library_id",
side_effect=ValueError("Request file is missing required 'id' field."),
)
with pytest.raises(ValueError, match="Failed to run the nox session"):
_run_nox_sessions(["unit-3.9"], "librarian", "repo")
def test_run_nox_sessions_individual_session_failure(
mocker, mock_generate_request_data_for_nox
):
"""Tests that _run_nox_sessions raises ValueError if _run_individual_session fails."""
mocker.patch("cli._read_json_file", return_value=mock_generate_request_data_for_nox)
mocker.patch("cli._get_library_id", return_value="mock-library")
mock_run_individual_session = mocker.patch(
"cli._run_individual_session",
side_effect=[None, subprocess.CalledProcessError(1, "nox", "session failed")],
)
sessions_to_run = ["unit-3.9", "lint"]
with pytest.raises(ValueError, match="Failed to run the nox session"):
_run_nox_sessions(sessions_to_run, "librarian", "repo")
# Check that _run_individual_session was called at least once
assert mock_run_individual_session.call_count > 0
def test_handle_build_success(caplog, mocker):
"""
Tests the successful execution path of handle_build.
"""
caplog.set_level(logging.INFO)
mocker.patch("cli._run_nox_sessions")
handle_build()
assert "'build' command executed." in caplog.text
def test_read_valid_json(mocker):
"""Tests reading a valid JSON file."""
mock_content = '{"key": "value"}'
mocker.patch("builtins.open", mocker.mock_open(read_data=mock_content))
result = _read_json_file("fake/path.json")
assert result == {"key": "value"}
def test_file_not_found(mocker):
"""Tests behavior when the file does not exist."""
mocker.patch("builtins.open", side_effect=FileNotFoundError("No such file"))
with pytest.raises(FileNotFoundError):
_read_json_file("non/existent/path.json")
def test_invalid_json(mocker):
"""Tests reading a file with malformed JSON."""
mock_content = '{"key": "value",}'
mocker.patch("builtins.open", mocker.mock_open(read_data=mock_content))
with pytest.raises(json.JSONDecodeError):
_read_json_file("fake/path.json")
def test_copy_files_needed_for_post_processing_success(mocker):
mock_makedirs = mocker.patch("os.makedirs")
mock_shutil_copy = mocker.patch("shutil.copy")
_copy_files_needed_for_post_processing("output", "input", "library_id")
mock_makedirs.assert_called()
mock_shutil_copy.assert_called_once()
def test_clean_up_files_after_post_processing_success(mocker):
mock_shutil_rmtree = mocker.patch("shutil.rmtree")
mock_os_remove = mocker.patch("os.remove")
_clean_up_files_after_post_processing("output", "library_id")