Skip to content
This repository was archived by the owner on Dec 31, 2023. It is now read-only.

Commit 9f35e43

Browse files
authored
docs: Adding samples (#69)
1 parent 6f4dfbe commit 9f35e43

File tree

5 files changed

+325
-0
lines changed

5 files changed

+325
-0
lines changed

samples/snippets/noxfile.py

+247
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
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 os
18+
from pathlib import Path
19+
import sys
20+
from typing import Callable, Dict, List, Optional
21+
22+
import nox
23+
24+
25+
# WARNING - WARNING - WARNING - WARNING - WARNING
26+
# WARNING - WARNING - WARNING - WARNING - WARNING
27+
# DO NOT EDIT THIS FILE EVER!
28+
# WARNING - WARNING - WARNING - WARNING - WARNING
29+
# WARNING - WARNING - WARNING - WARNING - WARNING
30+
31+
# Copy `noxfile_config.py` to your directory and modify it instead.
32+
33+
34+
# `TEST_CONFIG` dict is a configuration hook that allows users to
35+
# modify the test configurations. The values here should be in sync
36+
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
37+
# their directory and modify it.
38+
39+
TEST_CONFIG = {
40+
# You can opt out from the test for specific Python versions.
41+
'ignored_versions': ["2.7"],
42+
43+
# Old samples are opted out of enforcing Python type hints
44+
# All new samples should feature them
45+
'enforce_type_hints': False,
46+
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+
54+
# A dictionary you want to inject into your test. Don't put any
55+
# secrets here. These values will override predefined values.
56+
'envs': {},
57+
}
58+
59+
60+
try:
61+
# Ensure we can import noxfile_config in the project's directory.
62+
sys.path.append('.')
63+
from noxfile_config import TEST_CONFIG_OVERRIDE
64+
except ImportError as e:
65+
print("No user noxfile_config found: detail: {}".format(e))
66+
TEST_CONFIG_OVERRIDE = {}
67+
68+
# Update the TEST_CONFIG with the user supplied values.
69+
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)
70+
71+
72+
def get_pytest_env_vars() -> Dict[str, str]:
73+
"""Returns a dict for pytest invocation."""
74+
ret = {}
75+
76+
# Override the GCLOUD_PROJECT and the alias.
77+
env_key = TEST_CONFIG['gcloud_project_env']
78+
# This should error out if not set.
79+
ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key]
80+
81+
# Apply user supplied envs.
82+
ret.update(TEST_CONFIG['envs'])
83+
return ret
84+
85+
86+
# DO NOT EDIT - automatically generated.
87+
# All versions used to tested samples.
88+
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"]
89+
90+
# Any default versions that should be ignored.
91+
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']
92+
93+
TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])
94+
95+
INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False))
96+
#
97+
# Style Checks
98+
#
99+
100+
101+
def _determine_local_import_names(start_dir: str) -> List[str]:
102+
"""Determines all import names that should be considered "local".
103+
104+
This is used when running the linter to insure that import order is
105+
properly checked.
106+
"""
107+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
108+
return [
109+
basename
110+
for basename, extension in file_ext_pairs
111+
if extension == ".py"
112+
or os.path.isdir(os.path.join(start_dir, basename))
113+
and basename not in ("__pycache__")
114+
]
115+
116+
117+
# Linting with flake8.
118+
#
119+
# We ignore the following rules:
120+
# E203: whitespace before ‘:’
121+
# E266: too many leading ‘#’ for block comment
122+
# E501: line too long
123+
# I202: Additional newline in a section of imports
124+
#
125+
# We also need to specify the rules which are ignored by default:
126+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
127+
FLAKE8_COMMON_ARGS = [
128+
"--show-source",
129+
"--builtin=gettext",
130+
"--max-complexity=20",
131+
"--import-order-style=google",
132+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
133+
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
134+
"--max-line-length=88",
135+
]
136+
137+
138+
@nox.session
139+
def lint(session: nox.sessions.Session) -> None:
140+
if not TEST_CONFIG['enforce_type_hints']:
141+
session.install("flake8", "flake8-import-order")
142+
else:
143+
session.install("flake8", "flake8-import-order", "flake8-annotations")
144+
145+
local_names = _determine_local_import_names(".")
146+
args = FLAKE8_COMMON_ARGS + [
147+
"--application-import-names",
148+
",".join(local_names),
149+
"."
150+
]
151+
session.run("flake8", *args)
152+
#
153+
# Black
154+
#
155+
156+
157+
@nox.session
158+
def blacken(session: nox.sessions.Session) -> None:
159+
session.install("black")
160+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
161+
162+
session.run("black", *python_files)
163+
164+
#
165+
# Sample Tests
166+
#
167+
168+
169+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
170+
171+
172+
def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None:
173+
"""Runs py.test for a particular project."""
174+
if os.path.exists("requirements.txt"):
175+
session.install("-r", "requirements.txt")
176+
177+
if os.path.exists("requirements-test.txt"):
178+
session.install("-r", "requirements-test.txt")
179+
180+
if INSTALL_LIBRARY_FROM_SOURCE:
181+
session.install("-e", _get_repo_root())
182+
183+
if post_install:
184+
post_install(session)
185+
186+
session.run(
187+
"pytest",
188+
*(PYTEST_COMMON_ARGS + session.posargs),
189+
# Pytest will return 5 when no tests are collected. This can happen
190+
# on travis where slow and flaky tests are excluded.
191+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
192+
success_codes=[0, 5],
193+
env=get_pytest_env_vars()
194+
)
195+
196+
197+
@nox.session(python=ALL_VERSIONS)
198+
def py(session: nox.sessions.Session) -> None:
199+
"""Runs py.test for a sample using the specified version of Python."""
200+
if session.python in TESTED_VERSIONS:
201+
_session_tests(session)
202+
else:
203+
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
204+
session.python
205+
))
206+
207+
208+
#
209+
# Readmegen
210+
#
211+
212+
213+
def _get_repo_root() -> Optional[str]:
214+
""" Returns the root folder of the project. """
215+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
216+
p = Path(os.getcwd())
217+
for i in range(10):
218+
if p is None:
219+
break
220+
if Path(p / ".git").exists():
221+
return str(p)
222+
# .git is not available in repos cloned via Cloud Build
223+
# setup.py is always in the library's root, so use that instead
224+
# https://github.com/googleapis/synthtool/issues/792
225+
if Path(p / "setup.py").exists():
226+
return str(p)
227+
p = p.parent
228+
raise Exception("Unable to detect repository root.")
229+
230+
231+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
232+
233+
234+
@nox.session
235+
@nox.parametrize("path", GENERATED_READMES)
236+
def readmegen(session: nox.sessions.Session, path: str) -> None:
237+
"""(Re-)generates the readme for a sample."""
238+
session.install("jinja2", "pyyaml")
239+
dir_ = os.path.dirname(path)
240+
241+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
242+
session.install("-r", os.path.join(dir_, "requirements.txt"))
243+
244+
in_file = os.path.join(dir_, "README.rst.in")
245+
session.run(
246+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
247+
)

samples/snippets/quickstart.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2021 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+
16+
# [START cloudbuild_quickstart]
17+
import google.auth
18+
from google.cloud.devtools import cloudbuild_v1
19+
20+
21+
def quickstart():
22+
"""Create and execute a simple Google Cloud Build configuration,
23+
print the in-progress status and print the completed status."""
24+
25+
# Authorize the client with Google defaults
26+
credentials, project_id = google.auth.default()
27+
client = cloudbuild_v1.services.cloud_build.CloudBuildClient()
28+
29+
build = cloudbuild_v1.Build()
30+
31+
# The following build steps will output "hello world"
32+
# For more information on build configuration, see
33+
# https://cloud.google.com/build/docs/configuring-builds/create-basic-configuration
34+
build.steps = [{"name": "ubuntu",
35+
"entrypoint": "bash",
36+
"args": ["-c", "echo hello world"]}]
37+
38+
operation = client.create_build(project_id=project_id, build=build)
39+
# Print the in-progress operation
40+
print("IN PROGRESS:")
41+
print(operation.metadata)
42+
43+
result = operation.result()
44+
# Print the completed status
45+
print("RESULT:", result.status)
46+
# [END cloudbuild_quickstart]
47+
48+
49+
if __name__ == "__main__":
50+
quickstart()

samples/snippets/quickstart_test.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Copyright 2021 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+
# https://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+
16+
import quickstart
17+
18+
19+
def test_quickstart(capsys):
20+
quickstart.quickstart()
21+
out, _ = capsys.readouterr()
22+
# Prints in-progress message
23+
assert "hello world" in out
24+
# Prints final status
25+
assert "Status.SUCCESS" in out
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytest==6.0.1

samples/snippets/requirements.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
google-cloud-build==3.0.2
2+
google-auth==1.28.0

0 commit comments

Comments
 (0)