"Fossies" - the Fresh Open Source Software Archive

Member "keystone-18.0.0/keystone/tests/unit/ksfixtures/hacking.py" (14 Oct 2020, 10379 Bytes) of package /linux/misc/openstack/keystone-18.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 "hacking.py": 17.0.0_vs_18.0.0.

    1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
    2 # not use this file except in compliance with the License. You may obtain
    3 # a copy of the License at
    4 #
    5 #      http://www.apache.org/licenses/LICENSE-2.0
    6 #
    7 # Unless required by applicable law or agreed to in writing, software
    8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   10 # License for the specific language governing permissions and limitations
   11 # under the License.
   12 
   13 # NOTE(morganfainberg) This file shouldn't have flake8 run on it as it has
   14 # code examples that will fail normal CI pep8/flake8 tests. This is expected.
   15 # The code has been moved here to ensure that proper tests occur on the
   16 # test_hacking_checks test cases.
   17 # flake8: noqa
   18 
   19 import sys
   20 
   21 import fixtures
   22 
   23 
   24 class HackingCode(fixtures.Fixture):
   25     """A fixture to house the various code examples for the keystone hacking
   26     style checks.
   27     """
   28 
   29     mutable_default_args = {
   30         'code': """
   31                 def f():
   32                     pass
   33 
   34                 def f(a, b='', c=None):
   35                     pass
   36 
   37                 def f(bad=[]):
   38                     pass
   39 
   40                 def f(foo, bad=[], more_bad=[x for x in range(3)]):
   41                     pass
   42 
   43                 def f(foo, bad={}):
   44                     pass
   45 
   46                 def f(foo, bad={}, another_bad=[], fine=None):
   47                     pass
   48 
   49                 def f(bad=[]): # noqa
   50                     pass
   51 
   52                 def funcs(bad=dict(), more_bad=list(), even_more_bad=set()):
   53                     "creating mutables through builtins"
   54 
   55                 def funcs(bad=something(), more_bad=some_object.something()):
   56                     "defaults from any functions"
   57 
   58                 def f(bad=set(), more_bad={x for x in range(3)},
   59                        even_more_bad={1, 2, 3}):
   60                     "set and set comprehession"
   61 
   62                 def f(bad={x: x for x in range(3)}):
   63                     "dict comprehension"
   64             """,
   65         'expected_errors': [
   66             (7, 10, 'K001'),
   67             (10, 15, 'K001'),
   68             (10, 28, 'K001'),
   69             (13, 15, 'K001'),
   70             (16, 15, 'K001'),
   71             (16, 31, 'K001'),
   72             (22, 14, 'K001'),
   73             (22, 31, 'K001'),
   74             (22, 53, 'K001'),
   75             (25, 14, 'K001'),
   76             (25, 36, 'K001'),
   77             (28, 10, 'K001'),
   78             (28, 26, 'K001'),
   79             (29, 21, 'K001'),
   80             (32, 10, 'K001'),
   81         ]}
   82 
   83     # NOTE(browne): This is gross, but in Python 3.4 and earlier, the ast
   84     # module returns the incorrect col_offset for two of the defined functions
   85     # in the code sample above.
   86     if sys.version_info < (3, 5):
   87         mutable_default_args['expected_errors'][12] = (28, 27, 'K001')
   88         mutable_default_args['expected_errors'][14] = (32, 11, 'K001')
   89 
   90     # NOTE(gmann): Python version < 3.8.2 (before Ubuntu Focal) returns
   91     # the incorrect col_offset for below function defined in above code sample
   92     # def f(foo, bad=[], more_bad=[x for x in range(3)]):
   93     if sys.version_info < (3, 8, 2):
   94         mutable_default_args['expected_errors'][2] = (10, 29, 'K001')
   95 
   96     comments_begin_with_space = {
   97         'code': """
   98             # This is a good comment
   99 
  100             #This is a bad one
  101 
  102             # This is alright and can
  103             #    be continued with extra indentation
  104             #    if that's what the developer wants.
  105         """,
  106         'expected_errors': [
  107             (3, 0, 'K002'),
  108         ]}
  109 
  110     asserting_none_equality = {
  111         'code': """
  112             class Test(object):
  113 
  114                 def test(self):
  115                     self.assertEqual('', '')
  116                     self.assertEqual('', None)
  117                     self.assertEqual(None, '')
  118                     self.assertNotEqual('', None)
  119                     self.assertNotEqual(None, '')
  120                     self.assertNotEqual('', None) # noqa
  121                     self.assertNotEqual(None, '') # noqa
  122         """,
  123         'expected_errors': [
  124             (5, 8, 'K003'),
  125             (6, 8, 'K003'),
  126             (7, 8, 'K004'),
  127             (8, 8, 'K004'),
  128         ]}
  129 
  130     dict_constructor = {
  131         'code': """
  132             lower_res = {k.lower(): v for k, v in res[1].items()}
  133             fool = dict(a='a', b='b')
  134             lower_res = dict((k.lower(), v) for k, v in res[1].items())
  135             attrs = dict([(k, _from_json(v))])
  136             dict([[i,i] for i in range(3)])
  137             dict(({1:2}))
  138         """,
  139         'expected_errors': [
  140             (3, 0, 'K008'),
  141             (4, 0, 'K008'),
  142             (5, 0, 'K008'),
  143         ]}
  144 
  145 
  146 class HackingTranslations(fixtures.Fixture):
  147     """Fixtures for checking translation rules.
  148 
  149     1. Exception messages should be translated
  150     2. Logging messages should not be translated
  151     3. If a message is used for both an exception and logging it
  152        should be translated
  153     """
  154 
  155     shared_imports = """
  156                 import logging
  157                 import logging as stlib_logging
  158                 from keystone.i18n import _
  159                 from keystone.i18n import _ as oslo_i18n
  160                 from oslo_log import log
  161                 from oslo_log import log as oslo_logging
  162     """
  163 
  164     examples = [
  165         {
  166             'code': """
  167                 # stdlib logging
  168                 LOG = logging.getLogger()
  169                 LOG.info(_('text'))
  170                 class C:
  171                     def __init__(self):
  172                         LOG.warning(oslo_i18n('text', {}))
  173             """,
  174             'expected_errors': [
  175                 (3, 9, 'K005'),
  176                 (6, 20, 'K005'),
  177             ],
  178         },
  179         {
  180             'code': """
  181                 # stdlib logging w/ alias and specifying a logger
  182                 class C:
  183                     def __init__(self):
  184                         self.L = logging.getLogger(__name__)
  185                     def m(self):
  186                         self.L.warning(
  187                             _('text'), {}
  188                         )
  189             """,
  190             'expected_errors': [
  191                 (7, 12, 'K005'),
  192             ],
  193         },
  194         {
  195             'code': """
  196                 # oslo logging and specifying a logger
  197                 L = log.getLogger(__name__)
  198                 L.error(oslo_i18n('text'))
  199             """,
  200             'expected_errors': [
  201                 (3, 8, 'K005'),
  202             ],
  203         },
  204         {
  205             'code': """
  206                 # oslo logging w/ alias
  207                 class C:
  208                     def __init__(self):
  209                         self.LOG = oslo_logging.getLogger()
  210                         self.LOG.critical(_('text'))
  211             """,
  212             'expected_errors': [
  213                 (5, 26, 'K005'),
  214             ],
  215         },
  216         {
  217             'code': """
  218                 LOG = log.getLogger(__name__)
  219                 # translation on a separate line
  220                 msg = _('text')
  221                 LOG.exception(msg)
  222             """,
  223             'expected_errors': [
  224                 (4, 14, 'K005'),
  225             ],
  226         },
  227         {
  228             'code': """
  229                 # this should be an error even if it'll be raised later.
  230                 L = log.getLogger(__name__)
  231                 msg = _('text')
  232                 L.warning(msg)
  233                 raise Exception(msg)
  234             """,
  235             'expected_errors': [
  236                 (4, 10, 'K005'),
  237             ],
  238         },
  239         {
  240             'code': """
  241                 L = log.getLogger(__name__)
  242                 def f():
  243                     msg = _('text')
  244                     L.warning(msg)
  245                     something = True  # add an extra statement here
  246                     raise Exception(msg)
  247             """,
  248             'expected_errors': [
  249                 (4, 14, 'K005'),
  250             ],
  251         },
  252         {
  253             'code': """
  254                 LOG = log.getLogger(__name__)
  255                 def func():
  256                     msg = _('text')
  257                     LOG.warning(msg)
  258                     raise Exception('some other message')
  259             """,
  260             'expected_errors': [
  261                 (4, 16, 'K005'),
  262             ],
  263         },
  264         {
  265             'code': """
  266                 LOG = log.getLogger(__name__)
  267                 if True:
  268                     msg = _('text')
  269                 else:
  270                     msg = _('text')
  271                 LOG.warning(msg)
  272                 raise Exception(msg)
  273             """,
  274             'expected_errors': [
  275                 (6, 12, 'K005'),
  276             ],
  277         },
  278         {
  279             'code': """
  280                 LOG = log.getLogger(__name__)
  281                 if True:
  282                     msg = _('text')
  283                 else:
  284                     msg = _('text')
  285                 LOG.warning(msg)
  286             """,
  287             'expected_errors': [
  288                 (6, 12, 'K005'),
  289             ],
  290         },
  291         {
  292             'code': """
  293                 LOG = log.getLogger(__name__)
  294                 msg = _LW('text')
  295                 LOG.warning(msg)
  296                 msg = _('something else')
  297                 raise Exception(msg)
  298             """,
  299             'expected_errors': [],
  300         },
  301         {
  302             'code': """
  303                 LOG = log.getLogger(__name__)
  304                 msg = _('hello %s') % 'world'
  305                 LOG.warning(msg)
  306             """,
  307             'expected_errors': [
  308                 (3, 12, 'K005'),
  309             ],
  310         },
  311         {
  312             'code': """
  313                 # this should not be an error
  314                 LOG = log.getLogger(__name__)
  315                 try:
  316                     something = True
  317                 except AssertionError as e:
  318                     LOG.warning(e)
  319                     raise exception.Unauthorized(e)
  320             """,
  321             'expected_errors': [],
  322         },
  323         {
  324             'code': """
  325                 # this should not be an error
  326                 LOG = log.getLogger(__name__)
  327                 try:
  328                     pass
  329                 except AssertionError as e:
  330                     msg = _('some message')
  331                     LOG.warning(msg)
  332                     raise exception.Unauthorized(message=msg)
  333             """,
  334             'expected_errors': [
  335                 (7, 16, 'K005'),
  336             ],
  337         },
  338     ]