Skip to content

Commit

Permalink
Add tox -e flake8, fix flake8 errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mgedmin committed Apr 10, 2020
1 parent 1c2a7b3 commit 9dcac26
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 97 deletions.
97 changes: 50 additions & 47 deletions setup.py
Expand Up @@ -25,6 +25,7 @@
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()


def alltests():
import os
import sys
Expand All @@ -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,
},
)
2 changes: 1 addition & 1 deletion src/zope/__init__.py
@@ -1 +1 @@
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
39 changes: 23 additions & 16 deletions src/zope/exceptions/__init__.py
Expand Up @@ -16,26 +16,33 @@
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
from zope.exceptions.interfaces import IUserError

from zope.exceptions.exceptionformatter import format_exception
from zope.exceptions.exceptionformatter import print_exception
from zope.exceptions.exceptionformatter import extract_stack
from zope.exceptions.interfaces import ( # noqa: F401
DuplicationError,
IDuplicationError,
UserError,
IUserError,
)

from zope.exceptions.exceptionformatter import ( # noqa: F401
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: F401
except ImportError as v: # pragma: no cover
# "ImportError: No module named security"
if 'security' not in str(v):
raise
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
else: # pragma: no cover
from zope.security.interfaces import ( # noqa: F401
IUnauthorized,
Unauthorized,
IForbidden,
IForbiddenAttribute,
Forbidden,
ForbiddenAttribute,
)
17 changes: 8 additions & 9 deletions src/zope/exceptions/exceptionformatter.py
Expand Up @@ -92,7 +92,7 @@ def formatSupplement(self, supplement, tb):
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.
Expand Down Expand Up @@ -150,7 +150,7 @@ def formatLine(self, tb=None, f=None):
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.
Expand All @@ -159,7 +159,7 @@ def formatLine(self, tb=None, f=None):
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.
Expand All @@ -175,7 +175,7 @@ def formatLastLine(self, exc_line):

def formatException(self, etype, value, tb):
# The next line provides a way to detect recursion.
__exception_formatter__ = 1
__exception_formatter__ = 1 # noqa: F841
result = []
while tb is not None:
if tb.tb_frame.f_locals.get('__exception_formatter__'):
Expand Down Expand Up @@ -207,7 +207,7 @@ def extractStack(self, f=None):
f = sys.exc_info()[2].tb_frame.f_back

# The next line provides a way to detect recursion.
__exception_formatter__ = 1
__exception_formatter__ = 1 # noqa: F841
result = []
while f is not None:
if f.f_locals.get('__exception_formatter__'):
Expand Down Expand Up @@ -250,10 +250,9 @@ def escape(self, s):
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)

Expand Down Expand Up @@ -309,7 +308,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:
Expand Down
1 change: 1 addition & 0 deletions src/zope/exceptions/log.py
Expand Up @@ -21,6 +21,7 @@

Buffer = io.StringIO if bytes is not str else io.BytesIO


class Formatter(logging.Formatter):

def formatException(self, ei):
Expand Down
43 changes: 27 additions & 16 deletions src/zope/exceptions/tests/test_exceptionformatter.py
Expand Up @@ -121,13 +121,16 @@ def test_formatSupplement_w_expression(self):
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()
Expand Down Expand Up @@ -407,9 +410,10 @@ def test_extractStack_w_recursive_frames(self):
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)

Expand Down Expand Up @@ -627,6 +631,7 @@ def test_supplement_html(self):
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
Expand Down Expand Up @@ -658,7 +663,8 @@ def test_multiline_exception(self):
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):
Expand All @@ -671,7 +677,6 @@ def test_traceback_info_non_ascii(self):
self.assertIsInstance(s, str)
self.assertIn('Have a Snowman', s)


def test_recursion_failure(self):
from zope.exceptions.exceptionformatter import TextExceptionFormatter

Expand Down Expand Up @@ -711,13 +716,16 @@ def test_format_exception_as_html(self):
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 "&lt;string&gt;", 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)
Expand Down Expand Up @@ -856,13 +864,15 @@ class TestingTracebackSupplement(object):
line = 634
column = 57
warnings = ['Repent, for the end is nigh']

def __init__(self, expression):
self.expression = expression


class DummySupplement(object):
def __init__(self, info=''):
self._info = info

def getInfo(self):
return self._info

Expand All @@ -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):
Expand All @@ -898,13 +911,11 @@ def __enter__(self):

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__)

0 comments on commit 9dcac26

Please sign in to comment.