"Fossies" - the Fresh Open Source Software Archive

Member "barbican-12.0.0/barbican/tests/test_hacking.py" (14 Apr 2021, 6761 Bytes) of package /linux/misc/openstack/barbican-12.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "test_hacking.py": 11.0.0_vs_12.0.0.

    1 #    Copyright 2016 GohighSec
    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 textwrap
   16 from unittest import mock
   17 
   18 import pycodestyle
   19 
   20 from barbican.hacking import checks
   21 import oslotest
   22 
   23 
   24 class HackingTestCase(oslotest.base.BaseTestCase):
   25     """Hacking test cases
   26 
   27     This class tests the hacking checks in barbican.hacking.checks by passing
   28     strings to the check methods like the pycodestyle/flake8 parser would. The
   29     parser
   30     loops over each line in the file and then passes the parameters to the
   31     check method. The parameter names in the check method dictate what type of
   32     object is passed to the check method. The parameter types are::
   33 
   34         logical_line: A processed line with the following modifications:
   35             - Multi-line statements converted to a single line.
   36             - Stripped left and right.
   37             - Contents of strings replaced with "xxx" of same length.
   38             - Comments removed.
   39         physical_line: Raw line of text from the input file.
   40         lines: a list of the raw lines from the input file
   41         tokens: the tokens that contribute to this logical line
   42         line_number: line number in the input file
   43         total_lines: number of lines in the input file
   44         blank_lines: blank lines before this one
   45         indent_char: indentation character in this file (" " or "\t")
   46         indent_level: indentation (with tabs expanded to multiples of 8)
   47         previous_indent_level: indentation on previous line
   48         previous_logical: previous logical line
   49         filename: Path of the file being run through pycodestyle
   50 
   51     When running a test on a check method the return will be False/None if
   52     there is no violation in the sample input. If there is an error a tuple is
   53     returned with a position in the line, and a message. So to check the result
   54     just assertTrue if the check is expected to fail and assertFalse if it
   55     should pass.
   56     """
   57 
   58     # We are patching pycodestyle so that only the check under test is actually
   59     # installed.
   60     @mock.patch('pycodestyle._checks',
   61                 {'physical_line': {}, 'logical_line': {}, 'tree': {}})
   62     def _run_check(self, code, checker, filename=None):
   63         pycodestyle.register_check(checker)
   64 
   65         lines = textwrap.dedent(code).strip().splitlines(True)
   66 
   67         checker = pycodestyle.Checker(filename=filename, lines=lines)
   68         checker.check_all()
   69         checker.report._deferred_print.sort()
   70         return checker.report._deferred_print
   71 
   72     def _assert_has_errors(self, code, checker, expected_errors=None,
   73                            filename=None):
   74         actual_errors = [e[:3] for e in
   75                          self._run_check(code, checker, filename)]
   76         self.assertEqual(expected_errors or [], actual_errors)
   77 
   78     def _assert_has_no_errors(self, code, checker, filename=None):
   79         self._assert_has_errors(code, checker, filename=filename)
   80 
   81     def test_logging_format_no_tuple_arguments(self):
   82         checker = checks.CheckLoggingFormatArgs
   83         code = """
   84                import logging
   85                LOG = logging.getLogger()
   86                LOG.info("Message without a second argument.")
   87                LOG.critical("Message with %s arguments.", 'two')
   88                LOG.debug("Volume %s caught fire and is at %d degrees C and"
   89                          " climbing.", 'volume1', 500)
   90                """
   91         self._assert_has_no_errors(code, checker)
   92 
   93     def test_dict_constructor_with_list_copy(self):
   94         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
   95             "    dict([(i, connect_info[i])"))))
   96 
   97         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
   98             "    attrs = dict([(k, _from_json(v))"))))
   99 
  100         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
  101             "        type_names = dict((value, key) for key, value in"))))
  102 
  103         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
  104             "   dict((value, key) for key, value in"))))
  105 
  106         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
  107             "foo(param=dict((k, v) for k, v in bar.items()))"))))
  108 
  109         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
  110             " dict([[i,i] for i in range(3)])"))))
  111 
  112         self.assertEqual(1, len(list(checks.dict_constructor_with_list_copy(
  113             "  dd = dict([i,i] for i in range(3))"))))
  114 
  115         self.assertEqual(0, len(list(checks.dict_constructor_with_list_copy(
  116             "        create_kwargs = dict(snapshot=snapshot,"))))
  117 
  118         self.assertEqual(0, len(list(checks.dict_constructor_with_list_copy(
  119             "      self._render_dict(xml, data_el, data.__dict__)"))))
  120 
  121     def test_no_xrange(self):
  122         self.assertEqual(1, len(list(checks.no_xrange("xrange(45)"))))
  123 
  124         self.assertEqual(0, len(list(checks.no_xrange("range(45)"))))
  125 
  126     def test_validate_assertTrue(self):
  127         test_value = True
  128         self.assertEqual(0, len(list(checks.validate_assertTrue(
  129             "assertTrue(True)"))))
  130         self.assertEqual(1, len(list(checks.validate_assertTrue(
  131             "assertEqual(True, %s)" % test_value))))
  132 
  133     def test_validate_assertIsNone(self):
  134         test_value = None
  135         self.assertEqual(0, len(list(checks.validate_assertIsNone(
  136             "assertIsNone(None)"))))
  137         self.assertEqual(1, len(list(checks.validate_assertIsNone(
  138             "assertEqual(None, %s)" % test_value))))
  139 
  140     def test_validate_assertIsNotNone(self):
  141         test_value = None
  142         self.assertEqual(0, len(list(checks.validate_assertIsNotNone(
  143             "assertIsNotNone(NotNone)"))))
  144         self.assertEqual(1, len(list(checks.validate_assertIsNotNone(
  145             "assertNotEqual(None, %s)" % test_value))))
  146         self.assertEqual(1, len(list(checks.validate_assertIsNotNone(
  147             "assertIsNot(None, %s)" % test_value))))
  148 
  149     def test_no_log_warn_check(self):
  150         self.assertEqual(0, len(list(checks.no_log_warn_check(
  151             "LOG.warning('This should not trigger LOG.warn"
  152             "hacking check.')"))))
  153         self.assertEqual(1, len(list(checks.no_log_warn_check(
  154             "LOG.warn('We should not use LOG.warn')"))))