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
2047 lines (1667 loc) · 73.6 KB
/
test_cli.py
File metadata and controls
2047 lines (1667 loc) · 73.6 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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 pathlib
import re
import subprocess
import yaml
import unittest.mock
from datetime import date, datetime
from pathlib import Path
from unittest.mock import MagicMock, mock_open
import pytest
from cli import (
_GENERATOR_INPUT_HEADER_TEXT,
GENERATE_REQUEST_FILE,
BUILD_REQUEST_FILE,
CONFIGURE_REQUEST_FILE,
RELEASE_STAGE_REQUEST_FILE,
SOURCE_DIR,
STATE_YAML_FILE,
LIBRARIAN_DIR,
REPO_DIR,
_add_header_to_files,
_clean_up_files_after_post_processing,
_copy_files_needed_for_post_processing,
_create_main_version_header,
_create_repo_metadata_from_service_config,
_determine_generator_command,
_determine_library_namespace,
_determine_release_level,
_generate_api,
_generate_repo_metadata_file,
_get_api_generator_options,
_get_library_dist_name,
_get_library_id,
_get_libraries_to_prepare_for_release,
_get_new_library_config,
_get_previous_version,
_get_repo_name_from_repo_metadata,
_get_staging_child_directory,
_add_new_library_version,
_prepare_new_library_config,
_process_changelog,
_process_version_file,
_read_bazel_build_py_rule,
_read_json_file,
_read_text_file,
_run_individual_session,
_run_nox_sessions,
_run_post_processor,
_run_protoc_command,
_stage_gapic_library,
_stage_proto_only_library,
_update_changelog_for_library,
_update_global_changelog,
_update_version_for_library,
_verify_library_dist_name,
_verify_library_namespace,
_write_json_file,
_write_text_file,
_copy_readme_to_docs,
_create_new_changelog_for_library,
handle_build,
handle_configure,
handle_generate,
handle_release_stage,
)
_MOCK_LIBRARY_CHANGES = [
{
"type": "feat",
"subject": "add new UpdateRepository API",
"body": "This adds the ability to update a repository's properties.",
"piper_cl_number": "786353207",
"commit_hash": "9461532e7d19c8d71709ec3b502e5d81340fb661",
},
{
"type": "fix",
"subject": "some fix",
"body": "some body",
"piper_cl_number": "786353208",
"commit_hash": "1231532e7d19c8d71709ec3b502e5d81340fb661",
},
{
"type": "fix",
"subject": "another fix",
"body": "",
"piper_cl_number": "786353209",
"commit_hash": "1241532e7d19c8d71709ec3b502e5d81340fb661",
},
{
"type": "docs",
"subject": "fix typo in BranchRule comment",
"body": "",
"piper_cl_number": "786353210",
"commit_hash": "9461532e7d19c8d71709ec3b502e5d81340fb661",
},
]
_MOCK_BAZEL_CONTENT_PY_GAPIC = """load(
"@com_google_googleapis_imports//:imports.bzl",
"py_gapic_assembly_pkg",
"py_gapic_library",
"py_test",
)
py_gapic_library(
name = "language_py_gapic",
srcs = [":language_proto"],
grpc_service_config = "language_grpc_service_config.json",
rest_numeric_enums = True,
service_yaml = "language_v1.yaml",
transport = "grpc+rest",
deps = [
],
opt_args = [
"python-gapic-namespace=google.cloud",
],
)"""
_MOCK_BAZEL_CONTENT_PY_PROTO = """load(
"@com_google_googleapis_imports//:imports.bzl",
"py_proto_library",
)
py_proto_library(
name = "language_py_proto",
)"""
@pytest.fixture
def setup_dirs(tmp_path):
"""Creates input and output directories."""
input_dir = tmp_path / "input"
output_dir = tmp_path / "output"
input_dir.mkdir()
output_dir.mkdir()
return input_dir, output_dir
@pytest.fixture(autouse=True)
def _clear_lru_cache():
"""Automatically clears the cache of all LRU-cached functions after each test."""
yield
_get_repo_name_from_repo_metadata.cache_clear()
@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_configure_request_data():
"""Returns mock data for configure-request.json."""
return {
"libraries": [
{
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1", "status": "new"}],
"version": "",
}
]
}
@pytest.fixture
def mock_configure_request_file(tmp_path, monkeypatch, mock_configure_request_data):
"""Creates the mock request file at the correct path inside a temp dir."""
# Create the path as expected by the script: .librarian/configure-request.json
request_path = f"{LIBRARIAN_DIR}/{CONFIGURE_REQUEST_FILE}"
request_dir = tmp_path / os.path.dirname(request_path)
request_dir.mkdir(parents=True, exist_ok=True)
request_file = request_dir / os.path.basename(request_path)
request_file.write_text(json.dumps(mock_configure_request_data))
# Change the current working directory to the temp path for the test.
monkeypatch.chdir(tmp_path)
return request_file
@pytest.fixture
def mock_build_bazel_file(tmp_path, monkeypatch):
"""Creates the mock BUILD.bazel file at the correct path inside a temp dir."""
bazel_build_path = f"{SOURCE_DIR}/google/cloud/language/v1/BUILD.bazel"
bazel_build_dir = tmp_path / Path(bazel_build_path).parent
os.makedirs(bazel_build_dir, exist_ok=True)
build_bazel_file = bazel_build_dir / os.path.basename(bazel_build_path)
build_bazel_file.write_text(_MOCK_BAZEL_CONTENT_PY_GAPIC)
return build_bazel_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"},
],
}
@pytest.fixture
def mock_release_stage_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/release-request.json
request_path = f"{LIBRARIAN_DIR}/{RELEASE_STAGE_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 = {
"libraries": [
{
"id": "google-cloud-another-library",
"apis": [{"path": "google/cloud/another/library/v1"}],
"release_triggered": False,
"version": "1.2.3",
"changes": [],
"tag_format": "{id}-v{version}",
},
{
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1"}],
"release_triggered": True,
"version": "1.2.3",
"changes": [],
"tag_format": "{id}-v{version}",
},
]
}
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_state_file(tmp_path, monkeypatch):
"""Creates the state file at the correct path inside a temp dir."""
# Create the path as expected by the script: .librarian/state.yaml
request_path = f"{LIBRARIAN_DIR}/{STATE_YAML_FILE}"
request_dir = tmp_path / os.path.dirname(request_path)
request_dir.mkdir()
request_file = request_dir / os.path.basename(request_path)
state_yaml_contents = {
"libraries": [{"id": "google-cloud-language", "version": "1.2.3"}]
}
request_file.write_text(yaml.dump(state_yaml_contents))
# Change the current working directory to the temp path for the test.
monkeypatch.chdir(tmp_path)
return request_file
def test_handle_configure_success(mock_configure_request_file, mocker):
"""Tests the successful execution path of handle_configure."""
mocker.patch("cli._update_global_changelog", return_value=None)
mock_write_json = mocker.patch("cli._write_json_file")
mock_prepare_config = mocker.patch(
"cli._prepare_new_library_config", return_value={"id": "prepared"}
)
mock_create_changelog = mocker.patch("cli._create_new_changelog_for_library")
handle_configure()
mock_prepare_config.assert_called_once()
mock_write_json.assert_called_once_with(
f"{LIBRARIAN_DIR}/configure-response.json", {"id": "prepared"}
)
def test_handle_configure_no_new_library(mocker):
"""Tests that handle_configure fails if no new library is found."""
mocker.patch("cli._read_json_file", return_value={"libraries": []})
# The call to _prepare_new_library_config with an empty dict will raise a ValueError
# because _get_library_id will fail.
with pytest.raises(ValueError, match="Configuring a new library failed."):
handle_configure()
def test_create_new_changelog_for_library(mocker):
"""Tests that the changelog files are created correctly."""
library_id = "google-cloud-language"
output = "output"
mock_makedirs = mocker.patch("os.makedirs")
mock_write_text_file = mocker.patch("cli._write_text_file")
_create_new_changelog_for_library(library_id, output)
package_changelog_path = f"{output}/packages/{library_id}/CHANGELOG.md"
docs_changelog_path = f"{output}/packages/{library_id}/docs/CHANGELOG.md"
# Check that makedirs was called for both parent directories
mock_makedirs.assert_any_call(
os.path.dirname(package_changelog_path), exist_ok=True
)
mock_makedirs.assert_any_call(os.path.dirname(docs_changelog_path), exist_ok=True)
assert mock_makedirs.call_count == 2
# Check that the files were "written" with the correct content
changelog_content = f"# Changelog\n\n[PyPI History][1]\n\n[1]: https://pypi.org/project/{library_id}/#history\n"
mock_write_text_file.assert_any_call(package_changelog_path, changelog_content)
mock_write_text_file.assert_any_call(docs_changelog_path, changelog_content)
assert mock_write_text_file.call_count == 2
def test_get_new_library_config_found(mock_configure_request_data):
"""Tests that the new library configuration is returned when found."""
config = _get_new_library_config(mock_configure_request_data)
assert config["id"] == "google-cloud-language"
# Assert that the config is NOT modified
assert "status" in config["apis"][0]
def test_get_new_library_config_not_found():
"""Tests that an empty dictionary is returned when no new library is found."""
request_data = {
"libraries": [
{
"id": "existing-library",
"apis": [{"path": "path/v1", "status": "existing"}],
},
]
}
config = _get_new_library_config(request_data)
assert config == {}
def test_get_new_library_config_empty_input():
"""Tests that an empty dictionary is returned for empty input."""
config = _get_new_library_config({})
assert config == {}
def test_prepare_new_library_config(mocker):
"""Tests the preparation of a new library's configuration."""
raw_config = {
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1", "status": "new"}],
"source_roots": None,
"preserve_regex": None,
"remove_regex": None,
"version": "",
}
prepared_config = _prepare_new_library_config(raw_config)
# Check that status is removed
assert "status" not in prepared_config["apis"][0]
# Check that defaults are added
assert prepared_config["source_roots"] == ["packages/google-cloud-language"]
assert (
"packages/google-cloud-language/CHANGELOG.md"
in prepared_config["preserve_regex"]
)
assert prepared_config["remove_regex"] == ["packages/google-cloud-language"]
assert prepared_config["tag_format"] == "{id}-v{version}"
assert prepared_config["version"] == "0.0.0"
def test_prepare_new_library_config_preserves_existing_values(mocker):
"""Tests that existing values in the config are not overwritten."""
raw_config = {
"id": "google-cloud-language",
"apis": [{"path": "google/cloud/language/v1", "status": "new"}],
"source_roots": ["packages/google-cloud-language-custom"],
"preserve_regex": ["custom/regex"],
"remove_regex": ["custom/remove"],
"tag_format": "custom-format-{{version}}",
"version": "4.5.6",
}
prepared_config = _prepare_new_library_config(raw_config)
# Check that status is removed
assert "status" not in prepared_config["apis"][0]
# Check that existing values are preserved
assert prepared_config["source_roots"] == ["packages/google-cloud-language-custom"]
assert prepared_config["preserve_regex"] == ["custom/regex"]
assert prepared_config["remove_regex"] == ["custom/remove"]
assert prepared_config["tag_format"] == "custom-format-{{version}}"
assert prepared_config["version"] == "4.5.6"
def test_add_new_library_version_populates_version(mocker):
"""Tests that the version is populated if it's missing."""
config = {"version": ""}
_add_new_library_version(config)
assert config["version"] == "0.0.0"
def test_add_new_library_version_preserves_version():
"""Tests that an existing version is preserved."""
config = {"version": "4.5.6"}
_add_new_library_version(config)
assert config["version"] == "4.5.6"
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)
@pytest.mark.parametrize(
"is_mono_repo,owlbot_py_exists", [(True, False), (False, False), (False, True)]
)
def test_run_post_processor_success(mocker, caplog, is_mono_repo, owlbot_py_exists):
"""
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")
mocker.patch("pathlib.Path.exists", return_value=owlbot_py_exists)
mocker.patch(
"cli.subprocess.run", return_value=MagicMock(stdout="ok", stderr="", check=True)
)
if is_mono_repo:
mock_owlbot = mocker.patch(
"cli.synthtool.languages.python_mono_repo.owlbot_main"
)
elif not owlbot_py_exists:
mock_owlbot = mocker.patch("cli.synthtool.languages.python.owlbot_main")
_run_post_processor("output", "google-cloud-language", is_mono_repo)
mock_chdir.assert_called_once()
if is_mono_repo:
mock_owlbot.assert_called_once_with("packages/google-cloud-language")
elif not owlbot_py_exists:
mock_owlbot.assert_called_once_with()
assert "Python post-processor ran successfully." in caplog.text
def test_read_bazel_build_py_rule_success(mocker, mock_build_bazel_file):
"""Tests successful reading and parsing of a valid BUILD.bazel file."""
api_path = "google/cloud/language/v1"
# Use the empty string as the source path, since the fixture has set the CWD to the temporary root.
source_dir = "source"
mocker.patch("cli._read_text_file", return_value=_MOCK_BAZEL_CONTENT_PY_GAPIC)
# The fixture already creates the file, so we just need to call the function
py_gapic_config = _read_bazel_build_py_rule(api_path, source_dir)
assert (
"language_py_gapic" not in py_gapic_config
) # Only rule attributes should be returned
assert py_gapic_config["grpc_service_config"] == "language_grpc_service_config.json"
assert py_gapic_config["rest_numeric_enums"] is True
assert py_gapic_config["transport"] == "grpc+rest"
assert py_gapic_config["opt_args"] == ["python-gapic-namespace=google.cloud"]
def test_read_bazel_build_py_rule_not_found(mocker, mock_build_bazel_file):
"""Tests successful parsing of a valid BUILD.bazel file for a proto-only library."""
api_path = "google/cloud/language/v1"
# Use the empty string as the source path, since the fixture has set the CWD to the temporary root.
source_dir = "source"
mocker.patch("cli._read_text_file", return_value=_MOCK_BAZEL_CONTENT_PY_PROTO)
# The fixture already creates the file, so we just need to call the function
py_gapic_config = _read_bazel_build_py_rule(api_path, source_dir)
assert "language_py_gapic" not in py_gapic_config
assert py_gapic_config == {}
def test_get_api_generator_options_all_options():
"""Tests option extraction when all relevant fields are present."""
api_path = "google/cloud/language/v1"
py_gapic_config = {
"grpc_service_config": "config.json",
"rest_numeric_enums": True,
"service_yaml": "service.yaml",
"transport": "grpc+rest",
"opt_args": ["single_arg", "another_arg"],
}
gapic_version = "1.2.99"
options = _get_api_generator_options(api_path, py_gapic_config, gapic_version)
expected = [
"retry-config=google/cloud/language/v1/config.json",
"rest-numeric-enums=True",
"service-yaml=google/cloud/language/v1/service.yaml",
"transport=grpc+rest",
"single_arg",
"another_arg",
"gapic-version=1.2.99",
]
assert sorted(options) == sorted(expected)
def test_get_api_generator_options_minimal_options():
"""Tests option extraction when only transport is present."""
api_path = "google/cloud/minimal/v1"
py_gapic_config = {
"transport": "grpc",
}
gapic_version = "1.2.99"
options = _get_api_generator_options(api_path, py_gapic_config, gapic_version)
expected = ["transport=grpc", "gapic-version=1.2.99"]
assert options == expected
def test_determine_generator_command_with_options():
"""Tests command construction with options."""
api_path = "google/cloud/test/v1"
tmp_dir = "/tmp/output/test"
options = ["transport=grpc", "custom_option=foo"]
command = _determine_generator_command(api_path, tmp_dir, options)
expected_options = "--python_gapic_opt=metadata,transport=grpc,custom_option=foo"
expected_command = (
f"protoc {api_path}/*.proto --python_gapic_out={tmp_dir} {expected_options}"
)
assert command == expected_command
def test_determine_generator_command_no_options():
"""Tests command construction without extra options."""
api_path = "google/cloud/test/v1"
tmp_dir = "/tmp/output/test"
options = []
command = _determine_generator_command(api_path, tmp_dir, options)
# Note: 'metadata' is always included if options list is empty or not
# only if `generator_options` is not empty. If it is empty, the result is:
expected_command_no_options = (
f"protoc {api_path}/*.proto --python_gapic_out={tmp_dir}"
)
assert command == expected_command_no_options
def test_run_protoc_command_success(mocker):
"""Tests successful execution of the protoc command."""
mock_run = mocker.patch(
"cli.subprocess.run", return_value=MagicMock(stdout="ok", stderr="", check=True)
)
command = "protoc api/*.proto --python_gapic_out=/tmp/out"
source = "/src"
_run_protoc_command(command, source)
mock_run.assert_called_once_with(
[command], cwd=source, shell=True, check=True, capture_output=True, text=True
)
def test_run_protoc_command_failure(mocker):
"""Tests failure when protoc command returns a non-zero exit code."""
mock_run = mocker.patch(
"cli.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "protoc", stderr="error"),
)
command = "protoc api/*.proto --python_gapic_out=/tmp/out"
source = "/src"
with pytest.raises(subprocess.CalledProcessError):
_run_protoc_command(command, source)
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_generate_api_success_py_gapic(mocker, caplog, is_mono_repo):
caplog.set_level(logging.INFO)
API_PATH = "google/cloud/language/v1"
LIBRARY_ID = "google-cloud-language"
SOURCE = "source"
OUTPUT = "output"
gapic_version = "1.2.99"
mock_read_bazel_build_py_rule = mocker.patch(
"cli._read_bazel_build_py_rule",
return_value={
"py_gapic_library": {
"name": "language_py_gapic",
}
},
)
mock_run_protoc_command = mocker.patch("cli._run_protoc_command")
mock_shutil_copytree = mocker.patch("shutil.copytree")
_generate_api(API_PATH, LIBRARY_ID, SOURCE, OUTPUT, gapic_version, is_mono_repo)
mock_read_bazel_build_py_rule.assert_called_once()
mock_run_protoc_command.assert_called_once()
mock_shutil_copytree.assert_called_once()
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_generate_api_success_py_proto(mocker, caplog, is_mono_repo):
caplog.set_level(logging.INFO)
API_PATH = "google/cloud/language/v1"
LIBRARY_ID = "google-cloud-language"
SOURCE = "source"
OUTPUT = "output"
gapic_version = "1.2.99"
mock_read_bazel_build_py_rule = mocker.patch(
"cli._read_bazel_build_py_rule", return_value={}
)
mock_run_protoc_command = mocker.patch("cli._run_protoc_command")
mock_shutil_copytree = mocker.patch("shutil.copytree")
_generate_api(API_PATH, LIBRARY_ID, SOURCE, OUTPUT, gapic_version, is_mono_repo)
mock_read_bazel_build_py_rule.assert_called_once()
mock_run_protoc_command.assert_called_once()
mock_shutil_copytree.assert_called_once()
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_handle_generate_success(
caplog, mock_generate_request_file, mock_build_bazel_file, mocker, is_mono_repo
):
"""
Tests the successful execution path of handle_generate.
"""
caplog.set_level(logging.INFO)
mock_generate_api = mocker.patch("cli._generate_api")
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"
)
mocker.patch("cli._generate_repo_metadata_file")
mocker.patch("pathlib.Path.exists", return_value=is_mono_repo)
handle_generate()
mock_run_post_processor.assert_called_once_with(
"output", "google-cloud-language", is_mono_repo
)
mock_copy_files_needed_for_post_processing.assert_called_once_with(
"output", "input", "google-cloud-language", is_mono_repo
)
mock_clean_up_files_after_post_processing.assert_called_once_with(
"output", "google-cloud-language", is_mono_repo
)
mock_generate_api.assert_called_once()
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()
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_run_individual_session_success(mocker, caplog, is_mono_repo):
"""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, is_mono_repo)
expected_command = [
"nox",
"-s",
test_session,
"-f",
(
f"{REPO_DIR}/packages/{test_library_id}/noxfile.py"
if is_mono_repo
else f"{REPO_DIR}/noxfile.py"
),
]
mock_subprocess_run.assert_called_once_with(
expected_command, text=True, check=True, timeout=1200
)
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", True)
@pytest.mark.parametrize(
"is_mono_repo, nox_session_python_runtime",
[
(False, "3.14"),
(True, "3.14"),
],
)
def test_run_nox_sessions_success(
mocker,
mock_generate_request_data_for_nox,
is_mono_repo,
nox_session_python_runtime,
):
"""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 = [
f"unit-{nox_session_python_runtime}(protobuf_implementation='python')",
]
_run_nox_sessions("mock-library", "repo", is_mono_repo)
assert mock_run_individual_session.call_count == len(sessions_to_run)
mock_run_individual_session.assert_has_calls(
[
mocker.call(
f"unit-{nox_session_python_runtime}(protobuf_implementation='python')",
"mock-library",
"repo",
is_mono_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("mock-library", "repo", True)
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("mock-library", "repo", True)
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_run_nox_sessions_individual_session_failure(
mocker, mock_generate_request_data_for_nox, is_mono_repo
):
"""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=[subprocess.CalledProcessError(1, "nox", "session failed")],
)
with pytest.raises(ValueError, match="Failed to run the nox session"):
_run_nox_sessions("mock-library", "repo", is_mono_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, mock_build_request_file):
"""
Tests the successful execution path of handle_build.
"""
caplog.set_level(logging.INFO)
mocker.patch("cli._run_nox_sessions")
mocker.patch("cli._verify_library_namespace")
mocker.patch("cli._verify_library_dist_name")
handle_build()
assert "'build' command executed." in caplog.text
def test_handle_build_fail(caplog):
"""
Tests the failed to read `librarian/build-request.json` file in handle_generates.
"""
with pytest.raises(ValueError):
handle_build()
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_json_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")
@pytest.mark.parametrize("is_mono_repo", [False, True])
def test_copy_files_needed_for_post_processing_copies_files_from_generator_input(
mocker, is_mono_repo
):
"""Tests that .repo-metadata.json is copied if it exists."""
mock_makedirs = mocker.patch("os.makedirs")
mock_shutil_copytree = mocker.patch("shutil.copytree")
mocker.patch("pathlib.Path.exists", return_value=True)
_copy_files_needed_for_post_processing(
"output", "input", "library_id", is_mono_repo
)
mock_shutil_copytree.assert_called()
mock_makedirs.assert_called()
def test_copy_files_needed_for_post_processing_copies_files_from_generator_input_skips_json_files(
setup_dirs,
):
"""Test that .json files are copied but NOT modified."""
input_dir, output_dir = setup_dirs
json_content = '{"key": "value"}'
(input_dir / ".repo-metadata.json").write_text(json_content)
_copy_files_needed_for_post_processing(
output=str(output_dir),
input=str(input_dir),
library_id="google-cloud-foo",
is_mono_repo=False,
)
dest_file = output_dir / ".repo-metadata.json"
assert dest_file.exists()
# Content should be exactly the same, no # comments added
assert dest_file.read_text() == json_content
def test_add_header_with_existing_license(tmp_path):
"""
Test that the header is inserted AFTER the existing license block.
"""
# Setup: Create a file with a license header
file_path = tmp_path / "example.py"
original_content = (
"# Copyright 2025 Google LLC\n" "# Licensed under Apache 2.0\n" "\n" "import os"
)
file_path.write_text(original_content, encoding="utf-8")
# Execute
_add_header_to_files(str(tmp_path))
# Verify
new_content = file_path.read_text(encoding="utf-8")
expected_content = (
"# Copyright 2025 Google LLC\n"
"# Licensed under Apache 2.0\n"
"\n"
f"{_GENERATOR_INPUT_HEADER_TEXT}\n"
"\n"
"import os"
)
assert new_content == expected_content
def test_add_header_to_files_add_header_no_license(tmp_path):
"""
Test that the header is inserted at the top if no license block exists.
"""
# Setup: Create a file starting directly with code
file_path = tmp_path / "script.sh"
original_content = "echo 'Hello World'"
file_path.write_text(original_content, encoding="utf-8")
# Execute
_add_header_to_files(str(tmp_path))
# Verify
new_content = file_path.read_text(encoding="utf-8")
expected_content = f"{_GENERATOR_INPUT_HEADER_TEXT}\n" "echo 'Hello World'"
assert new_content == expected_content
def test_add_header_to_files_skips_excluded_extensions(tmp_path):
"""
Test that .json and .yaml files are ignored.
"""
# Setup: Create files that should be ignored
json_file = tmp_path / "data.json"
yaml_file = tmp_path / "config.yaml"
content = "key: value"
json_file.write_text('{"key": "value"}', encoding="utf-8")
yaml_file.write_text(content, encoding="utf-8")
# Execute
_add_header_to_files(str(tmp_path))
# Verify contents remain exactly the same
assert json_file.read_text(encoding="utf-8") == '{"key": "value"}'