Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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…
"""Run PEP8 on all Python files in this directory and subdirectories as part of the tests."""
__author__ = 'Christopher Swenson'
__email__ = 'chris@caswenson.com'
__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)
@callmewhy
Copy link

callmewhy commented Sep 22, 2016

@dufferzafar you are right.

And should be 'errors=' not '+=' because total errors already sum the error count.

@tram0004
Copy link

tram0004 commented Oct 4, 2017

@dufferzafar++

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