Skip to content

Instantly share code, notes, and snippets.

@swenson
Last active October 4, 2017 18:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save swenson/8142788 to your computer and use it in GitHub Desktop.
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…
"""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)
Copy link

ghost 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