Skip to content

Commit 23a8e97

Browse files
busunkim96dandhlee
authored andcommitted
chore(samples): move samples and use standard templates for testing (#41)
1 parent 5798d47 commit 23a8e97

17 files changed

+2000
-0
lines changed

securitycenter/AUTHORING_GUIDE.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md

securitycenter/CONTRIBUTING.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md

securitycenter/snippets/noxfile.py

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

0 commit comments

Comments
 (0)