Skip to content

Instantly share code, notes, and snippets.

@dtcooper
Created November 5, 2012 19:39
Show Gist options
  • Save dtcooper/4019854 to your computer and use it in GitHub Desktop.
Save dtcooper/4019854 to your computer and use it in GitHub Desktop.
Django PEP8 Test Generator Example
import os
import re
import subprocess
from django.conf import settings
from django import test
class PEP8Tests(test.TestCase):
def _generate_pep8_tests(class_namespace):
function_name_scrubber_regex = re.compile(r'\W|^(?=\d)')
# Generate a PEP8 test method for a python file in a closure
def generate_pep8_test(python_filename):
def test_method(self):
# Run pep8 command on this file, if there's output fail with it
pep8_process = subprocess.Popen(
['pep8', '--ignore=E501', python_filename],
stdout=subprocess.PIPE,
)
pep8_process.wait()
pep8_output = pep8_process.stdout.read().strip()
if pep8_output:
self.fail("PEP8 failed on file: %s\n\n%s" % (
python_filename, pep8_output,
))
# Cleanly name this method based on the filename
test_method.__name__ = 'test_pep8_on_%s' % (
function_name_scrubber_regex.sub('_', python_filename),
)
return test_method
# Go through all Python files in PROJECT_ROOT
for root, dirs, files in os.walk(settings.PROJECT_ROOT):
for filename in files:
filename = os.path.join(root, filename)
if filename.endswith('.py') and os.path.exists(filename):
test_method = generate_pep8_test(filename)
# Bind method into TestCase's namespace
class_namespace[test_method.__name__] = test_method
_generate_pep8_tests(locals())
del _generate_pep8_tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment