Skip to content

Commit ca29697

Browse files
m-strzelczykbusunkim96dinagraves
authored
feat: Adding code samples and tests for them (#55)
* feat: Adding code samples and tests for them * chore: Remove unused import. * Update .github/CODEOWNERS Co-authored-by: Bu Sun Kim <[email protected]> * chore: Updating samples to meet reviewers suggestions. * chore: Fixing regions. * chore: Adjusting the testing scripts in .kokoro/samples. * Revert "chore: Adjusting the testing scripts in .kokoro/samples." This reverts commit 6d0b4276 * chore: Moving samples tests to dedicated noxfile.py. * chore: Adding 3.6 and 3.7 Python versions to samples noxfile.py * chore: Updating the Samples section to reflect new testing setup. * chore: Updating the Samples README. * chore: add standardized samples noxfile * chore: uncomment sections in synth.py * chore: Changing the waiting for operation part. * chore: Minor changes based on review. * README suggests using `gcloud auth application-default login` which is safer than Service Account key. * The name of created instance now starts with "quickstart-". * Changed one variable name. Co-authored-by: Bu Sun Kim <[email protected]> Co-authored-by: Bu Sun Kim <[email protected]> Co-authored-by: Dina Graves Portman <[email protected]>
0 parents  commit ca29697

File tree

6 files changed

+603
-0
lines changed

6 files changed

+603
-0
lines changed

compute/compute/snippets/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# google-cloud-compute library samples
2+
3+
These samples demonstrate usage of the google-cloud-compute library to interact
4+
with the Google Compute Engine API.
5+
6+
## Running the quickstart script
7+
8+
### Before you begin
9+
10+
1. If you haven't already, set up a Python Development Environment by following the [python setup guide](https://cloud.google.com/python/setup) and
11+
[create a project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project).
12+
13+
1. Use `gcloud auth application-default login` to allow the script to authenticate using
14+
your credentials to the Google Cloud APIs.
15+
16+
### Install requirements
17+
18+
Create a new virtual environment and install the required libraries.
19+
```bash
20+
virtualenv --python python3 name-of-your-virtualenv
21+
source name-of-your-virtualenv/bin/activate
22+
pip install -r requirements.txt
23+
```
24+
25+
### Run the demo
26+
27+
Run the quickstart script, it will create and destroy a `n1-standard-1`
28+
type machine in the `europe-central2-b` zone.
29+
```bash
30+
python quickstart.py
31+
```

compute/compute/snippets/noxfile.py

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
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+
# 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+
84+
# Apply user supplied envs.
85+
ret.update(TEST_CONFIG['envs'])
86+
return ret
87+
88+
89+
# DO NOT EDIT - automatically generated.
90+
# All versions used to tested samples.
91+
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"]
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+
# Style Checks
101+
#
102+
103+
104+
def _determine_local_import_names(start_dir: str) -> List[str]:
105+
"""Determines all import names that should be considered "local".
106+
107+
This is used when running the linter to insure that import order is
108+
properly checked.
109+
"""
110+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
111+
return [
112+
basename
113+
for basename, extension in file_ext_pairs
114+
if extension == ".py"
115+
or os.path.isdir(os.path.join(start_dir, basename))
116+
and basename not in ("__pycache__")
117+
]
118+
119+
120+
# Linting with flake8.
121+
#
122+
# We ignore the following rules:
123+
# E203: whitespace before ‘:’
124+
# E266: too many leading ‘#’ for block comment
125+
# E501: line too long
126+
# I202: Additional newline in a section of imports
127+
#
128+
# We also need to specify the rules which are ignored by default:
129+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
130+
FLAKE8_COMMON_ARGS = [
131+
"--show-source",
132+
"--builtin=gettext",
133+
"--max-complexity=20",
134+
"--import-order-style=google",
135+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
136+
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
137+
"--max-line-length=88",
138+
]
139+
140+
141+
@nox.session
142+
def lint(session: nox.sessions.Session) -> None:
143+
if not TEST_CONFIG['enforce_type_hints']:
144+
session.install("flake8", "flake8-import-order")
145+
else:
146+
session.install("flake8", "flake8-import-order", "flake8-annotations")
147+
148+
local_names = _determine_local_import_names(".")
149+
args = FLAKE8_COMMON_ARGS + [
150+
"--application-import-names",
151+
",".join(local_names),
152+
"."
153+
]
154+
session.run("flake8", *args)
155+
#
156+
# Black
157+
#
158+
159+
160+
@nox.session
161+
def blacken(session: nox.sessions.Session) -> None:
162+
session.install("black")
163+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
164+
165+
session.run("black", *python_files)
166+
167+
#
168+
# Sample Tests
169+
#
170+
171+
172+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
173+
174+
175+
def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None:
176+
if TEST_CONFIG["pip_version_override"]:
177+
pip_version = TEST_CONFIG["pip_version_override"]
178+
session.install(f"pip=={pip_version}")
179+
"""Runs py.test for a particular project."""
180+
if os.path.exists("requirements.txt"):
181+
if os.path.exists("constraints.txt"):
182+
session.install("-r", "requirements.txt", "-c", "constraints.txt")
183+
else:
184+
session.install("-r", "requirements.txt")
185+
186+
if os.path.exists("requirements-test.txt"):
187+
if os.path.exists("constraints-test.txt"):
188+
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
189+
else:
190+
session.install("-r", "requirements-test.txt")
191+
192+
if INSTALL_LIBRARY_FROM_SOURCE:
193+
session.install("-e", _get_repo_root())
194+
195+
if post_install:
196+
post_install(session)
197+
198+
session.run(
199+
"pytest",
200+
*(PYTEST_COMMON_ARGS + session.posargs),
201+
# Pytest will return 5 when no tests are collected. This can happen
202+
# on travis where slow and flaky tests are excluded.
203+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
204+
success_codes=[0, 5],
205+
env=get_pytest_env_vars()
206+
)
207+
208+
209+
@nox.session(python=ALL_VERSIONS)
210+
def py(session: nox.sessions.Session) -> None:
211+
"""Runs py.test for a sample using the specified version of Python."""
212+
if session.python in TESTED_VERSIONS:
213+
_session_tests(session)
214+
else:
215+
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
216+
session.python
217+
))
218+
219+
220+
#
221+
# Readmegen
222+
#
223+
224+
225+
def _get_repo_root() -> Optional[str]:
226+
""" Returns the root folder of the project. """
227+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
228+
p = Path(os.getcwd())
229+
for i in range(10):
230+
if p is None:
231+
break
232+
if Path(p / ".git").exists():
233+
return str(p)
234+
# .git is not available in repos cloned via Cloud Build
235+
# setup.py is always in the library's root, so use that instead
236+
# https://github.com/googleapis/synthtool/issues/792
237+
if Path(p / "setup.py").exists():
238+
return str(p)
239+
p = p.parent
240+
raise Exception("Unable to detect repository root.")
241+
242+
243+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
244+
245+
246+
@nox.session
247+
@nox.parametrize("path", GENERATED_READMES)
248+
def readmegen(session: nox.sessions.Session, path: str) -> None:
249+
"""(Re-)generates the readme for a sample."""
250+
session.install("jinja2", "pyyaml")
251+
dir_ = os.path.dirname(path)
252+
253+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
254+
session.install("-r", os.path.join(dir_, "requirements.txt"))
255+
256+
in_file = os.path.join(dir_, "README.rst.in")
257+
session.run(
258+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
259+
)

0 commit comments

Comments
 (0)