Skip to content

Commit b045c68

Browse files
committed
debug: add custom noxfile for debugging
1 parent b8ab76a commit b045c68

File tree

1 file changed

+306
-0
lines changed

1 file changed

+306
-0
lines changed

secretmanager/snippets/noxfile.py

Lines changed: 306 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
# Copyright 2019 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
from __future__ import print_function
17+
18+
from collections.abc import Callable
19+
import glob
20+
import os
21+
from pathlib import Path
22+
import sys
23+
24+
import nox
25+
26+
27+
# WARNING - WARNING - WARNING - WARNING - WARNING
28+
# WARNING - WARNING - WARNING - WARNING - WARNING
29+
# BE CAREFUL WHEN EDITING THIS FILE!
30+
# WARNING - WARNING - WARNING - WARNING - WARNING
31+
# WARNING - WARNING - WARNING - WARNING - WARNING
32+
33+
# Copy `noxfile_config.py` to your directory and modify it instead.
34+
35+
36+
# `TEST_CONFIG` dict is a configuration hook that allows users to
37+
# modify the test configurations. The values here should be in sync
38+
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
39+
# their directory and modify it.
40+
41+
TEST_CONFIG = {
42+
# You can opt out from the test for specific Python versions.
43+
"ignored_versions": ["2.7", "3.7", "3.8", "3.10", "3.11", "3.12"],
44+
# Old samples are opted out of enforcing Python type hints
45+
# All new samples should feature them
46+
"enforce_type_hints": False,
47+
# An envvar key for determining the project id to use. Change it
48+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
49+
# build specific Cloud project. You can also use your own string
50+
# to use your own Cloud project.
51+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
52+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
53+
# If you need to use a specific version of pip,
54+
# change pip_version_override to the string representation
55+
# of the version number, for example, "20.2.4"
56+
"pip_version_override": None,
57+
# A dictionary you want to inject into your test. Don't put any
58+
# secrets here. These values will override predefined values.
59+
"envs": {},
60+
}
61+
62+
63+
try:
64+
# Ensure we can import noxfile_config in the project's directory.
65+
sys.path.append(".")
66+
from noxfile_config import TEST_CONFIG_OVERRIDE
67+
except ImportError as e:
68+
print("No user noxfile_config found: detail: {}".format(e))
69+
TEST_CONFIG_OVERRIDE = {}
70+
71+
# Update the TEST_CONFIG with the user supplied values.
72+
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)
73+
74+
75+
def get_pytest_env_vars() -> dict[str, str]:
76+
"""Returns a dict for pytest invocation."""
77+
ret = {}
78+
79+
# Override the GCLOUD_PROJECT and the alias.
80+
env_key = TEST_CONFIG["gcloud_project_env"]
81+
# This should error out if not set.
82+
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
83+
ret["GCLOUD_PROJECT"] = os.environ[env_key] # deprecated
84+
85+
# Apply user supplied envs.
86+
ret.update(TEST_CONFIG["envs"])
87+
return ret
88+
89+
90+
# All versions used to tested samples.
91+
ALL_VERSIONS = ["2.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
92+
93+
# Any default versions that should be ignored.
94+
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
95+
96+
TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])
97+
98+
INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False))
99+
100+
# Error if a python version is missing
101+
nox.options.error_on_missing_interpreters = True
102+
103+
#
104+
# Style Checks
105+
#
106+
107+
108+
def _determine_local_import_names(start_dir: str) -> list[str]:
109+
"""Determines all import names that should be considered "local".
110+
111+
This is used when running the linter to ensure that import order is
112+
properly checked.
113+
"""
114+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
115+
return [
116+
basename
117+
for basename, extension in file_ext_pairs
118+
if extension == ".py"
119+
or os.path.isdir(os.path.join(start_dir, basename))
120+
and basename not in ("__pycache__")
121+
]
122+
123+
124+
# Linting with flake8.
125+
#
126+
# We ignore the following rules:
127+
# ANN101: missing type annotation for `self` in method
128+
# ANN102: missing type annotation for `cls` in method
129+
# E203: whitespace before ‘:’
130+
# E266: too many leading ‘#’ for block comment
131+
# E501: line too long
132+
# I202: Additional newline in a section of imports
133+
#
134+
# We also need to specify the rules which are ignored by default:
135+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
136+
#
137+
# For more information see: https://pypi.org/project/flake8-annotations
138+
FLAKE8_COMMON_ARGS = [
139+
"--show-source",
140+
"--builtin=gettext",
141+
"--max-complexity=20",
142+
"--import-order-style=google",
143+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
144+
"--ignore=ANN101,ANN102,E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
145+
"--max-line-length=88",
146+
]
147+
148+
149+
@nox.session
150+
def lint(session: nox.sessions.Session) -> None:
151+
if not TEST_CONFIG["enforce_type_hints"]:
152+
session.install("flake8", "flake8-import-order")
153+
else:
154+
session.install("flake8", "flake8-import-order", "flake8-annotations")
155+
156+
print("✨ Custom noxfile interception")
157+
local_names = _determine_local_import_names(".")
158+
args = FLAKE8_COMMON_ARGS + [
159+
"--application-import-names",
160+
",".join(local_names),
161+
".",
162+
]
163+
session.run("flake8", *args)
164+
165+
166+
#
167+
# Black
168+
#
169+
170+
171+
@nox.session
172+
def blacken(session: nox.sessions.Session) -> None:
173+
session.install("black")
174+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
175+
176+
session.run("black", *python_files)
177+
178+
179+
#
180+
# Sample Tests
181+
#
182+
183+
184+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
185+
186+
187+
def _session_tests(
188+
session: nox.sessions.Session, post_install: Callable = None
189+
) -> None:
190+
# check for presence of tests
191+
test_list = glob.glob("*_test.py") + glob.glob("test_*.py")
192+
test_list.extend(glob.glob("tests"))
193+
194+
if len(test_list) == 0:
195+
print("No tests found, skipping directory.")
196+
return
197+
198+
if TEST_CONFIG["pip_version_override"]:
199+
pip_version = TEST_CONFIG["pip_version_override"]
200+
session.install(f"pip=={pip_version}")
201+
else:
202+
session.install("--upgrade", "pip")
203+
204+
"""Runs py.test for a particular project."""
205+
concurrent_args = []
206+
if os.path.exists("requirements.txt"):
207+
with open("requirements.txt") as rfile:
208+
packages = rfile.read()
209+
if os.path.exists("constraints.txt"):
210+
session.install(
211+
"-r",
212+
"requirements.txt",
213+
"-c",
214+
"constraints.txt",
215+
"--only-binary",
216+
":all",
217+
)
218+
elif "pyspark" in packages:
219+
session.install("-r", "requirements.txt", "--use-pep517")
220+
else:
221+
session.install("-r", "requirements.txt", "--only-binary", ":all")
222+
223+
if os.path.exists("requirements-test.txt"):
224+
with open("requirements-test.txt") as rtfile:
225+
packages += rtfile.read()
226+
if os.path.exists("constraints-test.txt"):
227+
session.install(
228+
"-r",
229+
"requirements-test.txt",
230+
"-c",
231+
"constraints-test.txt",
232+
"--only-binary",
233+
":all",
234+
)
235+
else:
236+
session.install("-r", "requirements-test.txt", "--only-binary", ":all")
237+
238+
if INSTALL_LIBRARY_FROM_SOURCE:
239+
session.install("-e", _get_repo_root())
240+
241+
if post_install:
242+
post_install(session)
243+
244+
if "pytest-parallel" in packages:
245+
concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"])
246+
elif "pytest-xdist" in packages:
247+
concurrent_args.extend(["-n", "auto"])
248+
249+
session.run(
250+
"pytest",
251+
*(PYTEST_COMMON_ARGS + session.posargs + concurrent_args),
252+
# Pytest will return 5 when no tests are collected. This can happen
253+
# on travis where slow and flaky tests are excluded.
254+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
255+
success_codes=[0, 5],
256+
env=get_pytest_env_vars(),
257+
)
258+
259+
260+
@nox.session(python=ALL_VERSIONS)
261+
def py(session: nox.sessions.Session) -> None:
262+
"""Runs py.test for a sample using the specified version of Python."""
263+
if session.python in TESTED_VERSIONS:
264+
_session_tests(session)
265+
else:
266+
session.skip(
267+
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
268+
)
269+
270+
271+
#
272+
# Readmegen
273+
#
274+
275+
276+
def _get_repo_root() -> str | None:
277+
"""Returns the root folder of the project."""
278+
# Get root of this repository.
279+
# Assume we don't have directories nested deeper than 10 items.
280+
p = Path(os.getcwd())
281+
for i in range(10):
282+
if p is None:
283+
break
284+
if Path(p / ".git").exists():
285+
return str(p)
286+
p = p.parent
287+
raise Exception("Unable to detect repository root.")
288+
289+
290+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
291+
292+
293+
@nox.session
294+
@nox.parametrize("path", GENERATED_READMES)
295+
def readmegen(session: nox.sessions.Session, path: str) -> None:
296+
"""(Re-)generates the readme for a sample."""
297+
session.install("jinja2", "pyyaml")
298+
dir_ = os.path.dirname(path)
299+
300+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
301+
session.install("-r", os.path.join(dir_, "requirements.txt"))
302+
303+
in_file = os.path.join(dir_, "README.rst.in")
304+
session.run(
305+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
306+
)

0 commit comments

Comments
 (0)