Skip to content
This repository was archived by the owner on Mar 6, 2026. It is now read-only.

Commit f804d63

Browse files
authored
chore: standardize samples directory (#1727)
* Removed all dependencies from samples/snippets thats not google-cloud-bigquery * chore: standardizing extra-dependency samples * readded original dependencies to sample/snippets requirements
1 parent 84d64cd commit f804d63

17 files changed

+1049
-1
lines changed

noxfile.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,10 @@ def snippets(session):
263263
session.run(
264264
"py.test",
265265
"samples",
266+
"--ignore=samples/desktopapp",
266267
"--ignore=samples/magics",
267268
"--ignore=samples/geography",
269+
"--ignore=samples/notebooks",
268270
"--ignore=samples/snippets",
269271
*session.posargs,
270272
)

samples/desktopapp/__init__.py

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

samples/desktopapp/mypy.ini

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[mypy]
2+
; We require type annotations in all samples.
3+
strict = True
4+
exclude = noxfile\.py
5+
warn_unused_configs = True
6+
7+
[mypy-google.auth,google.oauth2,geojson,google_auth_oauthlib,IPython.*]
8+
ignore_missing_imports = True

samples/desktopapp/noxfile.py

Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
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, 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", "3.11"]
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+
# Linting with flake8.
113+
#
114+
# We ignore the following rules:
115+
# E203: whitespace before ‘:’
116+
# E266: too many leading ‘#’ for block comment
117+
# E501: line too long
118+
# I202: Additional newline in a section of imports
119+
#
120+
# We also need to specify the rules which are ignored by default:
121+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
122+
FLAKE8_COMMON_ARGS = [
123+
"--show-source",
124+
"--builtin=gettext",
125+
"--max-complexity=20",
126+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
127+
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
128+
"--max-line-length=88",
129+
]
130+
131+
132+
@nox.session
133+
def lint(session: nox.sessions.Session) -> None:
134+
if not TEST_CONFIG["enforce_type_hints"]:
135+
session.install("flake8")
136+
else:
137+
session.install("flake8", "flake8-annotations")
138+
139+
args = FLAKE8_COMMON_ARGS + [
140+
".",
141+
]
142+
session.run("flake8", *args)
143+
144+
145+
#
146+
# Black
147+
#
148+
149+
150+
@nox.session
151+
def blacken(session: nox.sessions.Session) -> None:
152+
"""Run black. Format code to uniform standard."""
153+
session.install(BLACK_VERSION)
154+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
155+
156+
session.run("black", *python_files)
157+
158+
159+
#
160+
# format = isort + black
161+
#
162+
163+
164+
@nox.session
165+
def format(session: nox.sessions.Session) -> None:
166+
"""
167+
Run isort to sort imports. Then run black
168+
to format code to uniform standard.
169+
"""
170+
session.install(BLACK_VERSION, ISORT_VERSION)
171+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
172+
173+
# Use the --fss option to sort imports using strict alphabetical order.
174+
# See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections
175+
session.run("isort", "--fss", *python_files)
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", recursive=True) + glob.glob(
192+
"**/test_*.py", recursive=True
193+
)
194+
test_list.extend(glob.glob("**/tests", recursive=True))
195+
196+
if len(test_list) == 0:
197+
print("No tests found, skipping directory.")
198+
return
199+
200+
if TEST_CONFIG["pip_version_override"]:
201+
pip_version = TEST_CONFIG["pip_version_override"]
202+
session.install(f"pip=={pip_version}")
203+
"""Runs py.test for a particular project."""
204+
concurrent_args = []
205+
if os.path.exists("requirements.txt"):
206+
if os.path.exists("constraints.txt"):
207+
session.install("-r", "requirements.txt", "-c", "constraints.txt")
208+
else:
209+
session.install("-r", "requirements.txt")
210+
with open("requirements.txt") as rfile:
211+
packages = rfile.read()
212+
213+
if os.path.exists("requirements-test.txt"):
214+
if os.path.exists("constraints-test.txt"):
215+
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
216+
else:
217+
session.install("-r", "requirements-test.txt")
218+
with open("requirements-test.txt") as rtfile:
219+
packages += rtfile.read()
220+
221+
if INSTALL_LIBRARY_FROM_SOURCE:
222+
session.install("-e", _get_repo_root())
223+
224+
if post_install:
225+
post_install(session)
226+
227+
if "pytest-parallel" in packages:
228+
concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"])
229+
elif "pytest-xdist" in packages:
230+
concurrent_args.extend(["-n", "auto"])
231+
232+
session.run(
233+
"pytest",
234+
*(PYTEST_COMMON_ARGS + session.posargs + concurrent_args),
235+
# Pytest will return 5 when no tests are collected. This can happen
236+
# on travis where slow and flaky tests are excluded.
237+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
238+
success_codes=[0, 5],
239+
env=get_pytest_env_vars(),
240+
)
241+
242+
243+
@nox.session(python=ALL_VERSIONS)
244+
def py(session: nox.sessions.Session) -> None:
245+
"""Runs py.test for a sample using the specified version of Python."""
246+
if session.python in TESTED_VERSIONS:
247+
_session_tests(session)
248+
else:
249+
session.skip(
250+
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
251+
)
252+
253+
254+
#
255+
# Readmegen
256+
#
257+
258+
259+
def _get_repo_root() -> Optional[str]:
260+
"""Returns the root folder of the project."""
261+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
262+
p = Path(os.getcwd())
263+
for i in range(10):
264+
if p is None:
265+
break
266+
if Path(p / ".git").exists():
267+
return str(p)
268+
# .git is not available in repos cloned via Cloud Build
269+
# setup.py is always in the library's root, so use that instead
270+
# https://github.com/googleapis/synthtool/issues/792
271+
if Path(p / "setup.py").exists():
272+
return str(p)
273+
p = p.parent
274+
raise Exception("Unable to detect repository root.")
275+
276+
277+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
278+
279+
280+
@nox.session
281+
@nox.parametrize("path", GENERATED_READMES)
282+
def readmegen(session: nox.sessions.Session, path: str) -> None:
283+
"""(Re-)generates the readme for a sample."""
284+
session.install("jinja2", "pyyaml")
285+
dir_ = os.path.dirname(path)
286+
287+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
288+
session.install("-r", os.path.join(dir_, "requirements.txt"))
289+
290+
in_file = os.path.join(dir_, "README.rst.in")
291+
session.run(
292+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
293+
)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Copyright 2020 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+
# Default TEST_CONFIG_OVERRIDE for python repos.
16+
17+
# You can copy this file into your directory, then it will be inported from
18+
# the noxfile.py.
19+
20+
# The source of truth:
21+
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py
22+
23+
TEST_CONFIG_OVERRIDE = {
24+
# You can opt out from the test for specific Python versions.
25+
"ignored_versions": [
26+
"2.7",
27+
# TODO: Enable 3.10 once there is a geopandas/fiona release.
28+
# https://github.com/Toblerity/Fiona/issues/1043
29+
"3.10",
30+
],
31+
# An envvar key for determining the project id to use. Change it
32+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
33+
# build specific Cloud project. You can also use your own string
34+
# to use your own Cloud project.
35+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
36+
# "gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_PROJECT",
37+
# A dictionary you want to inject into your test. Don't put any
38+
# secrets here. These values will override predefined values.
39+
"envs": {},
40+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
google-cloud-testutils==1.3.3
2+
pytest==7.4.0
3+
mock==5.1.0
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
db-dtypes==1.1.1
2+
google-cloud-bigquery==3.11.4
3+
google-cloud-bigquery-storage==2.22.0
4+
google-auth-oauthlib==1.0.0
5+
grpcio==1.57.0
6+
ipywidgets==8.1.0
7+
ipython===7.31.1; python_version == '3.7'
8+
ipython===8.0.1; python_version == '3.8'
9+
ipython==8.14.0; python_version >= '3.9'
10+
matplotlib===3.5.3; python_version == '3.7'
11+
matplotlib==3.7.2; python_version >= '3.8'
12+
pandas===1.3.5; python_version == '3.7'
13+
pandas==2.0.3; python_version >= '3.8'
14+
pyarrow==12.0.1; python_version == '3.7'
15+
pyarrow==14.0.1; python_version >= '3.8'
16+
pytz==2023.3
17+
typing-extensions==4.7.1

0 commit comments

Comments
 (0)