diff options
author | Marius Gedminas <marius@gedmin.as> | 2020-04-14 16:01:30 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-14 16:01:30 +0300 |
commit | 875be83c3f932a9d5bebdced76671dcbfedb3d55 (patch) | |
tree | e68041ad54fec8670d1669c0d81b88152f8a208a | |
parent | 6bd284b27df9c233f730053e38ae201692dbe5f6 (diff) | |
parent | cd7821f5968a80ae22067593688ea3cbf8e71638 (diff) | |
download | zope-exceptions-875be83c3f932a9d5bebdced76671dcbfedb3d55.tar.gz |
Merge pull request #14 from zopefoundation/flake8
Add tox -e flake8, fix flake8 errors
-rw-r--r-- | .travis.yml | 35 | ||||
-rw-r--r-- | setup.py | 97 | ||||
-rw-r--r-- | src/zope/__init__.py | 2 | ||||
-rw-r--r-- | src/zope/exceptions/__init__.py | 17 | ||||
-rw-r--r-- | src/zope/exceptions/exceptionformatter.py | 23 | ||||
-rw-r--r-- | src/zope/exceptions/log.py | 1 | ||||
-rw-r--r-- | src/zope/exceptions/tests/test_exceptionformatter.py | 43 | ||||
-rw-r--r-- | src/zope/exceptions/tests/test_log.py | 17 | ||||
-rw-r--r-- | tox.ini | 7 |
9 files changed, 142 insertions, 100 deletions
diff --git a/.travis.yml b/.travis.yml index 9cfc6f8..bfeef7d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,22 +1,29 @@ language: python python: - - 2.7 - - 3.5 - - 3.6 - - 3.7 - - 3.8 - - pypy + - 2.7 + - 3.5 + - 3.6 + - 3.7 + - 3.8 + - pypy +jobs: + include: + - name: flake8 + install: pip install flake8 + script: flake8 src setup.py + after_success: + env: CACHE_NAME=flake8 + allow_failures: + - env: CACHE_NAME=flake8 install: - - pip install -U pip setuptools - - pip install -U coverage coveralls - - pip install -U -e .[test,docs] + - pip install -U pip setuptools + - pip install -U coverage coveralls + - pip install -U -e .[test,docs] script: - - coverage run -m zope.testrunner --test-path=src - - coverage run -a -m sphinx -b doctest -d docs/_build/doctrees docs docs/_build/doctest + - coverage run -m zope.testrunner --test-path=src + - coverage run -a -m sphinx -b doctest -d docs/_build/doctrees docs docs/_build/doctest notifications: - email: false + email: false cache: pip -before_cache: - - rm -f $HOME/.cache/pip/log/debug.log after_success: - coveralls @@ -25,6 +25,7 @@ from setuptools import setup, find_packages def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() + def alltests(): import os import sys @@ -40,55 +41,57 @@ def alltests(): suites = list(zope.testrunner.find.find_suites(options)) return unittest.TestSuite(suites) + tests_require = [ 'zope.testrunner', ] -setup(name='zope.exceptions', - version='4.4.dev0', - author='Zope Foundation and Contributors', - author_email='zope-dev@zope.org', - description='Zope Exceptions', - long_description=(read('README.rst') + '\n\n' + - read('CHANGES.rst')), - keywords='zope exceptions', - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Zope Public License', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: Implementation :: CPython', - 'Programming Language :: Python :: Implementation :: PyPy', - 'Natural Language :: English', - 'Operating System :: OS Independent', - 'Topic :: Internet :: WWW/HTTP', - 'Framework :: Zope :: 3', - ], - url='https://github.com/zopefoundation/zope.exceptions', - license='ZPL 2.1', - packages=find_packages('src'), - package_dir={'': 'src'}, - namespace_packages=['zope'], - install_requires=[ - 'setuptools', - 'zope.interface', - ], - tests_require=[ - 'zope.testrunner', - ], - test_suite='__main__.alltests', - include_package_data=True, - zip_safe=False, - extras_require={ - 'docs': ['Sphinx', 'repoze.sphinx.autointerface'], - 'test': tests_require, - }, +setup( + name='zope.exceptions', + version='4.4.dev0', + author='Zope Foundation and Contributors', + author_email='zope-dev@zope.org', + description='Zope Exceptions', + long_description=(read('README.rst') + '\n\n' + + read('CHANGES.rst')), + keywords='zope exceptions', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Zope Public License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'Natural Language :: English', + 'Operating System :: OS Independent', + 'Topic :: Internet :: WWW/HTTP', + 'Framework :: Zope :: 3', + ], + url='https://github.com/zopefoundation/zope.exceptions', + license='ZPL 2.1', + packages=find_packages('src'), + package_dir={'': 'src'}, + namespace_packages=['zope'], + install_requires=[ + 'setuptools', + 'zope.interface', + ], + tests_require=[ + 'zope.testrunner', + ], + test_suite='__main__.alltests', + include_package_data=True, + zip_safe=False, + extras_require={ + 'docs': ['Sphinx', 'repoze.sphinx.autointerface'], + 'test': tests_require, + }, ) diff --git a/src/zope/__init__.py b/src/zope/__init__.py index 2cdb0e4..656dc0f 100644 --- a/src/zope/__init__.py +++ b/src/zope/__init__.py @@ -1 +1 @@ -__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover +__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover diff --git a/src/zope/exceptions/__init__.py b/src/zope/exceptions/__init__.py index 76c1695..84d1dd2 100644 --- a/src/zope/exceptions/__init__.py +++ b/src/zope/exceptions/__init__.py @@ -16,6 +16,7 @@ These exceptions are so general purpose that they don't belong in Zope application-specific packages. """ + from zope.exceptions.interfaces import DuplicationError from zope.exceptions.interfaces import IDuplicationError from zope.exceptions.interfaces import UserError @@ -25,17 +26,27 @@ from zope.exceptions.exceptionformatter import format_exception from zope.exceptions.exceptionformatter import print_exception from zope.exceptions.exceptionformatter import extract_stack +__all__ = [ + 'DuplicationError', 'IDuplicationError', 'UserError', 'IUserError', + 'format_exception', 'print_exception', 'extract_stack', +] + + # avoid dependency on zope.security: try: - import zope.security -except ImportError as v: #pragma: no cover + import zope.security # noqa: suppress unused import warning from flake8 +except ImportError as v: # pragma: no cover # "ImportError: No module named security" if 'security' not in str(v): raise -else: #pragma: no cover +else: # pragma: no cover from zope.security.interfaces import IUnauthorized from zope.security.interfaces import Unauthorized from zope.security.interfaces import IForbidden from zope.security.interfaces import IForbiddenAttribute from zope.security.interfaces import Forbidden from zope.security.interfaces import ForbiddenAttribute + __all__ += [ + 'IUnauthorized', 'Unauthorized', 'IForbidden', 'IForbiddenAttribute', + 'Forbidden', 'ForbiddenAttribute', + ] diff --git a/src/zope/exceptions/exceptionformatter.py b/src/zope/exceptions/exceptionformatter.py index 47e0f41..abf0ae7 100644 --- a/src/zope/exceptions/exceptionformatter.py +++ b/src/zope/exceptions/exceptionformatter.py @@ -92,7 +92,7 @@ class TextExceptionFormatter(object): extra = getInfo() if extra: result.append(self.formatSupplementInfo(extra)) - except: #pragma: no cover + except Exception: # pragma: no cover if DEBUG_EXCEPTION_FORMATTER: traceback.print_exc() # else just swallow the exception. @@ -150,7 +150,7 @@ class TextExceptionFormatter(object): try: supp = factory(*args) result.extend(self.formatSupplement(supp, tb)) - except: #pragma: no cover + except Exception: # pragma: no cover if DEBUG_EXCEPTION_FORMATTER: traceback.print_exc() # else just swallow the exception. @@ -159,7 +159,7 @@ class TextExceptionFormatter(object): tbi = f_locals.get('__traceback_info__', None) if tbi is not None: result.append(self.formatTracebackInfo(tbi)) - except: #pragma: no cover + except Exception: # pragma: no cover if DEBUG_EXCEPTION_FORMATTER: traceback.print_exc() # else just swallow the exception. @@ -174,8 +174,9 @@ class TextExceptionFormatter(object): return self.escape(exc_line) def formatException(self, etype, value, tb): - # The next line provides a way to detect recursion. - __exception_formatter__ = 1 + # The next line provides a way to detect recursion. The 'noqa' + # comment disables a flake8 warning about the unused variable. + __exception_formatter__ = 1 # noqa result = [] while tb is not None: if tb.tb_frame.f_locals.get('__exception_formatter__'): @@ -206,8 +207,9 @@ class TextExceptionFormatter(object): except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back - # The next line provides a way to detect recursion. - __exception_formatter__ = 1 + # The next line provides a way to detect recursion. The 'noqa' + # comment disables a flake8 warning about the unused variable. + __exception_formatter__ = 1 # noqa result = [] while f is not None: if f.f_locals.get('__exception_formatter__'): @@ -250,10 +252,9 @@ class HTMLExceptionFormatter(TextExceptionFormatter): s = str(s) except UnicodeError: if hasattr(s, 'encode'): - # We probably got a unicode string on - # Python 2. + # We probably got a unicode string on Python 2. s = s.encode('utf-8') - else: # pragma: no cover + else: # pragma: no cover raise return escape(s, quote=False) @@ -309,7 +310,7 @@ def print_exception(t, v, tb, limit=None, file=None, as_html=False, information to the traceback and accepts two options, 'as_html' and 'with_filenames'. """ - if file is None: # pragma: no cover + if file is None: # pragma: no cover file = sys.stderr lines = format_exception(t, v, tb, limit, as_html, with_filenames) for line in lines: diff --git a/src/zope/exceptions/log.py b/src/zope/exceptions/log.py index 574ccd3..657ea7b 100644 --- a/src/zope/exceptions/log.py +++ b/src/zope/exceptions/log.py @@ -21,6 +21,7 @@ from zope.exceptions.exceptionformatter import print_exception Buffer = io.StringIO if bytes is not str else io.BytesIO + class Formatter(logging.Formatter): def formatException(self, ei): diff --git a/src/zope/exceptions/tests/test_exceptionformatter.py b/src/zope/exceptions/tests/test_exceptionformatter.py index 9046950..23afe12 100644 --- a/src/zope/exceptions/tests/test_exceptionformatter.py +++ b/src/zope/exceptions/tests/test_exceptionformatter.py @@ -121,13 +121,16 @@ class TextExceptionFormatterTests(unittest.TestCase): def test_formatSupplement_w_warnings(self): fmt = self._makeOne() supplement = DummySupplement() - supplement.warnings = ['Beware the ides of March!', - 'You\'re gonna get wasted.', - ] - self.assertEqual(fmt.formatSupplement(supplement, tb=None), - [' - Warning: Beware the ides of March!', - ' - Warning: You\'re gonna get wasted.', - ]) + supplement.warnings = [ + 'Beware the ides of March!', + 'You\'re gonna get wasted.', + ] + self.assertEqual( + fmt.formatSupplement(supplement, tb=None), + [ + ' - Warning: Beware the ides of March!', + ' - Warning: You\'re gonna get wasted.', + ]) def test_formatSupplement_w_getInfo_empty(self): fmt = self._makeOne() @@ -407,9 +410,10 @@ class TextExceptionFormatterTests(unittest.TestCase): expected = [ ' File "dummy/filename.py", line 17, in dummy_function\n', ' File "dummy/filename.py", line 27, in dummy_function\n', - '(Recursive extractStack() stopped, trying traceback.format_stack)\n', + ('(Recursive extractStack() stopped,' + ' trying traceback.format_stack)\n'), ' Module dummy/filename.py, line 43, in dummy_function\n', - ] + ] self.assertEqual(expected, lines) @@ -627,6 +631,7 @@ class Test_format_exception(unittest.TestCase): def test_multiple_levels(self): # Ensure many levels are shown in a traceback. HOW_MANY = 10 + def f(n): """Produces a (n + 1)-level traceback.""" __traceback_info__ = 'level%d' % n @@ -658,7 +663,8 @@ class Test_format_exception(unittest.TestCase): s = self._callFUT(False) lines = s.splitlines()[-3:] self.assertEqual(lines[0], ' syntax error') - self.assertTrue(lines[1].endswith(' ^')) #PyPy has a shorter prefix + # PyPy has a shorter prefix + self.assertTrue(lines[1].endswith(' ^')) self.assertEqual(lines[2], 'SyntaxError: invalid syntax') def test_traceback_info_non_ascii(self): @@ -671,7 +677,6 @@ class Test_format_exception(unittest.TestCase): self.assertIsInstance(s, str) self.assertIn('Have a Snowman', s) - def test_recursion_failure(self): from zope.exceptions.exceptionformatter import TextExceptionFormatter @@ -711,13 +716,16 @@ class Test_format_exception(unittest.TestCase): expected = dedent("""\ <p>Traceback (most recent call last):</p> <ul> - <li> Module zope.exceptions.tests.test_exceptionformatter, line ABC, in test_format_exception_as_html<br /> + <li> Module {module}, line ABC, in {fn}<br /> exec('import')</li> </ul><p> File "<string>", line 1<br /> import<br /> ^<br /> SyntaxError: invalid syntax<br /> - </p>""") + </p>""").format( + module='zope.exceptions.tests.test_exceptionformatter', + fn='test_format_exception_as_html', + ) # HTML formatter uses Windows line endings for some reason. result = result.replace('\r\n', '\n') result = re.sub(r'line \d\d\d,', 'line ABC,', result) @@ -856,6 +864,7 @@ class TestingTracebackSupplement(object): line = 634 column = 57 warnings = ['Repent, for the end is nigh'] + def __init__(self, expression): self.expression = expression @@ -863,6 +872,7 @@ class TestingTracebackSupplement(object): class DummySupplement(object): def __init__(self, info=''): self._info = info + def getInfo(self): return self._info @@ -875,15 +885,18 @@ class DummyTB(object): class DummyFrame(object): f_lineno = 137 f_back = None + def __init__(self): self.f_locals = {} self.f_globals = {} self.f_code = DummyCode() + class DummyCode(object): co_filename = 'dummy/filename.py' co_name = 'dummy_function' + class _Monkey(object): # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): @@ -898,13 +911,11 @@ class _Monkey(object): def __exit__(self, exc_type, exc_val, exc_tb): for key, value in self.to_restore.items(): - if value is not self: # pragma: no cover + if value is not self: # pragma: no cover setattr(self.module, key, value) else: delattr(self.module, key) - - def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) diff --git a/src/zope/exceptions/tests/test_log.py b/src/zope/exceptions/tests/test_log.py index 9e01eea..35c78f2 100644 --- a/src/zope/exceptions/tests/test_log.py +++ b/src/zope/exceptions/tests/test_log.py @@ -36,9 +36,8 @@ class FormatterTests(unittest.TestCase): self.assertEqual(lines[0], 'Traceback (most recent call last):') self.assertEqual(lines[1], ' File "dummy/filename.py", line 14, ' 'in dummy_function') - self.assertEqual(lines[2], - traceback.format_exception_only( - ValueError, exc)[0][:-1]) #trailing \n + emsg = traceback.format_exception_only(ValueError, exc)[0] + self.assertEqual(lines[2], emsg[:-1]) # strip trailing \n from emsg def test_unicode_traceback_info(self): import traceback @@ -58,11 +57,10 @@ class FormatterTests(unittest.TestCase): # utf-8 encoded on Python 2, unicode on Python 3 expected += '\xe2\x98\x83' if bytes is str else u'\u2603' - self.assertEqual(lines[2], - expected) - self.assertEqual(lines[3], - traceback.format_exception_only( - ValueError, exc)[0][:-1]) #trailing \n + self.assertEqual(lines[2], expected) + + emsg = traceback.format_exception_only(ValueError, exc)[0] + self.assertEqual(lines[3], emsg[:-1]) # strip trailing \n from emsg class DummyTB(object): @@ -72,14 +70,17 @@ class DummyTB(object): def __init__(self): self.tb_frame = DummyFrame() + class DummyFrame(object): f_lineno = 137 f_back = None + def __init__(self): self.f_locals = {} self.f_globals = {} self.f_code = DummyCode() + class DummyCode(object): co_filename = 'dummy/filename.py' co_name = 'dummy_function' @@ -25,3 +25,10 @@ basepython = commands = sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest + +[testenv:flake8] +skip_install = true +deps = + flake8 +commands = + flake8 src/ setup.py |