from django.test import TestCase
from mezzanine.utils.tests import run_pyflakes_for_package, _run_checker_for_package


class SyntaxTest(TestCase):
    def test_syntax(self):
        """
        Run pyflakes/pep8 across the code base to check for potential errors.
        """
        packages = ['common', 'comps', 'discuss', 'rets', 'manticore_tastypie_urbanairship']
        warnings = []
        # Eventually should use flake8 instead so we can ignore specific lines via a comment
        for package in packages:
            warnings.extend(run_pyflakes_for_package(package, extra_ignore=("_settings",)))
            warnings.extend(run_pep8_for_package(package, extra_ignore=("_settings",)))
        if warnings:
            self.fail("{0} Syntax warnings!\n\n{1}".format(len(warnings), "\n".join(warnings)))


def run_pep8_for_package(package_name, extra_ignore=None):
    """
    Shamelessly copied from Mezzanine utils to modify the max line length
    """
    import pep8

    class Checker(pep8.Checker):
        """
        Subclass pep8's Checker to hook into error reporting.
        """
        def __init__(self, *args, **kwargs):
            super(Checker, self).__init__(*args, **kwargs)
            self.report_error = self._report_error
            self.errors = []

        def _report_error(self, line_number, offset, text, check):
            """
            Store pairs of line numbers and errors.
            """
            self.errors.append((line_number, text.split(" ", 1)[1]))

        def check_all(self, *args, **kwargs):
            """
            Assign the errors attribute and return it after running.
            """
            self.errors = []
            super(Checker, self).check_all(*args, **kwargs)
            return self.errors

    def pep8_checker(path):
        for line_number, text in Checker(path, max_line_length=121).check_all():
            yield "%s:%s: %s" % (path, line_number, text)

    args = (pep8_checker, package_name, extra_ignore)
    return _run_checker_for_package(*args)

@@ -111,16 +111,32 @@
 package%0A
+import settings%0A
 %0A%0Aclass 
@@ -309,81 +309,33 @@
 s = 
-%5B'common', 'comps', 'discuss', 'rets', 'manticore_tastypie_urbanairship'%5D
+settings.PACKAGES_TO_TEST
 %0A   

Fix to test only specified packages