"Fossies" - the Fresh Open Source Software Archive

Member "keystone-17.0.0/keystone/tests/unit/ksfixtures/hacking.py" (13 May 2020, 10062 Bytes) of package /linux/misc/openstack/keystone-17.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": 16.0.1_vs_17.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, 29, '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     comments_begin_with_space = {
   91         'code': """
   92             # This is a good comment
   93 
   94             #This is a bad one
   95 
   96             # This is alright and can
   97             #    be continued with extra indentation
   98             #    if that's what the developer wants.
   99         """,
  100         'expected_errors': [
  101             (3, 0, 'K002'),
  102         ]}
  103 
  104     asserting_none_equality = {
  105         'code': """
  106             class Test(object):
  107 
  108                 def test(self):
  109                     self.assertEqual('', '')
  110                     self.assertEqual('', None)
  111                     self.assertEqual(None, '')
  112                     self.assertNotEqual('', None)
  113                     self.assertNotEqual(None, '')
  114                     self.assertNotEqual('', None) # noqa
  115                     self.assertNotEqual(None, '') # noqa
  116         """,
  117         'expected_errors': [
  118             (5, 8, 'K003'),
  119             (6, 8, 'K003'),
  120             (7, 8, 'K004'),
  121             (8, 8, 'K004'),
  122         ]}
  123 
  124     dict_constructor = {
  125         'code': """
  126             lower_res = {k.lower(): v for k, v in res[1].items()}
  127             fool = dict(a='a', b='b')
  128             lower_res = dict((k.lower(), v) for k, v in res[1].items())
  129             attrs = dict([(k, _from_json(v))])
  130             dict([[i,i] for i in range(3)])
  131             dict(({1:2}))
  132         """,
  133         'expected_errors': [
  134             (3, 0, 'K008'),
  135             (4, 0, 'K008'),
  136             (5, 0, 'K008'),
  137         ]}
  138 
  139 
  140 class HackingTranslations(fixtures.Fixture):
  141     """Fixtures for checking translation rules.
  142 
  143     1. Exception messages should be translated
  144     2. Logging messages should not be translated
  145     3. If a message is used for both an exception and logging it
  146        should be translated
  147     """
  148 
  149     shared_imports = """
  150                 import logging
  151                 import logging as stlib_logging
  152                 from keystone.i18n import _
  153                 from keystone.i18n import _ as oslo_i18n
  154                 from oslo_log import log
  155                 from oslo_log import log as oslo_logging
  156     """
  157 
  158     examples = [
  159         {
  160             'code': """
  161                 # stdlib logging
  162                 LOG = logging.getLogger()
  163                 LOG.info(_('text'))
  164                 class C:
  165                     def __init__(self):
  166                         LOG.warning(oslo_i18n('text', {}))
  167             """,
  168             'expected_errors': [
  169                 (3, 9, 'K005'),
  170                 (6, 20, 'K005'),
  171             ],
  172         },
  173         {
  174             'code': """
  175                 # stdlib logging w/ alias and specifying a logger
  176                 class C:
  177                     def __init__(self):
  178                         self.L = logging.getLogger(__name__)
  179                     def m(self):
  180                         self.L.warning(
  181                             _('text'), {}
  182                         )
  183             """,
  184             'expected_errors': [
  185                 (7, 12, 'K005'),
  186             ],
  187         },
  188         {
  189             'code': """
  190                 # oslo logging and specifying a logger
  191                 L = log.getLogger(__name__)
  192                 L.error(oslo_i18n('text'))
  193             """,
  194             'expected_errors': [
  195                 (3, 8, 'K005'),
  196             ],
  197         },
  198         {
  199             'code': """
  200                 # oslo logging w/ alias
  201                 class C:
  202                     def __init__(self):
  203                         self.LOG = oslo_logging.getLogger()
  204                         self.LOG.critical(_('text'))
  205             """,
  206             'expected_errors': [
  207                 (5, 26, 'K005'),
  208             ],
  209         },
  210         {
  211             'code': """
  212                 LOG = log.getLogger(__name__)
  213                 # translation on a separate line
  214                 msg = _('text')
  215                 LOG.exception(msg)
  216             """,
  217             'expected_errors': [
  218                 (4, 14, 'K005'),
  219             ],
  220         },
  221         {
  222             'code': """
  223                 # this should be an error even if it'll be raised later.
  224                 L = log.getLogger(__name__)
  225                 msg = _('text')
  226                 L.warning(msg)
  227                 raise Exception(msg)
  228             """,
  229             'expected_errors': [
  230                 (4, 10, 'K005'),
  231             ],
  232         },
  233         {
  234             'code': """
  235                 L = log.getLogger(__name__)
  236                 def f():
  237                     msg = _('text')
  238                     L.warning(msg)
  239                     something = True  # add an extra statement here
  240                     raise Exception(msg)
  241             """,
  242             'expected_errors': [
  243                 (4, 14, 'K005'),
  244             ],
  245         },
  246         {
  247             'code': """
  248                 LOG = log.getLogger(__name__)
  249                 def func():
  250                     msg = _('text')
  251                     LOG.warning(msg)
  252                     raise Exception('some other message')
  253             """,
  254             'expected_errors': [
  255                 (4, 16, 'K005'),
  256             ],
  257         },
  258         {
  259             'code': """
  260                 LOG = log.getLogger(__name__)
  261                 if True:
  262                     msg = _('text')
  263                 else:
  264                     msg = _('text')
  265                 LOG.warning(msg)
  266                 raise Exception(msg)
  267             """,
  268             'expected_errors': [
  269                 (6, 12, 'K005'),
  270             ],
  271         },
  272         {
  273             'code': """
  274                 LOG = log.getLogger(__name__)
  275                 if True:
  276                     msg = _('text')
  277                 else:
  278                     msg = _('text')
  279                 LOG.warning(msg)
  280             """,
  281             'expected_errors': [
  282                 (6, 12, 'K005'),
  283             ],
  284         },
  285         {
  286             'code': """
  287                 LOG = log.getLogger(__name__)
  288                 msg = _LW('text')
  289                 LOG.warning(msg)
  290                 msg = _('something else')
  291                 raise Exception(msg)
  292             """,
  293             'expected_errors': [],
  294         },
  295         {
  296             'code': """
  297                 LOG = log.getLogger(__name__)
  298                 msg = _('hello %s') % 'world'
  299                 LOG.warning(msg)
  300             """,
  301             'expected_errors': [
  302                 (3, 12, 'K005'),
  303             ],
  304         },
  305         {
  306             'code': """
  307                 # this should not be an error
  308                 LOG = log.getLogger(__name__)
  309                 try:
  310                     something = True
  311                 except AssertionError as e:
  312                     LOG.warning(e)
  313                     raise exception.Unauthorized(e)
  314             """,
  315             'expected_errors': [],
  316         },
  317         {
  318             'code': """
  319                 # this should not be an error
  320                 LOG = log.getLogger(__name__)
  321                 try:
  322                     pass
  323                 except AssertionError as e:
  324                     msg = _('some message')
  325                     LOG.warning(msg)
  326                     raise exception.Unauthorized(message=msg)
  327             """,
  328             'expected_errors': [
  329                 (7, 16, 'K005'),
  330             ],
  331         },
  332     ]