Debian Codegraph @

neutron_lib/hacking/checks.py

raw
1 # Copyright (c) 2014 OpenStack Foundation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # 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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import re
16
17 from debtcollector import removals
18 from hacking import core
19
20 from neutron_lib.hacking import translation_checks
21
22 # Guidelines for writing new hacking checks
23 #
24 # - Use only for Neutron specific tests. OpenStack general tests
25 # should be submitted to the common 'hacking' module.
26 # - Pick numbers in the range N5xx. Find the current test with
27 # the highest allocated number and then pick the next value.
28 # - Keep the test method code in the source file ordered based
29 # on the N5xx value.
30 # - List the new rule in the top level HACKING.rst file
31 # - Add test cases for each new rule to
32 # neutron_lib/tests/unit/hacking/test_checks.py
33
34 mutable_default_args = re.compile(r"^\s*def .+\((.+=\{\}|.+=\[\])")
35
36 namespace_imports_dot = re.compile(r"import[\s]+([\w]+)[.][^\s]+")
37 namespace_imports_from_dot = re.compile(r"from[\s]+([\w]+)[.]")
38 namespace_imports_from_root = re.compile(r"from[\s]+([\w]+)[\s]+import[\s]+")
39 contextlib_nested = re.compile(r"^\s*with (contextlib\.)?nested\(")
40
41 assert_equal_none_re = re.compile(
42 r"assertEqual\(.*?,\s+None\)(( |\t)*#.*)?$|assertEqual\(None,")
43 assert_is_none_re = re.compile(
44 r"assertIs(Not)?\(.*,\s+None\)(( |\t)*#.*)?$|assertIs(Not)?\(None,")
45
46
47 @core.off_by_default
48 @core.flake8ext
49 def use_jsonutils(logical_line, filename):
50 """N521 - jsonutils must be used instead of json.
51
52 :param logical_line: The logical line to check.
53 :param filename: The file name where the logical line exists.
54 :returns: None if the logical line passes the check, otherwise a tuple
55 is yielded that contains the offending index in logical line and a
56 message describe the check validation failure.
57 """
58 msg = "N521: jsonutils.%(fun)s must be used instead of json.%(fun)s"
59
60 # Some files in the tree are not meant to be run from inside Neutron
61 # itself, so we should not complain about them not using jsonutils
62 json_check_skipped_patterns = [
63 "neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/etc/xapi.d/"
64 "plugins/netwrap",
65 ]
66
67 for pattern in json_check_skipped_patterns:
68 if pattern in filename:
69 return
70
71 if "json." in logical_line:
72 json_funcs = ['dumps(', 'dump(', 'loads(', 'load(']
73 for f in json_funcs:
74 pos = logical_line.find(f'json.{f}')
75 if pos != -1:
76 yield (pos, msg % {'fun': f[:-1]})
77
78
79 def _check_imports(regex, submatch, logical_line):
80 m = re.match(regex, logical_line)
81 if m and m.group(1) == submatch:
82 return True
83
84
85 def _check_namespace_imports(failure_code, namespace, new_ns, logical_line,
86 message_override=None):
87 if message_override is not None:
88 msg_o = f"{failure_code}: {message_override}"
89 else:
90 msg_o = None
91
92 if _check_imports(namespace_imports_from_dot, namespace, logical_line):
93 msg = ("{}: '{}' must be used instead of '{}'.").format(
94 failure_code,
95 logical_line.replace(f'{namespace}.', new_ns),
96 logical_line)
97 return (0, msg_o or msg)
98 elif _check_imports(namespace_imports_from_root, namespace, logical_line):
99 msg = ("{}: '{}' must be used instead of '{}'.").format(
100 failure_code,
101 logical_line.replace(
102 f'from {namespace} import ', f'import {new_ns}'),
103 logical_line)
104 return (0, msg_o or msg)
105 elif _check_imports(namespace_imports_dot, namespace, logical_line):
106 msg = ("{}: '{}' must be used instead of '{}'.").format(
107 failure_code,
108 logical_line.replace('import', 'from').replace('.', ' import '),
109 logical_line)
110 return (0, msg_o or msg)
111
112
113 @core.off_by_default
114 @core.flake8ext
115 def check_no_contextlib_nested(logical_line, filename):
116 """N524 - Use of contextlib.nested is deprecated.
117
118 :param logical_line: The logical line to check.
119 :param filename: The file name where the logical line exists.
120 :returns: None if the logical line passes the check, otherwise a tuple
121 is yielded that contains the offending index in logical line and a
122 message describe the check validation failure.
123 """
124 msg = ("N524: contextlib.nested is deprecated. With Python 2.7 and later "
125 "the with-statement supports multiple nested objects. See https://"
126 "docs.python.org/2/library/contextlib.html#contextlib.nested for "
127 "more information.")
128
129 if contextlib_nested.match(logical_line):
130 yield (0, msg)
131
132
133 @core.off_by_default
134 @core.flake8ext
135 def no_mutable_default_args(logical_line):
136 """N529 - Method's default argument shouldn't be mutable.
137
138 :param logical_line: The logical line to check.
139 :returns: None if the logical line passes the check, otherwise a tuple
140 is yielded that contains the offending index in logical line and a
141 message describe the check validation failure.
142 """
143 msg = "N529: Method's default argument shouldn't be mutable!"
144 if mutable_default_args.match(logical_line):
145 yield (0, msg)
146
147
148 # Chances are that most projects will need to put an ignore on this rule
149 # until they can fully migrate to the lib.
150
151 @core.off_by_default
152 @core.flake8ext
153 def check_neutron_namespace_imports(logical_line):
154 """N530 - Direct neutron imports not allowed.
155
156 :param logical_line: The logical line to check.
157 :returns: None if the logical line passes the check, otherwise a tuple
158 is yielded that contains the offending index in logical line and a
159 message describe the check validation failure.
160 """
161 x = _check_namespace_imports(
162 'N530', 'neutron', 'neutron_lib.', logical_line,
163 message_override="direct neutron imports not allowed")
164 if x is not None:
165 yield x
166
167
168 @core.off_by_default
169 @core.flake8ext
170 def check_no_eventlet_imports(logical_line):
171 """N535 - Usage of Python eventlet module not allowed.
172
173 :param logical_line: The logical line to check.
174 :returns: None if the logical line passes the check, otherwise a tuple
175 is yielded that contains the offending index in logical line and a
176 message describe the check validation failure.
177 """
178 if re.match(r'(import|from)\s+[(]?eventlet', logical_line):
179 msg = 'N535: Usage of Python eventlet module not allowed'
180 yield logical_line.index('eventlet'), msg
181
182
183 @removals.remove(message='Use H203 check instead')
184 @core.off_by_default
185 @core.flake8ext
186 def assert_equal_none(logical_line):
187 """N536 - Use assertIsNone."""
188 if assert_equal_none_re.search(logical_line):
189 msg = ("N536: Use assertIsNone rather than assertEqual "
190 "to check for None values")
191 yield logical_line.index('assert'), msg
192
193 if assert_is_none_re.search(logical_line):
194 msg = ("N536: Use assertIsNone or assertIsNotNone rather than "
195 "assertIs or assertIsNone to check for None values.")
196 yield logical_line.index('assert'), msg
197
198
199 # TODO(amotoki): Drop this once all neutron related projects
200 # have switched to hacking 2.x
201 def factory(register):
202 """Hacking check factory for neutron-lib adopter compliant checks.
203
204 Hacking check factory for use with tox.ini. This factory registers all
205 neutron-lib adopter checks consumers should seek to comply with.
206
207 :param register: The function to register the check functions with.
208 :returns: None.
209 """
210 register(use_jsonutils)
211 register(check_no_contextlib_nested)
212 register(no_mutable_default_args)
213 register(check_neutron_namespace_imports)
214 register(translation_checks.no_translate_logs)
215 register(translation_checks.check_log_warn_deprecated)
216 register(translation_checks.check_raised_localized_exceptions)