Last active
October 4, 2017 18:08
-
-
Save swenson/8142788 to your computer and use it in GitHub Desktop.
Test for running PEP8 against all Python files. Useful to hook up to nose and as part of your CI. I modify PEP8 in two ways by default: don't enforce 4-spacing (I prefer 2-spacing), and use 100 for the default line length, because we don't use 80-column punch cards anymore. Licensed under CC0 (public domain): do what you want. http://creativecom…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Run PEP8 on all Python files in this directory and subdirectories as part of the tests.""" | |
__author__ = 'Christopher Swenson' | |
__email__ = '[email protected]' | |
__license__ = 'CC0 http://creativecommons.org/publicdomain/zero/1.0/' | |
import os | |
import os.path | |
import unittest | |
import pep8 | |
# ignore stuff in virtualenvs or version control directories | |
ignore_patterns = ('.svn', 'bin', 'lib' + os.sep + 'python') | |
def ignore(dir): | |
"""Should the directory be ignored?""" | |
for pattern in ignore_patterns: | |
if pattern in dir: | |
return True | |
return False | |
class TestPep8(unittest.TestCase): | |
"""Run PEP8 on all files in this directory and subdirectories.""" | |
def test_pep8(self): | |
style = pep8.StyleGuide(quiet=True) | |
style.options.ignore += ('E111',) # 4-spacing is just too much | |
style.options.max_line_length = 100 # because it isn't 1928 anymore | |
errors = 0 | |
for root, _, files in os.walk('.'): | |
if ignore(root): | |
continue | |
python_files = [f for f in files if f.endswith('.py')] | |
errors += style.check_files(python_files).total_errors | |
self.assertEqual(errors, 0, 'PEP8 style errors: %d' % errors) |
Working code, reading style edits from tox.ini
:
import os
import unittest
import pycodestyle
class TestPep8(unittest.TestCase):
"""Run PEP8 on all project files."""
def test_pep8(self):
style = pycodestyle.StyleGuide(quiet=False, config_file='tox.ini')
for root, dirs, files in os.walk('myproject/'):
python_files = [os.path.join(root, f) for f in files if f.endswith('.py')]
style.check_files(python_files)
n = style.check_files().total_errors
self.assertEqual(n, 0, 'PEP8 style errors: %d' % n)
And tox.ini
looks like this:
[tox]
envlist = py34
[testenv]
deps = pytest
commands = {envpython} setup.py test
[pycodestyle]
ignore = E501
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dufferzafar you are right.
And should be 'errors=' not '+=' because
total errors
already sum the error count.