"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "barbican/tests/test_hacking.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).

test_hacking.py  (barbican-11.0.0):test_hacking.py  (barbican-12.0.0)
skipping to change at line 15 skipping to change at line 15
# a copy of the License at # a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# 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 sys
import textwrap import textwrap
from unittest import mock from unittest import mock
import ddt import pycodestyle
import pep8
from barbican.hacking import checks from barbican.hacking import checks
from barbican.tests import utils import oslotest
@ddt.ddt class HackingTestCase(oslotest.base.BaseTestCase):
class HackingTestCase(utils.BaseTestCase):
"""Hacking test cases """Hacking test cases
This class tests the hacking checks in barbican.hacking.checks by passing This class tests the hacking checks in barbican.hacking.checks by passing
strings to the check methods like the pep8/flake8 parser would. The parser strings to the check methods like the pycodestyle/flake8 parser would. The
parser
loops over each line in the file and then passes the parameters to the loops over each line in the file and then passes the parameters to the
check method. The parameter names in the check method dictate what type of check method. The parameter names in the check method dictate what type of
object is passed to the check method. The parameter types are:: object is passed to the check method. The parameter types are::
logical_line: A processed line with the following modifications: logical_line: A processed line with the following modifications:
- Multi-line statements converted to a single line. - Multi-line statements converted to a single line.
- Stripped left and right. - Stripped left and right.
- Contents of strings replaced with "xxx" of same length. - Contents of strings replaced with "xxx" of same length.
- Comments removed. - Comments removed.
physical_line: Raw line of text from the input file. physical_line: Raw line of text from the input file.
lines: a list of the raw lines from the input file lines: a list of the raw lines from the input file
tokens: the tokens that contribute to this logical line tokens: the tokens that contribute to this logical line
line_number: line number in the input file line_number: line number in the input file
total_lines: number of lines in the input file total_lines: number of lines in the input file
blank_lines: blank lines before this one blank_lines: blank lines before this one
indent_char: indentation character in this file (" " or "\t") indent_char: indentation character in this file (" " or "\t")
indent_level: indentation (with tabs expanded to multiples of 8) indent_level: indentation (with tabs expanded to multiples of 8)
previous_indent_level: indentation on previous line previous_indent_level: indentation on previous line
previous_logical: previous logical line previous_logical: previous logical line
filename: Path of the file being run through pep8 filename: Path of the file being run through pycodestyle
When running a test on a check method the return will be False/None if When running a test on a check method the return will be False/None if
there is no violation in the sample input. If there is an error a tuple is there is no violation in the sample input. If there is an error a tuple is
returned with a position in the line, and a message. So to check the result returned with a position in the line, and a message. So to check the result
just assertTrue if the check is expected to fail and assertFalse if it just assertTrue if the check is expected to fail and assertFalse if it
should pass. should pass.
""" """
# We are patching pep8 so that only the check under test is actually # We are patching pycodestyle so that only the check under test is actually
# installed. # installed.
@mock.patch('pep8._checks', @mock.patch('pycodestyle._checks',
{'physical_line': {}, 'logical_line': {}, 'tree': {}}) {'physical_line': {}, 'logical_line': {}, 'tree': {}})
def _run_check(self, code, checker, filename=None): def _run_check(self, code, checker, filename=None):
pep8.register_check(checker) pycodestyle.register_check(checker)
lines = textwrap.dedent(code).strip().splitlines(True) lines = textwrap.dedent(code).strip().splitlines(True)
checker = pep8.Checker(filename=filename, lines=lines) checker = pycodestyle.Checker(filename=filename, lines=lines)
checker.check_all() checker.check_all()
checker.report._deferred_print.sort() checker.report._deferred_print.sort()
return checker.report._deferred_print return checker.report._deferred_print
def _assert_has_errors(self, code, checker, expected_errors=None, def _assert_has_errors(self, code, checker, expected_errors=None,
filename=None): filename=None):
actual_errors = [e[:3] for e in actual_errors = [e[:3] for e in
self._run_check(code, checker, filename)] self._run_check(code, checker, filename)]
self.assertEqual(expected_errors or [], actual_errors) self.assertEqual(expected_errors or [], actual_errors)
skipping to change at line 94 skipping to change at line 92
code = """ code = """
import logging import logging
LOG = logging.getLogger() LOG = logging.getLogger()
LOG.info("Message without a second argument.") LOG.info("Message without a second argument.")
LOG.critical("Message with %s arguments.", 'two') LOG.critical("Message with %s arguments.", 'two')
LOG.debug("Volume %s caught fire and is at %d degrees C and" LOG.debug("Volume %s caught fire and is at %d degrees C and"
" climbing.", 'volume1', 500) " climbing.", 'volume1', 500)
""" """
self._assert_has_no_errors(code, checker) self._assert_has_no_errors(code, checker)
@ddt.data(*checks.CheckLoggingFormatArgs.LOG_METHODS)
def test_logging_with_tuple_argument(self, log_method):
checker = checks.CheckLoggingFormatArgs
code = """
import logging
LOG = logging.getLogger()
LOG.{0}("Volume %s caught fire and is at %d degrees C and "
"climbing.", ('volume1', 500))
"""
if (sys.version_info >= (3, 8)):
exc_errors = [(4, 20, 'B310')]
else:
exc_errors = [(4, 21, 'B310')]
self._assert_has_errors(code.format(log_method), checker,
expected_errors=exc_errors)
def test_str_on_exception(self):
checker = checks.CheckForStrUnicodeExc
code = """
def f(a, b):
try:
p = str(a) + str(b)
except ValueError as e:
p = str(e)
return p
"""
errors = [(5, 16, 'B314')]
self._assert_has_errors(code, checker, expected_errors=errors)
def test_no_str_unicode_on_exception(self):
checker = checks.CheckForStrUnicodeExc
code = """
def f(a, b):
try:
p = unicode(a) + str(b)
except ValueError as e:
p = e
return p
"""
self._assert_has_no_errors(code, checker)
def test_unicode_on_exception(self):
checker = checks.CheckForStrUnicodeExc
code = """
def f(a, b):
try:
p = str(a) + str(b)
except ValueError as e:
p = unicode(e)
return p
"""
errors = [(5, 20, 'B314')]
self._assert_has_errors(code, checker, expected_errors=errors)
def test_str_on_multiple_exceptions(self):
checker = checks.CheckForStrUnicodeExc
code = """
def f(a, b):
try:
p = str(a) + str(b)
except ValueError as e:
try:
p = unicode(a) + unicode(b)
except ValueError as ve:
p = str(e) + str(ve)
p = e
return p
"""
errors = [(8, 20, 'B314'), (8, 29, 'B314')]
self._assert_has_errors(code, checker, expected_errors=errors)
def test_str_unicode_on_multiple_exceptions(self):
checker = checks.CheckForStrUnicodeExc
code = """
def f(a, b):
try:
p = str(a) + str(b)
except ValueError as e:
try:
p = unicode(a) + unicode(b)
except ValueError as ve:
p = str(e) + unicode(ve)
p = str(e)
return p
"""
errors = [(8, 20, 'B314'), (8, 33, 'B314'), (9, 16, 'B314')]
self._assert_has_errors(code, checker, expected_errors=errors)
def test_dict_constructor_with_list_copy(self): def test_dict_constructor_with_list_copy(self):
self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy( self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
" dict([(i, connect_info[i])")))) " dict([(i, connect_info[i])"))))
self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy( self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
" attrs = dict([(k, _from_json(v))")))) " attrs = dict([(k, _from_json(v))"))))
self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy( self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
" type_names = dict((value, key) for key, value in")))) " type_names = dict((value, key) for key, value in"))))
 End of changes. 11 change blocks. 
101 lines changed or deleted 10 lines changed or added

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