Skip to content

Commit 958d735

Browse files
authored
Chore: Add requirements.txt and noxfile.py for new samples (#45)
* add noxfile and requirements.txt * refactor requirements.txt * add newline * add newline * add newline
1 parent 2547a0a commit 958d735

File tree

3 files changed

+239
-0
lines changed

3 files changed

+239
-0
lines changed

document_ai/snippets/noxfile.py

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

document_ai/snippets/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
google-cloud-documentai==0.3.0
2+
google-cloud-storage==1.32.0

0 commit comments

Comments
 (0)