forked from SciTools/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_coding_standards.py
240 lines (204 loc) · 8.1 KB
/
test_coding_standards.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
# import iris.tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests # isort:skip
from datetime import datetime
from fnmatch import fnmatch
from glob import glob
import os
from pathlib import Path
import subprocess
from typing import List, Tuple
import iris
from iris.fileformats.netcdf import _thread_safe_nc
from iris.tests import system_test
LICENSE_TEMPLATE = """# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details."""
# Guess iris repo directory of Iris - realpath is used to mitigate against
# Python finding the iris package via a symlink.
IRIS_DIR = os.path.realpath(os.path.dirname(iris.__file__))
IRIS_INSTALL_DIR = os.path.dirname(os.path.dirname(IRIS_DIR))
DOCS_DIR = os.path.join(IRIS_INSTALL_DIR, "docs", "iris")
DOCS_DIR = iris.config.get_option("Resources", "doc_dir", default=DOCS_DIR)
exclusion = ["Makefile", "build"]
DOCS_DIRS = glob(os.path.join(DOCS_DIR, "*"))
DOCS_DIRS = [
DOC_DIR
for DOC_DIR in DOCS_DIRS
if os.path.basename(DOC_DIR) not in exclusion
]
# Get a dirpath to the git repository : allow setting with an environment
# variable, so Travis can test for headers in the repo, not the installation.
IRIS_REPO_DIRPATH = os.environ.get("IRIS_REPO_DIR", IRIS_INSTALL_DIR)
def test_netcdf4_import():
"""Use of netCDF4 must be via iris.fileformats.netcdf._thread_safe_nc ."""
# Please avoid including these phrases in any comments/strings throughout
# Iris (e.g. use "from the netCDF4 library" instead) - this allows the
# below search to remain quick and simple.
import_strings = ("import netCDF4", "from netCDF4")
files_including_import = []
for file_path in Path(IRIS_DIR).rglob("*.py"):
file_text = file_path.read_text()
if any([i in file_text for i in import_strings]):
files_including_import.append(file_path)
expected = [
Path(_thread_safe_nc.__file__),
Path(system_test.__file__),
Path(__file__),
]
assert set(files_including_import) == set(expected)
def test_python_versions():
"""
This test is designed to fail whenever Iris' supported Python versions are
updated, insisting that versions are updated EVERYWHERE in-sync.
"""
latest_supported = "3.10"
all_supported = ["3.8", "3.9", latest_supported]
root_dir = Path(__file__).parents[3]
workflows_dir = root_dir / ".github" / "workflows"
benchmarks_dir = root_dir / "benchmarks"
# Places that are checked:
setup_cfg_file = root_dir / "setup.cfg"
requirements_dir = root_dir / "requirements"
nox_file = root_dir / "noxfile.py"
ci_wheels_file = workflows_dir / "ci-wheels.yml"
ci_tests_file = workflows_dir / "ci-tests.yml"
asv_config_file = benchmarks_dir / "asv.conf.json"
benchmark_runner_file = benchmarks_dir / "bm_runner.py"
text_searches: List[Tuple[Path, str]] = [
(
setup_cfg_file,
"\n ".join(
[
"Programming Language :: Python :: " + ver
for ver in all_supported
]
),
),
(
nox_file,
"_PY_VERSIONS_ALL = ["
+ ", ".join([f'"{ver}"' for ver in all_supported]),
),
(
ci_wheels_file,
"python-version: ["
+ ", ".join([f'"{ver}"' for ver in all_supported]),
),
(
ci_tests_file,
(
f'python-version: ["{latest_supported}"]\n'
f'{" " * 8}session: ["doctest", "gallery", "linkcheck"]'
),
),
(asv_config_file, f"PY_VER={latest_supported}"),
(benchmark_runner_file, f'python_version = "{latest_supported}"'),
]
for ver in all_supported:
req_yaml = requirements_dir / f"py{ver.replace('.', '')}.yml"
text_searches.append((req_yaml, f"- python ={ver}"))
text_searches.append(
(
ci_tests_file,
f'python-version: "{ver}"\n{" " * 12}session: "tests"',
)
)
for path, search in text_searches:
assert search in path.read_text()
class TestLicenseHeaders(tests.IrisTest):
@staticmethod
def whatchanged_parse(whatchanged_output):
"""
Returns a generator of tuples of data parsed from
"git whatchanged --pretty='TIME:%at". The tuples are of the form
``(filename, last_commit_datetime)``
Sample input::
['TIME:1366884020', '',
':000000 100644 0000000... 5862ced... A\tlib/iris/cube.py']
"""
dt = None
for line in whatchanged_output:
if not line.strip():
continue
elif line.startswith("TIME:"):
dt = datetime.fromtimestamp(int(line[5:]))
else:
# Non blank, non date, line -> must be the lines
# containing the file info.
fname = " ".join(line.split("\t")[1:])
yield fname, dt
@staticmethod
def last_change_by_fname():
"""
Return a dictionary of all the files under git which maps to
the datetime of their last modification in the git history.
.. note::
This function raises a ValueError if the repo root does
not have a ".git" folder. If git is not installed on the system,
or cannot be found by subprocess, an IOError may also be raised.
"""
# Check the ".git" folder exists at the repo dir.
if not os.path.isdir(os.path.join(IRIS_REPO_DIRPATH, ".git")):
msg = "{} is not a git repository."
raise ValueError(msg.format(IRIS_REPO_DIRPATH))
# Call "git whatchanged" to get the details of all the files and when
# they were last changed.
output = subprocess.check_output(
["git", "whatchanged", "--pretty=TIME:%ct"], cwd=IRIS_REPO_DIRPATH
)
output = output.decode().split("\n")
res = {}
for fname, dt in TestLicenseHeaders.whatchanged_parse(output):
if fname not in res or dt > res[fname]:
res[fname] = dt
return res
def test_license_headers(self):
exclude_patterns = (
"setup.py",
"noxfile.py",
"build/*",
"dist/*",
"docs/gallery_code/*/*.py",
"docs/src/developers_guide/documenting/*.py",
"docs/src/userguide/plotting_examples/*.py",
"docs/src/userguide/regridding_plots/*.py",
"docs/src/_build/*",
"lib/iris/analysis/_scipy_interpolate.py",
)
try:
last_change_by_fname = self.last_change_by_fname()
except ValueError as err:
# Caught the case where this is not a git repo.
msg = (
"Iris installation did not look like a git repo?"
"\nERR = {}\n\n"
)
return self.skipTest(msg.format(str(err)))
failed = False
for fname, last_change in sorted(last_change_by_fname.items()):
full_fname = os.path.join(IRIS_REPO_DIRPATH, fname)
if (
full_fname.endswith(".py")
and os.path.isfile(full_fname)
and not any(fnmatch(fname, pat) for pat in exclude_patterns)
):
with open(full_fname) as fh:
content = fh.read()
if not content.startswith(LICENSE_TEMPLATE):
print(
"The file {} does not start with the required "
"license header.".format(fname)
)
failed = True
if failed:
raise ValueError("There were license header failures. See stdout.")
if __name__ == "__main__":
tests.main()