forked from googleapis/gapic-generator-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
noxfile.py
517 lines (440 loc) · 16.4 KB
/
noxfile.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
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
# Copyright 2017, 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.
from __future__ import absolute_import
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import os
import sys
import tempfile
import typing
import nox # type: ignore
from contextlib import contextmanager
from os import path
import shutil
nox.options.error_on_missing_interpreters = True
showcase_version = os.environ.get("SHOWCASE_VERSION", "0.35.0")
ADS_TEMPLATES = path.join(path.dirname(__file__), "gapic", "ads-templates")
ALL_PYTHON = (
"3.7",
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
)
NEWEST_PYTHON = ALL_PYTHON[-1]
@nox.session(python=ALL_PYTHON)
def unit(session):
"""Run the unit test suite."""
session.install(
"coverage", "pytest-cov", "pytest", "pytest-xdist", "pyfakefs", "grpcio-status", "proto-plus",
)
session.install("-e", ".")
session.run(
"py.test",
*(
session.posargs
or [
"-vv",
"-n=auto",
"--cov=gapic",
"--cov-config=.coveragerc",
"--cov-report=term",
"--cov-fail-under=100",
path.join("tests", "unit"),
]
),
)
FRAG_DIR = Path("tests") / "fragments"
FRAGMENT_FILES = tuple(
Path(dirname).relative_to(FRAG_DIR) / f
for dirname, _, files in os.walk(FRAG_DIR)
for f in files
if os.path.splitext(f)[1] == ".proto" and f.startswith("test_")
)
# Note: this class lives outside 'fragment'
# so that, if necessary, it can be pickled for a ProcessPoolExecutor
# A callable class is necessary so that the session can be closed over
# instead of passed in, which simplifies the invocation via map.
class FragTester:
def __init__(self, session, use_ads_templates):
self.session = session
self.use_ads_templates = use_ads_templates
def __call__(self, frag):
with tempfile.TemporaryDirectory() as tmp_dir:
# Generate the fragment GAPIC.
outputs = []
templates = (
path.join(path.dirname(__file__), "gapic", "ads-templates")
if self.use_ads_templates
else "DEFAULT"
)
maybe_old_naming = ",old-naming" if self.use_ads_templates else ""
session_args = [
"python",
"-m",
"grpc_tools.protoc",
f"--proto_path={str(FRAG_DIR)}",
f"--python_gapic_out={tmp_dir}",
f"--python_gapic_opt=transport=grpc+rest,python-gapic-templates={templates}{maybe_old_naming}",
]
outputs.append(
self.session.run(*session_args, str(frag), external=True, silent=True,)
)
# Install the generated fragment library.
if self.use_ads_templates:
self.session.install(tmp_dir, "-e", ".", "-qqq")
else:
# Use the constraints file for the specific python runtime version.
# We do this to make sure that we're testing against the lowest
# supported version of a dependency.
# This is needed to recreate the issue reported in
# https://github.com/googleapis/gapic-generator-python/issues/1748
# The ads templates do not have constraints files.
constraints_path = str(
f"{tmp_dir}/testing/constraints-{self.session.python}.txt"
)
self.session.install(tmp_dir, "-e", ".", "-qqq", "-r", constraints_path)
# Run the fragment's generated unit tests.
# Don't bother parallelizing them: we already parallelize
# the fragments, and there usually aren't too many tests per fragment.
outputs.append(
self.session.run(
"py.test",
"--quiet",
f"--cov-config={str(Path(tmp_dir) / '.coveragerc')}",
"--cov-report=term",
"--cov-fail-under=100",
str(Path(tmp_dir) / "tests" / "unit"),
silent=True,
)
)
return "".join(outputs)
@nox.session(python=ALL_PYTHON)
def fragment(session, use_ads_templates=False):
session.install(
"coverage",
"pytest",
"pytest-cov",
"pytest-xdist",
"asyncmock; python_version < '3.8'",
"pytest-asyncio",
"grpcio-tools",
)
session.install("-e", ".")
frag_files = [Path(f) for f in session.posargs] if session.posargs else FRAGMENT_FILES
if os.environ.get("PARALLEL_FRAGMENT_TESTS", "false").lower() == "true":
with ThreadPoolExecutor() as p:
all_outs = p.map(FragTester(session, use_ads_templates), frag_files)
output = "".join(all_outs)
session.log(output)
else:
tester = FragTester(session, use_ads_templates)
for frag in frag_files:
session.log(tester(frag))
@nox.session(python=ALL_PYTHON)
def fragment_alternative_templates(session):
fragment(session, use_ads_templates=True)
@contextmanager
def showcase_library(
session, templates="DEFAULT", other_opts: typing.Iterable[str] = (),
include_service_yaml=True,
retry_config=True,
):
"""Install the generated library into the session for showcase tests."""
session.log("-" * 70)
session.log("Note: Showcase must be running for these tests to work.")
session.log("See https://github.com/googleapis/gapic-showcase")
session.log("-" * 70)
# Install gapic-generator-python
session.install("-e", ".")
# Install grpcio-tools for protoc
session.install("grpcio-tools")
# Install a client library for Showcase.
with tempfile.TemporaryDirectory() as tmp_dir:
# Download the Showcase descriptor.
session.run(
"curl",
"https://github.com/googleapis/gapic-showcase/releases/"
f"download/v{showcase_version}/"
f"gapic-showcase-{showcase_version}.desc",
"-L",
"--output",
path.join(tmp_dir, "showcase.desc"),
external=True,
silent=True,
)
if include_service_yaml:
session.run(
"curl",
"https://github.com/googleapis/gapic-showcase/releases/"
f"download/v{showcase_version}/"
f"showcase_v1beta1.yaml",
"-L",
"--output",
path.join(tmp_dir, "showcase_v1beta1.yaml"),
external=True,
silent=True,
)
if retry_config:
session.run(
"curl",
"https://github.com/googleapis/gapic-showcase/releases/"
f"download/v{showcase_version}/"
f"showcase_grpc_service_config.json",
"-L",
"--output",
path.join(tmp_dir, "showcase_grpc_service_config.json"),
external=True,
silent=True,
)
# Write out a client library for Showcase.
template_opt = f"python-gapic-templates={templates}"
opts = "--python_gapic_opt="
if include_service_yaml and retry_config:
opts += ",".join(other_opts + (f"{template_opt}", "transport=grpc+rest", f"service-yaml={tmp_dir}/showcase_v1beta1.yaml", f"retry-config={tmp_dir}/showcase_grpc_service_config.json"))
else:
opts += ",".join(other_opts + (f"{template_opt}", "transport=grpc+rest",))
cmd_tup = (
"python",
"-m",
"grpc_tools.protoc",
f"--experimental_allow_proto3_optional",
f"--descriptor_set_in={tmp_dir}{path.sep}showcase.desc",
opts,
f"--python_gapic_out={tmp_dir}",
f"google/showcase/v1beta1/echo.proto",
f"google/showcase/v1beta1/identity.proto",
f"google/showcase/v1beta1/messaging.proto",
)
session.run(
*cmd_tup, external=True,
)
# Install the generated showcase library.
if templates == "DEFAULT":
# Use the constraints file for the specific python runtime version.
# We do this to make sure that we're testing against the lowest
# supported version of a dependency.
# This is needed to recreate the issue reported in
# https://github.com/googleapis/google-cloud-python/issues/12254
constraints_path = str(
f"{tmp_dir}/testing/constraints-{session.python}.txt"
)
# Install the library with a constraints file.
session.install("-e", tmp_dir, "-r", constraints_path)
else:
# The ads templates do not have constraints files.
# See https://github.com/googleapis/gapic-generator-python/issues/1788
# Install the library without a constraints file.
session.install("-e", tmp_dir)
yield tmp_dir
@nox.session(python=ALL_PYTHON)
def showcase(
session,
templates="DEFAULT",
other_opts: typing.Iterable[str] = (),
env: typing.Optional[typing.Dict[str, str]] = {},
):
"""Run the Showcase test suite."""
with showcase_library(session, templates=templates, other_opts=other_opts):
session.install("pytest", "pytest-asyncio")
test_directory = Path("tests", "system")
ignore_file = env.get("IGNORE_FILE")
pytest_command = [
"py.test",
"--quiet",
*(session.posargs or [str(test_directory)]),
]
if ignore_file:
ignore_path = test_directory / ignore_file
pytest_command.extend(["--ignore", str(ignore_path)])
session.run(
*pytest_command,
env=env,
)
@nox.session(python=NEWEST_PYTHON)
def showcase_mtls(
session,
templates="DEFAULT",
other_opts: typing.Iterable[str] = (),
env: typing.Optional[typing.Dict[str, str]] = {},
):
"""Run the Showcase mtls test suite."""
with showcase_library(session, templates=templates, other_opts=other_opts):
session.install("pytest", "pytest-asyncio")
test_directory = Path("tests", "system")
ignore_file = env.get("IGNORE_FILE")
pytest_command = [
"py.test",
"--quiet",
"--mtls",
*(session.posargs or [str(test_directory)]),
]
if ignore_file:
ignore_path = test_directory / ignore_file
pytest_command.extend(["--ignore", str(ignore_path)])
session.run(
*pytest_command,
env=env,
)
@nox.session(python=ALL_PYTHON)
def showcase_alternative_templates(session):
templates = path.join(path.dirname(__file__), "gapic", "ads-templates")
showcase(
session,
templates=templates,
other_opts=("old-naming",),
env={"GAPIC_PYTHON_ASYNC": "False", "IGNORE_FILE": "test_universe_domain.py"},
)
@nox.session(python=NEWEST_PYTHON)
def showcase_mtls_alternative_templates(session):
templates = path.join(path.dirname(__file__), "gapic", "ads-templates")
showcase_mtls(
session,
templates=templates,
other_opts=("old-naming",),
env={"GAPIC_PYTHON_ASYNC": "False", "IGNORE_FILE": "test_universe_domain.py"},
)
def run_showcase_unit_tests(session, fail_under=100):
session.install(
"coverage",
"pytest",
"pytest-cov",
"pytest-xdist",
"asyncmock; python_version < '3.8'",
"pytest-asyncio",
)
# Run the tests.
session.run(
"py.test",
*(
session.posargs
or [
"-n=auto",
"--quiet",
"--cov=google",
"--cov-append",
f"--cov-fail-under={str(fail_under)}",
path.join("tests", "unit"),
]
),
)
@nox.session(python=ALL_PYTHON)
def showcase_unit(
session, templates="DEFAULT", other_opts: typing.Iterable[str] = (),
):
"""Run the generated unit tests against the Showcase library."""
with showcase_library(session, templates=templates, other_opts=other_opts) as lib:
session.chdir(lib)
run_showcase_unit_tests(session)
@nox.session(python=ALL_PYTHON)
def showcase_unit_alternative_templates(session):
with showcase_library(
session, templates=ADS_TEMPLATES, other_opts=("old-naming",)
) as lib:
session.chdir(lib)
run_showcase_unit_tests(session)
@nox.session(python=NEWEST_PYTHON)
def showcase_unit_add_iam_methods(session):
with showcase_library(session, other_opts=("add-iam-methods",)) as lib:
session.chdir(lib)
run_showcase_unit_tests(session, fail_under=100)
@nox.session(python=ALL_PYTHON)
def showcase_unit_mixins(session):
with showcase_library(session, include_service_yaml=True) as lib:
session.chdir(lib)
run_showcase_unit_tests(session)
@nox.session(python=ALL_PYTHON)
def showcase_unit_alternative_templates_mixins(session):
with showcase_library(
session, templates=ADS_TEMPLATES, other_opts=("old-naming",),
include_service_yaml=True
) as lib:
session.chdir(lib)
run_showcase_unit_tests(session)
@nox.session(python=NEWEST_PYTHON)
def showcase_mypy(
session, templates="DEFAULT", other_opts: typing.Iterable[str] = (),
):
"""Perform typecheck analysis on the generated Showcase library."""
# Install pytest and gapic-generator-python
session.install("mypy", "types-pkg-resources", "types-protobuf", "types-requests", "types-dataclasses")
with showcase_library(session, templates=templates, other_opts=other_opts) as lib:
session.chdir(lib)
# Run the tests.
session.run("mypy", "-p", "google")
@nox.session(python=NEWEST_PYTHON)
def showcase_mypy_alternative_templates(session):
showcase_mypy(session, templates=ADS_TEMPLATES, other_opts=("old-naming",))
@nox.session(python=NEWEST_PYTHON)
def snippetgen(session):
# Clone googleapis/api-common-protos which are referenced by the snippet
# protos
api_common_protos = "api-common-protos"
try:
session.run("git", "-C", api_common_protos, "pull", external=True)
except nox.command.CommandFailed:
session.run(
"git",
"clone",
"--single-branch",
f"https://github.com/googleapis/{api_common_protos}",
external=True,
)
# Install gapic-generator-python
session.install("-e", ".")
session.install("grpcio-tools", "pytest", "pytest-asyncio")
session.run("py.test", "-vv", "tests/snippetgen")
@nox.session(python="3.10")
def docs(session):
"""Build the docs."""
session.install(
# We need to pin to specific versions of the `sphinxcontrib-*` packages
# which still support sphinx 4.x.
# See https://github.com/googleapis/sphinx-docfx-yaml/issues/344
# and https://github.com/googleapis/sphinx-docfx-yaml/issues/345.
"sphinxcontrib-applehelp==1.0.4",
"sphinxcontrib-devhelp==1.0.2",
"sphinxcontrib-htmlhelp==2.0.1",
"sphinxcontrib-qthelp==1.0.3",
"sphinxcontrib-serializinghtml==1.1.5",
"sphinx==4.5.0",
"sphinx_rtd_theme"
)
session.install(".")
# Build the docs!
session.run("rm", "-rf", "docs/_build/")
session.run(
"sphinx-build",
"-W",
"-b",
"html",
"-d",
"docs/_build/doctrees",
"docs/",
"docs/_build/html/",
)
@nox.session(python=ALL_PYTHON)
def mypy(session):
"""Perform typecheck analysis."""
# Pin to click==8.1.3 to workaround https://github.com/pallets/click/issues/2558
session.install(
"mypy",
"types-protobuf<=3.19.7",
"types-PyYAML",
"types-dataclasses",
"click==8.1.3",
)
session.install(".")
session.run("mypy", "-p", "gapic")