"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "barbican/hacking/checks.py" between
barbican-11.0.0.tar.gz and barbican-12.0.0.tar.gz

About: OpenStack Barbican is the OpenStack Key Manager service. It provides secure storage, provisioning and management of secret data.
The "Wallaby" series (latest release).

checks.py  (barbican-11.0.0):checks.py  (barbican-12.0.0)
skipping to change at line 20 skipping to change at line 20
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import ast import ast
import re import re
import six import six
import pep8 from hacking import core
import pycodestyle
""" """
Guidelines for writing new hacking checks Guidelines for writing new hacking checks
- Use only for Barbican specific tests. OpenStack general tests - Use only for Barbican specific tests. OpenStack general tests
should be submitted to the common 'hacking' module. should be submitted to the common 'hacking' module.
- Pick numbers in the range B3xx. Find the current test with - Pick numbers in the range B3xx. Find the current test with
the highest allocated number and then pick the next value. the highest allocated number and then pick the next value.
- Keep the test method code in the source file ordered based - Keep the test method code in the source file ordered based
on the B3xx value. on the B3xx value.
skipping to change at line 62 skipping to change at line 63
object. object.
Subclasses should also provide a class variable named CHECK_DESC to Subclasses should also provide a class variable named CHECK_DESC to
be used for the human readable error message. be used for the human readable error message.
""" """
CHECK_DESC = 'No check message specified' CHECK_DESC = 'No check message specified'
def __init__(self, tree, filename): def __init__(self, tree, filename):
"""This object is created automatically by pep8. """This object is created automatically by pycodestyle.
:param tree: an AST tree :param tree: an AST tree
:param filename: name of the file being analyzed :param filename: name of the file being analyzed
(ignored by our checks) (ignored by our checks)
""" """
self._tree = tree self._tree = tree
self._errors = [] self._errors = []
def run(self): def run(self):
"""Called automatically by pep8.""" """Called automatically by pycodestyle."""
self.visit(self._tree) self.visit(self._tree)
return self._errors return self._errors
def add_error(self, node, message=None): def add_error(self, node, message=None):
"""Add an error caused by a node to the list of errors for pep8.""" """Add an error caused by a node to the list of errors for pep8."""
message = message or self.CHECK_DESC message = message or self.CHECK_DESC
error = (node.lineno, node.col_offset, message, self.__class__) error = (node.lineno, node.col_offset, message, self.__class__)
self._errors.append(error) self._errors.append(error)
def _check_call_names(self, call_node, names): def _check_call_names(self, call_node, names):
if isinstance(call_node, ast.Call): if isinstance(call_node, ast.Call):
if isinstance(call_node.func, ast.Name): if isinstance(call_node.func, ast.Name):
if call_node.func.id in names: if call_node.func.id in names:
return True return True
return False return False
class CheckLoggingFormatArgs(BaseASTChecker): class CheckLoggingFormatArgs(BaseASTChecker):
"""Check for improper use of logging format arguments. """Check for improper use of logging format arguments.
LOG.debug("Volume %s caught fire and is at %d degrees C and climbing.", LOG.debug("Volume %s caught fire and is at %d degrees C and climbing.",
('volume1', 500)) ('volume1', 500))
The format arguments should not be a tuple as it is easy to miss. The format arguments should not be a tuple as it is easy to miss.
""" """
name = "check_logging_format_args"
version = "1.0"
CHECK_DESC = 'B310 Log method arguments should not be a tuple.' CHECK_DESC = 'B310 Log method arguments should not be a tuple.'
LOG_METHODS = [ LOG_METHODS = [
'debug', 'info', 'debug', 'info',
'warn', 'warning', 'warn', 'warning',
'error', 'exception', 'error', 'exception',
'critical', 'fatal', 'critical', 'fatal',
'trace', 'log' 'trace', 'log'
] ]
skipping to change at line 153 skipping to change at line 157
if not len(node.args): if not len(node.args):
return super(CheckLoggingFormatArgs, self).generic_visit(node) return super(CheckLoggingFormatArgs, self).generic_visit(node)
# any argument should not be a tuple # any argument should not be a tuple
for arg in node.args: for arg in node.args:
if isinstance(arg, ast.Tuple): if isinstance(arg, ast.Tuple):
self.add_error(arg) self.add_error(arg)
return super(CheckLoggingFormatArgs, self).generic_visit(node) return super(CheckLoggingFormatArgs, self).generic_visit(node)
class CheckForStrUnicodeExc(BaseASTChecker): @core.flake8ext
"""Checks for the use of str() or unicode() on an exception. def check_oslo_namespace_imports(physical_line, logical_line, filename):
This currently only handles the case where str() or unicode()
is used in the scope of an exception handler. If the exception
is passed into a function, returned from an assertRaises, or
used on an exception created in the same scope, this does not
catch it.
"""
CHECK_DESC = ('B314 str() and unicode() cannot be used on an '
'exception. Remove or use six.text_type()')
def __init__(self, tree, filename):
super(CheckForStrUnicodeExc, self).__init__(tree, filename)
self.name = []
self.already_checked = []
# Python 2
def visit_TryExcept(self, node):
for handler in node.handlers:
if handler.name:
self.name.append(handler.name.id)
super(CheckForStrUnicodeExc, self).generic_visit(node)
self.name = self.name[:-1]
else:
super(CheckForStrUnicodeExc, self).generic_visit(node)
# Python 3
def visit_ExceptHandler(self, node):
if node.name:
self.name.append(node.name)
super(CheckForStrUnicodeExc, self).generic_visit(node)
self.name = self.name[:-1]
else:
super(CheckForStrUnicodeExc, self).generic_visit(node)
def visit_Call(self, node):
if self._check_call_names(node, ['str', 'unicode']):
if node not in self.already_checked:
self.already_checked.append(node)
if isinstance(node.args[0], ast.Name):
if node.args[0].id in self.name:
self.add_error(node.args[0])
super(CheckForStrUnicodeExc, self).generic_visit(node)
def check_oslo_namespace_imports(logical_line, physical_line, filename):
"""'oslo_' should be used instead of 'oslo.' """'oslo_' should be used instead of 'oslo.'
B317 B317
""" """
if pep8.noqa(physical_line): if pycodestyle.noqa(physical_line):
return return
if re.match(oslo_namespace_imports, logical_line): if re.match(oslo_namespace_imports, logical_line):
msg = ("B317: '%s' must be used instead of '%s'.") % ( msg = ("B317: '%s' must be used instead of '%s'.") % (
logical_line.replace('oslo.', 'oslo_'), logical_line.replace('oslo.', 'oslo_'),
logical_line) logical_line)
yield(0, msg) yield(0, msg)
@core.flake8ext
def dict_constructor_with_list_copy(logical_line): def dict_constructor_with_list_copy(logical_line):
"""Use a dict comprehension instead of a dict constructor """Use a dict comprehension instead of a dict constructor
B318 B318
""" """
msg = ("B318: Must use a dict comprehension instead of a dict constructor" msg = ("B318: Must use a dict comprehension instead of a dict constructor"
" with a sequence of key-value pairs." " with a sequence of key-value pairs."
) )
if dict_constructor_with_list_copy_re.match(logical_line): if dict_constructor_with_list_copy_re.match(logical_line):
yield (0, msg) yield (0, msg)
@core.flake8ext
def no_xrange(logical_line): def no_xrange(logical_line):
"""Do not use 'xrange' """Do not use 'xrange'
B319 B319
""" """
if assert_no_xrange_re.match(logical_line): if assert_no_xrange_re.match(logical_line):
yield(0, "B319: Do not use xrange().") yield(0, "B319: Do not use xrange().")
@core.flake8ext
def validate_assertTrue(logical_line): def validate_assertTrue(logical_line):
"""Use 'assertTrue' instead of 'assertEqual' """Use 'assertTrue' instead of 'assertEqual'
B312 B312
""" """
if re.match(assert_True, logical_line): if re.match(assert_True, logical_line):
msg = ("B312: Unit tests should use assertTrue(value) instead" msg = ("B312: Unit tests should use assertTrue(value) instead"
" of using assertEqual(True, value).") " of using assertEqual(True, value).")
yield(0, msg) yield(0, msg)
@core.flake8ext
def validate_assertIsNone(logical_line): def validate_assertIsNone(logical_line):
"""Use 'assertIsNone' instead of 'assertEqual' """Use 'assertIsNone' instead of 'assertEqual'
B311 B311
""" """
if re.match(assert_None, logical_line): if re.match(assert_None, logical_line):
msg = ("B311: Unit tests should use assertIsNone(value) instead" msg = ("B311: Unit tests should use assertIsNone(value) instead"
" of using assertEqual(None, value).") " of using assertEqual(None, value).")
yield(0, msg) yield(0, msg)
@core.flake8ext
def no_log_warn_check(logical_line): def no_log_warn_check(logical_line):
"""Disallow 'LOG.warn' """Disallow 'LOG.warn'
B320 B320
""" """
msg = ("B320: LOG.warn is deprecated, please use LOG.warning!") msg = ("B320: LOG.warn is deprecated, please use LOG.warning!")
if re.match(no_log_warn, logical_line): if re.match(no_log_warn, logical_line):
yield(0, msg) yield(0, msg)
@core.flake8ext
def validate_assertIsNotNone(logical_line): def validate_assertIsNotNone(logical_line):
"""Use 'assertIsNotNone' """Use 'assertIsNotNone'
B321 B321
""" """
if re.match(assert_Not_Equal, logical_line) or \ if re.match(assert_Not_Equal, logical_line) or \
re.match(assert_Is_Not, logical_line): re.match(assert_Is_Not, logical_line):
msg = ("B321: Unit tests should use assertIsNotNone(value) instead" msg = ("B321: Unit tests should use assertIsNotNone(value) instead"
" of using assertNotEqual(None, value) or" " of using assertNotEqual(None, value) or"
" assertIsNot(None, value).") " assertIsNot(None, value).")
yield(0, msg) yield(0, msg)
def factory(register):
register(CheckForStrUnicodeExc)
register(CheckLoggingFormatArgs)
register(check_oslo_namespace_imports)
register(dict_constructor_with_list_copy)
register(no_xrange)
register(validate_assertTrue)
register(validate_assertIsNone)
register(no_log_warn_check)
register(validate_assertIsNotNone)
 End of changes. 14 change blocks. 
51 lines changed or deleted 16 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)