Skip to content

Commit 2e41659

Browse files
m-strzelczykgcf-owl-bot[bot]parthea
authored
docs(samples): Adding first sample code + tests (#22)
* docs(samples): Adding basic code samples + tests * Checking something * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * Fixing noxfile * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * Fixing noxfile with new test detection * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * Trying to understand what's wrong * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * use latest post processor image * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * Fixing the requirements * Making tests more resilent * Improving tests * Tests no longer use logging * Another fix... * Fixing lint problems * Fixing tests Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <[email protected]>
1 parent 4b06783 commit 2e41659

14 files changed

+705
-0
lines changed

compute/batch/__init__.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Copyright 2022 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.

compute/batch/noxfile.py

Lines changed: 313 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
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 print_function
16+
17+
import glob
18+
import os
19+
from pathlib import Path
20+
import sys
21+
from typing import Callable, Dict, List, Optional
22+
23+
import nox
24+
25+
26+
# WARNING - WARNING - WARNING - WARNING - WARNING
27+
# WARNING - WARNING - WARNING - WARNING - WARNING
28+
# DO NOT EDIT THIS FILE EVER!
29+
# WARNING - WARNING - WARNING - WARNING - WARNING
30+
# WARNING - WARNING - WARNING - WARNING - WARNING
31+
32+
BLACK_VERSION = "black==22.3.0"
33+
ISORT_VERSION = "isort==5.10.1"
34+
35+
# Copy `noxfile_config.py` to your directory and modify it instead.
36+
37+
# `TEST_CONFIG` dict is a configuration hook that allows users to
38+
# modify the test configurations. The values here should be in sync
39+
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
40+
# their directory and modify it.
41+
42+
TEST_CONFIG = {
43+
# You can opt out from the test for specific Python versions.
44+
"ignored_versions": [],
45+
# Old samples are opted out of enforcing Python type hints
46+
# All new samples should feature them
47+
"enforce_type_hints": False,
48+
# An envvar key for determining the project id to use. Change it
49+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
50+
# build specific Cloud project. You can also use your own string
51+
# to use your own Cloud project.
52+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
53+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
54+
# If you need to use a specific version of pip,
55+
# change pip_version_override to the string representation
56+
# of the version number, for example, "20.2.4"
57+
"pip_version_override": None,
58+
# A dictionary you want to inject into your test. Don't put any
59+
# secrets here. These values will override predefined values.
60+
"envs": {},
61+
}
62+
63+
64+
try:
65+
# Ensure we can import noxfile_config in the project's directory.
66+
sys.path.append(".")
67+
from noxfile_config import TEST_CONFIG_OVERRIDE
68+
except ImportError as e:
69+
print("No user noxfile_config found: detail: {}".format(e))
70+
TEST_CONFIG_OVERRIDE = {}
71+
72+
# Update the TEST_CONFIG with the user supplied values.
73+
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)
74+
75+
76+
def get_pytest_env_vars() -> Dict[str, str]:
77+
"""Returns a dict for pytest invocation."""
78+
ret = {}
79+
80+
# Override the GCLOUD_PROJECT and the alias.
81+
env_key = TEST_CONFIG["gcloud_project_env"]
82+
# This should error out if not set.
83+
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
84+
85+
# Apply user supplied envs.
86+
ret.update(TEST_CONFIG["envs"])
87+
return ret
88+
89+
90+
# DO NOT EDIT - automatically generated.
91+
# All versions used to test samples.
92+
ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"]
93+
94+
# Any default versions that should be ignored.
95+
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
96+
97+
TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])
98+
99+
INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in (
100+
"True",
101+
"true",
102+
)
103+
104+
# Error if a python version is missing
105+
nox.options.error_on_missing_interpreters = True
106+
107+
#
108+
# Style Checks
109+
#
110+
111+
112+
def _determine_local_import_names(start_dir: str) -> List[str]:
113+
"""Determines all import names that should be considered "local".
114+
115+
This is used when running the linter to insure that import order is
116+
properly checked.
117+
"""
118+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
119+
return [
120+
basename
121+
for basename, extension in file_ext_pairs
122+
if extension == ".py"
123+
or os.path.isdir(os.path.join(start_dir, basename))
124+
and basename not in ("__pycache__")
125+
]
126+
127+
128+
# Linting with flake8.
129+
#
130+
# We ignore the following rules:
131+
# E203: whitespace before ‘:’
132+
# E266: too many leading ‘#’ for block comment
133+
# E501: line too long
134+
# I202: Additional newline in a section of imports
135+
#
136+
# We also need to specify the rules which are ignored by default:
137+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
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=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+
local_names = _determine_local_import_names(".")
157+
args = FLAKE8_COMMON_ARGS + [
158+
"--application-import-names",
159+
",".join(local_names),
160+
".",
161+
]
162+
session.run("flake8", *args)
163+
164+
165+
#
166+
# Black
167+
#
168+
169+
170+
@nox.session
171+
def blacken(session: nox.sessions.Session) -> None:
172+
"""Run black. Format code to uniform standard."""
173+
session.install(BLACK_VERSION)
174+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
175+
176+
session.run("black", *python_files)
177+
178+
179+
#
180+
# format = isort + black
181+
#
182+
183+
184+
@nox.session
185+
def format(session: nox.sessions.Session) -> None:
186+
"""
187+
Run isort to sort imports. Then run black
188+
to format code to uniform standard.
189+
"""
190+
session.install(BLACK_VERSION, ISORT_VERSION)
191+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
192+
193+
# Use the --fss option to sort imports using strict alphabetical order.
194+
# See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections
195+
session.run("isort", "--fss", *python_files)
196+
session.run("black", *python_files)
197+
198+
199+
#
200+
# Sample Tests
201+
#
202+
203+
204+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
205+
206+
207+
def _session_tests(
208+
session: nox.sessions.Session, post_install: Callable = None
209+
) -> None:
210+
# check for presence of tests
211+
test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob(
212+
"**/test_*.py", recursive=True
213+
)
214+
test_list.extend(glob.glob("**/tests", recursive=True))
215+
216+
if len(test_list) == 0:
217+
print("No tests found, skipping directory.")
218+
return
219+
220+
if TEST_CONFIG["pip_version_override"]:
221+
pip_version = TEST_CONFIG["pip_version_override"]
222+
session.install(f"pip=={pip_version}")
223+
"""Runs py.test for a particular project."""
224+
concurrent_args = []
225+
if os.path.exists("requirements.txt"):
226+
if os.path.exists("constraints.txt"):
227+
session.install("-r", "requirements.txt", "-c", "constraints.txt")
228+
else:
229+
session.install("-r", "requirements.txt")
230+
with open("requirements.txt") as rfile:
231+
packages = rfile.read()
232+
233+
if os.path.exists("requirements-test.txt"):
234+
if os.path.exists("constraints-test.txt"):
235+
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
236+
else:
237+
session.install("-r", "requirements-test.txt")
238+
with open("requirements-test.txt") as rtfile:
239+
packages += rtfile.read()
240+
241+
if INSTALL_LIBRARY_FROM_SOURCE:
242+
session.install("-e", _get_repo_root())
243+
244+
if post_install:
245+
post_install(session)
246+
247+
if "pytest-parallel" in packages:
248+
concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"])
249+
elif "pytest-xdist" in packages:
250+
concurrent_args.extend(["-n", "auto"])
251+
252+
session.run(
253+
"pytest",
254+
*(PYTEST_COMMON_ARGS + session.posargs + concurrent_args),
255+
# Pytest will return 5 when no tests are collected. This can happen
256+
# on travis where slow and flaky tests are excluded.
257+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
258+
success_codes=[0, 5],
259+
env=get_pytest_env_vars(),
260+
)
261+
262+
263+
@nox.session(python=ALL_VERSIONS)
264+
def py(session: nox.sessions.Session) -> None:
265+
"""Runs py.test for a sample using the specified version of Python."""
266+
if session.python in TESTED_VERSIONS:
267+
_session_tests(session)
268+
else:
269+
session.skip(
270+
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
271+
)
272+
273+
274+
#
275+
# Readmegen
276+
#
277+
278+
279+
def _get_repo_root() -> Optional[str]:
280+
"""Returns the root folder of the project."""
281+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
282+
p = Path(os.getcwd())
283+
for i in range(10):
284+
if p is None:
285+
break
286+
if Path(p / ".git").exists():
287+
return str(p)
288+
# .git is not available in repos cloned via Cloud Build
289+
# setup.py is always in the library's root, so use that instead
290+
# https://github.com/googleapis/synthtool/issues/792
291+
if Path(p / "setup.py").exists():
292+
return str(p)
293+
p = p.parent
294+
raise Exception("Unable to detect repository root.")
295+
296+
297+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
298+
299+
300+
@nox.session
301+
@nox.parametrize("path", GENERATED_READMES)
302+
def readmegen(session: nox.sessions.Session, path: str) -> None:
303+
"""(Re-)generates the readme for a sample."""
304+
session.install("jinja2", "pyyaml")
305+
dir_ = os.path.dirname(path)
306+
307+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
308+
session.install("-r", os.path.join(dir_, "requirements.txt"))
309+
310+
in_file = os.path.join(dir_, "README.rst.in")
311+
session.run(
312+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
313+
)

compute/batch/noxfile_config.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Copyright 2022 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+
TEST_CONFIG_OVERRIDE = {
16+
"gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_PROJECT",
17+
}

compute/batch/requirements-test.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pytest==7.1.2
2+
pytest-parallel==0.1.1

compute/batch/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
isort==5.10.1
2+
black==22.6.0
3+
google-cloud-batch==0.1.2

compute/batch/snippets/__init__.py

Whitespace-only changes.

compute/batch/snippets/create/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)