Commit e2ae8b04 authored by Ray Ashman Jr's avatar Ray Ashman Jr
Browse files

Correct flake8 E302 violations

parent 3bc0d46a
Loading
Loading
Loading
Loading
+38 −1
Original line number Diff line number Diff line
@@ -144,6 +144,8 @@ if sys.platform.startswith('java'):
# Option constants.

OPTIONFLAGS_BY_NAME = {}


def register_optionflag(name):
    # Create a new flag unless `name` is already known.
    return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
@@ -194,6 +196,7 @@ ELLIPSIS_MARKER = '...'
## 1. Utility Functions
######################################################################


def _extract_future_flags(globs):
    """
    Return the compiler-flags associated with the future features that
@@ -206,6 +209,7 @@ def _extract_future_flags(globs):
            flags |= feature.compiler_flag
    return flags


def _normalize_module(module, depth=2):
    """
    Return the module specified by `module`.  In particular:
@@ -225,6 +229,7 @@ def _normalize_module(module, depth=2):
    else:
        raise TypeError("Expected a module, string, or None")


def _load_testfile(filename, package, module_relative):
    if module_relative:
        package = _normalize_module(package, 3)
@@ -238,6 +243,7 @@ def _load_testfile(filename, package, module_relative):
    with open(filename) as fp:
        return fp.read(), filename


def _indent(s, indent=4):
    """
    Add the given number of space characters to the beginning every
@@ -246,6 +252,7 @@ def _indent(s, indent=4):
    # This regexp matches the start of non-blank lines:
    return re.sub('(?m)^(?!$)', indent*' ', s)


def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
@@ -257,6 +264,7 @@ def _exception_traceback(exc_info):
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()


# Override some StringIO methods.
class _SpoofOut(StringIO):
    def getvalue(self):
@@ -277,6 +285,7 @@ class _SpoofOut(StringIO):
        if hasattr(self, "softspace"):
            del self.softspace


# Worst-case linear-time ellipsis matching.
def _ellipsis_match(want, got):
    """
@@ -327,6 +336,7 @@ def _ellipsis_match(want, got):

    return True


def _comment_line(line):
    "Return a commented form of the given line"
    line = line.rstrip()
@@ -335,6 +345,7 @@ def _comment_line(line):
    else:
        return '#'


class _OutputRedirectingPdb(pdb.Pdb):
    """
    A specialized version of the python debugger that redirects stdout
@@ -368,6 +379,7 @@ class _OutputRedirectingPdb(pdb.Pdb):
        finally:
            sys.stdout = save_stdout


# [XX] Normalize with respect to os.path.pardir?
def _module_relative_path(module, path):
    if not inspect.ismodule(module):
@@ -405,6 +417,7 @@ def _module_relative_path(module, path):
##   a string (such as an object's docstring).  The DocTest class also
##   includes information about where the string was extracted from.


class Example:
    """
    A single doctest example, consisting of source code and expected
@@ -458,6 +471,7 @@ class Example:
        self.options = options
        self.exc_msg = exc_msg


class DocTest:
    """
    A collection of doctest examples that should be run in a single
@@ -506,10 +520,10 @@ class DocTest:
        return ('<DocTest %s from %s:%s (%s)>' %
                (self.name, self.filename, self.lineno, examples))


    # This lets us sort tests by name:
    def _cmpkey(self):
        return (self.name, self.filename, self.lineno, id(self))

    def __cmp__(self, other):
        if not isinstance(other, DocTest):
            return -1
@@ -1054,6 +1068,7 @@ class DocTestFinder:
## 5. DocTest Runner
######################################################################


class DocTestRunner:
    """
    A class used to run DocTest test cases, and accumulate statistics.
@@ -1408,6 +1423,7 @@ class DocTestRunner:
    __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
                                         r'(?P<name>[\w\.]+)'
                                         r'\[(?P<examplenum>\d+)\]>$')

    def __patched_linecache_getlines(self, filename, module_globals=None):
        m = self.__LINECACHE_FILENAME_RE.match(filename)
        if m and m.group('name') == self.test.name:
@@ -1541,6 +1557,7 @@ class DocTestRunner:
                t = t + t2
            d[name] = f, t


class OutputChecker:
    """
    A class used to check the whether the actual output from a doctest
@@ -1674,6 +1691,7 @@ class OutputChecker:
        else:
            return 'Expected nothing\nGot nothing\n'


class DocTestFailure(Exception):
    """A DocTest example has failed in debugging mode.

@@ -1693,6 +1711,7 @@ class DocTestFailure(Exception):
    def __str__(self):
        return str(self.test)


class UnexpectedException(Exception):
    """A DocTest example has encountered an unexpected exception

@@ -1712,6 +1731,7 @@ class UnexpectedException(Exception):
    def __str__(self):
        return str(self.test)


class DebugRunner(DocTestRunner):
    r"""Run doc tests but raise an exception as soon as there is a failure.

@@ -1824,6 +1844,7 @@ class DebugRunner(DocTestRunner):
# class, updated by testmod.
master = None


def testmod(m=None, name=None, globs=None, verbose=None,
            report=True, optionflags=0, extraglobs=None,
            raise_on_error=False, exclude_empty=False):
@@ -1928,6 +1949,7 @@ def testmod(m=None, name=None, globs=None, verbose=None,

    return runner.failures, runner.tries


def testfile(filename, module_relative=True, name=None, package=None,
             globs=None, verbose=None, report=True, optionflags=0,
             extraglobs=None, raise_on_error=False, parser=DocTestParser(),
@@ -2051,6 +2073,7 @@ def testfile(filename, module_relative=True, name=None, package=None,

    return runner.failures, runner.tries


def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
@@ -2080,6 +2103,7 @@ def run_docstring_examples(f, globs, verbose=False, name="NoName",
# This is provided only for backwards compatibility.  It's not
# actually used in any way.


class Tester:
    def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):

@@ -2145,6 +2169,7 @@ class Tester:

_unittest_reportflags = 0


def set_unittest_reportflags(flags):
    """Sets the unittest option flags.

@@ -2328,6 +2353,7 @@ class DocTestCase(unittest.TestCase):
    def shortDescription(self):
        return "Doctest: " + self._dt_test.name


def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
                 test_class=DocTestCase, **options):
    """
@@ -2391,6 +2417,7 @@ def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,

    return suite


class DocFileCase(DocTestCase):

    def id(self):
@@ -2405,6 +2432,7 @@ class DocFileCase(DocTestCase):
                % (self._dt_test.name, self._dt_test.filename, err)
                )


def DocFileTest(path, module_relative=True, package=None,
                globs=None, parser=DocTestParser(),
                encoding=None, **options):
@@ -2434,6 +2462,7 @@ def DocFileTest(path, module_relative=True, package=None,
    test = parser.get_doctest(doc, globs, name, path, 0)
    return DocFileCase(test, **options)


def DocFileSuite(*paths, **kw):
    """A unittest suite for one or more doctest files.

@@ -2507,6 +2536,7 @@ def DocFileSuite(*paths, **kw):
## 9. Debugging Support
######################################################################


def script_from_examples(s):
    r"""Extract script from text with examples.

@@ -2587,6 +2617,7 @@ def script_from_examples(s):
    # Combine the output, and return it.
    return '\n'.join(output)


def testsource(module, name):
    """Extract the test sources from a doctest docstring as a script.

@@ -2603,11 +2634,13 @@ def testsource(module, name):
    testsrc = script_from_examples(test.docstring)
    return testsrc


def debug_src(src, pm=False, globs=None):
    """Debug a single doctest docstring, in argument `src`'"""
    testsrc = script_from_examples(src)
    debug_script(testsrc, pm, globs)


def debug_script(src, pm=False, globs=None):
    "Debug a test script.  `src` is the script, as a string."
    import pdb
@@ -2639,6 +2672,7 @@ def debug_script(src, pm=False, globs=None):
    finally:
        os.remove(srcfilename)


def debug(module, name, pm=False):
    """Debug a single doctest docstring.

@@ -2653,6 +2687,8 @@ def debug(module, name, pm=False):
######################################################################
## 10. Example Usage
######################################################################


class _TestClass:
    """
    A pointless class, for sanity-checking of docstring testing.
@@ -2747,6 +2783,7 @@ __test__ = {"_TestClass": _TestClass,
            """,
           }


def _test():
    r = unittest.TextTestRunner()
    r.run(DocTestSuite())
+3 −0
Original line number Diff line number Diff line
@@ -61,9 +61,11 @@ real_enter_transaction_management = transaction.enter_transaction_management
real_leave_transaction_management = transaction.leave_transaction_management
real_abort = transaction.abort


def nop(*args, **kwargs):
    return


def disable_transaction_methods():
    transaction.commit = nop
    transaction.rollback = nop
@@ -71,6 +73,7 @@ def disable_transaction_methods():
    transaction.leave_transaction_management = nop
    transaction.abort = nop


def restore_transaction_methods():
    transaction.commit = real_commit
    transaction.rollback = real_rollback
+1 −0
Original line number Diff line number Diff line
@@ -53,6 +53,7 @@ def npath(path):
        return path.encode(fs_encoding)
    return path


def safe_join(base, *paths):
    """
    Joins one or more path components to the base path component intelligently.
+8 −0
Original line number Diff line number Diff line
@@ -119,6 +119,7 @@ def gen_filenames():
        if os.path.exists(filename):
            yield filename


def inotify_code_changed():
    """
    Checks for changed code using inotify. After being called
@@ -149,6 +150,7 @@ def inotify_code_changed():
    # If we are here the code must have changed.
    return True


def kqueue_code_changed():
    """
    Checks for changed code using kqueue. After being called
@@ -193,6 +195,7 @@ def kqueue_code_changed():

    return True


def code_changed():
    global _mtimes, _win
    for filename in gen_filenames():
@@ -212,6 +215,7 @@ def code_changed():
            return True
    return False


def check_errors(fn):
    def wrapper(*args, **kwargs):
        try:
@@ -233,6 +237,7 @@ def check_errors(fn):

    return wrapper


def ensure_echo_on():
    if termios:
        fd = sys.stdin
@@ -248,6 +253,7 @@ def ensure_echo_on():
                if old_handler is not None:
                    signal.signal(signal.SIGTTOU, old_handler)


def reloader_thread():
    ensure_echo_on()
    if USE_INOTIFY:
@@ -273,6 +279,7 @@ def restart_with_reloader():
        if exit_code != 3:
            return exit_code


def python_reloader(main_func, args, kwargs):
    if os.environ.get("RUN_MAIN") == "true":
        thread.start_new_thread(main_func, args, kwargs)
@@ -290,6 +297,7 @@ def python_reloader(main_func, args, kwargs):
        except KeyboardInterrupt:
            pass


def jython_reloader(main_func, args, kwargs):
    from _systemrestart import SystemRestart
    thread.start_new_thread(main_func, args)
+12 −0
Original line number Diff line number Diff line
@@ -31,6 +31,7 @@ from django.utils.translation import get_language

cc_delim_re = re.compile(r'\s*,\s*')


def patch_cache_control(response, **kwargs):
    """
    This function patches the Cache-Control header by adding all
@@ -79,6 +80,7 @@ def patch_cache_control(response, **kwargs):
    cc = ', '.join(dictvalue(el) for el in cc.items())
    response['Cache-Control'] = cc


def get_max_age(response):
    """
    Returns the max-age from the response Cache-Control header as an integer
@@ -94,11 +96,13 @@ def get_max_age(response):
        except (ValueError, TypeError):
            pass


def _set_response_etag(response):
    if not response.streaming:
        response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
    return response


def patch_response_headers(response, cache_timeout=None):
    """
    Adds some useful headers to the given HttpResponse object:
@@ -124,12 +128,14 @@ def patch_response_headers(response, cache_timeout=None):
        response['Expires'] = http_date(time.time() + cache_timeout)
    patch_cache_control(response, max_age=cache_timeout)


def add_never_cache_headers(response):
    """
    Adds headers to a response to indicate that a page should never be cached.
    """
    patch_response_headers(response, cache_timeout=-1)


def patch_vary_headers(response, newheaders):
    """
    Adds (or updates) the "Vary" header in the given HttpResponse object.
@@ -149,6 +155,7 @@ def patch_vary_headers(response, newheaders):
                          if newheader.lower() not in existing_headers]
    response['Vary'] = ', '.join(vary_headers + additional_headers)


def has_vary_header(response, header_query):
    """
    Checks to see if the response has a given header name in its Vary header.
@@ -159,6 +166,7 @@ def has_vary_header(response, header_query):
    existing_headers = set(header.lower() for header in vary_headers)
    return header_query.lower() in existing_headers


def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
@@ -175,6 +183,7 @@ def _i18n_cache_key_suffix(request, cache_key):
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key


def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
@@ -187,6 +196,7 @@ def _generate_cache_key(request, method, headerlist, key_prefix):
        key_prefix, method, path.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)


def _generate_cache_header_key(key_prefix, request):
    """Returns a cache key for the header cache."""
    path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
@@ -194,6 +204,7 @@ def _generate_cache_header_key(key_prefix, request):
        key_prefix, path.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)


def get_cache_key(request, key_prefix=None, method='GET', cache=None):
    """
    Returns a cache key based on the request path and query. It can be used
@@ -215,6 +226,7 @@ def get_cache_key(request, key_prefix=None, method='GET', cache=None):
    else:
        return None


def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
    """
    Learns what headers to take into account for some request path from the
Loading