././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/0000755000175100001770000000000014635727603012704 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/AUTHORS.rst0000644000175100001770000000372314635727563014575 0ustar00runnerdockerMain contributors ----------------- - Hideo Hattori (https://github.com/hhatto) - Steven Myint (https://github.com/myint) - Bill Wendling (https://github.com/gwelymernans) Patches ------- - Fraser Tweedale (https://github.com/frasertweedale) - clach04 (https://github.com/clach04) - Marc Abramowitz (https://github.com/msabramo) - dellis23 (https://github.com/dellis23) - Sam Vilain (https://github.com/samv) - Florent Xicluna (https://github.com/florentx) - Andras Tim (https://github.com/andras-tim) - tomscytale (https://github.com/tomscytale) - Filip Noetzel (https://github.com/peritus) - Erik Bray (https://github.com/iguananaut) - Christopher Medrela (https://github.com/chrismedrela) - 小明 (https://github.com/dongweiming) - Andy Hayden (https://github.com/hayd) - Fabio Zadrozny (https://github.com/fabioz) - Alex Chernetz (https://github.com/achernet) - Marc Schlaich (https://github.com/schlamar) - E. M. Bray (https://github.com/embray) - Thomas Hisch (https://github.com/thisch) - Florian Best (https://github.com/spaceone) - Ian Clark (https://github.com/evenicoulddoit) - Khairi Hafsham (https://github.com/khairihafsham) - Neil Halelamien (https://github.com/neilsh) - Hashem Nasarat (https://github.com/Hnasar) - Hugo van Kemenade (https://github.com/hugovk) - gmbnomis (https://github.com/gmbnomis) - Samuel Lelièvre (https://github.com/slel) - bigredengineer (https://github.com/bigredengineer) - Kai Chen (https://github.com/kx-chen) - Anthony Sottile (https://github.com/asottile) - 秋葉 (https://github.com/Hanaasagi) - Christian Clauss (https://github.com/cclauss) - tobixx (https://github.com/tobixx) - bigredengineer (https://github.com/bigredengineer) - Bastien Gérard (https://github.com/bagerard) - nicolasbonifas (https://github.com/nicolasbonifas) - Andrii Yurchuk (https://github.com/Ch00k) - José M. Guisado (https://github.com/pvxe) - Dai Truong (https://github.com/NovaDev94) - jnozsc (https://github.com/jnozsc) - Edwin Shepherd (https://github.com/shardros) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/LICENSE0000644000175100001770000000223514635727563013720 0ustar00runnerdockerCopyright (C) 2010-2011 Hideo Hattori Copyright (C) 2011-2013 Hideo Hattori, Steven Myint Copyright (C) 2013-2016 Hideo Hattori, Steven Myint, Bill Wendling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/MANIFEST.in0000644000175100001770000000134114635727563014446 0ustar00runnerdockerinclude AUTHORS.rst include LICENSE include README.rst include test/__init__.py include test/acid.py include test/bad_encoding.py include test/bad_encoding2.py include test/e101_example.py include test/example include test/example/x.py include test/example.py include test/iso_8859_1.py include test/fake_configuration/.pep8 include test/fake_pycodestyle_configuration/tox.ini include tox.ini recursive-exclude test/suite *.py recursive-exclude test/suite/out *.py exclude .travis.yml exclude CONTRIBUTING.rst exclude Makefile exclude hooks exclude hooks/pre-push exclude install_hooks.bash exclude test/.gitignore exclude test/acid_pypi.py exclude test/suite exclude test/suite/out exclude test/vim_autopep8.py exclude update_readme.py ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/PKG-INFO0000644000175100001770000004110614635727603014003 0ustar00runnerdockerMetadata-Version: 2.1 Name: autopep8 Version: 2.3.1 Summary: A tool that automatically formats Python code to conform to the PEP 8 style guide Author-email: Hideo Hattori Project-URL: Repository, https://github.com/hhatto/autopep8 Keywords: automation,pep8,format,pycodestyle Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Quality Assurance Requires-Python: >=3.8 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS.rst Requires-Dist: pycodestyle>=2.12.0 Requires-Dist: tomli; python_version < "3.11" ======== autopep8 ======== .. image:: https://img.shields.io/pypi/v/autopep8.svg :target: https://pypi.org/project/autopep8/ :alt: PyPI Version .. image:: https://github.com/hhatto/autopep8/workflows/Python%20package/badge.svg :target: https://github.com/hhatto/autopep8/actions :alt: Build status .. image:: https://codecov.io/gh/hhatto/autopep8/branch/main/graph/badge.svg :target: https://codecov.io/gh/hhatto/autopep8 :alt: Code Coverage autopep8 automatically formats Python code to conform to the `PEP 8`_ style guide. It uses the pycodestyle_ utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues_ that can be reported by pycodestyle. .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _issues: https://pycodestyle.readthedocs.org/en/latest/intro.html#error-codes .. contents:: Installation ============ From pip:: $ pip install --upgrade autopep8 Consider using the ``--user`` option_. .. _option: https://pip.pypa.io/en/latest/user_guide/#user-installs Requirements ============ autopep8 requires pycodestyle_. .. _pycodestyle: https://github.com/PyCQA/pycodestyle Usage ===== To modify a file in place (with aggressive level 2):: $ autopep8 --in-place --aggressive --aggressive Before running autopep8. .. code-block:: python import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): #Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) After running autopep8. .. code-block:: python import math import sys def example1(): # This is a long comment. This should be wrapped to fit within 72 # characters. some_tuple = (1, 2, 3, 'a') some_variable = { 'long': 'Long code lines should be wrapped within 79 characters.', 'other': [ math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'], 'more': { 'inner': 'This whole logical line should be wrapped.', some_tuple: [ 1, 20, 300, 40000, 500000000, 60000000000000000]}} return (some_tuple, some_variable) def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True} class Example3(object): def __init__(self, bar): # Comments should have a space after the hash. if bar: bar += 1 bar = bar * bar return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) Options:: usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename] [--ignore-local-config] [-r] [-j n] [-p n] [-a] [--experimental] [--exclude globs] [--list-fixes] [--ignore errors] [--select errors] [--max-line-length n] [--line-range line line] [--hang-closing] [--exit-code] [files [files ...]] Automatically formats Python code to conform to the PEP 8 style guide. positional arguments: files files to format or '-' for standard in optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v, --verbose print verbose messages; multiple -v result in more verbose messages -d, --diff print the diff for the fixed source -i, --in-place make changes to files in place --global-config filename path to a global pep8 config file; if this file does not exist then this is ignored (default: ~/.config/pep8) --ignore-local-config don't look for and apply local config files; if not passed, defaults are updated with any config files in the project's root directory -r, --recursive run recursively over directories; must be used with --in-place or --diff -j n, --jobs n number of parallel jobs; match CPU count if value is less than 1 -p n, --pep8-passes n maximum number of additional pep8 passes (default: infinite) -a, --aggressive enable non-whitespace changes; multiple -a result in more aggressive changes --experimental enable experimental fixes --exclude globs exclude file/directory names that match these comma- separated globs --list-fixes list codes for fixes; used by --ignore and --select --ignore errors do not fix these errors/warnings (default: E226,E24,W50,W690) --select errors fix only these errors/warnings (e.g. E4,W) --max-line-length n set maximum allowed line length (default: 79) --line-range line line, --range line line only fix errors found within this inclusive range of line numbers (e.g. 1 99); line numbers are indexed at 1 --hang-closing hang-closing option passed to pycodestyle --exit-code change to behavior of exit code. default behavior of return value, 0 is no differences, 1 is error exit. return 2 when add this option. 2 is exists differences. Features ======== autopep8 fixes the following issues_ reported by pycodestyle_:: E101 - Reindent all lines. E11 - Fix indentation. E121 - Fix indentation to be a multiple of four. E122 - Add absent indentation for hanging indentation. E123 - Align closing bracket to match opening bracket. E124 - Align closing bracket to match visual indentation. E125 - Indent to distinguish line from next logical line. E126 - Fix over-indented hanging indentation. E127 - Fix visual indentation. E128 - Fix visual indentation. E129 - Fix visual indentation. E131 - Fix hanging indent for unaligned continuation line. E133 - Fix missing indentation for closing bracket. E20 - Remove extraneous whitespace. E211 - Remove extraneous whitespace. E22 - Fix extraneous whitespace around keywords. E224 - Remove extraneous whitespace around operator. E225 - Fix missing whitespace around operator. E226 - Fix missing whitespace around arithmetic operator. E227 - Fix missing whitespace around bitwise/shift operator. E228 - Fix missing whitespace around modulo operator. E231 - Add missing whitespace. E241 - Fix extraneous whitespace around keywords. E242 - Remove extraneous whitespace around operator. E251 - Remove whitespace around parameter '=' sign. E252 - Missing whitespace around parameter equals. E26 - Fix spacing after comment hash for inline comments. E265 - Fix spacing after comment hash for block comments. E266 - Fix too many leading '#' for block comments. E27 - Fix extraneous whitespace around keywords. E301 - Add missing blank line. E302 - Add missing 2 blank lines. E303 - Remove extra blank lines. E304 - Remove blank line following function decorator. E305 - Expected 2 blank lines after end of function or class. E306 - Expected 1 blank line before a nested definition. E401 - Put imports on separate lines. E402 - Fix module level import not at top of file E501 - Try to make lines fit within --max-line-length characters. E502 - Remove extraneous escape of newline. E701 - Put colon-separated compound statement on separate lines. E70 - Put semicolon-separated compound statement on separate lines. E711 - Fix comparison with None. E712 - Fix comparison with boolean. E713 - Use 'not in' for test for membership. E714 - Use 'is not' test for object identity. E721 - Use "isinstance()" instead of comparing types directly. E722 - Fix bare except. E731 - Use a def when use do not assign a lambda expression. W291 - Remove trailing whitespace. W292 - Add a single newline at the end of the file. W293 - Remove trailing whitespace on blank line. W391 - Remove trailing blank lines. W503 - Fix line break before binary operator. W504 - Fix line break after binary operator. W605 - Fix invalid escape sequence 'x'. autopep8 also fixes some issues not found by pycodestyle_. - Normalize files with mixed line endings. - Put a blank line between a class docstring and its first method declaration. (Enabled with ``E301``.) - Remove blank lines between a function declaration and its docstring. (Enabled with ``E303``.) autopep8 avoids fixing some issues found by pycodestyle_. - ``E112``/``E113`` for non comments are reports of bad indentation that break syntax rules. These should not be modified at all. - ``E265``, which refers to spacing after comment hash, is ignored if the comment looks like code. autopep8 avoids modifying these since they are not real comments. If you really want to get rid of the pycodestyle_ warning, consider just removing the commented-out code. (This can be automated via eradicate_.) .. _eradicate: https://github.com/myint/eradicate More advanced usage =================== By default autopep8 only makes whitespace changes. Thus, by default, it does not fix ``E711`` and ``E712``. (Changing ``x == None`` to ``x is None`` may change the meaning of the program if ``x`` has its ``__eq__`` method overridden.) Nor does it correct deprecated code ``W6``. To enable these more aggressive fixes, use the ``--aggressive`` option:: $ autopep8 --aggressive Use multiple ``--aggressive`` to increase the aggressiveness level. For example, ``E712`` requires aggressiveness level 2 (since ``x == True`` could be changed to either ``x`` or ``x is True``, but autopep8 chooses the former). ``--aggressive`` will also shorten lines more aggressively. It will also remove trailing whitespace more aggressively. (Usually, we don't touch trailing whitespace in docstrings and other multiline strings. And to do even more aggressive changes to docstrings, use docformatter_.) .. _docformatter: https://github.com/myint/docformatter To enable only a subset of the fixes, use the ``--select`` option. For example, to fix various types of indentation issues:: $ autopep8 --select=E1,W1 If the file being fixed is large, you may want to enable verbose progress messages:: $ autopep8 -v Passing in ``--experimental`` enables the following functionality: - Shortens code lines by taking its length into account :: $ autopep8 --experimental Disabling line-by-line ---------------------- It is possible to disable autopep8 untill it it turned back on again in the file, using ``autopep8: off`` and then renabling ``autopep8: on``. .. code-block:: python # autopep8: off [ [23, 23, 13, 43], [32, 34, 34, 34], [56, 34, 34, 11], [10, 10, 10, 10], ] # autopep8: on ``fmt: off`` and ``fmt: on`` are also valid. Use as a module =============== The simplest way of using autopep8 as a module is via the ``fix_code()`` function: >>> import autopep8 >>> autopep8.fix_code('x= 123\n') 'x = 123\n' Or with options: >>> import autopep8 >>> autopep8.fix_code('print( 123 )\n', ... options={'ignore': ['E']}) 'print( 123 )\n' Configuration ============= By default, if ``$HOME/.config/pycodestyle`` (``~\.pycodestyle`` in Windows environment) exists, it will be used as global configuration file. Alternatively, you can specify the global configuration file with the ``--global-config`` option. Also, if ``setup.cfg``, ``tox.ini``, ``.pep8`` and ``.flake8`` files exist in the directory where the target file exists, it will be used as the configuration file. ``pep8``, ``pycodestyle``, and ``flake8`` can be used as a section. configuration file example:: [pycodestyle] max_line_length = 120 ignore = E501 pyproject.toml -------------- autopep8 can also use ``pyproject.toml``. The section must be ``[tool.autopep8]``, and ``pyproject.toml`` takes precedence over any other configuration files. configuration file example:: [tool.autopep8] max_line_length = 120 ignore = "E501,W6" # or ["E501", "W6"] in-place = true recursive = true aggressive = 3 Usage with pre-commit ===================== autopep8 can be used as a hook for pre-commit_. To add autopep8 as a plugin, add this repo definition to your configuration: .. code-block:: yaml repos: - repo: https://github.com/hhatto/autopep8 rev: ... # select the tag or revision you want, or run `pre-commit autoupdate` hooks: - id: autopep8 .. _`pre-commit`: https://pre-commit.com Testing ======= Test cases are in ``test/test_autopep8.py``. They can be run directly via ``python test/test_autopep8.py`` or via tox_. The latter is useful for testing against multiple Python interpreters. (We currently test against CPython versions 3.8, 3.9, 3.10, 3.11 and 3.12. We also test against PyPy.) .. _`tox`: https://pypi.org/project/tox/ Broad spectrum testing is available via ``test/acid.py``. This script runs autopep8 against Python code and checks for correctness and completeness of the code fixes. It can check that the bytecode remains identical. ``test/acid_pypi.py`` makes use of ``acid.py`` to test against the latest released packages on PyPI. Troubleshooting =============== ``pkg_resources.DistributionNotFound`` -------------------------------------- If you are using an ancient version of ``setuptools``, you might encounter ``pkg_resources.DistributionNotFound`` when trying to run ``autopep8``. Try upgrading ``setuptools`` to workaround this ``setuptools`` problem:: $ pip install --upgrade setuptools Use ``sudo`` if you are installing to the system. Links ===== * PyPI_ * GitHub_ * `Travis CI`_ * Codecov_ .. _PyPI: https://pypi.org/project/autopep8/ .. _GitHub: https://github.com/hhatto/autopep8 .. _`Travis CI`: https://travis-ci.org/hhatto/autopep8 .. _`Codecov`: https://app.codecov.io/gh/hhatto/autopep8 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/README.rst0000644000175100001770000003662514635727563014414 0ustar00runnerdocker======== autopep8 ======== .. image:: https://img.shields.io/pypi/v/autopep8.svg :target: https://pypi.org/project/autopep8/ :alt: PyPI Version .. image:: https://github.com/hhatto/autopep8/workflows/Python%20package/badge.svg :target: https://github.com/hhatto/autopep8/actions :alt: Build status .. image:: https://codecov.io/gh/hhatto/autopep8/branch/main/graph/badge.svg :target: https://codecov.io/gh/hhatto/autopep8 :alt: Code Coverage autopep8 automatically formats Python code to conform to the `PEP 8`_ style guide. It uses the pycodestyle_ utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues_ that can be reported by pycodestyle. .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _issues: https://pycodestyle.readthedocs.org/en/latest/intro.html#error-codes .. contents:: Installation ============ From pip:: $ pip install --upgrade autopep8 Consider using the ``--user`` option_. .. _option: https://pip.pypa.io/en/latest/user_guide/#user-installs Requirements ============ autopep8 requires pycodestyle_. .. _pycodestyle: https://github.com/PyCQA/pycodestyle Usage ===== To modify a file in place (with aggressive level 2):: $ autopep8 --in-place --aggressive --aggressive Before running autopep8. .. code-block:: python import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): #Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) After running autopep8. .. code-block:: python import math import sys def example1(): # This is a long comment. This should be wrapped to fit within 72 # characters. some_tuple = (1, 2, 3, 'a') some_variable = { 'long': 'Long code lines should be wrapped within 79 characters.', 'other': [ math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'], 'more': { 'inner': 'This whole logical line should be wrapped.', some_tuple: [ 1, 20, 300, 40000, 500000000, 60000000000000000]}} return (some_tuple, some_variable) def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True} class Example3(object): def __init__(self, bar): # Comments should have a space after the hash. if bar: bar += 1 bar = bar * bar return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) Options:: usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename] [--ignore-local-config] [-r] [-j n] [-p n] [-a] [--experimental] [--exclude globs] [--list-fixes] [--ignore errors] [--select errors] [--max-line-length n] [--line-range line line] [--hang-closing] [--exit-code] [files [files ...]] Automatically formats Python code to conform to the PEP 8 style guide. positional arguments: files files to format or '-' for standard in optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v, --verbose print verbose messages; multiple -v result in more verbose messages -d, --diff print the diff for the fixed source -i, --in-place make changes to files in place --global-config filename path to a global pep8 config file; if this file does not exist then this is ignored (default: ~/.config/pep8) --ignore-local-config don't look for and apply local config files; if not passed, defaults are updated with any config files in the project's root directory -r, --recursive run recursively over directories; must be used with --in-place or --diff -j n, --jobs n number of parallel jobs; match CPU count if value is less than 1 -p n, --pep8-passes n maximum number of additional pep8 passes (default: infinite) -a, --aggressive enable non-whitespace changes; multiple -a result in more aggressive changes --experimental enable experimental fixes --exclude globs exclude file/directory names that match these comma- separated globs --list-fixes list codes for fixes; used by --ignore and --select --ignore errors do not fix these errors/warnings (default: E226,E24,W50,W690) --select errors fix only these errors/warnings (e.g. E4,W) --max-line-length n set maximum allowed line length (default: 79) --line-range line line, --range line line only fix errors found within this inclusive range of line numbers (e.g. 1 99); line numbers are indexed at 1 --hang-closing hang-closing option passed to pycodestyle --exit-code change to behavior of exit code. default behavior of return value, 0 is no differences, 1 is error exit. return 2 when add this option. 2 is exists differences. Features ======== autopep8 fixes the following issues_ reported by pycodestyle_:: E101 - Reindent all lines. E11 - Fix indentation. E121 - Fix indentation to be a multiple of four. E122 - Add absent indentation for hanging indentation. E123 - Align closing bracket to match opening bracket. E124 - Align closing bracket to match visual indentation. E125 - Indent to distinguish line from next logical line. E126 - Fix over-indented hanging indentation. E127 - Fix visual indentation. E128 - Fix visual indentation. E129 - Fix visual indentation. E131 - Fix hanging indent for unaligned continuation line. E133 - Fix missing indentation for closing bracket. E20 - Remove extraneous whitespace. E211 - Remove extraneous whitespace. E22 - Fix extraneous whitespace around keywords. E224 - Remove extraneous whitespace around operator. E225 - Fix missing whitespace around operator. E226 - Fix missing whitespace around arithmetic operator. E227 - Fix missing whitespace around bitwise/shift operator. E228 - Fix missing whitespace around modulo operator. E231 - Add missing whitespace. E241 - Fix extraneous whitespace around keywords. E242 - Remove extraneous whitespace around operator. E251 - Remove whitespace around parameter '=' sign. E252 - Missing whitespace around parameter equals. E26 - Fix spacing after comment hash for inline comments. E265 - Fix spacing after comment hash for block comments. E266 - Fix too many leading '#' for block comments. E27 - Fix extraneous whitespace around keywords. E301 - Add missing blank line. E302 - Add missing 2 blank lines. E303 - Remove extra blank lines. E304 - Remove blank line following function decorator. E305 - Expected 2 blank lines after end of function or class. E306 - Expected 1 blank line before a nested definition. E401 - Put imports on separate lines. E402 - Fix module level import not at top of file E501 - Try to make lines fit within --max-line-length characters. E502 - Remove extraneous escape of newline. E701 - Put colon-separated compound statement on separate lines. E70 - Put semicolon-separated compound statement on separate lines. E711 - Fix comparison with None. E712 - Fix comparison with boolean. E713 - Use 'not in' for test for membership. E714 - Use 'is not' test for object identity. E721 - Use "isinstance()" instead of comparing types directly. E722 - Fix bare except. E731 - Use a def when use do not assign a lambda expression. W291 - Remove trailing whitespace. W292 - Add a single newline at the end of the file. W293 - Remove trailing whitespace on blank line. W391 - Remove trailing blank lines. W503 - Fix line break before binary operator. W504 - Fix line break after binary operator. W605 - Fix invalid escape sequence 'x'. autopep8 also fixes some issues not found by pycodestyle_. - Normalize files with mixed line endings. - Put a blank line between a class docstring and its first method declaration. (Enabled with ``E301``.) - Remove blank lines between a function declaration and its docstring. (Enabled with ``E303``.) autopep8 avoids fixing some issues found by pycodestyle_. - ``E112``/``E113`` for non comments are reports of bad indentation that break syntax rules. These should not be modified at all. - ``E265``, which refers to spacing after comment hash, is ignored if the comment looks like code. autopep8 avoids modifying these since they are not real comments. If you really want to get rid of the pycodestyle_ warning, consider just removing the commented-out code. (This can be automated via eradicate_.) .. _eradicate: https://github.com/myint/eradicate More advanced usage =================== By default autopep8 only makes whitespace changes. Thus, by default, it does not fix ``E711`` and ``E712``. (Changing ``x == None`` to ``x is None`` may change the meaning of the program if ``x`` has its ``__eq__`` method overridden.) Nor does it correct deprecated code ``W6``. To enable these more aggressive fixes, use the ``--aggressive`` option:: $ autopep8 --aggressive Use multiple ``--aggressive`` to increase the aggressiveness level. For example, ``E712`` requires aggressiveness level 2 (since ``x == True`` could be changed to either ``x`` or ``x is True``, but autopep8 chooses the former). ``--aggressive`` will also shorten lines more aggressively. It will also remove trailing whitespace more aggressively. (Usually, we don't touch trailing whitespace in docstrings and other multiline strings. And to do even more aggressive changes to docstrings, use docformatter_.) .. _docformatter: https://github.com/myint/docformatter To enable only a subset of the fixes, use the ``--select`` option. For example, to fix various types of indentation issues:: $ autopep8 --select=E1,W1 If the file being fixed is large, you may want to enable verbose progress messages:: $ autopep8 -v Passing in ``--experimental`` enables the following functionality: - Shortens code lines by taking its length into account :: $ autopep8 --experimental Disabling line-by-line ---------------------- It is possible to disable autopep8 untill it it turned back on again in the file, using ``autopep8: off`` and then renabling ``autopep8: on``. .. code-block:: python # autopep8: off [ [23, 23, 13, 43], [32, 34, 34, 34], [56, 34, 34, 11], [10, 10, 10, 10], ] # autopep8: on ``fmt: off`` and ``fmt: on`` are also valid. Use as a module =============== The simplest way of using autopep8 as a module is via the ``fix_code()`` function: >>> import autopep8 >>> autopep8.fix_code('x= 123\n') 'x = 123\n' Or with options: >>> import autopep8 >>> autopep8.fix_code('print( 123 )\n', ... options={'ignore': ['E']}) 'print( 123 )\n' Configuration ============= By default, if ``$HOME/.config/pycodestyle`` (``~\.pycodestyle`` in Windows environment) exists, it will be used as global configuration file. Alternatively, you can specify the global configuration file with the ``--global-config`` option. Also, if ``setup.cfg``, ``tox.ini``, ``.pep8`` and ``.flake8`` files exist in the directory where the target file exists, it will be used as the configuration file. ``pep8``, ``pycodestyle``, and ``flake8`` can be used as a section. configuration file example:: [pycodestyle] max_line_length = 120 ignore = E501 pyproject.toml -------------- autopep8 can also use ``pyproject.toml``. The section must be ``[tool.autopep8]``, and ``pyproject.toml`` takes precedence over any other configuration files. configuration file example:: [tool.autopep8] max_line_length = 120 ignore = "E501,W6" # or ["E501", "W6"] in-place = true recursive = true aggressive = 3 Usage with pre-commit ===================== autopep8 can be used as a hook for pre-commit_. To add autopep8 as a plugin, add this repo definition to your configuration: .. code-block:: yaml repos: - repo: https://github.com/hhatto/autopep8 rev: ... # select the tag or revision you want, or run `pre-commit autoupdate` hooks: - id: autopep8 .. _`pre-commit`: https://pre-commit.com Testing ======= Test cases are in ``test/test_autopep8.py``. They can be run directly via ``python test/test_autopep8.py`` or via tox_. The latter is useful for testing against multiple Python interpreters. (We currently test against CPython versions 3.8, 3.9, 3.10, 3.11 and 3.12. We also test against PyPy.) .. _`tox`: https://pypi.org/project/tox/ Broad spectrum testing is available via ``test/acid.py``. This script runs autopep8 against Python code and checks for correctness and completeness of the code fixes. It can check that the bytecode remains identical. ``test/acid_pypi.py`` makes use of ``acid.py`` to test against the latest released packages on PyPI. Troubleshooting =============== ``pkg_resources.DistributionNotFound`` -------------------------------------- If you are using an ancient version of ``setuptools``, you might encounter ``pkg_resources.DistributionNotFound`` when trying to run ``autopep8``. Try upgrading ``setuptools`` to workaround this ``setuptools`` problem:: $ pip install --upgrade setuptools Use ``sudo`` if you are installing to the system. Links ===== * PyPI_ * GitHub_ * `Travis CI`_ * Codecov_ .. _PyPI: https://pypi.org/project/autopep8/ .. _GitHub: https://github.com/hhatto/autopep8 .. _`Travis CI`: https://travis-ci.org/hhatto/autopep8 .. _`Codecov`: https://app.codecov.io/gh/hhatto/autopep8 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/autopep8.egg-info/0000755000175100001770000000000014635727603016143 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/PKG-INFO0000644000175100001770000004110614635727603017242 0ustar00runnerdockerMetadata-Version: 2.1 Name: autopep8 Version: 2.3.1 Summary: A tool that automatically formats Python code to conform to the PEP 8 style guide Author-email: Hideo Hattori Project-URL: Repository, https://github.com/hhatto/autopep8 Keywords: automation,pep8,format,pycodestyle Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Quality Assurance Requires-Python: >=3.8 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS.rst Requires-Dist: pycodestyle>=2.12.0 Requires-Dist: tomli; python_version < "3.11" ======== autopep8 ======== .. image:: https://img.shields.io/pypi/v/autopep8.svg :target: https://pypi.org/project/autopep8/ :alt: PyPI Version .. image:: https://github.com/hhatto/autopep8/workflows/Python%20package/badge.svg :target: https://github.com/hhatto/autopep8/actions :alt: Build status .. image:: https://codecov.io/gh/hhatto/autopep8/branch/main/graph/badge.svg :target: https://codecov.io/gh/hhatto/autopep8 :alt: Code Coverage autopep8 automatically formats Python code to conform to the `PEP 8`_ style guide. It uses the pycodestyle_ utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues_ that can be reported by pycodestyle. .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _issues: https://pycodestyle.readthedocs.org/en/latest/intro.html#error-codes .. contents:: Installation ============ From pip:: $ pip install --upgrade autopep8 Consider using the ``--user`` option_. .. _option: https://pip.pypa.io/en/latest/user_guide/#user-installs Requirements ============ autopep8 requires pycodestyle_. .. _pycodestyle: https://github.com/PyCQA/pycodestyle Usage ===== To modify a file in place (with aggressive level 2):: $ autopep8 --in-place --aggressive --aggressive Before running autopep8. .. code-block:: python import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): #Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) After running autopep8. .. code-block:: python import math import sys def example1(): # This is a long comment. This should be wrapped to fit within 72 # characters. some_tuple = (1, 2, 3, 'a') some_variable = { 'long': 'Long code lines should be wrapped within 79 characters.', 'other': [ math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'], 'more': { 'inner': 'This whole logical line should be wrapped.', some_tuple: [ 1, 20, 300, 40000, 500000000, 60000000000000000]}} return (some_tuple, some_variable) def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True} class Example3(object): def __init__(self, bar): # Comments should have a space after the hash. if bar: bar += 1 bar = bar * bar return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) Options:: usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename] [--ignore-local-config] [-r] [-j n] [-p n] [-a] [--experimental] [--exclude globs] [--list-fixes] [--ignore errors] [--select errors] [--max-line-length n] [--line-range line line] [--hang-closing] [--exit-code] [files [files ...]] Automatically formats Python code to conform to the PEP 8 style guide. positional arguments: files files to format or '-' for standard in optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v, --verbose print verbose messages; multiple -v result in more verbose messages -d, --diff print the diff for the fixed source -i, --in-place make changes to files in place --global-config filename path to a global pep8 config file; if this file does not exist then this is ignored (default: ~/.config/pep8) --ignore-local-config don't look for and apply local config files; if not passed, defaults are updated with any config files in the project's root directory -r, --recursive run recursively over directories; must be used with --in-place or --diff -j n, --jobs n number of parallel jobs; match CPU count if value is less than 1 -p n, --pep8-passes n maximum number of additional pep8 passes (default: infinite) -a, --aggressive enable non-whitespace changes; multiple -a result in more aggressive changes --experimental enable experimental fixes --exclude globs exclude file/directory names that match these comma- separated globs --list-fixes list codes for fixes; used by --ignore and --select --ignore errors do not fix these errors/warnings (default: E226,E24,W50,W690) --select errors fix only these errors/warnings (e.g. E4,W) --max-line-length n set maximum allowed line length (default: 79) --line-range line line, --range line line only fix errors found within this inclusive range of line numbers (e.g. 1 99); line numbers are indexed at 1 --hang-closing hang-closing option passed to pycodestyle --exit-code change to behavior of exit code. default behavior of return value, 0 is no differences, 1 is error exit. return 2 when add this option. 2 is exists differences. Features ======== autopep8 fixes the following issues_ reported by pycodestyle_:: E101 - Reindent all lines. E11 - Fix indentation. E121 - Fix indentation to be a multiple of four. E122 - Add absent indentation for hanging indentation. E123 - Align closing bracket to match opening bracket. E124 - Align closing bracket to match visual indentation. E125 - Indent to distinguish line from next logical line. E126 - Fix over-indented hanging indentation. E127 - Fix visual indentation. E128 - Fix visual indentation. E129 - Fix visual indentation. E131 - Fix hanging indent for unaligned continuation line. E133 - Fix missing indentation for closing bracket. E20 - Remove extraneous whitespace. E211 - Remove extraneous whitespace. E22 - Fix extraneous whitespace around keywords. E224 - Remove extraneous whitespace around operator. E225 - Fix missing whitespace around operator. E226 - Fix missing whitespace around arithmetic operator. E227 - Fix missing whitespace around bitwise/shift operator. E228 - Fix missing whitespace around modulo operator. E231 - Add missing whitespace. E241 - Fix extraneous whitespace around keywords. E242 - Remove extraneous whitespace around operator. E251 - Remove whitespace around parameter '=' sign. E252 - Missing whitespace around parameter equals. E26 - Fix spacing after comment hash for inline comments. E265 - Fix spacing after comment hash for block comments. E266 - Fix too many leading '#' for block comments. E27 - Fix extraneous whitespace around keywords. E301 - Add missing blank line. E302 - Add missing 2 blank lines. E303 - Remove extra blank lines. E304 - Remove blank line following function decorator. E305 - Expected 2 blank lines after end of function or class. E306 - Expected 1 blank line before a nested definition. E401 - Put imports on separate lines. E402 - Fix module level import not at top of file E501 - Try to make lines fit within --max-line-length characters. E502 - Remove extraneous escape of newline. E701 - Put colon-separated compound statement on separate lines. E70 - Put semicolon-separated compound statement on separate lines. E711 - Fix comparison with None. E712 - Fix comparison with boolean. E713 - Use 'not in' for test for membership. E714 - Use 'is not' test for object identity. E721 - Use "isinstance()" instead of comparing types directly. E722 - Fix bare except. E731 - Use a def when use do not assign a lambda expression. W291 - Remove trailing whitespace. W292 - Add a single newline at the end of the file. W293 - Remove trailing whitespace on blank line. W391 - Remove trailing blank lines. W503 - Fix line break before binary operator. W504 - Fix line break after binary operator. W605 - Fix invalid escape sequence 'x'. autopep8 also fixes some issues not found by pycodestyle_. - Normalize files with mixed line endings. - Put a blank line between a class docstring and its first method declaration. (Enabled with ``E301``.) - Remove blank lines between a function declaration and its docstring. (Enabled with ``E303``.) autopep8 avoids fixing some issues found by pycodestyle_. - ``E112``/``E113`` for non comments are reports of bad indentation that break syntax rules. These should not be modified at all. - ``E265``, which refers to spacing after comment hash, is ignored if the comment looks like code. autopep8 avoids modifying these since they are not real comments. If you really want to get rid of the pycodestyle_ warning, consider just removing the commented-out code. (This can be automated via eradicate_.) .. _eradicate: https://github.com/myint/eradicate More advanced usage =================== By default autopep8 only makes whitespace changes. Thus, by default, it does not fix ``E711`` and ``E712``. (Changing ``x == None`` to ``x is None`` may change the meaning of the program if ``x`` has its ``__eq__`` method overridden.) Nor does it correct deprecated code ``W6``. To enable these more aggressive fixes, use the ``--aggressive`` option:: $ autopep8 --aggressive Use multiple ``--aggressive`` to increase the aggressiveness level. For example, ``E712`` requires aggressiveness level 2 (since ``x == True`` could be changed to either ``x`` or ``x is True``, but autopep8 chooses the former). ``--aggressive`` will also shorten lines more aggressively. It will also remove trailing whitespace more aggressively. (Usually, we don't touch trailing whitespace in docstrings and other multiline strings. And to do even more aggressive changes to docstrings, use docformatter_.) .. _docformatter: https://github.com/myint/docformatter To enable only a subset of the fixes, use the ``--select`` option. For example, to fix various types of indentation issues:: $ autopep8 --select=E1,W1 If the file being fixed is large, you may want to enable verbose progress messages:: $ autopep8 -v Passing in ``--experimental`` enables the following functionality: - Shortens code lines by taking its length into account :: $ autopep8 --experimental Disabling line-by-line ---------------------- It is possible to disable autopep8 untill it it turned back on again in the file, using ``autopep8: off`` and then renabling ``autopep8: on``. .. code-block:: python # autopep8: off [ [23, 23, 13, 43], [32, 34, 34, 34], [56, 34, 34, 11], [10, 10, 10, 10], ] # autopep8: on ``fmt: off`` and ``fmt: on`` are also valid. Use as a module =============== The simplest way of using autopep8 as a module is via the ``fix_code()`` function: >>> import autopep8 >>> autopep8.fix_code('x= 123\n') 'x = 123\n' Or with options: >>> import autopep8 >>> autopep8.fix_code('print( 123 )\n', ... options={'ignore': ['E']}) 'print( 123 )\n' Configuration ============= By default, if ``$HOME/.config/pycodestyle`` (``~\.pycodestyle`` in Windows environment) exists, it will be used as global configuration file. Alternatively, you can specify the global configuration file with the ``--global-config`` option. Also, if ``setup.cfg``, ``tox.ini``, ``.pep8`` and ``.flake8`` files exist in the directory where the target file exists, it will be used as the configuration file. ``pep8``, ``pycodestyle``, and ``flake8`` can be used as a section. configuration file example:: [pycodestyle] max_line_length = 120 ignore = E501 pyproject.toml -------------- autopep8 can also use ``pyproject.toml``. The section must be ``[tool.autopep8]``, and ``pyproject.toml`` takes precedence over any other configuration files. configuration file example:: [tool.autopep8] max_line_length = 120 ignore = "E501,W6" # or ["E501", "W6"] in-place = true recursive = true aggressive = 3 Usage with pre-commit ===================== autopep8 can be used as a hook for pre-commit_. To add autopep8 as a plugin, add this repo definition to your configuration: .. code-block:: yaml repos: - repo: https://github.com/hhatto/autopep8 rev: ... # select the tag or revision you want, or run `pre-commit autoupdate` hooks: - id: autopep8 .. _`pre-commit`: https://pre-commit.com Testing ======= Test cases are in ``test/test_autopep8.py``. They can be run directly via ``python test/test_autopep8.py`` or via tox_. The latter is useful for testing against multiple Python interpreters. (We currently test against CPython versions 3.8, 3.9, 3.10, 3.11 and 3.12. We also test against PyPy.) .. _`tox`: https://pypi.org/project/tox/ Broad spectrum testing is available via ``test/acid.py``. This script runs autopep8 against Python code and checks for correctness and completeness of the code fixes. It can check that the bytecode remains identical. ``test/acid_pypi.py`` makes use of ``acid.py`` to test against the latest released packages on PyPI. Troubleshooting =============== ``pkg_resources.DistributionNotFound`` -------------------------------------- If you are using an ancient version of ``setuptools``, you might encounter ``pkg_resources.DistributionNotFound`` when trying to run ``autopep8``. Try upgrading ``setuptools`` to workaround this ``setuptools`` problem:: $ pip install --upgrade setuptools Use ``sudo`` if you are installing to the system. Links ===== * PyPI_ * GitHub_ * `Travis CI`_ * Codecov_ .. _PyPI: https://pypi.org/project/autopep8/ .. _GitHub: https://github.com/hhatto/autopep8 .. _`Travis CI`: https://travis-ci.org/hhatto/autopep8 .. _`Codecov`: https://app.codecov.io/gh/hhatto/autopep8 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/SOURCES.txt0000644000175100001770000000101514635727603020024 0ustar00runnerdockerAUTHORS.rst LICENSE MANIFEST.in README.rst autopep8.py pyproject.toml setup.cfg tox.ini autopep8.egg-info/PKG-INFO autopep8.egg-info/SOURCES.txt autopep8.egg-info/dependency_links.txt autopep8.egg-info/entry_points.txt autopep8.egg-info/requires.txt autopep8.egg-info/top_level.txt test/__init__.py test/acid.py test/bad_encoding.py test/bad_encoding2.py test/e101_example.py test/example.py test/iso_8859_1.py test/test_autopep8.py test/test_suite.py test/fake_configuration/.pep8 test/fake_pycodestyle_configuration/tox.ini././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/dependency_links.txt0000644000175100001770000000000114635727603022211 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/entry_points.txt0000644000175100001770000000005314635727603021437 0ustar00runnerdocker[console_scripts] autopep8 = autopep8:main ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/requires.txt0000644000175100001770000000006614635727603020545 0ustar00runnerdockerpycodestyle>=2.12.0 [:python_version < "3.11"] tomli ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119747.0 autopep8-2.3.1/autopep8.egg-info/top_level.txt0000644000175100001770000000001114635727603020665 0ustar00runnerdockerautopep8 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/autopep8.py0000755000175100001770000046511714635727563015051 0ustar00runnerdocker#!/usr/bin/env python # Copyright (C) 2010-2011 Hideo Hattori # Copyright (C) 2011-2013 Hideo Hattori, Steven Myint # Copyright (C) 2013-2016 Hideo Hattori, Steven Myint, Bill Wendling # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Copyright (C) 2006-2009 Johann C. Rocholl # Copyright (C) 2009-2013 Florent Xicluna # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Automatically formats Python code to conform to the PEP 8 style guide. Fixes that only need be done once can be added by adding a function of the form "fix_(source)" to this module. They should return the fixed source code. These fixes are picked up by apply_global_fixes(). Fixes that depend on pycodestyle should be added as methods to FixPEP8. See the class documentation for more information. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import codecs import collections import copy import difflib import fnmatch import importlib import inspect import io import itertools import keyword import locale import os import re import signal import sys import textwrap import token import tokenize import warnings import ast from configparser import ConfigParser as SafeConfigParser, Error import pycodestyle __version__ = '2.3.1' CR = '\r' LF = '\n' CRLF = '\r\n' PYTHON_SHEBANG_REGEX = re.compile(r'^#!.*\bpython[23]?\b\s*$') LAMBDA_REGEX = re.compile(r'([\w.]+)\s=\slambda\s*([)(=\w,\s.]*):') COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+([^][)(}{]+?)\s+(in|is)\s') COMPARE_NEGATIVE_REGEX_THROUGH = re.compile(r'\b(not\s+in|is\s+not)\s') BARE_EXCEPT_REGEX = re.compile(r'except\s*:') STARTSWITH_DEF_REGEX = re.compile(r'^(async\s+def|def)\s.*\):') DOCSTRING_START_REGEX = re.compile(r'^u?r?(?P["\']{3})') ENABLE_REGEX = re.compile(r'# *(fmt|autopep8): *on') DISABLE_REGEX = re.compile(r'# *(fmt|autopep8): *off') ENCODING_MAGIC_COMMENT = re.compile( r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)' ) COMPARE_TYPE_REGEX = re.compile( r'([=!]=)\s+type(?:\s*\(\s*([^)]*[^ )])\s*\))' r'|\btype(?:\s*\(\s*([^)]*[^ )])\s*\))\s+([=!]=)' ) TYPE_REGEX = re.compile(r'(type\s*\(\s*[^)]*?[^\s)]\s*\))') EXIT_CODE_OK = 0 EXIT_CODE_ERROR = 1 EXIT_CODE_EXISTS_DIFF = 2 EXIT_CODE_ARGPARSE_ERROR = 99 # For generating line shortening candidates. SHORTEN_OPERATOR_GROUPS = frozenset([ frozenset([',']), frozenset(['%']), frozenset([',', '(', '[', '{']), frozenset(['%', '(', '[', '{']), frozenset([',', '(', '[', '{', '%', '+', '-', '*', '/', '//']), frozenset(['%', '+', '-', '*', '/', '//']), ]) DEFAULT_IGNORE = 'E226,E24,W50,W690' # TODO: use pycodestyle.DEFAULT_IGNORE DEFAULT_INDENT_SIZE = 4 # these fixes conflict with each other, if the `--ignore` setting causes both # to be enabled, disable both of them CONFLICTING_CODES = ('W503', 'W504') if sys.platform == 'win32': # pragma: no cover DEFAULT_CONFIG = os.path.expanduser(r'~\.pycodestyle') else: DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'pycodestyle') # fallback, use .pep8 if not os.path.exists(DEFAULT_CONFIG): # pragma: no cover if sys.platform == 'win32': DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8') else: DEFAULT_CONFIG = os.path.join(os.path.expanduser('~/.config'), 'pep8') PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8', '.flake8') MAX_PYTHON_FILE_DETECTION_BYTES = 1024 IS_SUPPORT_TOKEN_FSTRING = False if sys.version_info >= (3, 12): # pgrama: no cover IS_SUPPORT_TOKEN_FSTRING = True def _custom_formatwarning(message, category, _, __, line=None): return f"{category.__name__}: {message}\n" def open_with_encoding(filename, mode='r', encoding=None, limit_byte_check=-1): """Return opened file with a specific encoding.""" if not encoding: encoding = detect_encoding(filename, limit_byte_check=limit_byte_check) return io.open(filename, mode=mode, encoding=encoding, newline='') # Preserve line endings def _detect_encoding_from_file(filename: str): try: with open(filename) as input_file: for idx, line in enumerate(input_file): if idx == 0 and line[0] == '\ufeff': return "utf-8-sig" if idx >= 2: break match = ENCODING_MAGIC_COMMENT.search(line) if match: return match.groups()[0] except Exception: pass # Python3's default encoding return 'utf-8' def detect_encoding(filename, limit_byte_check=-1): """Return file encoding.""" encoding = _detect_encoding_from_file(filename) if encoding == "utf-8-sig": return encoding try: with open_with_encoding(filename, encoding=encoding) as test_file: test_file.read(limit_byte_check) return encoding except (LookupError, SyntaxError, UnicodeDecodeError): return 'latin-1' def readlines_from_file(filename): """Return contents of file.""" with open_with_encoding(filename) as input_file: return input_file.readlines() def extended_blank_lines(logical_line, blank_lines, blank_before, indent_level, previous_logical): """Check for missing blank lines after class declaration.""" if previous_logical.startswith(('def ', 'async def ')): if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line): yield (0, 'E303 too many blank lines ({})'.format(blank_lines)) elif pycodestyle.DOCSTRING_REGEX.match(previous_logical): # Missing blank line between class docstring and method declaration. if ( indent_level and not blank_lines and not blank_before and logical_line.startswith(('def ', 'async def ')) and '(self' in logical_line ): yield (0, 'E301 expected 1 blank line, found 0') def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa): """Override pycodestyle's function to provide indentation information.""" first_row = tokens[0][2][0] nrows = 1 + tokens[-1][2][0] - first_row if noqa or nrows == 1: return # indent_next tells us whether the next block is indented. Assuming # that it is indented by 4 spaces, then we should not allow 4-space # indents on the final continuation line. In turn, some other # indents are allowed to have an extra 4 spaces. indent_next = logical_line.endswith(':') row = depth = 0 valid_hangs = ( (DEFAULT_INDENT_SIZE,) if indent_char != '\t' else (DEFAULT_INDENT_SIZE, 2 * DEFAULT_INDENT_SIZE) ) # Remember how many brackets were opened on each line. parens = [0] * nrows # Relative indents of physical lines. rel_indent = [0] * nrows # For each depth, collect a list of opening rows. open_rows = [[0]] # For each depth, memorize the hanging indentation. hangs = [None] # Visual indents. indent_chances = {} last_indent = tokens[0][2] indent = [last_indent[1]] last_token_multiline = None line = None last_line = '' last_line_begins_with_multiline = False for token_type, text, start, end, line in tokens: newline = row < start[0] - first_row if newline: row = start[0] - first_row newline = (not last_token_multiline and token_type not in (tokenize.NL, tokenize.NEWLINE)) last_line_begins_with_multiline = last_token_multiline if newline: # This is the beginning of a continuation line. last_indent = start # Record the initial indent. rel_indent[row] = pycodestyle.expand_indent(line) - indent_level # Identify closing bracket. close_bracket = (token_type == tokenize.OP and text in ']})') # Is the indent relative to an opening bracket line? for open_row in reversed(open_rows[depth]): hang = rel_indent[row] - rel_indent[open_row] hanging_indent = hang in valid_hangs if hanging_indent: break if hangs[depth]: hanging_indent = (hang == hangs[depth]) visual_indent = (not close_bracket and hang > 0 and indent_chances.get(start[1])) if close_bracket and indent[depth]: # Closing bracket for visual indent. if start[1] != indent[depth]: yield (start, 'E124 {}'.format(indent[depth])) elif close_bracket and not hang: # closing bracket matches indentation of opening bracket's line if hang_closing: yield (start, 'E133 {}'.format(indent[depth])) elif indent[depth] and start[1] < indent[depth]: if visual_indent is not True: # Visual indent is broken. yield (start, 'E128 {}'.format(indent[depth])) elif (hanging_indent or (indent_next and rel_indent[row] == 2 * DEFAULT_INDENT_SIZE)): # Hanging indent is verified. if close_bracket and not hang_closing: yield (start, 'E123 {}'.format(indent_level + rel_indent[open_row])) hangs[depth] = hang elif visual_indent is True: # Visual indent is verified. indent[depth] = start[1] elif visual_indent in (text, str): # Ignore token lined up with matching one from a previous line. pass else: one_indented = (indent_level + rel_indent[open_row] + DEFAULT_INDENT_SIZE) # Indent is broken. if hang <= 0: error = ('E122', one_indented) elif indent[depth]: error = ('E127', indent[depth]) elif not close_bracket and hangs[depth]: error = ('E131', one_indented) elif hang > DEFAULT_INDENT_SIZE: error = ('E126', one_indented) else: hangs[depth] = hang error = ('E121', one_indented) yield (start, '{} {}'.format(*error)) # Look for visual indenting. if ( parens[row] and token_type not in (tokenize.NL, tokenize.COMMENT) and not indent[depth] ): indent[depth] = start[1] indent_chances[start[1]] = True # Deal with implicit string concatenation. elif (token_type in (tokenize.STRING, tokenize.COMMENT) or text in ('u', 'ur', 'b', 'br')): indent_chances[start[1]] = str # Special case for the "if" statement because len("if (") is equal to # 4. elif not indent_chances and not row and not depth and text == 'if': indent_chances[end[1] + 1] = True elif text == ':' and line[end[1]:].isspace(): open_rows[depth].append(row) # Keep track of bracket depth. if token_type == tokenize.OP: if text in '([{': depth += 1 indent.append(0) hangs.append(None) if len(open_rows) == depth: open_rows.append([]) open_rows[depth].append(row) parens[row] += 1 elif text in ')]}' and depth > 0: # Parent indents should not be more than this one. prev_indent = indent.pop() or last_indent[1] hangs.pop() for d in range(depth): if indent[d] > prev_indent: indent[d] = 0 for ind in list(indent_chances): if ind >= prev_indent: del indent_chances[ind] del open_rows[depth + 1:] depth -= 1 if depth: indent_chances[indent[depth]] = True for idx in range(row, -1, -1): if parens[idx]: parens[idx] -= 1 break assert len(indent) == depth + 1 if ( start[1] not in indent_chances and # This is for purposes of speeding up E121 (GitHub #90). not last_line.rstrip().endswith(',') ): # Allow to line up tokens. indent_chances[start[1]] = text last_token_multiline = (start[0] != end[0]) if last_token_multiline: rel_indent[end[0] - first_row] = rel_indent[row] last_line = line if ( indent_next and not last_line_begins_with_multiline and pycodestyle.expand_indent(line) == indent_level + DEFAULT_INDENT_SIZE ): pos = (start[0], indent[0] + 4) desired_indent = indent_level + 2 * DEFAULT_INDENT_SIZE if visual_indent: yield (pos, 'E129 {}'.format(desired_indent)) else: yield (pos, 'E125 {}'.format(desired_indent)) # NOTE: need reload with runpy and call twice # see: https://github.com/hhatto/autopep8/issues/625 importlib.reload(pycodestyle) del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation] pycodestyle.register_check(extended_blank_lines) pycodestyle.register_check(continued_indentation) class FixPEP8(object): """Fix invalid code. Fixer methods are prefixed "fix_". The _fix_source() method looks for these automatically. The fixer method can take either one or two arguments (in addition to self). The first argument is "result", which is the error information from pycodestyle. The second argument, "logical", is required only for logical-line fixes. The fixer method can return the list of modified lines or None. An empty list would mean that no changes were made. None would mean that only the line reported in the pycodestyle error was modified. Note that the modified line numbers that are returned are indexed at 1. This typically would correspond with the line number reported in the pycodestyle error information. [fixed method list] - e111,e114,e115,e116 - e121,e122,e123,e124,e125,e126,e127,e128,e129 - e201,e202,e203 - e211 - e221,e222,e223,e224,e225 - e231 - e251,e252 - e261,e262 - e271,e272,e273,e274,e275 - e301,e302,e303,e304,e305,e306 - e401,e402 - e502 - e701,e702,e703,e704 - e711,e712,e713,e714 - e721,e722 - e731 - w291 - w503,504 """ def __init__(self, filename, options, contents=None, long_line_ignore_cache=None): self.filename = filename if contents is None: self.source = readlines_from_file(filename) else: sio = io.StringIO(contents) self.source = sio.readlines() self.options = options self.indent_word = _get_indentword(''.join(self.source)) self.original_source = copy.copy(self.source) # collect imports line self.imports = {} for i, line in enumerate(self.source): if (line.find("import ") == 0 or line.find("from ") == 0) and \ line not in self.imports: # collect only import statements that first appeared self.imports[line] = i self.long_line_ignore_cache = ( set() if long_line_ignore_cache is None else long_line_ignore_cache) # Many fixers are the same even though pycodestyle categorizes them # differently. self.fix_e115 = self.fix_e112 self.fix_e121 = self._fix_reindent self.fix_e122 = self._fix_reindent self.fix_e123 = self._fix_reindent self.fix_e124 = self._fix_reindent self.fix_e126 = self._fix_reindent self.fix_e127 = self._fix_reindent self.fix_e128 = self._fix_reindent self.fix_e129 = self._fix_reindent self.fix_e133 = self.fix_e131 self.fix_e202 = self.fix_e201 self.fix_e203 = self.fix_e201 self.fix_e204 = self.fix_e201 self.fix_e211 = self.fix_e201 self.fix_e221 = self.fix_e271 self.fix_e222 = self.fix_e271 self.fix_e223 = self.fix_e271 self.fix_e226 = self.fix_e225 self.fix_e227 = self.fix_e225 self.fix_e228 = self.fix_e225 self.fix_e241 = self.fix_e271 self.fix_e242 = self.fix_e224 self.fix_e252 = self.fix_e225 self.fix_e261 = self.fix_e262 self.fix_e272 = self.fix_e271 self.fix_e273 = self.fix_e271 self.fix_e274 = self.fix_e271 self.fix_e275 = self.fix_e271 self.fix_e306 = self.fix_e301 self.fix_e501 = ( self.fix_long_line_logically if options and (options.aggressive >= 2 or options.experimental) else self.fix_long_line_physically) self.fix_e703 = self.fix_e702 self.fix_w292 = self.fix_w291 self.fix_w293 = self.fix_w291 def _check_affected_anothers(self, result) -> bool: """Check if the fix affects the number of lines of another remark.""" line_index = result['line'] - 1 target = self.source[line_index] original_target = self.original_source[line_index] return target != original_target def _fix_source(self, results): try: (logical_start, logical_end) = _find_logical(self.source) logical_support = True except (SyntaxError, tokenize.TokenError): # pragma: no cover logical_support = False completed_lines = set() for result in sorted(results, key=_priority_key): if result['line'] in completed_lines: continue fixed_methodname = 'fix_' + result['id'].lower() if hasattr(self, fixed_methodname): fix = getattr(self, fixed_methodname) line_index = result['line'] - 1 original_line = self.source[line_index] is_logical_fix = len(_get_parameters(fix)) > 2 if is_logical_fix: logical = None if logical_support: logical = _get_logical(self.source, result, logical_start, logical_end) if logical and set(range( logical[0][0] + 1, logical[1][0] + 1)).intersection( completed_lines): continue if self._check_affected_anothers(result): continue modified_lines = fix(result, logical) else: if self._check_affected_anothers(result): continue modified_lines = fix(result) if modified_lines is None: # Force logical fixes to report what they modified. assert not is_logical_fix if self.source[line_index] == original_line: modified_lines = [] if modified_lines: completed_lines.update(modified_lines) elif modified_lines == []: # Empty list means no fix if self.options.verbose >= 2: print( '---> Not fixing {error} on line {line}'.format( error=result['id'], line=result['line']), file=sys.stderr) else: # We assume one-line fix when None. completed_lines.add(result['line']) else: if self.options.verbose >= 3: print( "---> '{}' is not defined.".format(fixed_methodname), file=sys.stderr) info = result['info'].strip() print('---> {}:{}:{}:{}'.format(self.filename, result['line'], result['column'], info), file=sys.stderr) def fix(self): """Return a version of the source code with PEP 8 violations fixed.""" pep8_options = { 'ignore': self.options.ignore, 'select': self.options.select, 'max_line_length': self.options.max_line_length, 'hang_closing': self.options.hang_closing, } results = _execute_pep8(pep8_options, self.source) if self.options.verbose: progress = {} for r in results: if r['id'] not in progress: progress[r['id']] = set() progress[r['id']].add(r['line']) print('---> {n} issue(s) to fix {progress}'.format( n=len(results), progress=progress), file=sys.stderr) if self.options.line_range: start, end = self.options.line_range results = [r for r in results if start <= r['line'] <= end] self._fix_source(filter_results(source=''.join(self.source), results=results, aggressive=self.options.aggressive)) if self.options.line_range: # If number of lines has changed then change line_range. count = sum(sline.count('\n') for sline in self.source[start - 1:end]) self.options.line_range[1] = start + count - 1 return ''.join(self.source) def _fix_reindent(self, result): """Fix a badly indented line. This is done by adding or removing from its initial indent only. """ num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] self.source[line_index] = ' ' * num_indent_spaces + target.lstrip() def fix_e112(self, result): """Fix under-indented comments.""" line_index = result['line'] - 1 target = self.source[line_index] if not target.lstrip().startswith('#'): # Don't screw with invalid syntax. return [] self.source[line_index] = self.indent_word + target def fix_e113(self, result): """Fix unexpected indentation.""" line_index = result['line'] - 1 target = self.source[line_index] indent = _get_indentation(target) stripped = target.lstrip() self.source[line_index] = indent[1:] + stripped def fix_e116(self, result): """Fix over-indented comments.""" line_index = result['line'] - 1 target = self.source[line_index] indent = _get_indentation(target) stripped = target.lstrip() if not stripped.startswith('#'): # Don't screw with invalid syntax. return [] self.source[line_index] = indent[1:] + stripped def fix_e117(self, result): """Fix over-indented.""" line_index = result['line'] - 1 target = self.source[line_index] indent = _get_indentation(target) if indent == '\t': return [] stripped = target.lstrip() self.source[line_index] = indent[1:] + stripped def fix_e125(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) indent = len(_get_indentation(target)) modified_lines = [] while len(_get_indentation(self.source[line_index])) >= indent: self.source[line_index] = (' ' * spaces_to_add + self.source[line_index]) modified_lines.append(1 + line_index) # Line indexed at 1. line_index -= 1 return modified_lines def fix_e131(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) indent_length = len(_get_indentation(target)) spaces_to_add = num_indent_spaces - indent_length if num_indent_spaces == 0 and indent_length == 0: spaces_to_add = 4 if spaces_to_add >= 0: self.source[line_index] = (' ' * spaces_to_add + self.source[line_index]) else: offset = abs(spaces_to_add) self.source[line_index] = self.source[line_index][offset:] def fix_e201(self, result): """Remove extraneous whitespace.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 fixed = fix_whitespace(target, offset=offset, replacement='') self.source[line_index] = fixed def fix_e224(self, result): """Remove extraneous whitespace around operator.""" target = self.source[result['line'] - 1] offset = result['column'] - 1 fixed = target[:offset] + target[offset:].replace('\t', ' ') self.source[result['line'] - 1] = fixed def fix_e225(self, result): """Fix missing whitespace around operator.""" target = self.source[result['line'] - 1] offset = result['column'] - 1 fixed = target[:offset] + ' ' + target[offset:] # Only proceed if non-whitespace characters match. # And make sure we don't break the indentation. if ( fixed.replace(' ', '') == target.replace(' ', '') and _get_indentation(fixed) == _get_indentation(target) ): self.source[result['line'] - 1] = fixed error_code = result.get('id', 0) try: ts = generate_tokens(fixed) except (SyntaxError, tokenize.TokenError): return if not check_syntax(fixed.lstrip()): return try: _missing_whitespace = ( pycodestyle.missing_whitespace_around_operator ) except AttributeError: # pycodestyle >= 2.11.0 _missing_whitespace = pycodestyle.missing_whitespace errors = list(_missing_whitespace(fixed, ts)) for e in reversed(errors): if error_code != e[1].split()[0]: continue offset = e[0][1] fixed = fixed[:offset] + ' ' + fixed[offset:] self.source[result['line'] - 1] = fixed else: return [] def fix_e231(self, result): """Add missing whitespace.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] fixed = target[:offset].rstrip() + ' ' + target[offset:].lstrip() self.source[line_index] = fixed def fix_e251(self, result): """Remove whitespace around parameter '=' sign.""" line_index = result['line'] - 1 target = self.source[line_index] # This is necessary since pycodestyle sometimes reports columns that # goes past the end of the physical line. This happens in cases like, # foo(bar\n=None) c = min(result['column'] - 1, len(target) - 1) if target[c].strip(): fixed = target else: fixed = target[:c].rstrip() + target[c:].lstrip() # There could be an escaped newline # # def foo(a=\ # 1) if fixed.endswith(('=\\\n', '=\\\r\n', '=\\\r')): self.source[line_index] = fixed.rstrip('\n\r \t\\') self.source[line_index + 1] = self.source[line_index + 1].lstrip() return [line_index + 1, line_index + 2] # Line indexed at 1 self.source[result['line'] - 1] = fixed def fix_e262(self, result): """Fix spacing after inline comment hash.""" target = self.source[result['line'] - 1] offset = result['column'] code = target[:offset].rstrip(' \t#') comment = target[offset:].lstrip(' \t#') fixed = code + (' # ' + comment if comment.strip() else '\n') self.source[result['line'] - 1] = fixed def fix_e265(self, result): """Fix spacing after block comment hash.""" target = self.source[result['line'] - 1] indent = _get_indentation(target) line = target.lstrip(' \t') pos = next((index for index, c in enumerate(line) if c != '#')) hashes = line[:pos] comment = line[pos:].lstrip(' \t') # Ignore special comments, even in the middle of the file. if comment.startswith('!'): return fixed = indent + hashes + (' ' + comment if comment.strip() else '\n') self.source[result['line'] - 1] = fixed def fix_e266(self, result): """Fix too many block comment hashes.""" target = self.source[result['line'] - 1] # Leave stylistic outlined blocks alone. if target.strip().endswith('#'): return indentation = _get_indentation(target) fixed = indentation + '# ' + target.lstrip('# \t') self.source[result['line'] - 1] = fixed def fix_e271(self, result): """Fix extraneous whitespace around keywords.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 fixed = fix_whitespace(target, offset=offset, replacement=' ') if fixed == target: return [] else: self.source[line_index] = fixed def fix_e301(self, result): """Add missing blank line.""" cr = '\n' self.source[result['line'] - 1] = cr + self.source[result['line'] - 1] def fix_e302(self, result): """Add missing 2 blank lines.""" add_linenum = 2 - int(result['info'].split()[-1]) offset = 1 if self.source[result['line'] - 2].strip() == "\\": offset = 2 cr = '\n' * add_linenum self.source[result['line'] - offset] = ( cr + self.source[result['line'] - offset] ) def fix_e303(self, result): """Remove extra blank lines.""" delete_linenum = int(result['info'].split('(')[1].split(')')[0]) - 2 delete_linenum = max(1, delete_linenum) # We need to count because pycodestyle reports an offset line number if # there are comments. cnt = 0 line = result['line'] - 2 modified_lines = [] while cnt < delete_linenum and line >= 0: if not self.source[line].strip(): self.source[line] = '' modified_lines.append(1 + line) # Line indexed at 1 cnt += 1 line -= 1 return modified_lines def fix_e304(self, result): """Remove blank line following function decorator.""" line = result['line'] - 2 if not self.source[line].strip(): self.source[line] = '' def fix_e305(self, result): """Add missing 2 blank lines after end of function or class.""" add_delete_linenum = 2 - int(result['info'].split()[-1]) cnt = 0 offset = result['line'] - 2 modified_lines = [] if add_delete_linenum < 0: # delete cr add_delete_linenum = abs(add_delete_linenum) while cnt < add_delete_linenum and offset >= 0: if not self.source[offset].strip(): self.source[offset] = '' modified_lines.append(1 + offset) # Line indexed at 1 cnt += 1 offset -= 1 else: # add cr cr = '\n' # check comment line while True: if offset < 0: break line = self.source[offset].lstrip() if not line: break if line[0] != '#': break offset -= 1 offset += 1 self.source[offset] = cr + self.source[offset] modified_lines.append(1 + offset) # Line indexed at 1. return modified_lines def fix_e401(self, result): """Put imports on separate lines.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 if not target.lstrip().startswith('import'): return [] indentation = re.split(pattern=r'\bimport\b', string=target, maxsplit=1)[0] fixed = (target[:offset].rstrip('\t ,') + '\n' + indentation + 'import ' + target[offset:].lstrip('\t ,')) self.source[line_index] = fixed def fix_e402(self, result): (line_index, offset, target) = get_index_offset_contents(result, self.source) for i in range(1, 100): line = "".join(self.source[line_index:line_index+i]) try: generate_tokens("".join(line)) except (SyntaxError, tokenize.TokenError): continue break if not (target in self.imports and self.imports[target] != line_index): mod_offset = get_module_imports_on_top_of_file(self.source, line_index) self.source[mod_offset] = line + self.source[mod_offset] for offset in range(i): self.source[line_index+offset] = '' def fix_long_line_logically(self, result, logical): """Try to make lines fit within --max-line-length characters.""" if ( not logical or len(logical[2]) == 1 or self.source[result['line'] - 1].lstrip().startswith('#') ): return self.fix_long_line_physically(result) start_line_index = logical[0][0] end_line_index = logical[1][0] logical_lines = logical[2] previous_line = get_item(self.source, start_line_index - 1, default='') next_line = get_item(self.source, end_line_index + 1, default='') single_line = join_logical_line(''.join(logical_lines)) try: fixed = self.fix_long_line( target=single_line, previous_line=previous_line, next_line=next_line, original=''.join(logical_lines)) except (SyntaxError, tokenize.TokenError): return self.fix_long_line_physically(result) if fixed: for line_index in range(start_line_index, end_line_index + 1): self.source[line_index] = '' self.source[start_line_index] = fixed return range(start_line_index + 1, end_line_index + 1) return [] def fix_long_line_physically(self, result): """Try to make lines fit within --max-line-length characters.""" line_index = result['line'] - 1 target = self.source[line_index] previous_line = get_item(self.source, line_index - 1, default='') next_line = get_item(self.source, line_index + 1, default='') try: fixed = self.fix_long_line( target=target, previous_line=previous_line, next_line=next_line, original=target) except (SyntaxError, tokenize.TokenError): return [] if fixed: self.source[line_index] = fixed return [line_index + 1] return [] def fix_long_line(self, target, previous_line, next_line, original): cache_entry = (target, previous_line, next_line) if cache_entry in self.long_line_ignore_cache: return [] if target.lstrip().startswith('#'): if self.options.aggressive: # Wrap commented lines. return shorten_comment( line=target, max_line_length=self.options.max_line_length, last_comment=not next_line.lstrip().startswith('#')) return [] fixed = get_fixed_long_line( target=target, previous_line=previous_line, original=original, indent_word=self.indent_word, max_line_length=self.options.max_line_length, aggressive=self.options.aggressive, experimental=self.options.experimental, verbose=self.options.verbose) if fixed and not code_almost_equal(original, fixed): return fixed self.long_line_ignore_cache.add(cache_entry) return None def fix_e502(self, result): """Remove extraneous escape of newline.""" (line_index, _, target) = get_index_offset_contents(result, self.source) self.source[line_index] = target.rstrip('\n\r \t\\') + '\n' def fix_e701(self, result): """Put colon-separated compound statement on separate lines.""" line_index = result['line'] - 1 target = self.source[line_index] c = result['column'] fixed_source = (target[:c] + '\n' + _get_indentation(target) + self.indent_word + target[c:].lstrip('\n\r \t\\')) self.source[result['line'] - 1] = fixed_source return [result['line'], result['line'] + 1] def fix_e702(self, result, logical): """Put semicolon-separated compound statement on separate lines.""" if not logical: return [] # pragma: no cover logical_lines = logical[2] # Avoid applying this when indented. # https://docs.python.org/reference/compound_stmts.html for line in logical_lines: if ( result['id'] == 'E702' and ':' in line and pycodestyle.STARTSWITH_INDENT_STATEMENT_REGEX.match(line) ): if self.options.verbose: print( '---> avoid fixing {error} with ' 'other compound statements'.format(error=result['id']), file=sys.stderr ) return [] line_index = result['line'] - 1 target = self.source[line_index] if target.rstrip().endswith('\\'): # Normalize '1; \\\n2' into '1; 2'. self.source[line_index] = target.rstrip('\n \r\t\\') self.source[line_index + 1] = self.source[line_index + 1].lstrip() return [line_index + 1, line_index + 2] if target.rstrip().endswith(';'): self.source[line_index] = target.rstrip('\n \r\t;') + '\n' return [line_index + 1] offset = result['column'] - 1 first = target[:offset].rstrip(';').rstrip() second = (_get_indentation(logical_lines[0]) + target[offset:].lstrip(';').lstrip()) # Find inline comment. inline_comment = None if target[offset:].lstrip(';').lstrip()[:2] == '# ': inline_comment = target[offset:].lstrip(';') if inline_comment: self.source[line_index] = first + inline_comment else: self.source[line_index] = first + '\n' + second return [line_index + 1] def fix_e704(self, result): """Fix multiple statements on one line def""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = STARTSWITH_DEF_REGEX.match(target) if match: self.source[line_index] = '{}\n{}{}'.format( match.group(0), _get_indentation(target) + self.indent_word, target[match.end(0):].lstrip()) def fix_e711(self, result): """Fix comparison with None.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) right_offset = offset + 2 if right_offset >= len(target): return [] left = target[:offset].rstrip() center = target[offset:right_offset] right = target[right_offset:].lstrip() if center.strip() == '==': new_center = 'is' elif center.strip() == '!=': new_center = 'is not' else: return [] self.source[line_index] = ' '.join([left, new_center, right]) def fix_e712(self, result): """Fix (trivial case of) comparison with boolean.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # Handle very easy "not" special cases. if re.match(r'^\s*if [\w."\'\[\]]+ == False:$', target): self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) == False:', r'if not \1:', target, count=1) elif re.match(r'^\s*if [\w."\'\[\]]+ != True:$', target): self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) != True:', r'if not \1:', target, count=1) else: right_offset = offset + 2 if right_offset >= len(target): return [] left = target[:offset].rstrip() center = target[offset:right_offset] right = target[right_offset:].lstrip() # Handle simple cases only. new_right = None if center.strip() == '==': if re.match(r'\bTrue\b', right): new_right = re.sub(r'\bTrue\b *', '', right, count=1) elif center.strip() == '!=': if re.match(r'\bFalse\b', right): new_right = re.sub(r'\bFalse\b *', '', right, count=1) if new_right is None: return [] if new_right[0].isalnum(): new_right = ' ' + new_right self.source[line_index] = left + new_right def fix_e713(self, result): """Fix (trivial case of) non-membership check.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'not in' -> 'in' before_target = target[:offset] target = target[offset:] match_notin = COMPARE_NEGATIVE_REGEX_THROUGH.search(target) notin_pos_start, notin_pos_end = 0, 0 if match_notin: notin_pos_start = match_notin.start(1) notin_pos_end = match_notin.end() target = '{}{} {}'.format( target[:notin_pos_start], 'in', target[notin_pos_end:]) # fix 'not in' match = COMPARE_NEGATIVE_REGEX.search(target) if match: if match.group(3) == 'in': pos_start = match.start(1) new_target = '{5}{0}{1} {2} {3} {4}'.format( target[:pos_start], match.group(2), match.group(1), match.group(3), target[match.end():], before_target) if match_notin: # revert 'in' -> 'not in' pos_start = notin_pos_start + offset pos_end = notin_pos_end + offset - 4 # len('not ') new_target = '{}{} {}'.format( new_target[:pos_start], 'not in', new_target[pos_end:]) self.source[line_index] = new_target def fix_e714(self, result): """Fix object identity should be 'is not' case.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'is not' -> 'is' before_target = target[:offset] target = target[offset:] match_isnot = COMPARE_NEGATIVE_REGEX_THROUGH.search(target) isnot_pos_start, isnot_pos_end = 0, 0 if match_isnot: isnot_pos_start = match_isnot.start(1) isnot_pos_end = match_isnot.end() target = '{}{} {}'.format( target[:isnot_pos_start], 'in', target[isnot_pos_end:]) match = COMPARE_NEGATIVE_REGEX.search(target) if match: if match.group(3).startswith('is'): pos_start = match.start(1) new_target = '{5}{0}{1} {2} {3} {4}'.format( target[:pos_start], match.group(2), match.group(3), match.group(1), target[match.end():], before_target) if match_isnot: # revert 'is' -> 'is not' pos_start = isnot_pos_start + offset pos_end = isnot_pos_end + offset - 4 # len('not ') new_target = '{}{} {}'.format( new_target[:pos_start], 'is not', new_target[pos_end:]) self.source[line_index] = new_target def fix_e721(self, result): """fix comparison type""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = COMPARE_TYPE_REGEX.search(target) if match: # NOTE: match objects # * type(a) == type(b) -> (None, None, 'a', '==') # * str == type(b) -> ('==', 'b', None, None) # * type("") != type(b) -> (None, None, '""', '!=') start = match.start() end = match.end() _prefix = "" _suffix = "" first_match_type_obj = match.groups()[1] if first_match_type_obj is None: _target_obj = match.groups()[2] else: _target_obj = match.groups()[1] _suffix = target[end:] isinstance_stmt = " isinstance" is_not_condition = ( match.groups()[0] == "!=" or match.groups()[3] == "!=" ) if is_not_condition: isinstance_stmt = " not isinstance" _type_comp = f"{_target_obj}, {target[:start]}" _prefix_tmp = target[:start].split() if len(_prefix_tmp) >= 1: _type_comp = f"{_target_obj}, {target[:start]}" if first_match_type_obj is not None: _prefix = " ".join(_prefix_tmp[:-1]) _type_comp = f"{_target_obj}, {_prefix_tmp[-1]}" else: _prefix = " ".join(_prefix_tmp) _suffix_tmp = target[end:] _suffix_type_match = TYPE_REGEX.search(_suffix_tmp) if len(_suffix_tmp.split()) >= 1 and _suffix_type_match: if _suffix_type_match: type_match_end = _suffix_type_match.end() _suffix = _suffix_tmp[type_match_end:] if _suffix_type_match: cmp_b = _suffix_type_match.groups()[0] _type_comp = f"{_target_obj}, {cmp_b}" fix_line = f"{_prefix}{isinstance_stmt}({_type_comp}){_suffix}" self.source[line_index] = fix_line def fix_e722(self, result): """fix bare except""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = BARE_EXCEPT_REGEX.search(target) if match: self.source[line_index] = '{}{}{}'.format( target[:result['column'] - 1], "except BaseException:", target[match.end():]) def fix_e731(self, result): """Fix do not assign a lambda expression check.""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = LAMBDA_REGEX.search(target) if match: end = match.end() self.source[line_index] = '{}def {}({}): return {}'.format( target[:match.start(0)], match.group(1), match.group(2), target[end:].lstrip()) def fix_w291(self, result): """Remove trailing whitespace.""" fixed_line = self.source[result['line'] - 1].rstrip() self.source[result['line'] - 1] = fixed_line + '\n' def fix_w391(self, _): """Remove trailing blank lines.""" blank_count = 0 for line in reversed(self.source): line = line.rstrip() if line: break else: blank_count += 1 original_length = len(self.source) self.source = self.source[:original_length - blank_count] return range(1, 1 + original_length) def fix_w503(self, result): (line_index, _, target) = get_index_offset_contents(result, self.source) one_string_token = target.split()[0] try: ts = generate_tokens(one_string_token) except (SyntaxError, tokenize.TokenError): return if not _is_binary_operator(ts[0][0], one_string_token): return # find comment comment_index = 0 found_not_comment_only_line = False comment_only_linenum = 0 for i in range(5): # NOTE: try to parse code in 5 times if (line_index - i) < 0: break from_index = line_index - i - 1 if from_index < 0 or len(self.source) <= from_index: break to_index = line_index + 1 strip_line = self.source[from_index].lstrip() if ( not found_not_comment_only_line and strip_line and strip_line[0] == '#' ): comment_only_linenum += 1 continue found_not_comment_only_line = True try: ts = generate_tokens("".join(self.source[from_index:to_index])) except (SyntaxError, tokenize.TokenError): continue newline_count = 0 newline_index = [] for index, t in enumerate(ts): if t[0] in (tokenize.NEWLINE, tokenize.NL): newline_index.append(index) newline_count += 1 if newline_count > 2: tts = ts[newline_index[-3]:] else: tts = ts old = [] for t in tts: if t[0] in (tokenize.NEWLINE, tokenize.NL): newline_count -= 1 if newline_count <= 1: break if tokenize.COMMENT == t[0] and old and old[0] != tokenize.NL: comment_index = old[3][1] break old = t break i = target.index(one_string_token) fix_target_line = line_index - 1 - comment_only_linenum self.source[line_index] = '{}{}'.format( target[:i], target[i + len(one_string_token):].lstrip()) nl = find_newline(self.source[fix_target_line:line_index]) before_line = self.source[fix_target_line] bl = before_line.index(nl) if comment_index: self.source[fix_target_line] = '{} {} {}'.format( before_line[:comment_index], one_string_token, before_line[comment_index + 1:]) else: if before_line[:bl].endswith("#"): # special case # see: https://github.com/hhatto/autopep8/issues/503 self.source[fix_target_line] = '{}{} {}'.format( before_line[:bl-2], one_string_token, before_line[bl-2:]) else: self.source[fix_target_line] = '{} {}{}'.format( before_line[:bl], one_string_token, before_line[bl:]) def fix_w504(self, result): (line_index, _, target) = get_index_offset_contents(result, self.source) # NOTE: is not collect pointed out in pycodestyle==2.4.0 comment_index = 0 operator_position = None # (start_position, end_position) for i in range(1, 6): to_index = line_index + i try: ts = generate_tokens("".join(self.source[line_index:to_index])) except (SyntaxError, tokenize.TokenError): continue newline_count = 0 newline_index = [] for index, t in enumerate(ts): if _is_binary_operator(t[0], t[1]): if t[2][0] == 1 and t[3][0] == 1: operator_position = (t[2][1], t[3][1]) elif t[0] == tokenize.NAME and t[1] in ("and", "or"): if t[2][0] == 1 and t[3][0] == 1: operator_position = (t[2][1], t[3][1]) elif t[0] in (tokenize.NEWLINE, tokenize.NL): newline_index.append(index) newline_count += 1 if newline_count > 2: tts = ts[:newline_index[-3]] else: tts = ts old = [] for t in tts: if tokenize.COMMENT == t[0] and old: comment_row, comment_index = old[3] break old = t break if not operator_position: return target_operator = target[operator_position[0]:operator_position[1]] if comment_index and comment_row == 1: self.source[line_index] = '{}{}'.format( target[:operator_position[0]].rstrip(), target[comment_index:]) else: self.source[line_index] = '{}{}{}'.format( target[:operator_position[0]].rstrip(), target[operator_position[1]:].lstrip(), target[operator_position[1]:]) next_line = self.source[line_index + 1] next_line_indent = 0 m = re.match(r'\s*', next_line) if m: next_line_indent = m.span()[1] self.source[line_index + 1] = '{}{} {}'.format( next_line[:next_line_indent], target_operator, next_line[next_line_indent:]) def fix_w605(self, result): (line_index, offset, target) = get_index_offset_contents(result, self.source) self.source[line_index] = '{}\\{}'.format( target[:offset + 1], target[offset + 1:]) def get_module_imports_on_top_of_file(source, import_line_index): """return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function(): """ def is_string_literal(line): if line[0] in 'uUbB': line = line[1:] if line and line[0] in 'rR': line = line[1:] return line and (line[0] == '"' or line[0] == "'") def is_future_import(line): nodes = ast.parse(line) for n in nodes.body: if isinstance(n, ast.ImportFrom) and n.module == '__future__': return True return False def has_future_import(source): offset = 0 line = '' for _, next_line in source: for line_part in next_line.strip().splitlines(True): line = line + line_part try: return is_future_import(line), offset except SyntaxError: continue offset += 1 return False, offset allowed_try_keywords = ('try', 'except', 'else', 'finally') in_docstring = False docstring_kind = '"""' source_stream = iter(enumerate(source)) for cnt, line in source_stream: if not in_docstring: m = DOCSTRING_START_REGEX.match(line.lstrip()) if m is not None: in_docstring = True docstring_kind = m.group('kind') remain = line[m.end(): m.endpos].rstrip() if remain[-3:] == docstring_kind: # one line doc in_docstring = False continue if in_docstring: if line.rstrip()[-3:] == docstring_kind: in_docstring = False continue if not line.rstrip(): continue elif line.startswith('#'): continue if line.startswith('import '): if cnt == import_line_index: continue return cnt elif line.startswith('from '): if cnt == import_line_index: continue hit, offset = has_future_import( itertools.chain([(cnt, line)], source_stream) ) if hit: # move to the back return cnt + offset + 1 return cnt elif pycodestyle.DUNDER_REGEX.match(line): return cnt elif any(line.startswith(kw) for kw in allowed_try_keywords): continue elif is_string_literal(line): return cnt else: return cnt return 0 def get_index_offset_contents(result, source): """Return (line_index, column_offset, line_contents).""" line_index = result['line'] - 1 return (line_index, result['column'] - 1, source[line_index]) def get_fixed_long_line(target, previous_line, original, indent_word=' ', max_line_length=79, aggressive=0, experimental=False, verbose=False): """Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking the candidates to heuristically select the best option. """ indent = _get_indentation(target) source = target[len(indent):] assert source.lstrip() == source assert not target.lstrip().startswith('#') # Check for partial multiline. tokens = list(generate_tokens(source)) candidates = shorten_line( tokens, source, indent, indent_word, max_line_length, aggressive=aggressive, experimental=experimental, previous_line=previous_line) # Also sort alphabetically as a tie breaker (for determinism). candidates = sorted( sorted(set(candidates).union([target, original])), key=lambda x: line_shortening_rank( x, indent_word, max_line_length, experimental=experimental)) if verbose >= 4: print(('-' * 79 + '\n').join([''] + candidates + ['']), file=wrap_output(sys.stderr, 'utf-8')) if candidates: best_candidate = candidates[0] # Don't allow things to get longer. if longest_line_length(best_candidate) > longest_line_length(original): return None return best_candidate def longest_line_length(code): """Return length of longest line.""" if len(code) == 0: return 0 return max(len(line) for line in code.splitlines()) def join_logical_line(logical_line): """Return single line based on logical line input.""" indentation = _get_indentation(logical_line) return indentation + untokenize_without_newlines( generate_tokens(logical_line.lstrip())) + '\n' def untokenize_without_newlines(tokens): """Return source code based on tokens.""" text = '' last_row = 0 last_column = -1 for t in tokens: token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] if start_row > last_row: last_column = 0 if ( (start_column > last_column or token_string == '\n') and not text.endswith(' ') ): text += ' ' if token_string != '\n': text += token_string last_row = end_row last_column = end_column return text.rstrip() def _find_logical(source_lines): # Make a variable which is the index of all the starts of lines. logical_start = [] logical_end = [] last_newline = True parens = 0 for t in generate_tokens(''.join(source_lines)): if t[0] in [tokenize.COMMENT, tokenize.DEDENT, tokenize.INDENT, tokenize.NL, tokenize.ENDMARKER]: continue if not parens and t[0] in [tokenize.NEWLINE, tokenize.SEMI]: last_newline = True logical_end.append((t[3][0] - 1, t[2][1])) continue if last_newline and not parens: logical_start.append((t[2][0] - 1, t[2][1])) last_newline = False if t[0] == tokenize.OP: if t[1] in '([{': parens += 1 elif t[1] in '}])': parens -= 1 return (logical_start, logical_end) def _get_logical(source_lines, result, logical_start, logical_end): """Return the logical line corresponding to the result. Assumes input is already E702-clean. """ row = result['line'] - 1 col = result['column'] - 1 ls = None le = None for i in range(0, len(logical_start), 1): assert logical_end x = logical_end[i] if x[0] > row or (x[0] == row and x[1] > col): le = x ls = logical_start[i] break if ls is None: return None original = source_lines[ls[0]:le[0] + 1] return ls, le, original def get_item(items, index, default=None): if 0 <= index < len(items): return items[index] return default def reindent(source, indent_size, leave_tabs=False): """Reindent all lines.""" reindenter = Reindenter(source, leave_tabs) return reindenter.run(indent_size) def code_almost_equal(a, b): """Return True if code is similar. Ignore whitespace when comparing specific line. """ split_a = split_and_strip_non_empty_lines(a) split_b = split_and_strip_non_empty_lines(b) if len(split_a) != len(split_b): return False for (index, _) in enumerate(split_a): if ''.join(split_a[index].split()) != ''.join(split_b[index].split()): return False return True def split_and_strip_non_empty_lines(text): """Return lines split by newline. Ignore empty lines. """ return [line.strip() for line in text.splitlines() if line.strip()] def find_newline(source): """Return type of newline used in source. Input is a list of lines. """ assert not isinstance(source, str) counter = collections.defaultdict(int) for line in source: if line.endswith(CRLF): counter[CRLF] += 1 elif line.endswith(CR): counter[CR] += 1 elif line.endswith(LF): counter[LF] += 1 return (sorted(counter, key=counter.get, reverse=True) or [LF])[0] def _get_indentword(source): """Return indentation type.""" indent_word = ' ' # Default in case source has no indentation try: for t in generate_tokens(source): if t[0] == token.INDENT: indent_word = t[1] break except (SyntaxError, tokenize.TokenError): pass return indent_word def _get_indentation(line): """Return leading whitespace.""" if line.strip(): non_whitespace_index = len(line) - len(line.lstrip()) return line[:non_whitespace_index] return '' def get_diff_text(old, new, filename): """Return text of unified diff between old and new.""" newline = '\n' diff = difflib.unified_diff( old, new, 'original/' + filename, 'fixed/' + filename, lineterm=newline) text = '' for line in diff: text += line # Work around missing newline (http://bugs.python.org/issue2142). if text and not line.endswith(newline): text += newline + r'\ No newline at end of file' + newline return text def _priority_key(pep8_result): """Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation. """ priority = [ # Fix multiline colon-based before semicolon based. 'e701', # Break multiline statements early. 'e702', # Things that make lines longer. 'e225', 'e231', # Remove extraneous whitespace before breaking lines. 'e201', # Shorten whitespace in comment before resorting to wrapping. 'e262' ] middle_index = 10000 lowest_priority = [ # We need to shorten lines last since the logical fixer can get in a # loop, which causes us to exit early. 'e501', ] key = pep8_result['id'].lower() try: return priority.index(key) except ValueError: try: return middle_index + lowest_priority.index(key) + 1 except ValueError: return middle_index def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=0, experimental=False, previous_line=''): """Separate line at OPERATOR. Multiple candidates will be yielded. """ for candidate in _shorten_line(tokens=tokens, source=source, indentation=indentation, indent_word=indent_word, aggressive=aggressive, previous_line=previous_line): yield candidate if aggressive: for key_token_strings in SHORTEN_OPERATOR_GROUPS: shortened = _shorten_line_at_tokens( tokens=tokens, source=source, indentation=indentation, indent_word=indent_word, key_token_strings=key_token_strings, aggressive=aggressive) if shortened is not None and shortened != source: yield shortened if experimental: for shortened in _shorten_line_at_tokens_new( tokens=tokens, source=source, indentation=indentation, max_line_length=max_line_length): yield shortened def _shorten_line(tokens, source, indentation, indent_word, aggressive=0, previous_line=''): """Separate line at OPERATOR. The input is expected to be free of newlines except for inside multiline strings and at the end. Multiple candidates will be yielded. """ in_string = False for (token_type, token_string, start_offset, end_offset) in token_offsets(tokens): if IS_SUPPORT_TOKEN_FSTRING: if token_type == tokenize.FSTRING_START: in_string = True elif token_type == tokenize.FSTRING_END: in_string = False if in_string: continue if ( token_type == tokenize.COMMENT and not is_probably_part_of_multiline(previous_line) and not is_probably_part_of_multiline(source) and not source[start_offset + 1:].strip().lower().startswith( ('noqa', 'pragma:', 'pylint:')) ): # Move inline comments to previous line. first = source[:start_offset] second = source[start_offset:] yield (indentation + second.strip() + '\n' + indentation + first.strip() + '\n') elif token_type == token.OP and token_string != '=': # Don't break on '=' after keyword as this violates PEP 8. assert token_type != token.INDENT first = source[:end_offset] second_indent = indentation if (first.rstrip().endswith('(') and source[end_offset:].lstrip().startswith(')')): pass elif first.rstrip().endswith('('): second_indent += indent_word elif '(' in first: second_indent += ' ' * (1 + first.find('(')) else: second_indent += indent_word second = (second_indent + source[end_offset:].lstrip()) if ( not second.strip() or second.lstrip().startswith('#') ): continue # Do not begin a line with a comma if second.lstrip().startswith(','): continue # Do end a line with a dot if first.rstrip().endswith('.'): continue if token_string in '+-*/': fixed = first + ' \\' + '\n' + second else: fixed = first + '\n' + second # Only fix if syntax is okay. if check_syntax(normalize_multiline(fixed) if aggressive else fixed): yield indentation + fixed def _is_binary_operator(token_type, text): return ((token_type == tokenize.OP or text in ['and', 'or']) and text not in '()[]{},:.;@=%~') # A convenient way to handle tokens. Token = collections.namedtuple('Token', ['token_type', 'token_string', 'spos', 'epos', 'line']) class ReformattedLines(object): """The reflowed lines of atoms. Each part of the line is represented as an "atom." They can be moved around when need be to get the optimal formatting. """ ########################################################################### # Private Classes class _Indent(object): """Represent an indentation in the atom stream.""" def __init__(self, indent_amt): self._indent_amt = indent_amt def emit(self): return ' ' * self._indent_amt @property def size(self): return self._indent_amt class _Space(object): """Represent a space in the atom stream.""" def emit(self): return ' ' @property def size(self): return 1 class _LineBreak(object): """Represent a line break in the atom stream.""" def emit(self): return '\n' @property def size(self): return 0 def __init__(self, max_line_length): self._max_line_length = max_line_length self._lines = [] self._bracket_depth = 0 self._prev_item = None self._prev_prev_item = None self._in_fstring = False def __repr__(self): return self.emit() ########################################################################### # Public Methods def add(self, obj, indent_amt, break_after_open_bracket): if isinstance(obj, Atom): self._add_item(obj, indent_amt) return self._add_container(obj, indent_amt, break_after_open_bracket) def add_comment(self, item): num_spaces = 2 if len(self._lines) > 1: if isinstance(self._lines[-1], self._Space): num_spaces -= 1 if len(self._lines) > 2: if isinstance(self._lines[-2], self._Space): num_spaces -= 1 while num_spaces > 0: self._lines.append(self._Space()) num_spaces -= 1 self._lines.append(item) def add_indent(self, indent_amt): self._lines.append(self._Indent(indent_amt)) def add_line_break(self, indent): self._lines.append(self._LineBreak()) self.add_indent(len(indent)) def add_line_break_at(self, index, indent_amt): self._lines.insert(index, self._LineBreak()) self._lines.insert(index + 1, self._Indent(indent_amt)) def add_space_if_needed(self, curr_text, equal=False): if ( not self._lines or isinstance( self._lines[-1], (self._LineBreak, self._Indent, self._Space)) ): return prev_text = str(self._prev_item) prev_prev_text = ( str(self._prev_prev_item) if self._prev_prev_item else '') if ( # The previous item was a keyword or identifier and the current # item isn't an operator that doesn't require a space. ((self._prev_item.is_keyword or self._prev_item.is_string or self._prev_item.is_name or self._prev_item.is_number) and (curr_text[0] not in '([{.,:}])' or (curr_text[0] == '=' and equal))) or # Don't place spaces around a '.', unless it's in an 'import' # statement. ((prev_prev_text != 'from' and prev_text[-1] != '.' and curr_text != 'import') and # Don't place a space before a colon. curr_text[0] != ':' and # Don't split up ending brackets by spaces. ((prev_text[-1] in '}])' and curr_text[0] not in '.,}])') or # Put a space after a colon or comma. prev_text[-1] in ':,' or # Put space around '=' if asked to. (equal and prev_text == '=') or # Put spaces around non-unary arithmetic operators. ((self._prev_prev_item and (prev_text not in '+-' and (self._prev_prev_item.is_name or self._prev_prev_item.is_number or self._prev_prev_item.is_string)) and prev_text in ('+', '-', '%', '*', '/', '//', '**', 'in'))))) ): self._lines.append(self._Space()) def previous_item(self): """Return the previous non-whitespace item.""" return self._prev_item def fits_on_current_line(self, item_extent): return self.current_size() + item_extent <= self._max_line_length def current_size(self): """The size of the current line minus the indentation.""" size = 0 for item in reversed(self._lines): size += item.size if isinstance(item, self._LineBreak): break return size def line_empty(self): return (self._lines and isinstance(self._lines[-1], (self._LineBreak, self._Indent))) def emit(self): string = '' for item in self._lines: if isinstance(item, self._LineBreak): string = string.rstrip() string += item.emit() return string.rstrip() + '\n' ########################################################################### # Private Methods def _add_item(self, item, indent_amt): """Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not. """ if item.is_fstring_start: self._in_fstring = True elif self._prev_item and self._prev_item.is_fstring_end: self._in_fstring = False if self._prev_item and self._prev_item.is_string and item.is_string: # Place consecutive string literals on separate lines. self._lines.append(self._LineBreak()) self._lines.append(self._Indent(indent_amt)) item_text = str(item) if self._lines and self._bracket_depth: # Adding the item into a container. self._prevent_default_initializer_splitting(item, indent_amt) if item_text in '.,)]}': self._split_after_delimiter(item, indent_amt) elif self._lines and not self.line_empty(): # Adding the item outside of a container. if self.fits_on_current_line(len(item_text)): self._enforce_space(item) else: # Line break for the new item. self._lines.append(self._LineBreak()) self._lines.append(self._Indent(indent_amt)) self._lines.append(item) self._prev_item, self._prev_prev_item = item, self._prev_item if item_text in '([{' and not self._in_fstring: self._bracket_depth += 1 elif item_text in '}])' and not self._in_fstring: self._bracket_depth -= 1 assert self._bracket_depth >= 0 def _add_container(self, container, indent_amt, break_after_open_bracket): actual_indent = indent_amt + 1 if ( str(self._prev_item) != '=' and not self.line_empty() and not self.fits_on_current_line( container.size + self._bracket_depth + 2) ): if str(container)[0] == '(' and self._prev_item.is_name: # Don't split before the opening bracket of a call. break_after_open_bracket = True actual_indent = indent_amt + 4 elif ( break_after_open_bracket or str(self._prev_item) not in '([{' ): # If the container doesn't fit on the current line and the # current line isn't empty, place the container on the next # line. self._lines.append(self._LineBreak()) self._lines.append(self._Indent(indent_amt)) break_after_open_bracket = False else: actual_indent = self.current_size() + 1 break_after_open_bracket = False if isinstance(container, (ListComprehension, IfExpression)): actual_indent = indent_amt # Increase the continued indentation only if recursing on a # container. container.reflow(self, ' ' * actual_indent, break_after_open_bracket=break_after_open_bracket) def _prevent_default_initializer_splitting(self, item, indent_amt): """Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. This goes back along the current line to determine if we have a default initializer, and, if so, to remove extraneous whitespaces and add a line break/indent before it if needed. """ if str(item) == '=': # This is the assignment in the initializer. Just remove spaces for # now. self._delete_whitespace() return if (not self._prev_item or not self._prev_prev_item or str(self._prev_item) != '='): return self._delete_whitespace() prev_prev_index = self._lines.index(self._prev_prev_item) if ( isinstance(self._lines[prev_prev_index - 1], self._Indent) or self.fits_on_current_line(item.size + 1) ): # The default initializer is already the only item on this line. # Don't insert a newline here. return # Replace the space with a newline/indent combo. if isinstance(self._lines[prev_prev_index - 1], self._Space): del self._lines[prev_prev_index - 1] self.add_line_break_at(self._lines.index(self._prev_prev_item), indent_amt) def _split_after_delimiter(self, item, indent_amt): """Split the line only after a delimiter.""" self._delete_whitespace() if self.fits_on_current_line(item.size): return last_space = None for current_item in reversed(self._lines): if ( last_space and (not isinstance(current_item, Atom) or not current_item.is_colon) ): break else: last_space = None if isinstance(current_item, self._Space): last_space = current_item if isinstance(current_item, (self._LineBreak, self._Indent)): return if not last_space: return self.add_line_break_at(self._lines.index(last_space), indent_amt) def _enforce_space(self, item): """Enforce a space in certain situations. There are cases where we will want a space where normally we wouldn't put one. This just enforces the addition of a space. """ if isinstance(self._lines[-1], (self._Space, self._LineBreak, self._Indent)): return if not self._prev_item: return item_text = str(item) prev_text = str(self._prev_item) # Prefer a space around a '.' in an import statement, and between the # 'import' and '('. if ( (item_text == '.' and prev_text == 'from') or (item_text == 'import' and prev_text == '.') or (item_text == '(' and prev_text == 'import') ): self._lines.append(self._Space()) def _delete_whitespace(self): """Delete all whitespace from the end of the line.""" while isinstance(self._lines[-1], (self._Space, self._LineBreak, self._Indent)): del self._lines[-1] class Atom(object): """The smallest unbreakable unit that can be reflowed.""" def __init__(self, atom): self._atom = atom def __repr__(self): return self._atom.token_string def __len__(self): return self.size def reflow( self, reflowed_lines, continued_indent, extent, break_after_open_bracket=False, is_list_comp_or_if_expr=False, next_is_dot=False ): if self._atom.token_type == tokenize.COMMENT: reflowed_lines.add_comment(self) return total_size = extent if extent else self.size if self._atom.token_string not in ',:([{}])': # Some atoms will need an extra 1-sized space token after them. total_size += 1 prev_item = reflowed_lines.previous_item() if ( not is_list_comp_or_if_expr and not reflowed_lines.fits_on_current_line(total_size) and not (next_is_dot and reflowed_lines.fits_on_current_line(self.size + 1)) and not reflowed_lines.line_empty() and not self.is_colon and not (prev_item and prev_item.is_name and str(self) == '(') ): # Start a new line if there is already something on the line and # adding this atom would make it go over the max line length. reflowed_lines.add_line_break(continued_indent) else: reflowed_lines.add_space_if_needed(str(self)) reflowed_lines.add(self, len(continued_indent), break_after_open_bracket) def emit(self): return self.__repr__() @property def is_keyword(self): return keyword.iskeyword(self._atom.token_string) @property def is_string(self): return self._atom.token_type == tokenize.STRING @property def is_fstring_start(self): if not IS_SUPPORT_TOKEN_FSTRING: return False return self._atom.token_type == tokenize.FSTRING_START @property def is_fstring_end(self): if not IS_SUPPORT_TOKEN_FSTRING: return False return self._atom.token_type == tokenize.FSTRING_END @property def is_name(self): return self._atom.token_type == tokenize.NAME @property def is_number(self): return self._atom.token_type == tokenize.NUMBER @property def is_comma(self): return self._atom.token_string == ',' @property def is_colon(self): return self._atom.token_string == ':' @property def size(self): return len(self._atom.token_string) class Container(object): """Base class for all container types.""" def __init__(self, items): self._items = items def __repr__(self): string = '' last_was_keyword = False for item in self._items: if item.is_comma: string += ', ' elif item.is_colon: string += ': ' else: item_string = str(item) if ( string and (last_was_keyword or (not string.endswith(tuple('([{,.:}]) ')) and not item_string.startswith(tuple('([{,.:}])')))) ): string += ' ' string += item_string last_was_keyword = item.is_keyword return string def __iter__(self): for element in self._items: yield element def __getitem__(self, idx): return self._items[idx] def reflow(self, reflowed_lines, continued_indent, break_after_open_bracket=False): last_was_container = False for (index, item) in enumerate(self._items): next_item = get_item(self._items, index + 1) if isinstance(item, Atom): is_list_comp_or_if_expr = ( isinstance(self, (ListComprehension, IfExpression))) item.reflow(reflowed_lines, continued_indent, self._get_extent(index), is_list_comp_or_if_expr=is_list_comp_or_if_expr, next_is_dot=(next_item and str(next_item) == '.')) if last_was_container and item.is_comma: reflowed_lines.add_line_break(continued_indent) last_was_container = False else: # isinstance(item, Container) reflowed_lines.add(item, len(continued_indent), break_after_open_bracket) last_was_container = not isinstance(item, (ListComprehension, IfExpression)) if ( break_after_open_bracket and index == 0 and # Prefer to keep empty containers together instead of # separating them. str(item) == self.open_bracket and (not next_item or str(next_item) != self.close_bracket) and (len(self._items) != 3 or not isinstance(next_item, Atom)) ): reflowed_lines.add_line_break(continued_indent) break_after_open_bracket = False else: next_next_item = get_item(self._items, index + 2) if ( str(item) not in ['.', '%', 'in'] and next_item and not isinstance(next_item, Container) and str(next_item) != ':' and next_next_item and (not isinstance(next_next_item, Atom) or str(next_item) == 'not') and not reflowed_lines.line_empty() and not reflowed_lines.fits_on_current_line( self._get_extent(index + 1) + 2) ): reflowed_lines.add_line_break(continued_indent) def _get_extent(self, index): """The extent of the full element. E.g., the length of a function call or keyword. """ extent = 0 prev_item = get_item(self._items, index - 1) seen_dot = prev_item and str(prev_item) == '.' while index < len(self._items): item = get_item(self._items, index) index += 1 if isinstance(item, (ListComprehension, IfExpression)): break if isinstance(item, Container): if prev_item and prev_item.is_name: if seen_dot: extent += 1 else: extent += item.size prev_item = item continue elif (str(item) not in ['.', '=', ':', 'not'] and not item.is_name and not item.is_string): break if str(item) == '.': seen_dot = True extent += item.size prev_item = item return extent @property def is_string(self): return False @property def size(self): return len(self.__repr__()) @property def is_keyword(self): return False @property def is_name(self): return False @property def is_comma(self): return False @property def is_colon(self): return False @property def open_bracket(self): return None @property def close_bracket(self): return None class Tuple(Container): """A high-level representation of a tuple.""" @property def open_bracket(self): return '(' @property def close_bracket(self): return ')' class List(Container): """A high-level representation of a list.""" @property def open_bracket(self): return '[' @property def close_bracket(self): return ']' class DictOrSet(Container): """A high-level representation of a dictionary or set.""" @property def open_bracket(self): return '{' @property def close_bracket(self): return '}' class ListComprehension(Container): """A high-level representation of a list comprehension.""" @property def size(self): length = 0 for item in self._items: if isinstance(item, IfExpression): break length += item.size return length class IfExpression(Container): """A high-level representation of an if-expression.""" def _parse_container(tokens, index, for_or_if=None): """Parse a high-level container, such as a list, tuple, etc.""" # Store the opening bracket. items = [Atom(Token(*tokens[index]))] index += 1 num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) if tok.token_string in ',)]}': # First check if we're at the end of a list comprehension or # if-expression. Don't add the ending token as part of the list # comprehension or if-expression, because they aren't part of those # constructs. if for_or_if == 'for': return (ListComprehension(items), index - 1) elif for_or_if == 'if': return (IfExpression(items), index - 1) # We've reached the end of a container. items.append(Atom(tok)) # If not, then we are at the end of a container. if tok.token_string == ')': # The end of a tuple. return (Tuple(items), index) elif tok.token_string == ']': # The end of a list. return (List(items), index) elif tok.token_string == '}': # The end of a dictionary or set. return (DictOrSet(items), index) elif tok.token_string in '([{': # A sub-container is being defined. (container, index) = _parse_container(tokens, index) items.append(container) elif tok.token_string == 'for': (container, index) = _parse_container(tokens, index, 'for') items.append(container) elif tok.token_string == 'if': (container, index) = _parse_container(tokens, index, 'if') items.append(container) else: items.append(Atom(tok)) index += 1 return (None, None) def _parse_tokens(tokens): """Parse the tokens. This converts the tokens into a form where we can manipulate them more easily. """ index = 0 parsed_tokens = [] num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) assert tok.token_type != token.INDENT if tok.token_type == tokenize.NEWLINE: # There's only one newline and it's at the end. break if tok.token_string in '([{': (container, index) = _parse_container(tokens, index) if not container: return None parsed_tokens.append(container) else: parsed_tokens.append(Atom(tok)) index += 1 return parsed_tokens def _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line): """Reflow the lines so that it looks nice.""" if str(parsed_tokens[0]) == 'def': # A function definition gets indented a bit more. continued_indent = indentation + ' ' * 2 * DEFAULT_INDENT_SIZE else: continued_indent = indentation + ' ' * DEFAULT_INDENT_SIZE break_after_open_bracket = not start_on_prefix_line lines = ReformattedLines(max_line_length) lines.add_indent(len(indentation.lstrip('\r\n'))) if not start_on_prefix_line: # If splitting after the opening bracket will cause the first element # to be aligned weirdly, don't try it. first_token = get_item(parsed_tokens, 0) second_token = get_item(parsed_tokens, 1) if ( first_token and second_token and str(second_token)[0] == '(' and len(indentation) + len(first_token) + 1 == len(continued_indent) ): return None for item in parsed_tokens: lines.add_space_if_needed(str(item), equal=True) save_continued_indent = continued_indent if start_on_prefix_line and isinstance(item, Container): start_on_prefix_line = False continued_indent = ' ' * (lines.current_size() + 1) item.reflow(lines, continued_indent, break_after_open_bracket) continued_indent = save_continued_indent return lines.emit() def _shorten_line_at_tokens_new(tokens, source, indentation, max_line_length): """Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end. """ # Yield the original source so to see if it's a better choice than the # shortened candidate lines we generate here. yield indentation + source parsed_tokens = _parse_tokens(tokens) if parsed_tokens: # Perform two reflows. The first one starts on the same line as the # prefix. The second starts on the line after the prefix. fixed = _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line=True) if fixed and check_syntax(normalize_multiline(fixed.lstrip())): yield fixed fixed = _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line=False) if fixed and check_syntax(normalize_multiline(fixed.lstrip())): yield fixed def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive): """Separate line by breaking at tokens in key_token_strings. The input is expected to be free of newlines except for inside multiline strings and at the end. """ offsets = [] for (index, _t) in enumerate(token_offsets(tokens)): (token_type, token_string, start_offset, end_offset) = _t assert token_type != token.INDENT if token_string in key_token_strings: # Do not break in containers with zero or one items. unwanted_next_token = { '(': ')', '[': ']', '{': '}'}.get(token_string) if unwanted_next_token: if ( get_item(tokens, index + 1, default=[None, None])[1] == unwanted_next_token or get_item(tokens, index + 2, default=[None, None])[1] == unwanted_next_token ): continue if ( index > 2 and token_string == '(' and tokens[index - 1][1] in ',(%[' ): # Don't split after a tuple start, or before a tuple start if # the tuple is in a list. continue if end_offset < len(source) - 1: # Don't split right before newline. offsets.append(end_offset) else: # Break at adjacent strings. These were probably meant to be on # separate lines in the first place. previous_token = get_item(tokens, index - 1) if ( token_type == tokenize.STRING and previous_token and previous_token[0] == tokenize.STRING ): offsets.append(start_offset) current_indent = None fixed = None for line in split_at_offsets(source, offsets): if fixed: fixed += '\n' + current_indent + line for symbol in '([{': if line.endswith(symbol): current_indent += indent_word else: # First line. fixed = line assert not current_indent current_indent = indent_word assert fixed is not None if check_syntax(normalize_multiline(fixed) if aggressive > 1 else fixed): return indentation + fixed return None def token_offsets(tokens): """Yield tokens and offsets.""" end_offset = 0 previous_end_row = 0 previous_end_column = 0 for t in tokens: token_type = t[0] token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] # Account for the whitespace between tokens. end_offset += start_column if previous_end_row == start_row: end_offset -= previous_end_column # Record the start offset of the token. start_offset = end_offset # Account for the length of the token itself. end_offset += len(token_string) yield (token_type, token_string, start_offset, end_offset) previous_end_row = end_row previous_end_column = end_column def normalize_multiline(line): """Normalize multiline-related code that will cause syntax error. This is for purposes of checking syntax. """ if line.startswith(('def ', 'async def ')) and line.rstrip().endswith(':'): return line + ' pass' elif line.startswith('return '): return 'def _(): ' + line elif line.startswith('@'): return line + 'def _(): pass' elif line.startswith('class '): return line + ' pass' elif line.startswith(('if ', 'elif ', 'for ', 'while ')): return line + ' pass' return line def fix_whitespace(line, offset, replacement): """Replace whitespace at offset and return fixed line.""" # Replace escaped newlines too left = line[:offset].rstrip('\n\r \t\\') right = line[offset:].lstrip('\n\r \t\\') if right.startswith('#'): return line return left + replacement + right def _execute_pep8(pep8_options, source): """Execute pycodestyle via python method calls.""" class QuietReport(pycodestyle.BaseReport): """Version of checker that does not print.""" def __init__(self, options): super(QuietReport, self).__init__(options) self.__full_error_results = [] def error(self, line_number, offset, text, check): """Collect errors.""" code = super(QuietReport, self).error(line_number, offset, text, check) if code: self.__full_error_results.append( {'id': code, 'line': line_number, 'column': offset + 1, 'info': text}) def full_error_results(self): """Return error results in detail. Results are in the form of a list of dictionaries. Each dictionary contains 'id', 'line', 'column', and 'info'. """ return self.__full_error_results checker = pycodestyle.Checker('', lines=source, reporter=QuietReport, **pep8_options) checker.check_all() return checker.report.full_error_results() def _remove_leading_and_normalize(line, with_rstrip=True): # ignore FF in first lstrip() if with_rstrip: return line.lstrip(' \t\v').rstrip(CR + LF) + '\n' return line.lstrip(' \t\v') class Reindenter(object): """Reindents badly-indented code to uniformly use four-space indentation. Released to the public domain, by Tim Peters, 03 October 2000. """ def __init__(self, input_text, leave_tabs=False): sio = io.StringIO(input_text) source_lines = sio.readlines() self.string_content_line_numbers = multiline_string_lines(input_text) # File lines, rstripped & tab-expanded. Dummy at start is so # that we can use tokenize's 1-based line numbering easily. # Note that a line is all-blank iff it is a newline. self.lines = [] for line_number, line in enumerate(source_lines, start=1): # Do not modify if inside a multiline string. if line_number in self.string_content_line_numbers: self.lines.append(line) else: # Only expand leading tabs. with_rstrip = line_number != len(source_lines) if leave_tabs: self.lines.append( _get_indentation(line) + _remove_leading_and_normalize(line, with_rstrip) ) else: self.lines.append( _get_indentation(line).expandtabs() + _remove_leading_and_normalize(line, with_rstrip) ) self.lines.insert(0, None) self.index = 1 # index into self.lines of next line self.input_text = input_text def run(self, indent_size=DEFAULT_INDENT_SIZE): """Fix indentation and return modified line numbers. Line numbers are indexed at 1. """ if indent_size < 1: return self.input_text try: stats = _reindent_stats(tokenize.generate_tokens(self.getline)) except (SyntaxError, tokenize.TokenError): return self.input_text # Remove trailing empty lines. lines = self.lines # Sentinel. stats.append((len(lines), 0)) # Map count of leading spaces to # we want. have2want = {} # Program after transformation. after = [] # Copy over initial empty lines -- there's nothing to do until # we see a line with *something* on it. i = stats[0][0] after.extend(lines[1:i]) for i in range(len(stats) - 1): thisstmt, thislevel = stats[i] nextstmt = stats[i + 1][0] have = _leading_space_count(lines[thisstmt]) want = thislevel * indent_size if want < 0: # A comment line. if have: # An indented comment line. If we saw the same # indentation before, reuse what it most recently # mapped to. want = have2want.get(have, -1) if want < 0: # Then it probably belongs to the next real stmt. for j in range(i + 1, len(stats) - 1): jline, jlevel = stats[j] if jlevel >= 0: if have == _leading_space_count(lines[jline]): want = jlevel * indent_size break # Maybe it's a hanging comment like this one, if want < 0: # in which case we should shift it like its base # line got shifted. for j in range(i - 1, -1, -1): jline, jlevel = stats[j] if jlevel >= 0: want = (have + _leading_space_count( after[jline - 1]) - _leading_space_count(lines[jline])) break if want < 0: # Still no luck -- leave it alone. want = have else: want = 0 assert want >= 0 have2want[have] = want diff = want - have if diff == 0 or have == 0: after.extend(lines[thisstmt:nextstmt]) else: for line_number, line in enumerate(lines[thisstmt:nextstmt], start=thisstmt): if line_number in self.string_content_line_numbers: after.append(line) elif diff > 0: if line == '\n': after.append(line) else: after.append(' ' * diff + line) else: remove = min(_leading_space_count(line), -diff) after.append(line[remove:]) return ''.join(after) def getline(self): """Line-getter for tokenize.""" if self.index >= len(self.lines): line = '' else: line = self.lines[self.index] self.index += 1 return line def _reindent_stats(tokens): """Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache! """ find_stmt = 1 # Next token begins a fresh stmt? level = 0 # Current indent level. stats = [] for t in tokens: token_type = t[0] sline = t[2][0] line = t[4] if token_type == tokenize.NEWLINE: # A program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? find_stmt = 1 elif token_type == tokenize.INDENT: find_stmt = 1 level += 1 elif token_type == tokenize.DEDENT: find_stmt = 1 level -= 1 elif token_type == tokenize.COMMENT: if find_stmt: stats.append((sline, -1)) # But we're still looking for a new stmt, so leave # find_stmt alone. elif token_type == tokenize.NL: pass elif find_stmt: # This is the first "real token" following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER. find_stmt = 0 if line: # Not endmarker. stats.append((sline, level)) return stats def _leading_space_count(line): """Return number of leading spaces in line.""" i = 0 while i < len(line) and line[i] == ' ': i += 1 return i def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '', 'exec', dont_inherit=True) except (SyntaxError, TypeError, ValueError): return False def find_with_line_numbers(pattern, contents): """A wrapper around 're.finditer' to find line numbers. Returns a list of line numbers where pattern was found in contents. """ matches = list(re.finditer(pattern, contents)) if not matches: return [] end = matches[-1].start() # -1 so a failed `rfind` maps to the first line. newline_offsets = { -1: 0 } for line_num, m in enumerate(re.finditer(r'\n', contents), 1): offset = m.start() if offset > end: break newline_offsets[offset] = line_num def get_line_num(match, contents): """Get the line number of string in a files contents. Failing to find the newline is OK, -1 maps to 0 """ newline_offset = contents.rfind('\n', 0, match.start()) return newline_offsets[newline_offset] return [get_line_num(match, contents) + 1 for match in matches] def get_disabled_ranges(source): """Returns a list of tuples representing the disabled ranges. If disabled and no re-enable will disable for rest of file. """ enable_line_nums = find_with_line_numbers(ENABLE_REGEX, source) disable_line_nums = find_with_line_numbers(DISABLE_REGEX, source) total_lines = len(re.findall("\n", source)) + 1 enable_commands = {} for num in enable_line_nums: enable_commands[num] = True for num in disable_line_nums: enable_commands[num] = False disabled_ranges = [] currently_enabled = True disabled_start = None for line, commanded_enabled in sorted(enable_commands.items()): if commanded_enabled is False and currently_enabled is True: disabled_start = line currently_enabled = False elif commanded_enabled is True and currently_enabled is False: disabled_ranges.append((disabled_start, line)) currently_enabled = True if currently_enabled is False: disabled_ranges.append((disabled_start, total_lines)) return disabled_ranges def filter_disabled_results(result, disabled_ranges): """Filter out reports based on tuple of disabled ranges. """ line = result['line'] for disabled_range in disabled_ranges: if disabled_range[0] <= line <= disabled_range[1]: return False return True def filter_results(source, results, aggressive): """Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712). """ non_docstring_string_line_numbers = multiline_string_lines( source, include_docstrings=False) all_string_line_numbers = multiline_string_lines( source, include_docstrings=True) commented_out_code_line_numbers = commented_out_code_lines(source) # Filter out the disabled ranges disabled_ranges = get_disabled_ranges(source) if disabled_ranges: results = [ result for result in results if filter_disabled_results( result, disabled_ranges, ) ] has_e901 = any(result['id'].lower() == 'e901' for result in results) for r in results: issue_id = r['id'].lower() if r['line'] in non_docstring_string_line_numbers: if issue_id.startswith(('e1', 'e501', 'w191')): continue if r['line'] in all_string_line_numbers: if issue_id in ['e501']: continue # We must offset by 1 for lines that contain the trailing contents of # multiline strings. if not aggressive and (r['line'] + 1) in all_string_line_numbers: # Do not modify multiline strings in non-aggressive mode. Remove # trailing whitespace could break doctests. if issue_id.startswith(('w29', 'w39')): continue if aggressive <= 0: if issue_id.startswith(('e711', 'e72', 'w6')): continue if aggressive <= 1: if issue_id.startswith(('e712', 'e713', 'e714')): continue if aggressive <= 2: if issue_id.startswith(('e704')): continue if r['line'] in commented_out_code_line_numbers: if issue_id.startswith(('e261', 'e262', 'e501')): continue # Do not touch indentation if there is a token error caused by # incomplete multi-line statement. Otherwise, we risk screwing up the # indentation. if has_e901: if issue_id.startswith(('e1', 'e7')): continue yield r def multiline_string_lines(source, include_docstrings=False): """Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored. """ line_numbers = set() previous_token_type = '' _check_target_tokens = [tokenize.STRING] if IS_SUPPORT_TOKEN_FSTRING: _check_target_tokens.extend([ tokenize.FSTRING_START, tokenize.FSTRING_MIDDLE, tokenize.FSTRING_END, ]) try: for t in generate_tokens(source): token_type = t[0] start_row = t[2][0] end_row = t[3][0] if token_type in _check_target_tokens and start_row != end_row: if ( include_docstrings or previous_token_type != tokenize.INDENT ): # We increment by one since we want the contents of the # string. line_numbers |= set(range(1 + start_row, 1 + end_row)) previous_token_type = token_type except (SyntaxError, tokenize.TokenError): pass return line_numbers def commented_out_code_lines(source): """Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter. """ line_numbers = [] try: for t in generate_tokens(source): token_type = t[0] token_string = t[1] start_row = t[2][0] line = t[4] # Ignore inline comments. if not line.lstrip().startswith('#'): continue if token_type == tokenize.COMMENT: stripped_line = token_string.lstrip('#').strip() with warnings.catch_warnings(): # ignore SyntaxWarning in Python3.8+ # refs: # https://bugs.python.org/issue15248 # https://docs.python.org/3.8/whatsnew/3.8.html#other-language-changes warnings.filterwarnings("ignore", category=SyntaxWarning) if ( ' ' in stripped_line and '#' not in stripped_line and check_syntax(stripped_line) ): line_numbers.append(start_row) except (SyntaxError, tokenize.TokenError): pass return line_numbers def shorten_comment(line, max_line_length, last_comment=False): """Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text. """ assert len(line) > max_line_length line = line.rstrip() # PEP 8 recommends 72 characters for comment text. indentation = _get_indentation(line) + '# ' max_line_length = min(max_line_length, len(indentation) + 72) MIN_CHARACTER_REPEAT = 5 if ( len(line) - len(line.rstrip(line[-1])) >= MIN_CHARACTER_REPEAT and not line[-1].isalnum() ): # Trim comments that end with things like --------- return line[:max_line_length] + '\n' elif last_comment and re.match(r'\s*#+\s*\w+', line): split_lines = textwrap.wrap(line.lstrip(' \t#'), initial_indent=indentation, subsequent_indent=indentation, width=max_line_length, break_long_words=False, break_on_hyphens=False) return '\n'.join(split_lines) + '\n' return line + '\n' def normalize_line_endings(lines, newline): """Return fixed line endings. All lines will be modified to use the most common line ending. """ line = [line.rstrip('\n\r') + newline for line in lines] if line and lines[-1] == lines[-1].rstrip('\n\r'): line[-1] = line[-1].rstrip('\n\r') return line def mutual_startswith(a, b): return b.startswith(a) or a.startswith(b) def code_match(code, select, ignore): if ignore: assert not isinstance(ignore, str) for ignored_code in [c.strip() for c in ignore]: if mutual_startswith(code.lower(), ignored_code.lower()): return False if select: assert not isinstance(select, str) for selected_code in [c.strip() for c in select]: if mutual_startswith(code.lower(), selected_code.lower()): return True return False return True def fix_code(source, options=None, encoding=None, apply_config=False): """Return fixed source code. "encoding" will be used to decode "source" if it is a byte string. """ options = _get_options(options, apply_config) # normalize options.ignore = [opt.upper() for opt in options.ignore] options.select = [opt.upper() for opt in options.select] # check ignore args # NOTE: If W50x is not included, add W50x because the code # correction result is indefinite. ignore_opt = options.ignore if not {"W50", "W503", "W504"} & set(ignore_opt): options.ignore.append("W50") if not isinstance(source, str): source = source.decode(encoding or get_encoding()) sio = io.StringIO(source) return fix_lines(sio.readlines(), options=options) def _get_options(raw_options, apply_config): """Return parsed options.""" if not raw_options: return parse_args([''], apply_config=apply_config) if isinstance(raw_options, dict): options = parse_args([''], apply_config=apply_config) for name, value in raw_options.items(): if not hasattr(options, name): raise ValueError("No such option '{}'".format(name)) # Check for very basic type errors. expected_type = type(getattr(options, name)) if not isinstance(expected_type, (str, )): if isinstance(value, (str, )): raise ValueError( "Option '{}' should not be a string".format(name)) setattr(options, name, value) else: options = raw_options return options def fix_lines(source_lines, options, filename=''): """Return fixed source code.""" # Transform everything to line feed. Then change them back to original # before returning fixed source code. original_newline = find_newline(source_lines) tmp_source = ''.join(normalize_line_endings(source_lines, '\n')) # Keep a history to break out of cycles. previous_hashes = set() if options.line_range: # Disable "apply_local_fixes()" for now due to issue #175. fixed_source = tmp_source else: # Apply global fixes only once (for efficiency). fixed_source = apply_global_fixes(tmp_source, options, filename=filename) passes = 0 long_line_ignore_cache = set() while hash(fixed_source) not in previous_hashes: if options.pep8_passes >= 0 and passes > options.pep8_passes: break passes += 1 previous_hashes.add(hash(fixed_source)) tmp_source = copy.copy(fixed_source) fix = FixPEP8( filename, options, contents=tmp_source, long_line_ignore_cache=long_line_ignore_cache) fixed_source = fix.fix() sio = io.StringIO(fixed_source) return ''.join(normalize_line_endings(sio.readlines(), original_newline)) def fix_file(filename, options=None, output=None, apply_config=False): if not options: options = parse_args([filename], apply_config=apply_config) original_source = readlines_from_file(filename) fixed_source = original_source if options.in_place or options.diff or output: encoding = detect_encoding(filename) if output: output = LineEndingWrapper(wrap_output(output, encoding=encoding)) fixed_source = fix_lines(fixed_source, options, filename=filename) if options.diff: new = io.StringIO(fixed_source) new = new.readlines() diff = get_diff_text(original_source, new, filename) if output: output.write(diff) output.flush() elif options.jobs > 1: diff = diff.encode(encoding) return diff elif options.in_place: original = "".join(original_source).splitlines() fixed = fixed_source.splitlines() original_source_last_line = ( original_source[-1].split("\n")[-1] if original_source else "" ) fixed_source_last_line = fixed_source.split("\n")[-1] if original != fixed or ( original_source_last_line != fixed_source_last_line ): with open_with_encoding(filename, 'w', encoding=encoding) as fp: fp.write(fixed_source) return fixed_source return None else: if output: output.write(fixed_source) output.flush() return fixed_source def global_fixes(): """Yield multiple (code, function) tuples.""" for function in list(globals().values()): if inspect.isfunction(function): arguments = _get_parameters(function) if arguments[:1] != ['source']: continue code = extract_code_from_function(function) if code: yield (code, function) def _get_parameters(function): # pylint: disable=deprecated-method if sys.version_info.major >= 3: # We need to match "getargspec()", which includes "self" as the first # value for methods. # https://bugs.python.org/issue17481#msg209469 if inspect.ismethod(function): function = function.__func__ return list(inspect.signature(function).parameters) else: return inspect.getargspec(function)[0] def apply_global_fixes(source, options, where='global', filename='', codes=None): """Run global fixes on source code. These are fixes that only need be done once (unlike those in FixPEP8, which are dependent on pycodestyle). """ if codes is None: codes = [] if any(code_match(code, select=options.select, ignore=options.ignore) for code in ['E101', 'E111']): source = reindent( source, indent_size=options.indent_size, leave_tabs=not ( code_match( 'W191', select=options.select, ignore=options.ignore ) ) ) for (code, function) in global_fixes(): if code_match(code, select=options.select, ignore=options.ignore): if options.verbose: print('---> Applying {} fix for {}'.format(where, code.upper()), file=sys.stderr) source = function(source, aggressive=options.aggressive) return source def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None return code def _get_package_version(): packages = ["pycodestyle: {}".format(pycodestyle.__version__)] return ", ".join(packages) def create_parser(): """Return command-line parser.""" parser = argparse.ArgumentParser(description=docstring_summary(__doc__), prog='autopep8') parser.add_argument('--version', action='version', version='%(prog)s {} ({})'.format( __version__, _get_package_version())) parser.add_argument('-v', '--verbose', action='count', default=0, help='print verbose messages; ' 'multiple -v result in more verbose messages') parser.add_argument('-d', '--diff', action='store_true', help='print the diff for the fixed source') parser.add_argument('-i', '--in-place', action='store_true', help='make changes to files in place') parser.add_argument('--global-config', metavar='filename', default=DEFAULT_CONFIG, help='path to a global pep8 config file; if this file ' 'does not exist then this is ignored ' '(default: {})'.format(DEFAULT_CONFIG)) parser.add_argument('--ignore-local-config', action='store_true', help="don't look for and apply local config files; " 'if not passed, defaults are updated with any ' "config files in the project's root directory") parser.add_argument('-r', '--recursive', action='store_true', help='run recursively over directories; ' 'must be used with --in-place or --diff') parser.add_argument('-j', '--jobs', type=int, metavar='n', default=1, help='number of parallel jobs; ' 'match CPU count if value is less than 1') parser.add_argument('-p', '--pep8-passes', metavar='n', default=-1, type=int, help='maximum number of additional pep8 passes ' '(default: infinite)') parser.add_argument('-a', '--aggressive', action='count', default=0, help='enable non-whitespace changes; ' 'multiple -a result in more aggressive changes') parser.add_argument('--experimental', action='store_true', help='enable experimental fixes') parser.add_argument('--exclude', metavar='globs', help='exclude file/directory names that match these ' 'comma-separated globs') parser.add_argument('--list-fixes', action='store_true', help='list codes for fixes; ' 'used by --ignore and --select') parser.add_argument('--ignore', metavar='errors', default='', help='do not fix these errors/warnings ' '(default: {})'.format(DEFAULT_IGNORE)) parser.add_argument('--select', metavar='errors', default='', help='fix only these errors/warnings (e.g. E4,W)') parser.add_argument('--max-line-length', metavar='n', default=79, type=int, help='set maximum allowed line length ' '(default: %(default)s)') parser.add_argument('--line-range', '--range', metavar='line', default=None, type=int, nargs=2, help='only fix errors found within this inclusive ' 'range of line numbers (e.g. 1 99); ' 'line numbers are indexed at 1') parser.add_argument('--indent-size', default=DEFAULT_INDENT_SIZE, type=int, help=argparse.SUPPRESS) parser.add_argument('--hang-closing', action='store_true', help='hang-closing option passed to pycodestyle') parser.add_argument('--exit-code', action='store_true', help='change to behavior of exit code.' ' default behavior of return value, 0 is no ' 'differences, 1 is error exit. return 2 when' ' add this option. 2 is exists differences.') parser.add_argument('files', nargs='*', help="files to format or '-' for standard in") return parser def _expand_codes(codes, ignore_codes): """expand to individual E/W codes""" ret = set() is_conflict = False if all( any( conflicting_code.startswith(code) for code in codes ) for conflicting_code in CONFLICTING_CODES ): is_conflict = True is_ignore_w503 = "W503" in ignore_codes is_ignore_w504 = "W504" in ignore_codes for code in codes: if code == "W": if is_ignore_w503 and is_ignore_w504: ret.update({"W1", "W2", "W3", "W505", "W6"}) elif is_ignore_w503: ret.update({"W1", "W2", "W3", "W504", "W505", "W6"}) else: ret.update({"W1", "W2", "W3", "W503", "W505", "W6"}) elif code in ("W5", "W50"): if is_ignore_w503 and is_ignore_w504: ret.update({"W505"}) elif is_ignore_w503: ret.update({"W504", "W505"}) else: ret.update({"W503", "W505"}) elif not (code in ("W503", "W504") and is_conflict): ret.add(code) return ret def _parser_error_with_code( parser: argparse.ArgumentParser, code: int, msg: str, ) -> None: """wrap parser.error with exit code""" parser.print_usage(sys.stderr) parser.exit(code, f"{msg}\n") def parse_args(arguments, apply_config=False): """Parse command-line options.""" parser = create_parser() args = parser.parse_args(arguments) if not args.files and not args.list_fixes: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, 'incorrect number of arguments', ) args.files = [decode_filename(name) for name in args.files] if apply_config: parser = read_config(args, parser) # prioritize settings when exist pyproject.toml's tool.autopep8 section try: parser_with_pyproject_toml = read_pyproject_toml(args, parser) except Exception: parser_with_pyproject_toml = None if parser_with_pyproject_toml: parser = parser_with_pyproject_toml args = parser.parse_args(arguments) args.files = [decode_filename(name) for name in args.files] if '-' in args.files: if len(args.files) > 1: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, 'cannot mix stdin and regular files', ) if args.diff: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--diff cannot be used with standard input', ) if args.in_place: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--in-place cannot be used with standard input', ) if args.recursive: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--recursive cannot be used with standard input', ) if len(args.files) > 1 and not (args.in_place or args.diff): _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, 'autopep8 only takes one filename as argument ' 'unless the "--in-place" or "--diff" args are used', ) if args.recursive and not (args.in_place or args.diff): _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--recursive must be used with --in-place or --diff', ) if args.in_place and args.diff: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--in-place and --diff are mutually exclusive', ) if args.max_line_length <= 0: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--max-line-length must be greater than 0', ) if args.indent_size <= 0: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--indent-size must be greater than 0', ) if args.select: args.select = _expand_codes( _split_comma_separated(args.select), (_split_comma_separated(args.ignore) if args.ignore else []) ) if args.ignore: args.ignore = _split_comma_separated(args.ignore) if all( not any( conflicting_code.startswith(ignore_code) for ignore_code in args.ignore ) for conflicting_code in CONFLICTING_CODES ): args.ignore.update(CONFLICTING_CODES) elif not args.select: if args.aggressive: # Enable everything by default if aggressive. args.select = {'E', 'W1', 'W2', 'W3', 'W6'} else: args.ignore = _split_comma_separated(DEFAULT_IGNORE) if args.exclude: args.exclude = _split_comma_separated(args.exclude) else: args.exclude = {} if args.jobs < 1: # Do not import multiprocessing globally in case it is not supported # on the platform. import multiprocessing args.jobs = multiprocessing.cpu_count() if args.jobs > 1 and not (args.in_place or args.diff): _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, 'parallel jobs requires --in-place', ) if args.line_range: if args.line_range[0] <= 0: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, '--range must be positive numbers', ) if args.line_range[0] > args.line_range[1]: _parser_error_with_code( parser, EXIT_CODE_ARGPARSE_ERROR, 'First value of --range should be less than or equal ' 'to the second', ) original_formatwarning = warnings.formatwarning warnings.formatwarning = _custom_formatwarning if args.experimental: warnings.warn( "`experimental` option is deprecated and will be " "removed in a future version.", DeprecationWarning, ) warnings.formatwarning = original_formatwarning return args def _get_normalize_options(args, config, section, option_list): for (k, v) in config.items(section): norm_opt = k.lstrip('-').replace('-', '_') if not option_list.get(norm_opt): continue opt_type = option_list[norm_opt] if opt_type is int: if v.strip() == "auto": # skip to special case if args.verbose: print(f"ignore config: {k}={v}") continue value = config.getint(section, k) elif opt_type is bool: value = config.getboolean(section, k) else: value = config.get(section, k) yield norm_opt, k, value def read_config(args, parser): """Read both user configuration and local configuration.""" config = SafeConfigParser() try: if args.verbose and os.path.exists(args.global_config): print("read config path: {}".format(args.global_config)) config.read(args.global_config) if not args.ignore_local_config: parent = tail = args.files and os.path.abspath( os.path.commonprefix(args.files)) while tail: if config.read([os.path.join(parent, fn) for fn in PROJECT_CONFIG]): if args.verbose: for fn in PROJECT_CONFIG: config_file = os.path.join(parent, fn) if not os.path.exists(config_file): continue print( "read config path: {}".format( os.path.join(parent, fn) ) ) break (parent, tail) = os.path.split(parent) defaults = {} option_list = {o.dest: o.type or type(o.default) for o in parser._actions} for section in ['pep8', 'pycodestyle', 'flake8']: if not config.has_section(section): continue for norm_opt, k, value in _get_normalize_options( args, config, section, option_list ): if args.verbose: print("enable config: section={}, key={}, value={}".format( section, k, value)) defaults[norm_opt] = value parser.set_defaults(**defaults) except Error: # Ignore for now. pass return parser def read_pyproject_toml(args, parser): """Read pyproject.toml and load configuration.""" if sys.version_info >= (3, 11): import tomllib else: import tomli as tomllib config = None if os.path.exists(args.global_config): with open(args.global_config, "rb") as fp: config = tomllib.load(fp) if not args.ignore_local_config: parent = tail = args.files and os.path.abspath( os.path.commonprefix(args.files)) while tail: pyproject_toml = os.path.join(parent, "pyproject.toml") if os.path.exists(pyproject_toml): with open(pyproject_toml, "rb") as fp: config = tomllib.load(fp) break (parent, tail) = os.path.split(parent) if not config: return None if config.get("tool", {}).get("autopep8") is None: return None config = config.get("tool", {}).get("autopep8") defaults = {} option_list = {o.dest: o.type or type(o.default) for o in parser._actions} TUPLED_OPTIONS = ("ignore", "select") for (k, v) in config.items(): norm_opt = k.lstrip('-').replace('-', '_') if not option_list.get(norm_opt): continue if type(v) in (list, tuple) and norm_opt in TUPLED_OPTIONS: value = ",".join(v) else: value = v if args.verbose: print("enable pyproject.toml config: " "key={}, value={}".format(k, value)) defaults[norm_opt] = value if defaults: # set value when exists key-value in defaults dict parser.set_defaults(**defaults) return parser def _split_comma_separated(string): """Return a set of strings.""" return {text.strip() for text in string.split(',') if text.strip()} def decode_filename(filename): """Return Unicode filename.""" if isinstance(filename, str): return filename return filename.decode(sys.getfilesystemencoding()) def supported_fixes(): """Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description. """ yield ('E101', docstring_summary(reindent.__doc__)) instance = FixPEP8(filename=None, options=None, contents='') for attribute in dir(instance): code = re.match('fix_([ew][0-9][0-9][0-9])', attribute) if code: yield ( code.group(1).upper(), re.sub(r'\s+', ' ', docstring_summary(getattr(instance, attribute).__doc__)) ) for (code, function) in sorted(global_fixes()): yield (code.upper() + (4 - len(code)) * ' ', re.sub(r'\s+', ' ', docstring_summary(function.__doc__))) def docstring_summary(docstring): """Return summary of docstring.""" return docstring.split('\n')[0] if docstring else '' def line_shortening_rank(candidate, indent_word, max_line_length, experimental=False): """Return rank of candidate. This is for sorting candidates. """ if not candidate.strip(): return 0 rank = 0 lines = candidate.rstrip().split('\n') offset = 0 if ( not lines[0].lstrip().startswith('#') and lines[0].rstrip()[-1] not in '([{' ): for (opening, closing) in ('()', '[]', '{}'): # Don't penalize empty containers that aren't split up. Things like # this "foo(\n )" aren't particularly good. opening_loc = lines[0].find(opening) closing_loc = lines[0].find(closing) if opening_loc >= 0: if closing_loc < 0 or closing_loc != opening_loc + 1: offset = max(offset, 1 + opening_loc) current_longest = max(offset + len(x.strip()) for x in lines) rank += 4 * max(0, current_longest - max_line_length) rank += len(lines) # Too much variation in line length is ugly. rank += 2 * standard_deviation(len(line) for line in lines) bad_staring_symbol = { '(': ')', '[': ']', '{': '}'}.get(lines[0][-1]) if len(lines) > 1: if ( bad_staring_symbol and lines[1].lstrip().startswith(bad_staring_symbol) ): rank += 20 for lineno, current_line in enumerate(lines): current_line = current_line.strip() if current_line.startswith('#'): continue for bad_start in ['.', '%', '+', '-', '/']: if current_line.startswith(bad_start): rank += 100 # Do not tolerate operators on their own line. if current_line == bad_start: rank += 1000 if ( current_line.endswith(('.', '%', '+', '-', '/')) and "': " in current_line ): rank += 1000 if current_line.endswith(('(', '[', '{', '.')): # Avoid lonely opening. They result in longer lines. if len(current_line) <= len(indent_word): rank += 100 # Avoid the ugliness of ", (\n". if ( current_line.endswith('(') and current_line[:-1].rstrip().endswith(',') ): rank += 100 # Avoid the ugliness of "something[\n" and something[index][\n. if ( current_line.endswith('[') and len(current_line) > 1 and (current_line[-2].isalnum() or current_line[-2] in ']') ): rank += 300 # Also avoid the ugliness of "foo.\nbar" if current_line.endswith('.'): rank += 100 if has_arithmetic_operator(current_line): rank += 100 # Avoid breaking at unary operators. if re.match(r'.*[(\[{]\s*[\-\+~]$', current_line.rstrip('\\ ')): rank += 1000 if re.match(r'.*lambda\s*\*$', current_line.rstrip('\\ ')): rank += 1000 if current_line.endswith(('%', '(', '[', '{')): rank -= 20 # Try to break list comprehensions at the "for". if current_line.startswith('for '): rank -= 50 if current_line.endswith('\\'): # If a line ends in \-newline, it may be part of a # multiline string. In that case, we would like to know # how long that line is without the \-newline. If it's # longer than the maximum, or has comments, then we assume # that the \-newline is an okay candidate and only # penalize it a bit. total_len = len(current_line) lineno += 1 while lineno < len(lines): total_len += len(lines[lineno]) if lines[lineno].lstrip().startswith('#'): total_len = max_line_length break if not lines[lineno].endswith('\\'): break lineno += 1 if total_len < max_line_length: rank += 10 else: rank += 100 if experimental else 1 # Prefer breaking at commas rather than colon. if ',' in current_line and current_line.endswith(':'): rank += 10 # Avoid splitting dictionaries between key and value. if current_line.endswith(':'): rank += 100 rank += 10 * count_unbalanced_brackets(current_line) return max(0, rank) def standard_deviation(numbers): """Return standard deviation.""" numbers = list(numbers) if not numbers: return 0 mean = sum(numbers) / len(numbers) return (sum((n - mean) ** 2 for n in numbers) / len(numbers)) ** .5 def has_arithmetic_operator(line): """Return True if line contains any arithmetic operators.""" for operator in pycodestyle.ARITHMETIC_OP: if operator in line: return True return False def count_unbalanced_brackets(line): """Return number of unmatched open/close brackets.""" count = 0 for opening, closing in ['()', '[]', '{}']: count += abs(line.count(opening) - line.count(closing)) return count def split_at_offsets(line, offsets): """Split line at offsets. Return list of strings. """ result = [] previous_offset = 0 current_offset = 0 for current_offset in sorted(offsets): if current_offset < len(line) and previous_offset != current_offset: result.append(line[previous_offset:current_offset].strip()) previous_offset = current_offset result.append(line[current_offset:]) return result class LineEndingWrapper(object): r"""Replace line endings to work with sys.stdout. It seems that sys.stdout expects only '\n' as the line ending, no matter the platform. Otherwise, we get repeated line endings. """ def __init__(self, output): self.__output = output def write(self, s): self.__output.write(s.replace('\r\n', '\n').replace('\r', '\n')) def flush(self): self.__output.flush() def match_file(filename, exclude): """Return True if file is okay for modifying/recursing.""" base_name = os.path.basename(filename) if base_name.startswith('.'): return False for pattern in exclude: if fnmatch.fnmatch(base_name, pattern): return False if fnmatch.fnmatch(filename, pattern): return False if not os.path.isdir(filename) and not is_python_file(filename): return False return True def find_files(filenames, recursive, exclude): """Yield filenames.""" while filenames: name = filenames.pop(0) if recursive and os.path.isdir(name): for root, directories, children in os.walk(name): filenames += [os.path.join(root, f) for f in children if match_file(os.path.join(root, f), exclude)] directories[:] = [d for d in directories if match_file(os.path.join(root, d), exclude)] else: is_exclude_match = False for pattern in exclude: if fnmatch.fnmatch(name, pattern): is_exclude_match = True break if not is_exclude_match: yield name def _fix_file(parameters): """Helper function for optionally running fix_file() in parallel.""" if parameters[1].verbose: print('[file:{}]'.format(parameters[0]), file=sys.stderr) try: return fix_file(*parameters) except IOError as error: print(str(error), file=sys.stderr) raise error def fix_multiple_files(filenames, options, output=None): """Fix list of files. Optionally fix files recursively. """ results = [] filenames = find_files(filenames, options.recursive, options.exclude) if options.jobs > 1: import multiprocessing pool = multiprocessing.Pool(options.jobs) rets = [] for name in filenames: ret = pool.apply_async(_fix_file, ((name, options),)) rets.append(ret) pool.close() pool.join() if options.diff: for r in rets: sys.stdout.write(r.get().decode()) sys.stdout.flush() results.extend([x.get() for x in rets if x is not None]) else: for name in filenames: ret = _fix_file((name, options, output)) if ret is None: continue if options.diff: if ret != '': results.append(ret) elif options.in_place: results.append(ret) else: original_source = readlines_from_file(name) if "".join(original_source).splitlines() != ret.splitlines(): results.append(ret) return results def is_python_file(filename): """Return True if filename is Python file.""" if filename.endswith('.py'): return True try: with open_with_encoding( filename, limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f: text = f.read(MAX_PYTHON_FILE_DETECTION_BYTES) if not text: return False first_line = text.splitlines()[0] except (IOError, IndexError): return False if not PYTHON_SHEBANG_REGEX.match(first_line): return False return True def is_probably_part_of_multiline(line): """Return True if line is likely part of a multiline string. When multiline strings are involved, pep8 reports the error as being at the start of the multiline string, which doesn't work for us. """ return ( '"""' in line or "'''" in line or line.rstrip().endswith('\\') ) def wrap_output(output, encoding): """Return output with specified encoding.""" return codecs.getwriter(encoding)(output.buffer if hasattr(output, 'buffer') else output) def get_encoding(): """Return preferred encoding.""" return locale.getpreferredencoding() or sys.getdefaultencoding() def main(argv=None, apply_config=True): """Command-line entry.""" if argv is None: argv = sys.argv try: # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: args = parse_args(argv[1:], apply_config=apply_config) if args.list_fixes: for code, description in sorted(supported_fixes()): print('{code} - {description}'.format( code=code, description=description)) return EXIT_CODE_OK if args.files == ['-']: assert not args.in_place encoding = sys.stdin.encoding or get_encoding() read_stdin = sys.stdin.read() fixed_stdin = fix_code(read_stdin, args, encoding=encoding) # LineEndingWrapper is unnecessary here due to the symmetry between # standard in and standard out. wrap_output(sys.stdout, encoding=encoding).write(fixed_stdin) if hash(read_stdin) != hash(fixed_stdin): if args.exit_code: return EXIT_CODE_EXISTS_DIFF else: if args.in_place or args.diff: args.files = list(set(args.files)) else: assert len(args.files) == 1 assert not args.recursive results = fix_multiple_files(args.files, args, sys.stdout) if args.diff: ret = any([len(ret) != 0 for ret in results]) else: # with in-place option ret = any([ret is not None for ret in results]) if args.exit_code and ret: return EXIT_CODE_EXISTS_DIFF except IOError: return EXIT_CODE_ERROR except KeyboardInterrupt: return EXIT_CODE_ERROR # pragma: no cover class CachedTokenizer(object): """A one-element cache around tokenize.generate_tokens(). Original code written by Ned Batchelder, in coverage.py. """ def __init__(self): self.last_text = None self.last_tokens = None def generate_tokens(self, text): """A stand-in for tokenize.generate_tokens().""" if text != self.last_text: string_io = io.StringIO(text) self.last_tokens = list( tokenize.generate_tokens(string_io.readline) ) self.last_text = text return self.last_tokens _cached_tokenizer = CachedTokenizer() generate_tokens = _cached_tokenizer.generate_tokens if __name__ == '__main__': sys.exit(main()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/pyproject.toml0000644000175100001770000000263514635727563015633 0ustar00runnerdocker[project] name = "autopep8" description = "A tool that automatically formats Python code to conform to the PEP 8 style guide" license = {file = "LICENSE.rst"} authors = [ {name = "Hideo Hattori", email = "hhatto.jp@gmail.com"}, ] readme = "README.rst" keywords = [ "automation", "pep8", "format", "pycodestyle", ] classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Quality Assurance", ] requires-python = ">=3.8" dependencies = [ "pycodestyle >= 2.12.0", "tomli; python_version < '3.11'", ] dynamic = ["version"] [project.urls] Repository = "https://github.com/hhatto/autopep8" [project.scripts] autopep8 = "autopep8:main" [tool.setuptools] py-modules = ["autopep8"] [tool.setuptools.dynamic] version = {attr = "autopep8.__version__"} [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/setup.cfg0000644000175100001770000000010314635727603014517 0ustar00runnerdocker[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/test/0000755000175100001770000000000014635727603013663 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/__init__.py0000644000175100001770000000000014635727563015767 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/acid.py0000755000175100001770000002121414635727563015145 0ustar00runnerdocker#!/usr/bin/env python """Test that autopep8 runs without crashing on various Python files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import random import shlex import sys import subprocess import tempfile try: basestring except NameError: basestring = str ROOT_PATH = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] # Override system-installed version of autopep8. sys.path = [ROOT_PATH] + sys.path import autopep8 if sys.stdout.isatty(): YELLOW = '\x1b[33m' END = '\x1b[0m' else: YELLOW = '' END = '' RANDOM_MAX = 1000 def colored(text, color): """Return color coded text.""" return color + text + END def run(filename, command, max_line_length=79, ignore='', check_ignore='', verbose=False, comparison_function=None, aggressive=0, experimental=False, line_range=None, random_range=False, pycodestyle=True): """Run autopep8 on file at filename. Return True on success. """ if random_range: if not line_range: line_range = [1, RANDOM_MAX] first = random.randint(*line_range) line_range = [first, random.randint(first, line_range[1])] command = (shlex.split(command) + (['--verbose'] if verbose else []) + ['--max-line-length={}'.format(max_line_length), '--ignore=' + ignore, filename] + aggressive * ['--aggressive'] + (['--experimental'] if experimental else []) + (['--line-range', str(line_range[0]), str(line_range[1])] if line_range else [])) print(' '.join(command), file=sys.stderr) with tempfile.NamedTemporaryFile(suffix='.py') as tmp_file: if subprocess.call(command, stdout=tmp_file) != 0: sys.stderr.write('autopep8 crashed on ' + filename + '\n') return False if pycodestyle and subprocess.call( [pycodestyle, '--ignore=' + ','.join([x for x in ignore.split(',') + check_ignore.split(',') if x]), '--show-source', tmp_file.name], stdout=sys.stdout) != 0: sys.stderr.write('autopep8 did not completely fix ' + filename + '\n') try: if check_syntax(filename): try: check_syntax(tmp_file.name, raise_error=True) except (SyntaxError, TypeError, UnicodeDecodeError) as exception: sys.stderr.write('autopep8 broke ' + filename + '\n' + str(exception) + '\n') return False if comparison_function: if not comparison_function(filename, tmp_file.name): return False except IOError as exception: sys.stderr.write(str(exception) + '\n') return True def check_syntax(filename, raise_error=False): """Return True if syntax is okay.""" with autopep8.open_with_encoding(filename) as input_file: try: compile(input_file.read(), '', 'exec', dont_inherit=True) return True except (SyntaxError, TypeError, UnicodeDecodeError): if raise_error: raise else: return False def process_args(): """Return processed arguments (options and positional arguments).""" compare_bytecode_ignore = 'E71,E721,W' parser = argparse.ArgumentParser() parser.add_argument( '--command', default='{} {}'.format(sys.executable, os.path.join(ROOT_PATH, 'autopep8.py')), help='autopep8 command (default: %(default)s)') parser.add_argument('--ignore', help='comma-separated errors to ignore', default='') parser.add_argument('--check-ignore', help='comma-separated errors to ignore when checking ' 'for completeness (default: %(default)s)', default='') parser.add_argument('--max-line-length', metavar='n', default=79, type=int, help='set maximum allowed line length ' '(default: %(default)s)') parser.add_argument('--compare-bytecode', action='store_true', help='compare bytecode before and after fixes; ' 'sets default --ignore=' + compare_bytecode_ignore) parser.add_argument('-a', '--aggressive', action='count', default=0, help='run autopep8 in aggressive mode') parser.add_argument('--experimental', action='store_true', help='run experimental fixes') parser.add_argument('--line-range', metavar='line', default=None, type=int, nargs=2, help='pass --line-range to autope8') parser.add_argument('--random-range', action='store_true', help='pass random --line-range to autope8') parser.add_argument('--pycodestyle', default='pycodestyle', help='location of pycodestyle; ' 'set to empty string to disable this check') parser.add_argument('-v', '--verbose', action='store_true', help='print verbose messages') parser.add_argument('paths', nargs='*', help='paths to use for testing') args = parser.parse_args() if args.compare_bytecode and not args.ignore: args.ignore = compare_bytecode_ignore return args def compare_bytecode(filename_a, filename_b): try: import pydiff except ImportError: raise SystemExit('pydiff required for bytecode comparison; ' 'run "pip install pydiff"') diff = pydiff.diff_bytecode_of_files(filename_a, filename_b) if diff: sys.stderr.write('New bytecode does not match original:\n' + diff + '\n') return not diff def check(paths, args): """Run recursively run autopep8 on directory of files. Return False if the fix results in broken syntax. """ if paths: dir_paths = paths else: dir_paths = [path for path in sys.path if os.path.isdir(path)] filenames = dir_paths completed_filenames = set() if args.compare_bytecode: comparison_function = compare_bytecode else: comparison_function = None while filenames: try: name = os.path.realpath(filenames.pop(0)) if not os.path.exists(name): # Invalid symlink. continue if name in completed_filenames: sys.stderr.write( colored( '---> Skipping previously tested ' + name + '\n', YELLOW)) continue else: completed_filenames.update(name) if os.path.isdir(name): for root, directories, children in os.walk(name): filenames += [os.path.join(root, f) for f in children if f.endswith('.py') and not f.startswith('.')] directories[:] = [d for d in directories if not d.startswith('.')] else: verbose_message = '---> Testing with ' + name sys.stderr.write(colored(verbose_message + '\n', YELLOW)) if not run(os.path.join(name), command=args.command, max_line_length=args.max_line_length, ignore=args.ignore, check_ignore=args.check_ignore, verbose=args.verbose, comparison_function=comparison_function, aggressive=args.aggressive, experimental=args.experimental, line_range=args.line_range, random_range=args.random_range, pycodestyle=args.pycodestyle): return False except (UnicodeDecodeError, UnicodeEncodeError) as exception: # Ignore annoying codec problems on Python 2. print(exception) continue return True def main(): """Run main.""" args = process_args() return 0 if check(args.paths, args) else 1 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/bad_encoding.py0000644000175100001770000000003314635727563016632 0ustar00runnerdocker# -*- coding: zlatin-1 -*- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/bad_encoding2.py0000644000175100001770000000003614635727563016717 0ustar00runnerdocker#coding: utf8 print('我') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/e101_example.py0000644000175100001770000012732114635727563016431 0ustar00runnerdocker# -*- coding: utf-8 -*- # From https://github.com/coto/gae-boilerplate/blob/233a88c59e46bb10de7a901ef4e6a5b60d0006a5/web/handlers.py """ This example will take a long time if we don't filter innocuous E101 errors from pep8. """ import models.models as models from webapp2_extras.auth import InvalidAuthIdError from webapp2_extras.auth import InvalidPasswordError from webapp2_extras import security from lib import utils from lib import captcha from lib.basehandler import BaseHandler from lib.basehandler import user_required from google.appengine.api import taskqueue import logging import config import webapp2 import web.forms as forms from webapp2_extras.i18n import gettext as _ from webapp2_extras.appengine.auth.models import Unique from lib import twitter class LoginBaseHandler(BaseHandler): """ Base class for handlers with login form. """ @webapp2.cached_property def form(self): return forms.LoginForm(self) class RegisterBaseHandler(BaseHandler): """ Base class for handlers with registration and login forms. """ @webapp2.cached_property def form(self): if self.is_mobile: return forms.RegisterMobileForm(self) else: return forms.RegisterForm(self) @webapp2.cached_property def form_login(self): return forms.LoginForm(self) @webapp2.cached_property def forms(self): return {'form_login' : self.form_login, 'form' : self.form} class SendEmailHandler(BaseHandler): """ Handler for sending Emails Use with TaskQueue """ def post(self): to = self.request.get("to") subject = self.request.get("subject") body = self.request.get("body") sender = self.request.get("sender") utils.send_email(to, subject, body, sender) class LoginHandler(LoginBaseHandler): """ Handler for authentication """ def get(self): """ Returns a simple HTML form for login """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_login.html', **params) def post(self): """ username: Get the username from POST dict password: Get the password from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() try: if utils.is_email_valid(username): user = models.User.get_by_email(username) if user: auth_id = user.auth_ids[0] else: raise InvalidAuthIdError else: auth_id = "own:%s" % username user = models.User.get_by_auth_id(auth_id) password = self.form.password.data.strip() remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False # Password to SHA512 password = utils.encrypt(password, config.salt) # Try to login user with password # Raises InvalidAuthIdError if user is not found # Raises InvalidPasswordError if provided password # doesn't match with specified user self.auth.get_user_by_password( auth_id, password, remember=remember_me) # if user account is not activated, logout and redirect to home if (user.activated == False): # logout self.auth.unset_session() # redirect to home with error message resend_email_uri = self.uri_for('resend-account-activation', encoded_email=utils.encode(user.email)) message = _('Sorry, your account') + ' {0:>s}'.format(username) + " " +\ _('has not been activated. Please check your email to activate your account') + ". " +\ _('Or click') + " " + _('this') + " " + _('to resend the email') self.add_message(message, 'error') return self.redirect_to('home') # check twitter association in session twitter_helper = twitter.TwitterAuth(self) twitter_association_data = twitter_helper.get_association_data() if twitter_association_data is not None: if models.SocialUser.check_unique(user.key, 'twitter', str(twitter_association_data['id'])): social_user = models.SocialUser( user = user.key, provider = 'twitter', uid = str(twitter_association_data['id']), extra_data = twitter_association_data ) social_user.put() logVisit = models.LogVisit( user=user.key, uastring=self.request.user_agent, ip=self.request.remote_addr, timestamp=utils.get_date_time() ) logVisit.put() self.redirect_to('home') except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Login invalid, Try again.") + "
" + _("Don't have an account?") + \ ' ' + _("Sign Up") + '' self.add_message(message, 'error') return self.redirect_to('login') class SocialLoginHandler(BaseHandler): """ Handler for Social authentication """ def get(self, provider_name): provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label'] if not config.enable_federated_login: message = _('Federated login is disabled.') self.add_message(message,'warning') return self.redirect_to('login') callback_url = "%s/social_login/%s/complete" % (self.request.host_url, provider_name) if provider_name == "twitter": twitter_helper = twitter.TwitterAuth(self, redirect_uri=callback_url) self.redirect(twitter_helper.auth_url()) else: message = _('%s authentication is not implemented yet.') % provider_display_name self.add_message(message,'warning') self.redirect_to('edit-profile') class CallbackSocialLoginHandler(BaseHandler): """ Callback (Save Information) for Social Authentication """ def get(self, provider_name): if not config.enable_federated_login: message = _('Federated login is disabled.') self.add_message(message,'warning') return self.redirect_to('login') if provider_name == "twitter": oauth_token = self.request.get('oauth_token') oauth_verifier = self.request.get('oauth_verifier') twitter_helper = twitter.TwitterAuth(self) user_data = twitter_helper.auth_complete(oauth_token, oauth_verifier) if self.user: # new association with twitter user_info = models.User.get_by_id(long(self.user_id)) if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['id'])): social_user = models.SocialUser( user = user_info.key, provider = 'twitter', uid = str(user_data['id']), extra_data = user_data ) social_user.put() message = _('Twitter association added!') self.add_message(message,'success') else: message = _('This Twitter account is already in use!') self.add_message(message,'error') self.redirect_to('edit-profile') else: # login with twitter social_user = models.SocialUser.get_by_provider_and_uid('twitter', str(user_data['id'])) if social_user: # Social user exists. Need authenticate related site account user = social_user.user.get() self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') else: # Social user does not exists. Need show login and registration forms twitter_helper.save_association_data(user_data) message = _('Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.') self.add_message(message,'info') self.redirect_to('login') # Debug Callback information provided # for k,v in user_data.items(): # print(k +":"+ v ) # google, myopenid, yahoo OpenID Providers elif provider_name in models.SocialUser.open_id_providers(): provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label'] # get info passed from OpenId Provider from google.appengine.api import users current_user = users.get_current_user() if current_user: if current_user.federated_identity(): uid = current_user.federated_identity() else: uid = current_user.user_id() email = current_user.email() else: message = _('No user authentication information received from %s. Please ensure you are logging in from an authorized OpenID Provider (OP).' % provider_display_name) self.add_message(message,'error') return self.redirect_to('login') if self.user: # add social account to user user_info = models.User.get_by_id(long(self.user_id)) if models.SocialUser.check_unique(user_info.key, provider_name, uid): social_user = models.SocialUser( user = user_info.key, provider = provider_name, uid = uid ) social_user.put() message = provider_display_name + _(' association added!') self.add_message(message,'success') else: message = _('This %s account is already in use!' % provider_display_name) self.add_message(message,'error') self.redirect_to('edit-profile') else: # login with OpenId Provider social_user = models.SocialUser.get_by_provider_and_uid(provider_name, uid) if social_user: # Social user found. Authenticate the user user = social_user.user.get() self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') else: # Social user does not exist yet so create it with the federated identity provided (uid) # and create prerequisite user and log the user account in if models.SocialUser.check_unique_uid(provider_name, uid): # create user # Returns a tuple, where first value is BOOL. # If True ok, If False no new user is created # Assume provider has already verified email address # if email is provided so set activated to True auth_id = "%s:%s" % (provider_name, uid) if email: unique_properties = ['email'] user_info = self.auth.store.user_model.create_user( auth_id, unique_properties, email=email, activated=True ) else: user_info = self.auth.store.user_model.create_user( auth_id, activated=True ) if not user_info[0]: #user is a tuple message = _('This %s account is already in use!' % provider_display_name) self.add_message(message, 'error') return self.redirect_to('register') user = user_info[1] # create social user and associate with user social_user = models.SocialUser( user = user.key, provider = provider_name, uid = uid ) social_user.put() # authenticate user self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') message = provider_display_name + _(' association added!') self.add_message(message,'success') self.redirect_to('home') else: message = _('This %s account is already in use!' % provider_display_name) self.add_message(message,'error') self.redirect_to('login') else: message = _('%s authentication is not implemented yet.') % provider_display_name self.add_message(message,'warning') self.redirect_to('login') class DeleteSocialProviderHandler(BaseHandler): """ Delete Social association with an account """ @user_required def get(self, provider_name): if self.user: user_info = models.User.get_by_id(long(self.user_id)) social_user = models.SocialUser.get_by_user_and_provider(user_info.key, provider_name) if social_user: social_user.key.delete() message = provider_name + _(' disassociated!') self.add_message(message,'success') else: message = _('Social account on ') + provider_name + _(' not found for this user!') self.add_message(message,'error') self.redirect_to('edit-profile') class LogoutHandler(BaseHandler): """ Destroy user session and redirect to login """ def get(self): if self.user: message = _("You've signed out successfully. Warning: Please clear all cookies and logout \ of OpenId providers too if you logged in on a public computer.") # Info message self.add_message(message, 'info') self.auth.unset_session() # User is logged out, let's try redirecting to login page try: self.redirect(self.auth_config['login_url']) except (AttributeError, KeyError), e: return _("User is logged out, but there was an error "\ "on the redirection.") class RegisterHandler(RegisterBaseHandler): """ Handler for Sign Up Users """ def get(self): """ Returns a simple HTML form for create a new user """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_register.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() name = self.form.name.data.strip() last_name = self.form.last_name.data.strip() email = self.form.email.data.lower() password = self.form.password.data.strip() country = self.form.country.data # Password to SHA512 password = utils.encrypt(password, config.salt) # Passing password_raw=password so password will be hashed # Returns a tuple, where first value is BOOL. # If True ok, If False no new user is created unique_properties = ['username', 'email'] auth_id = "own:%s" % username user = self.auth.store.user_model.create_user( auth_id, unique_properties, password_raw=password, username=username, name=name, last_name=last_name, email=email, country=country, activated=False ) if not user[0]: #user is a tuple message = _('Sorry, This user') + ' {0:>s}'.format(username) + " " +\ _('is already registered.') self.add_message(message, 'error') return self.redirect_to('register') else: # User registered successfully # But if the user registered using the form, the user has to check their email to activate the account ??? try: user_info = models.User.get_by_email(email) if (user_info.activated == False): # send email subject = config.app_name + " Account Verification Email" encoded_email = utils.encode(email) confirmation_url = self.uri_for("account-activation", encoded_email = encoded_email, _full = True) # load email's template template_val = { "app_name": config.app_name, "username": username, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } body_path = "emails/account_activation.txt" body = self.jinja2.render_template(body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': str(email), 'subject' : subject, 'body' : body, }) message = _('Congratulations') + ", " + str(username) + "! " + _('You are now registered') +\ ". " + _('Please check your email to activate your account') self.add_message(message, 'success') return self.redirect_to('home') # If the user didn't register using registration form ??? db_user = self.auth.get_user_by_password(user[1].auth_ids[0], password) # Check twitter association in session twitter_helper = twitter.TwitterAuth(self) twitter_association_data = twitter_helper.get_association_data() if twitter_association_data is not None: if models.SocialUser.check_unique(user[1].key, 'twitter', str(twitter_association_data['id'])): social_user = models.SocialUser( user = user[1].key, provider = 'twitter', uid = str(twitter_association_data['id']), extra_data = twitter_association_data ) social_user.put() message = _('Welcome') + " " + str(username) + ", " + _('you are now logged in.') self.add_message(message, 'success') return self.redirect_to('home') except (AttributeError, KeyError), e: message = _('Unexpected error creating '\ 'user') + " " + '{0:>s}.'.format(username) self.add_message(message, 'error') self.abort(403) class AccountActivationHandler(BaseHandler): """ Handler for account activation """ def get(self, encoded_email): try: email = utils.decode(encoded_email) user = models.User.get_by_email(email) # activate the user's account user.activated = True user.put() message = _('Congratulations') + "! " + _('Your account') + " (@" + user.username + ") " +\ _('has just been activated') + ". " + _('Please login to your account') self.add_message(message, "success") self.redirect_to('login') except (AttributeError, KeyError, InvalidAuthIdError), e: message = _('Unexpected error activating '\ 'account') + " " + '{0:>s}.'.format(user.username) self.add_message(message, 'error') self.abort(403) class ResendActivationEmailHandler(BaseHandler): """ Handler to resend activation email """ def get(self, encoded_email): try: email = utils.decode(encoded_email) user = models.User.get_by_email(email) if (user.activated == False): # send email subject = config.app_name + " Account Verification Email" encoded_email = utils.encode(email) confirmation_url = self.uri_for("account-activation", encoded_email = encoded_email, _full = True) # load email's template template_val = { "app_name": config.app_name, "username": user.username, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } body_path = "emails/account_activation.txt" body = self.jinja2.render_template(body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': str(email), 'subject' : subject, 'body' : body, }) message = _('The verification email has been resent to') + " " + str(email) + ". " +\ _('Please check your email to activate your account') self.add_message(message, "success") return self.redirect_to('home') else: message = _('Your account has been activated') + ". " +\ _('Please login to your account') self.add_message(message, "warning") return self.redirect_to('home') except (KeyError, AttributeError), e: message = _('Sorry') + ". " + _('Some error occurred') + "." self.add_message(message, "error") return self.redirect_to('home') class ContactHandler(BaseHandler): """ Handler for Contact Form """ def get(self): """ Returns a simple HTML for contact form """ if self.user: user_info = models.User.get_by_id(long(self.user_id)) if user_info.name or user_info.last_name: self.form.name.data = user_info.name + " " + user_info.last_name if user_info.email: self.form.email.data = user_info.email params = { "exception" : self.request.get('exception') } return self.render_template('boilerplate_contact.html', **params) def post(self): """ validate contact form """ if not self.form.validate(): return self.get() remoteip = self.request.remote_addr user_agent = self.request.user_agent exception = self.request.POST.get('exception') name = self.form.name.data.strip() email = self.form.email.data.lower() message = self.form.message.data.strip() try: subject = _("Contact") body = "" # exceptions for error pages that redirect to contact if exception != "": body = "* Exception error: %s" % exception body = body + """ * IP Address: %s * Web Browser: %s * Sender name: %s * Sender email: %s * Message: %s """ % (remoteip, user_agent, name, email, message) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': config.contact_recipient, 'subject' : subject, 'body' : body, 'sender' : config.contact_sender, }) message = _('Message sent successfully.') self.add_message(message, 'success') return self.redirect_to('contact') except (AttributeError, KeyError), e: message = _('Error sending the message. Please try again later.') self.add_message(message, 'error') return self.redirect_to('contact') @webapp2.cached_property def form(self): return forms.ContactForm(self) class EditProfileHandler(BaseHandler): """ Handler for Edit User Profile """ @user_required def get(self): """ Returns a simple HTML form for edit profile """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.username.data = user_info.username self.form.name.data = user_info.name self.form.last_name.data = user_info.last_name self.form.country.data = user_info.country providers_info = user_info.get_social_providers_info() params['used_providers'] = providers_info['used'] params['unused_providers'] = providers_info['unused'] params['country'] = user_info.country return self.render_template('boilerplate_edit_profile.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() name = self.form.name.data.strip() last_name = self.form.last_name.data.strip() country = self.form.country.data try: user_info = models.User.get_by_id(long(self.user_id)) try: message='' # update username if it has changed and it isn't already taken if username != user_info.username: user_info.unique_properties = ['username','email'] uniques = [ 'User.username:%s' % username, 'User.auth_id:own:%s' % username, ] # Create the unique username and auth_id. success, existing = Unique.create_multi(uniques) if success: # free old uniques Unique.delete_multi(['User.username:%s' % user_info.username, 'User.auth_id:own:%s' % user_info.username]) # The unique values were created, so we can save the user. user_info.username=username user_info.auth_ids[0]='own:%s' % username message+= _('Your new username is ') + '' + username + '.' else: message+= _('Username') + " " + username + " " + _('is already taken. It is not changed.') # At least one of the values is not unique. self.add_message(message,'error') return self.get() user_info.name=name user_info.last_name=last_name user_info.country=country user_info.put() message+= " " + _('Your profile has been updated!') self.add_message(message,'success') return self.get() except (AttributeError, KeyError, ValueError), e: message = _('Unable to update profile!') logging.error('Unable to update profile: ' + e) self.add_message(message,'error') return self.get() except (AttributeError, TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): return forms.EditProfileForm(self) class EditPasswordHandler(BaseHandler): """ Handler for Edit User Password """ @user_required def get(self): """ Returns a simple HTML form for editing password """ params = {} return self.render_template('boilerplate_edit_password.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() current_password = self.form.current_password.data.strip() password = self.form.password.data.strip() try: user_info = models.User.get_by_id(long(self.user_id)) auth_id = "own:%s" % user_info.username # Password to SHA512 current_password = utils.encrypt(current_password, config.salt) try: user = models.User.get_by_auth_password(auth_id, current_password) # Password to SHA512 password = utils.encrypt(password, config.salt) user.password = security.generate_password_hash(password, length=12) user.put() # send email subject = config.app_name + " Account Password Changed" # load email's template template_val = { "app_name": config.app_name, "first_name": user.name, "username": user.username, "email": user.email, "reset_password_url": self.uri_for("password-reset", _full=True) } email_body_path = "emails/password_changed.txt" email_body = self.jinja2.render_template(email_body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : email_body, 'sender' : config.contact_sender, }) # Login User self.auth.get_user_by_password(user.auth_ids[0], password) self.add_message(_('Password changed successfully'), 'success') return self.redirect_to('edit-profile') except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Your Current Password is wrong, please try again") self.add_message(message, 'error') return self.redirect_to('edit-password') except (AttributeError,TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): if self.is_mobile: return forms.EditPasswordMobileForm(self) else: return forms.EditPasswordForm(self) class EditEmailHandler(BaseHandler): """ Handler for Edit User's Email """ @user_required def get(self): """ Returns a simple HTML form for edit email """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.new_email.data = user_info.email return self.render_template('boilerplate_edit_email.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() new_email = self.form.new_email.data.strip() password = self.form.password.data.strip() try: user_info = models.User.get_by_id(long(self.user_id)) auth_id = "own:%s" % user_info.username # Password to SHA512 password = utils.encrypt(password, config.salt) try: # authenticate user by its password user = models.User.get_by_auth_password(auth_id, password) # if the user change his/her email address if new_email != user.email: # check whether the new email has been used by another user aUser = models.User.get_by_email(new_email) if aUser is not None: message = _("The email %s is already registered." % new_email) self.add_message(message, "error") return self.redirect_to("edit-email") # send email subject = config.app_name + " Email Changed Notification" user_token = models.User.create_auth_token(self.user_id) confirmation_url = self.uri_for("email-changed-check", user_id = user_info.get_id(), encoded_email = utils.encode(new_email), token = user_token, _full = True) # load email's template template_val = { "app_name": config.app_name, "first_name": user.name, "username": user.username, "new_email": new_email, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } old_body_path = "emails/email_changed_notification_old.txt" old_body = self.jinja2.render_template(old_body_path, **template_val) new_body_path = "emails/email_changed_notification_new.txt" new_body = self.jinja2.render_template(new_body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : old_body, }) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': new_email, 'subject' : subject, 'body' : new_body, }) logging.error(user) # display successful message msg = _("Please check your new email for confirmation. Your email will be updated after confirmation.") self.add_message(msg, 'success') return self.redirect_to('edit-profile') else: self.add_message(_("You didn't change your email"), "warning") return self.redirect_to("edit-email") except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Your password is wrong, please try again") self.add_message(message, 'error') return self.redirect_to('edit-email') except (AttributeError,TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): return forms.EditEmailForm(self) class PasswordResetHandler(LoginBaseHandler): """ Password Reset Handler with Captcha """ reCaptcha_public_key = config.captcha_public_key reCaptcha_private_key = config.captcha_private_key def get(self): chtml = captcha.displayhtml( public_key = self.reCaptcha_public_key, use_ssl = False, error = None) params = { 'captchahtml': chtml, } return self.render_template('boilerplate_password_reset.html', **params) def post(self): # check captcha challenge = self.request.POST.get('recaptcha_challenge_field') response = self.request.POST.get('recaptcha_response_field') remoteip = self.request.remote_addr cResponse = captcha.submit( challenge, response, self.reCaptcha_private_key, remoteip) if cResponse.is_valid: # captcha was valid... carry on..nothing to see here pass else: logging.warning(cResponse.error_code) _message = _('Wrong image verification code. Please try again.') self.add_message(_message, 'error') return self.redirect_to('password-reset') # check if we got an email or username email_or_username = str(self.request.POST.get('email_or_username')).lower().strip() if utils.is_email_valid(email_or_username): user = models.User.get_by_email(email_or_username) _message = _("If the e-mail address you entered") + " (%s) " % email_or_username else: auth_id = "own:%s" % email_or_username user = models.User.get_by_auth_id(auth_id) _message = _("If the username you entered") + " (%s) " % email_or_username if user is not None: user_id = user.get_id() token = models.User.create_auth_token(user_id) email_url = self.uri_for('taskqueue-send-email') reset_url = self.uri_for('password-reset-check', user_id=user_id, token=token, _full=True) subject = _("Password reminder") body = _('Please click below to create a new password:') +\ """ %s """ % reset_url taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : body, 'sender' : config.contact_sender, }) _message = _message + _("is associated with an account in our records, you will receive "\ "an e-mail from us with instructions for resetting your password. "\ "
If you don't receive this e-mail, please check your junk mail folder or ") +\ '' + _('contact us') + ' ' + _("for further assistance.") self.add_message(_message, 'success') return self.redirect_to('login') _message = _('Your email / username was not found. Please try another or ') + '' + _('create an account') + '' self.add_message(_message, 'error') return self.redirect_to('password-reset') class PasswordResetCompleteHandler(LoginBaseHandler): """ Handler to process the link of reset password that received the user """ def get(self, user_id, token): verify = models.User.get_by_auth_token(int(user_id), token) params = {} if verify[0] is None: message = _('There was an error or the link is outdated. Please copy and paste the link from your email or enter your details again below to get a new one.') self.add_message(message, 'warning') return self.redirect_to('password-reset') else: return self.render_template('boilerplate_password_reset_complete.html', **params) def post(self, user_id, token): verify = models.User.get_by_auth_token(int(user_id), token) user = verify[0] password = self.form.password.data.strip() if user and self.form.validate(): # Password to SHA512 password = utils.encrypt(password, config.salt) user.password = security.generate_password_hash(password, length=12) user.put() # Delete token models.User.delete_auth_token(int(user_id), token) # Login User self.auth.get_user_by_password(user.auth_ids[0], password) self.add_message(_('Password changed successfully'), 'success') return self.redirect_to('home') else: self.add_message(_('Please correct the form errors.'), 'error') return self.redirect_to('password-reset-check', user_id=user_id, token=token) @webapp2.cached_property def form(self): if self.is_mobile: return forms.PasswordResetCompleteMobileForm(self) else: return forms.PasswordResetCompleteForm(self) class EmailChangedCompleteHandler(BaseHandler): """ Handler for completed email change Will be called when the user click confirmation link from email """ def get(self, user_id, encoded_email, token): verify = models.User.get_by_auth_token(int(user_id), token) email = utils.decode(encoded_email) if verify[0] is None: self.add_message('There was an error or the link is outdated. Please copy and paste the link from your email.', 'warning') self.redirect_to('home') else: # save new email user = verify[0] user.email = email user.put() # delete token models.User.delete_auth_token(int(user_id), token) # add successful message and redirect self.add_message("Your email has been successfully updated!", "success") self.redirect_to('edit-profile') class SecureRequestHandler(BaseHandler): """ Only accessible to users that are logged in """ @user_required def get(self, **kwargs): user_session = self.user user_session_object = self.auth.store.get_session(self.request) user_info = models.User.get_by_id(long( self.user_id )) user_info_object = self.auth.store.user_model.get_by_auth_token( user_session['user_id'], user_session['token']) try: params = { "user_session" : user_session, "user_session_object" : user_session_object, "user_info" : user_info, "user_info_object" : user_info_object, "userinfo_logout-url" : self.auth_config['logout_url'], } return self.render_template('boilerplate_secure_zone.html', **params) except (AttributeError, KeyError), e: return _("Secure zone error:") + " %s." % e class HomeRequestHandler(RegisterBaseHandler): """ Handler to show the home page """ def get(self): """ Returns a simple HTML form for home """ params = {} return self.render_template('boilerplate_home.html', **params) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/example.py0000644000175100001770000000421614635727563015700 0ustar00runnerdockerimport sys, os def foo(): import subprocess, argparse import copy; import math, email print(1) print(2) # e261 d = {1: 2,# e261 3: 4} print(2) ## e262 print(2) #### e262 print(2) #e262 print(2) # e262 1 /1 1 *2 1 +1 1 -1 1 **2 def dummy1 ( a ): print(a) print(a) def dummy2(a) : if 1 in a: print("a") print(1+1) # e225 print(1 +1) # e225 print(1+ 1) # e225 print(1 +1) # e221+e225 print(1 + 1) # e221 print(1 * 1) # e221 print(1 + 1) # e222 print(1 * 1) # e222 print(a) def func1(): print("A") return 0 def func11(): a = (1,2, 3,"a") b = [1, 2, 3,"b"] c = 0,11/2 return 1 # comment after too empty lines def func2(): pass def func22(): pass; def func_oneline(): print(1) def func_last(): if True: print(1) pass def func_e251(a, b=1, c = 3): pass def func_e251_t(a, b=1, c = 3, d = 4): pass # e201 ( 1) [ 1] { 1: 2} # e202 (1 ) [1 ] {1: 2 } # e203 {4 : 2} [4 , 2] # e211 d = [1] d [0] dummy1 (0) def func_e702(): 4; 1; 4; 1; 4; 1; 4; 1; print(2); print(4); 6;8 if True: 1; 2; 3 0; 1 2;3 4; 5; def func_w602(): raise ValueError, "w602 test" raise ValueError, "w602 test" # my comment raise ValueError raise ValueError # comment raise ValueError, 'arg' ; print(1) raise ValueError, 'arg' ; print(2) # my comment raise ValueError, \ 'arg no comment' raise ValueError, \ 'arg' # my comment raise ValueError, \ """arg""" # my comment raise ValueError, \ """arg """ # my comment raise ValueError, \ '''multiline ''' # my comment a = 'a' raise ValueError, "%s" % (a,) raise 'string' def func_w603(): if 1 <> 2: if 2 <> 2: print(True) else: print(False) def func_w604(): a = 1.1 b = ```a``` def func_e101(): print('abc') if True: print('hello') if __name__ == '__main__': func_last() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/test/fake_configuration/0000755000175100001770000000000014635727603017520 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/fake_configuration/.pep80000644000175100001770000000002514635727563020377 0ustar00runnerdocker[pep8] indent-size=2 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1719119747.2835832 autopep8-2.3.1/test/fake_pycodestyle_configuration/0000755000175100001770000000000014635727603022144 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/fake_pycodestyle_configuration/tox.ini0000644000175100001770000000004314635727563023461 0ustar00runnerdocker[pycodestyle] max-line-length = 40 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/iso_8859_1.py0000644000175100001770000000003514635727563015747 0ustar00runnerdocker# -*- coding: iso-8859-1 -*- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/test_autopep8.py0000755000175100001770000075602114635727563017064 0ustar00runnerdocker"""Test suite for autopep8. Unit tests go in "UnitTests". System tests go in "SystemTests". """ import os import re import sys import time import contextlib import io import shutil import stat from subprocess import Popen, PIPE from tempfile import mkstemp, mkdtemp import tokenize import unittest import warnings from io import StringIO ROOT_DIR = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] sys.path.insert(0, ROOT_DIR) import autopep8 # NOQA: E402 from autopep8 import get_module_imports_on_top_of_file # NOQA: E402 FAKE_CONFIGURATION = os.path.join(ROOT_DIR, 'test', 'fake_configuration') FAKE_PYCODESTYLE_CONFIGURATION = os.path.join( ROOT_DIR, 'test', 'fake_pycodestyle_configuration' ) if 'AUTOPEP8_COVERAGE' in os.environ and int(os.environ['AUTOPEP8_COVERAGE']): AUTOPEP8_CMD_TUPLE = (sys.executable, '-Wignore::DeprecationWarning', '-m', 'coverage', 'run', '--branch', '--parallel', '--omit=*/site-packages/*', os.path.join(ROOT_DIR, 'autopep8.py'),) else: # We need to specify the executable to make sure the correct Python # interpreter gets used. AUTOPEP8_CMD_TUPLE = (sys.executable, '-Wignore::DeprecationWarning', os.path.join(ROOT_DIR, 'autopep8.py'),) # pragma: no cover class UnitTests(unittest.TestCase): def test_compile_value_error(self): source = '"\\xhh" \\' self.assertFalse(autopep8.check_syntax(source)) def test_find_newline_only_cr(self): source = ['print(1)\r', 'print(2)\r', 'print3\r'] self.assertEqual(autopep8.CR, autopep8.find_newline(source)) def test_find_newline_only_lf(self): source = ['print(1)\n', 'print(2)\n', 'print3\n'] self.assertEqual(autopep8.LF, autopep8.find_newline(source)) def test_find_newline_only_crlf(self): source = ['print(1)\r\n', 'print(2)\r\n', 'print3\r\n'] self.assertEqual(autopep8.CRLF, autopep8.find_newline(source)) def test_find_newline_cr1_and_lf2(self): source = ['print(1)\n', 'print(2)\r', 'print3\n'] self.assertEqual(autopep8.LF, autopep8.find_newline(source)) def test_find_newline_cr1_and_crlf2(self): source = ['print(1)\r\n', 'print(2)\r', 'print3\r\n'] self.assertEqual(autopep8.CRLF, autopep8.find_newline(source)) def test_find_newline_should_default_to_lf(self): self.assertEqual(autopep8.LF, autopep8.find_newline([])) self.assertEqual(autopep8.LF, autopep8.find_newline(['', ''])) def test_detect_encoding(self): self.assertEqual( 'utf-8', autopep8.detect_encoding( os.path.join(ROOT_DIR, 'test', 'test_autopep8.py'))) def test_detect_encoding_with_cookie(self): self.assertEqual( 'iso-8859-1', autopep8.detect_encoding( os.path.join(ROOT_DIR, 'test', 'iso_8859_1.py'))) def test_readlines_from_file_with_bad_encoding(self): """Bad encoding should not cause an exception.""" self.assertEqual( ['# -*- coding: zlatin-1 -*-\n'], autopep8.readlines_from_file( os.path.join(ROOT_DIR, 'test', 'bad_encoding.py'))) def test_readlines_from_file_with_bad_encoding2(self): """Bad encoding should not cause an exception.""" # This causes a warning on Python 3. with warnings.catch_warnings(record=True): self.assertTrue(autopep8.readlines_from_file( os.path.join(ROOT_DIR, 'test', 'bad_encoding2.py'))) def test_fix_whitespace(self): self.assertEqual( 'a b', autopep8.fix_whitespace('a b', offset=1, replacement=' ')) def test_fix_whitespace_with_tabs(self): self.assertEqual( 'a b', autopep8.fix_whitespace('a\t \t b', offset=1, replacement=' ')) def test_multiline_string_lines(self): self.assertEqual( {2}, autopep8.multiline_string_lines( """\ ''' ''' """)) def test_multiline_string_lines_with_many(self): self.assertEqual( {2, 7, 10, 11, 12}, autopep8.multiline_string_lines( """\ ''' ''' '''''' '''''' '''''' ''' ''' ''' ''' """)) def test_multiline_string_should_not_report_single_line(self): self.assertEqual( set(), autopep8.multiline_string_lines( """\ '''abc''' """)) def test_multiline_string_should_not_report_docstrings(self): self.assertEqual( {5}, autopep8.multiline_string_lines( """\ def foo(): '''Foo. Bar.''' hello = ''' ''' """)) def test_supported_fixes(self): self.assertIn('E121', [f[0] for f in autopep8.supported_fixes()]) def test_shorten_comment(self): self.assertEqual('# ' + '=' * 72 + '\n', autopep8.shorten_comment('# ' + '=' * 100 + '\n', max_line_length=79)) def test_shorten_comment_should_not_split_numbers(self): line = '# ' + '0' * 100 + '\n' self.assertEqual(line, autopep8.shorten_comment(line, max_line_length=79)) def test_shorten_comment_should_not_split_words(self): line = '# ' + 'a' * 100 + '\n' self.assertEqual(line, autopep8.shorten_comment(line, max_line_length=79)) def test_shorten_comment_should_not_split_urls(self): line = '# http://foo.bar/' + 'abc-' * 100 + '\n' self.assertEqual(line, autopep8.shorten_comment(line, max_line_length=79)) def test_shorten_comment_should_not_modify_special_comments(self): line = '#!/bin/blah ' + ' x' * 90 + '\n' self.assertEqual(line, autopep8.shorten_comment(line, max_line_length=79)) def test_format_block_comments(self): self.assertEqual( '# abc', fix_e265_and_e266('#abc')) self.assertEqual( '# abc', fix_e265_and_e266('####abc')) self.assertEqual( '# abc', fix_e265_and_e266('## # ##abc')) self.assertEqual( '# abc "# noqa"', fix_e265_and_e266('# abc "# noqa"')) self.assertEqual( '# *abc', fix_e265_and_e266('#*abc')) def test_format_block_comments_should_leave_outline_alone(self): line = """\ ################################################################### ## Some people like these crazy things. So leave them alone. ## ################################################################### """ self.assertEqual(line, fix_e265_and_e266(line)) line = """\ ################################################################# # Some people like these crazy things. So leave them alone. # ################################################################# """ self.assertEqual(line, fix_e265_and_e266(line)) def test_format_block_comments_with_multiple_lines(self): self.assertEqual( """\ # abc # blah blah # four space indentation ''' #do not modify strings #do not modify strings #do not modify strings #do not modify strings''' # """, fix_e265_and_e266("""\ # abc #blah blah #four space indentation ''' #do not modify strings #do not modify strings #do not modify strings #do not modify strings''' # """)) def test_format_block_comments_should_not_corrupt_special_comments(self): self.assertEqual( '#: abc', fix_e265_and_e266('#: abc')) self.assertEqual( '#!/bin/bash\n', fix_e265_and_e266('#!/bin/bash\n')) def test_format_block_comments_should_only_touch_real_comments(self): commented_out_code = '#x = 1' self.assertEqual( commented_out_code, fix_e266(commented_out_code)) def test_fix_file(self): ret = autopep8.fix_file( filename=os.path.join(ROOT_DIR, 'test', 'example.py') ) self.assertNotEqual(None, ret) if ret is not None: self.assertIn('import ', ret) def test_fix_file_with_diff(self): filename = os.path.join(ROOT_DIR, 'test', 'example.py') ret = autopep8.fix_file( filename=filename, options=autopep8.parse_args(['--diff', filename]) ) self.assertNotEqual(None, ret) if ret is not None: self.assertIn('@@', ret) def test_fix_lines(self): self.assertEqual( 'print(123)\n', autopep8.fix_lines(['print( 123 )\n'], options=autopep8.parse_args(['']))) def test_fix_code(self): self.assertEqual( 'print(123)\n', autopep8.fix_code('print( 123 )\n')) def test_fix_code_with_empty_string(self): self.assertEqual( '', autopep8.fix_code('')) def test_fix_code_with_multiple_lines(self): self.assertEqual( 'print(123)\nx = 4\n', autopep8.fix_code('print( 123 )\nx =4')) def test_fix_code_byte_string(self): """This feature is here for friendliness to Python 2.""" self.assertEqual( 'print(123)\n', autopep8.fix_code(b'print( 123 )\n')) def test_fix_code_with_options(self): self.assertEqual( 'print(123)\n', autopep8.fix_code('print( 123 )\n', options={'ignore': ['W']})) self.assertEqual( 'print( 123 )\n', autopep8.fix_code('print( 123 )\n', options={'ignore': ['E']})) def test_fix_code_with_bad_options(self): with self.assertRaises(ValueError): autopep8.fix_code('print( 123 )\n', options={'ignor': ['W']}) with self.assertRaises(ValueError): autopep8.fix_code('print( 123 )\n', options={'ignore': 'W'}) def test_normalize_line_endings(self): self.assertEqual( ['abc\n', 'def\n', '123\n', 'hello\n', 'world\n'], autopep8.normalize_line_endings( ['abc\n', 'def\n', '123\n', 'hello\r\n', 'world\r'], '\n')) def test_normalize_line_endings_with_crlf(self): self.assertEqual( ['abc\r\n', 'def\r\n', '123\r\n', 'hello\r\n', 'world\r\n'], autopep8.normalize_line_endings( ['abc\n', 'def\r\n', '123\r\n', 'hello\r\n', 'world\r'], '\r\n')) def test_normalize_multiline(self): self.assertEqual('def foo(): pass', autopep8.normalize_multiline('def foo():')) self.assertEqual('def _(): return 1', autopep8.normalize_multiline('return 1')) self.assertEqual('@decorator\ndef _(): pass', autopep8.normalize_multiline('@decorator\n')) self.assertEqual('class A: pass', autopep8.normalize_multiline('class A:')) def test_code_match(self): self.assertTrue(autopep8.code_match('E2', select=['E2', 'E3'], ignore=[])) self.assertTrue(autopep8.code_match('E26', select=['E2', 'E3'], ignore=[])) self.assertFalse(autopep8.code_match('E26', select=[], ignore=['E'])) self.assertFalse(autopep8.code_match('E2', select=['E2', 'E3'], ignore=['E2'])) self.assertFalse(autopep8.code_match('E26', select=['W'], ignore=[''])) self.assertFalse(autopep8.code_match('E26', select=['W'], ignore=['E1'])) def test_split_at_offsets(self): self.assertEqual([''], autopep8.split_at_offsets('', [0])) self.assertEqual(['1234'], autopep8.split_at_offsets('1234', [0])) self.assertEqual(['1', '234'], autopep8.split_at_offsets('1234', [1])) self.assertEqual(['12', '34'], autopep8.split_at_offsets('1234', [2])) self.assertEqual(['12', '3', '4'], autopep8.split_at_offsets('1234', [2, 3])) def test_split_at_offsets_with_out_of_order(self): self.assertEqual(['12', '3', '4'], autopep8.split_at_offsets('1234', [3, 2])) def test_is_python_file(self): self.assertTrue(autopep8.is_python_file( os.path.join(ROOT_DIR, 'autopep8.py'))) with temporary_file_context('#!/usr/bin/env python') as filename: self.assertTrue(autopep8.is_python_file(filename)) with temporary_file_context('#!/usr/bin/python') as filename: self.assertTrue(autopep8.is_python_file(filename)) with temporary_file_context('#!/usr/bin/python3') as filename: self.assertTrue(autopep8.is_python_file(filename)) with temporary_file_context('#!/usr/bin/pythonic') as filename: self.assertFalse(autopep8.is_python_file(filename)) with temporary_file_context('###!/usr/bin/python') as filename: self.assertFalse(autopep8.is_python_file(filename)) self.assertFalse(autopep8.is_python_file(os.devnull)) self.assertFalse(autopep8.is_python_file('/bin/bash')) def test_match_file(self): with temporary_file_context('', suffix='.py', prefix='.') as filename: self.assertFalse(autopep8.match_file(filename, exclude=[]), msg=filename) self.assertFalse(autopep8.match_file(os.devnull, exclude=[])) with temporary_file_context('', suffix='.py', prefix='') as filename: self.assertTrue(autopep8.match_file(filename, exclude=[]), msg=filename) def test_match_file_with_dummy_file(self): filename = "notexists.dummyfile.dummy" self.assertEqual(autopep8.match_file(filename, exclude=[]), False) def test_find_files(self): temp_directory = mkdtemp() try: target = os.path.join(temp_directory, 'dir') os.mkdir(target) with open(os.path.join(target, 'a.py'), 'w'): pass exclude = os.path.join(target, 'ex') os.mkdir(exclude) with open(os.path.join(exclude, 'b.py'), 'w'): pass sub = os.path.join(exclude, 'sub') os.mkdir(sub) with open(os.path.join(sub, 'c.py'), 'w'): pass # FIXME: Avoid changing directory. This may interfere with parallel # test runs. cwd = os.getcwd() os.chdir(temp_directory) try: files = list(autopep8.find_files( ['dir'], True, [os.path.join('dir', 'ex')])) finally: os.chdir(cwd) file_names = [os.path.basename(f) for f in files] self.assertIn('a.py', file_names) self.assertNotIn('b.py', file_names) self.assertNotIn('c.py', file_names) finally: shutil.rmtree(temp_directory) def test_line_shortening_rank(self): self.assertGreater( autopep8.line_shortening_rank('(1\n+1)\n', indent_word=' ', max_line_length=79), autopep8.line_shortening_rank('(1+\n1)\n', indent_word=' ', max_line_length=79)) self.assertGreaterEqual( autopep8.line_shortening_rank('(1+\n1)\n', indent_word=' ', max_line_length=79), autopep8.line_shortening_rank('(1+1)\n', indent_word=' ', max_line_length=79)) # Do not crash. autopep8.line_shortening_rank('\n', indent_word=' ', max_line_length=79) self.assertGreater( autopep8.line_shortening_rank('[foo(\nx) for x in y]\n', indent_word=' ', max_line_length=79), autopep8.line_shortening_rank('[foo(x)\nfor x in y]\n', indent_word=' ', max_line_length=79)) def test_extract_code_from_function(self): def fix_e123(): pass # pragma: no cover self.assertEqual('e123', autopep8.extract_code_from_function(fix_e123)) def foo(): pass # pragma: no cover self.assertEqual(None, autopep8.extract_code_from_function(foo)) def fix_foo(): pass # pragma: no cover self.assertEqual(None, autopep8.extract_code_from_function(fix_foo)) def e123(): pass # pragma: no cover self.assertEqual(None, autopep8.extract_code_from_function(e123)) def fix_(): pass # pragma: no cover self.assertEqual(None, autopep8.extract_code_from_function(fix_)) def test_reindenter(self): reindenter = autopep8.Reindenter('if True:\n pass\n') self.assertEqual('if True:\n pass\n', reindenter.run()) def test_reindenter_with_non_standard_indent_size(self): reindenter = autopep8.Reindenter('if True:\n pass\n') self.assertEqual('if True:\n pass\n', reindenter.run(3)) def test_reindenter_with_good_input(self): lines = 'if True:\n pass\n' reindenter = autopep8.Reindenter(lines) self.assertEqual(lines, reindenter.run()) def test_reindenter_should_leave_stray_comment_alone(self): lines = ' #\nif True:\n pass\n' reindenter = autopep8.Reindenter(lines) self.assertEqual(' #\nif True:\n pass\n', reindenter.run()) @unittest.skipIf('AUTOPEP8_COVERAGE' in os.environ, 'exists form-feed') def test_reindenter_not_affect_with_formfeed(self): lines = """print('hello') print('python') """ reindenter = autopep8.Reindenter(lines) self.assertEqual(lines, reindenter.run()) def test_fix_e225_avoid_failure(self): fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents=' 1\n') self.assertEqual( [], fix_pep8.fix_e225({'line': 1, 'column': 5})) def test_fix_e271_ignore_redundant(self): fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='x = 1\n') self.assertEqual( [], fix_pep8.fix_e271({'line': 1, 'column': 2})) def test_fix_e401_avoid_non_import(self): fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents=' 1\n') self.assertEqual( [], fix_pep8.fix_e401({'line': 1, 'column': 5})) def test_fix_e711_avoid_failure(self): fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='None == x\n') self.assertEqual( None, fix_pep8.fix_e711({'line': 1, 'column': 6})) self.assertEqual( [], fix_pep8.fix_e711({'line': 1, 'column': 700})) fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='x <> None\n') self.assertEqual( [], fix_pep8.fix_e711({'line': 1, 'column': 3})) def test_fix_e712_avoid_failure(self): fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='True == x\n') self.assertEqual( [], fix_pep8.fix_e712({'line': 1, 'column': 5})) self.assertEqual( [], fix_pep8.fix_e712({'line': 1, 'column': 700})) fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='x != True\n') self.assertEqual( [], fix_pep8.fix_e712({'line': 1, 'column': 3})) fix_pep8 = autopep8.FixPEP8(filename='', options=autopep8.parse_args(['']), contents='x == False\n') self.assertEqual( [], fix_pep8.fix_e712({'line': 1, 'column': 3})) def test_get_diff_text(self): # We ignore the first two lines since it differs on Python 2.6. self.assertEqual( """\ -foo +bar """, '\n'.join(autopep8.get_diff_text(['foo\n'], ['bar\n'], '').split('\n')[3:])) def test_get_diff_text_without_newline(self): # We ignore the first two lines since it differs on Python 2.6. self.assertEqual( """\ -foo \\ No newline at end of file +foo """, '\n'.join(autopep8.get_diff_text(['foo'], ['foo\n'], '').split('\n')[3:])) def test_count_unbalanced_brackets(self): self.assertEqual( 0, autopep8.count_unbalanced_brackets('()')) self.assertEqual( 1, autopep8.count_unbalanced_brackets('(')) self.assertEqual( 2, autopep8.count_unbalanced_brackets('([')) self.assertEqual( 1, autopep8.count_unbalanced_brackets('[])')) self.assertEqual( 1, autopep8.count_unbalanced_brackets( "'','.join(['%s=%s' % (col, col)')")) def test_commented_out_code_lines(self): self.assertEqual( [1, 4], autopep8.commented_out_code_lines("""\ #x = 1 #Hello #Hello world. #html_use_index = True """)) def test_standard_deviation(self): self.assertAlmostEqual( 2, autopep8.standard_deviation([2, 4, 4, 4, 5, 5, 7, 9])) self.assertAlmostEqual(0, autopep8.standard_deviation([])) self.assertAlmostEqual(0, autopep8.standard_deviation([1])) self.assertAlmostEqual(.5, autopep8.standard_deviation([1, 2])) def test_priority_key_with_non_existent_key(self): pep8_result = {'id': 'foobar'} self.assertGreater(autopep8._priority_key(pep8_result), 1) def test_decode_filename(self): self.assertEqual('foo.py', autopep8.decode_filename(b'foo.py')) def test_almost_equal(self): self.assertTrue(autopep8.code_almost_equal( """\ [1, 2, 3 4, 5] """, """\ [1, 2, 3 4, 5] """)) self.assertTrue(autopep8.code_almost_equal( """\ [1,2,3 4,5] """, """\ [1, 2, 3 4,5] """)) self.assertFalse(autopep8.code_almost_equal( """\ [1, 2, 3 4, 5] """, """\ [1, 2, 3, 4, 5] """)) def test_token_offsets(self): text = """\ 1 """ string_io = io.StringIO(text) self.assertEqual( [(tokenize.NUMBER, '1', 0, 1), (tokenize.NEWLINE, '\n', 1, 2), (tokenize.ENDMARKER, '', 2, 2)], list(autopep8.token_offsets( tokenize.generate_tokens(string_io.readline)))) def test_token_offsets_with_multiline(self): text = """\ x = ''' 1 2 ''' """ string_io = io.StringIO(text) self.assertEqual( [(tokenize.NAME, 'x', 0, 1), (tokenize.OP, '=', 2, 3), (tokenize.STRING, "'''\n1\n2\n'''", 4, 15), (tokenize.NEWLINE, '\n', 15, 16), (tokenize.ENDMARKER, '', 16, 16)], list(autopep8.token_offsets( tokenize.generate_tokens(string_io.readline)))) def test_token_offsets_with_escaped_newline(self): text = """\ True or \\ False """ string_io = io.StringIO(text) self.assertEqual( [(tokenize.NAME, 'True', 0, 4), (tokenize.NAME, 'or', 5, 7), (tokenize.NAME, 'False', 11, 16), (tokenize.NEWLINE, '\n', 16, 17), (tokenize.ENDMARKER, '', 17, 17)], list(autopep8.token_offsets( tokenize.generate_tokens(string_io.readline)))) def test_shorten_line_candidates_are_valid(self): for text in [ """\ [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, y] = [1, 2] """, """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, y = [1, 2] """, """\ lambda xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: line_shortening_rank(x, indent_word, max_line_length) """, ]: indent = autopep8._get_indentation(text) source = text[len(indent):] assert source.lstrip() == source tokens = list(autopep8.generate_tokens(source)) for candidate in autopep8.shorten_line( tokens, source, indent, indent_word=' ', max_line_length=79, aggressive=10, experimental=True, previous_line=''): self.assertEqual( re.sub(r'\s', '', text), re.sub(r'\s', '', candidate)) def test_get_fixed_long_line_empty(self): line = '' self.assertEqual(line, autopep8.get_fixed_long_line(line, line, line)) class SystemTestsE1(unittest.TestCase): def test_e101(self): line = """\ while True: if True: \t1 """ fixed = """\ while True: if True: 1 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_with_indent_size_1(self): line = """\ while True: if True: \t1 """ fixed = """\ while True: if True: 1 """ with autopep8_context(line, options=['--indent-size=1']) as result: self.assertEqual(fixed, result) def test_e101_with_indent_size_2(self): line = """\ while True: if True: \t1 """ fixed = """\ while True: if True: 1 """ with autopep8_context(line, options=['--indent-size=2']) as result: self.assertEqual(fixed, result) def test_e101_with_indent_size_3(self): line = """\ while True: if True: \t1 """ fixed = """\ while True: if True: 1 """ with autopep8_context(line, options=['--indent-size=3']) as result: self.assertEqual(fixed, result) def test_e101_should_not_expand_non_indentation_tabs(self): line = """\ while True: if True: \t1 == '\t' """ fixed = """\ while True: if True: 1 == '\t' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_should_ignore_multiline_strings(self): line = """\ x = ''' while True: if True: \t1 ''' """ fixed = """\ x = ''' while True: if True: \t1 ''' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_should_fix_docstrings(self): line = """\ class Bar(object): def foo(): ''' \tdocstring ''' """ fixed = """\ class Bar(object): def foo(): ''' docstring ''' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_when_pep8_mistakes_first_tab_in_string(self): # pep8 will complain about this even if the tab indentation found # elsewhere is in a multiline string. line = """\ x = ''' \tHello. ''' if True: 123 """ fixed = """\ x = ''' \tHello. ''' if True: 123 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_should_ignore_multiline_strings_complex(self): line = """\ print(3 != 4, ''' while True: if True: \t1 \t''', 4 != 5) """ fixed = """\ print(3 != 4, ''' while True: if True: \t1 \t''', 4 != 5) """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e101_with_comments(self): line = """\ while True: # My inline comment # with a hanging # comment. # Hello if True: \t# My comment \t1 \t# My other comment """ fixed = """\ while True: # My inline comment # with a hanging # comment. # Hello if True: # My comment 1 # My other comment """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e101_skip_if_bad_indentation(self): line = """\ try: \t pass except: pass """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e101_skip_innocuous(self): # pep8 will complain about this even if the tab indentation found # elsewhere is in a multiline string. If we don't filter the innocuous # report properly, the below command will take a long time. p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['-vvv', '--select=E101', '--diff', '--global-config={}'.format(os.devnull), os.path.join(ROOT_DIR, 'test', 'e101_example.py')], stdout=PIPE, stderr=PIPE) output = [x.decode('utf-8') for x in p.communicate()][0] setup_cfg_file = os.path.join(ROOT_DIR, "setup.cfg") tox_ini_file = os.path.join(ROOT_DIR, "tox.ini") expected = """\ read config path: /dev/null read config path: {} read config path: {} """.format(setup_cfg_file, tox_ini_file) self.assertEqual(expected, output) def test_e111_short(self): line = 'class Dummy:\n\n def __init__(self):\n pass\n' fixed = 'class Dummy:\n\n def __init__(self):\n pass\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_long(self): line = 'class Dummy:\n\n def __init__(self):\n pass\n' fixed = 'class Dummy:\n\n def __init__(self):\n pass\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_longer(self): line = """\ while True: if True: 1 elif True: 2 """ fixed = """\ while True: if True: 1 elif True: 2 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_multiple_levels(self): line = """\ while True: if True: 1 # My comment print('abc') """ fixed = """\ while True: if True: 1 # My comment print('abc') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_with_dedent(self): line = """\ def foo(): if True: 2 1 """ fixed = """\ def foo(): if True: 2 1 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_with_other_errors(self): line = """\ def foo(): if True: (2 , 1) 1 if True: print('hello')\t 2 """ fixed = """\ def foo(): if True: (2, 1) 1 if True: print('hello') 2 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e111_should_not_modify_string_contents(self): line = """\ if True: x = ''' 1 ''' """ fixed = """\ if True: x = ''' 1 ''' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e112_should_leave_bad_syntax_alone(self): line = """\ if True: pass """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e113(self): line = """\ a = 1 b = 2 """ fixed = """\ a = 1 b = 2 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e113_bad_syntax(self): line = """\ pass """ fixed = """\ pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e114(self): line = """\ # a = 1 """ fixed = """\ # a = 1 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e115(self): line = """\ if True: # A comment. pass """ fixed = """\ if True: # A comment. pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e116(self): line = """\ a = 1 # b = 2 """ fixed = """\ a = 1 # b = 2 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e117(self): line = """\ for a in [1, 2, 3]: print('hello world') for b in [1, 2, 3]: print(a, b) """ fixed = """\ for a in [1, 2, 3]: print('hello world') for b in [1, 2, 3]: print(a, b) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_reindent(self): line = """\ def foo_bar(baz, frop, fizz, bang): # E128 pass if True: x = { } # E123 #: E121 print "E121", ( "dent") #: E122 print "E122", ( "dent") #: E124 print "E124", ("visual", "indent_two" ) #: E125 if (row < 0 or self.moduleCount <= row or col < 0 or self.moduleCount <= col): raise Exception("%s,%s - %s" % (row, col, self.moduleCount)) #: E126 print "E126", ( "dent") #: E127 print "E127", ("over-", "over-indent") #: E128 print "E128", ("under-", "under-indent") """ fixed = """\ def foo_bar(baz, frop, fizz, bang): # E128 pass if True: x = { } # E123 #: E121 print "E121", ( "dent") #: E122 print "E122", ( "dent") #: E124 print "E124", ("visual", "indent_two" ) #: E125 if (row < 0 or self.moduleCount <= row or col < 0 or self.moduleCount <= col): raise Exception("%s,%s - %s" % (row, col, self.moduleCount)) #: E126 print "E126", ( "dent") #: E127 print "E127", ("over-", "over-indent") #: E128 print "E128", ("under-", "under-indent") """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_reindent_with_multiple_fixes(self): line = """\ sql = 'update %s set %s %s' % (from_table, ','.join(['%s=%s' % (col, col) for col in cols]), where_clause) """ fixed = """\ sql = 'update %s set %s %s' % (from_table, ','.join(['%s=%s' % (col, col) for col in cols]), where_clause) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_tricky(self): line = """\ #: E126 if ( x == ( 3 ) or x == ( 3 ) or y == 4): pass """ fixed = """\ #: E126 if ( x == ( 3 ) or x == ( 3 ) or y == 4): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_large(self): line = """\ class BogusController(controller.CementBaseController): class Meta: pass class BogusController2(controller.CementBaseController): class Meta: pass class BogusController3(controller.CementBaseController): class Meta: pass class BogusController4(controller.CementBaseController): class Meta: pass class TestBaseController(controller.CementBaseController): class Meta: pass class TestBaseController2(controller.CementBaseController): class Meta: pass class TestStackedController(controller.CementBaseController): class Meta: arguments = [ ] class TestDuplicateController(controller.CementBaseController): class Meta: config_defaults = dict( foo='bar', ) arguments = [ (['-f2', '--foo2'], dict(action='store')) ] def my_command(self): pass """ fixed = """\ class BogusController(controller.CementBaseController): class Meta: pass class BogusController2(controller.CementBaseController): class Meta: pass class BogusController3(controller.CementBaseController): class Meta: pass class BogusController4(controller.CementBaseController): class Meta: pass class TestBaseController(controller.CementBaseController): class Meta: pass class TestBaseController2(controller.CementBaseController): class Meta: pass class TestStackedController(controller.CementBaseController): class Meta: arguments = [ ] class TestDuplicateController(controller.CementBaseController): class Meta: config_defaults = dict( foo='bar', ) arguments = [ (['-f2', '--foo2'], dict(action='store')) ] def my_command(self): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_with_bad_indentation(self): line = r""" def bar(): foo(1, 2) def baz(): pass pass """ fixed = r""" def bar(): foo(1, 2) def baz(): pass pass """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e121_with_multiline_string(self): line = """\ testing = \\ '''inputs: d c b a ''' """ fixed = """\ testing = \\ '''inputs: d c b a ''' """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e122_with_fallback(self): line = """\ foooo('', scripts=[''], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', ]) """ fixed = """\ foooo('', scripts=[''], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', ]) """ with autopep8_context(line, options=[]) as result: self.assertEqual(fixed, result) def test_e123(self): line = """\ if True: foo = ( ) """ fixed = """\ if True: foo = ( ) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e123_with_escaped_newline(self): line = r""" x = \ ( ) """ fixed = r""" x = \ ( ) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e128_with_aaa_option(self): line = """\ def extractBlocks(self): addLine = (self.matchMultiple(linesIncludePatterns, line) and not self.matchMultiple(linesExcludePatterns, line)) or emptyLine """ fixed = """\ def extractBlocks(self): addLine = ( self.matchMultiple( linesIncludePatterns, line) and not self.matchMultiple( linesExcludePatterns, line)) or emptyLine """ with autopep8_context(line, options=['-aaa']) as result: self.assertEqual(fixed, result) def test_e129(self): line = """\ if (a and b in [ 'foo', ] or c): pass """ fixed = """\ if (a and b in [ 'foo', ] or c): pass """ with autopep8_context(line, options=['--select=E129']) as result: self.assertEqual(fixed, result) def test_e125_with_multiline_string(self): line = """\ for foo in ''' abc 123 '''.strip().split(): print(foo) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(line, result) def test_e125_with_multiline_string_okay(self): line = """\ def bar( a='''a'''): print(foo) """ fixed = """\ def bar( a='''a'''): print(foo) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e126(self): line = """\ if True: posted = models.DateField( default=datetime.date.today, help_text="help" ) """ fixed = """\ if True: posted = models.DateField( default=datetime.date.today, help_text="help" ) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e126_should_not_interfere_with_other_fixes(self): line = """\ self.assertEqual('bottom 1', SimpleNamedNode.objects.filter(id__gt=1).exclude( name='bottom 3').filter( name__in=['bottom 3', 'bottom 1'])[0].name) """ fixed = """\ self.assertEqual('bottom 1', SimpleNamedNode.objects.filter(id__gt=1).exclude( name='bottom 3').filter( name__in=['bottom 3', 'bottom 1'])[0].name) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e127(self): line = """\ if True: if True: chksum = (sum([int(value[i]) for i in xrange(0, 9, 2)]) * 7 - sum([int(value[i]) for i in xrange(1, 9, 2)])) % 10 """ fixed = """\ if True: if True: chksum = (sum([int(value[i]) for i in xrange(0, 9, 2)]) * 7 - sum([int(value[i]) for i in xrange(1, 9, 2)])) % 10 """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e127_align_visual_indent(self): line = """\ def draw(self): color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]), ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9]) ][self._p._colored ] self.draw_background(color) """ fixed = """\ def draw(self): color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]), ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored] self.draw_background(color) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e127_align_visual_indent_okay(self): """This is for code coverage.""" line = """\ want = (have + _leading_space_count( after[jline - 1]) - _leading_space_count(lines[jline])) """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e127_with_backslash(self): line = r""" if True: if True: self.date = meta.session.query(schedule.Appointment)\ .filter(schedule.Appointment.id == appointment_id).one().agenda.endtime """ fixed = r""" if True: if True: self.date = meta.session.query(schedule.Appointment)\ .filter(schedule.Appointment.id == appointment_id).one().agenda.endtime """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e127_with_bracket_then_parenthesis(self): line = r""" if True: foo = [food(1) for bar in bars] """ fixed = r""" if True: foo = [food(1) for bar in bars] """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e12_with_backslash(self): line = r""" if True: assert reeval == parsed, \ 'Repr gives different object:\n %r !=\n %r' % (parsed, reeval) """ fixed = r""" if True: assert reeval == parsed, \ 'Repr gives different object:\n %r !=\n %r' % (parsed, reeval) """ with autopep8_context(line, options=['--select=E12']) as result: self.assertEqual(fixed, result) def test_e133(self): line = """\ if True: e = [ 1, 2 ] """ fixed = """\ if True: e = [ 1, 2 ] """ with autopep8_context(line, options=['--hang-closing']) as result: self.assertEqual(fixed, result) def test_e133_no_indentation_line(self): line = """\ e = [ 1, 2 ] """ fixed = """\ e = [ 1, 2 ] """ with autopep8_context(line, options=['--hang-closing']) as result: self.assertEqual(fixed, result) def test_e133_not_effected(self): line = """\ if True: e = [ 1, 2 ] """ with autopep8_context(line, options=['--hang-closing']) as result: self.assertEqual(line, result) def test_w191(self): line = """\ while True: \tif True: \t\t1 """ fixed = """\ while True: if True: 1 """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w191_ignore(self): line = """\ while True: \tif True: \t\t1 """ with autopep8_context(line, options=['--aggressive', '--ignore=W191']) as result: self.assertEqual(line, result) def test_e131_with_select_option(self): line = 'd = f(\n a="hello"\n "world",\n b=1)\n' fixed = 'd = f(\n a="hello"\n "world",\n b=1)\n' with autopep8_context(line, options=['--select=E131']) as result: self.assertEqual(fixed, result) def test_e131_invalid_indent_with_select_option(self): line = 'd = (\n "hello"\n "world")\n' fixed = 'd = (\n "hello"\n "world")\n' with autopep8_context(line, options=['--select=E131']) as result: self.assertEqual(fixed, result) class SystemTestsE2(unittest.TestCase): def test_e201(self): line = '( 1)\n' fixed = '(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e202(self): line = '(1 )\n[2 ]\n{3 }\n' fixed = '(1)\n[2]\n{3}\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e202_multiline(self): line = """\ (''' a b c ''' ) """ fixed = """\ (''' a b c ''') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e202_skip_multiline_with_escaped_newline(self): line = r""" ('c\ ' ) """ fixed = r""" ('c\ ') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e203_colon(self): line = '{4 : 3}\n' fixed = '{4: 3}\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e203_comma(self): line = '[1 , 2 , 3]\n' fixed = '[1, 2, 3]\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e203_semicolon(self): line = "print(a, end=' ') ; nl = 0\n" fixed = "print(a, end=' '); nl = 0\n" with autopep8_context(line, options=['--select=E203']) as result: self.assertEqual(fixed, result) def test_e203_with_newline(self): line = "print(a\n, end=' ')\n" fixed = "print(a, end=' ')\n" with autopep8_context(line, options=['--select=E203']) as result: self.assertEqual(fixed, result) def test_e204(self): line = '@ decorator\n' fixed = '@decorator\n' with autopep8_context(line, options=['--select=E204']) as result: self.assertEqual(fixed, result) def test_e211(self): line = 'd = [1, 2, 3]\nprint(d [0])\n' fixed = 'd = [1, 2, 3]\nprint(d[0])\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e221(self): line = 'a = 1 + 1\n' fixed = 'a = 1 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e221_do_not_skip_multiline(self): line = '''\ def javascript(self): return u""" """ % { } ''' fixed = '''\ def javascript(self): return u""" """ % { } ''' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e222(self): line = 'a = 1 + 1\n' fixed = 'a = 1 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e222_with_multiline(self): line = 'a = \"\"\"bar\nbaz\"\"\"\n' fixed = 'a = \"\"\"bar\nbaz\"\"\"\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e223(self): line = 'a = 1 + 1\n' # include TAB fixed = 'a = 1 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e223_double(self): line = 'a = 1 + 1\n' # include TAB fixed = 'a = 1 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e223_with_tab_indentation(self): line = """\ class Foo(): \tdef __init__(self): \t\tx= 1\t+ 3 """ fixed = """\ class Foo(): \tdef __init__(self): \t\tx = 1 + 3 """ with autopep8_context(line, options=['--ignore=E1,W191']) as result: self.assertEqual(fixed, result) def test_e224(self): line = 'a = 11 + 1\n' # include TAB fixed = 'a = 11 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e224_double(self): line = 'a = 11 + 1\n' # include TAB fixed = 'a = 11 + 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e224_with_tab_indentation(self): line = """\ class Foo(): \tdef __init__(self): \t\tx= \t3 """ fixed = """\ class Foo(): \tdef __init__(self): \t\tx = 3 """ with autopep8_context(line, options=['--ignore=E1,W191']) as result: self.assertEqual(fixed, result) def test_e225(self): line = '1+1\n2 +2\n3+ 3\n' fixed = '1 + 1\n2 + 2\n3 + 3\n' with autopep8_context(line, options=['--select=E,W']) as result: self.assertEqual(fixed, result) def test_e225_with_indentation_fix(self): line = """\ class Foo(object): def bar(self): return self.elephant!='test' """ fixed = """\ class Foo(object): def bar(self): return self.elephant != 'test' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e226(self): line = '1*1\n2*2\n3*3\n' fixed = '1 * 1\n2 * 2\n3 * 3\n' with autopep8_context(line, options=['--select=E22']) as result: self.assertEqual(fixed, result) def test_e227(self): line = '1&1\n2&2\n3&3\n' fixed = '1 & 1\n2 & 2\n3 & 3\n' with autopep8_context(line, options=['--select=E22']) as result: self.assertEqual(fixed, result) def test_e228(self): line = '1%1\n2%2\n3%3\n' fixed = '1 % 1\n2 % 2\n3 % 3\n' with autopep8_context(line, options=['--select=E22']) as result: self.assertEqual(fixed, result) def test_e231(self): line = '[1,2,3]\n' fixed = '[1, 2, 3]\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e231_with_many_commas(self): fixed = str(list(range(200))) + '\n' line = re.sub(', ', ',', fixed) with autopep8_context(line, options=['--select=E231']) as result: self.assertEqual(fixed, result) def test_e231_with_colon_after_comma(self): """ws_comma fixer ignores this case.""" line = 'a[b1,:]\n' fixed = 'a[b1, :]\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e231_should_only_do_ws_comma_once(self): """If we don't check appropriately, we end up doing ws_comma multiple times and skipping all other fixes.""" line = """\ print( 1 ) foo[0,:] bar[zap[0][0]:zig[0][0],:] """ fixed = """\ print(1) foo[0, :] bar[zap[0][0]:zig[0][0], :] """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e241(self): line = 'l = (1, 2)\n' fixed = 'l = (1, 2)\n' with autopep8_context(line, options=['--select=E']) as result: self.assertEqual(fixed, result) def test_e241_should_be_enabled_by_aggressive(self): line = 'l = (1, 2)\n' fixed = 'l = (1, 2)\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e241_double(self): line = 'l = (1, 2)\n' fixed = 'l = (1, 2)\n' with autopep8_context(line, options=['--select=E']) as result: self.assertEqual(fixed, result) def test_e242(self): line = 'l = (1,\t2)\n' fixed = 'l = (1, 2)\n' with autopep8_context(line, options=['--select=E']) as result: self.assertEqual(fixed, result) def test_e242_double(self): line = 'l = (1,\t\t2)\n' fixed = 'l = (1, 2)\n' with autopep8_context(line, options=['--select=E']) as result: self.assertEqual(fixed, result) def test_e251(self): line = 'def a(arg = 1):\n print(arg)\n' fixed = 'def a(arg=1):\n print(arg)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e251_with_escaped_newline(self): line = '1\n\n\ndef a(arg=\\\n1):\n print(arg)\n' fixed = '1\n\n\ndef a(arg=1):\n print(arg)\n' with autopep8_context(line, options=['--select=E251']) as result: self.assertEqual(fixed, result) def test_e251_with_calling(self): line = 'foo(bar= True)\n' fixed = 'foo(bar=True)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e251_with_argument_on_next_line(self): line = 'foo(bar\n=None)\n' fixed = 'foo(bar=None)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e252(self): line = 'def a(arg1: int=1, arg2: int =1, arg3: int= 1):\n print(arg)\n' fixed = 'def a(arg1: int = 1, arg2: int = 1, arg3: int = 1):\n print(arg)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e252_with_argument_on_next_line(self): line = 'def a(arg: int\n=1):\n print(arg)\n' fixed = 'def a(arg: int\n= 1):\n print(arg)\n' with autopep8_context(line, options=['--select=E252']) as result: self.assertEqual(fixed, result) def test_e252_with_escaped_newline(self): line = 'def a(arg: int\\\n=1):\n print(arg)\n' fixed = 'def a(arg: int\\\n= 1):\n print(arg)\n' with autopep8_context(line, options=['--select=E252']) as result: self.assertEqual(fixed, result) def test_e261(self): line = "print('a b ')# comment\n" fixed = "print('a b ') # comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e261_with_inline_commented_out_code(self): line = '1 # 0 + 0\n' fixed = '1 # 0 + 0\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e261_with_dictionary(self): line = 'd = {# comment\n1: 2}\n' fixed = 'd = { # comment\n 1: 2}\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e261_with_dictionary_no_space(self): line = 'd = {#comment\n1: 2}\n' fixed = 'd = { # comment\n 1: 2}\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e261_with_comma(self): line = '{1: 2 # comment\n , }\n' fixed = '{1: 2 # comment\n , }\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e262_more_space(self): line = "print('a b ') # comment\n" fixed = "print('a b ') # comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e262_none_space(self): line = "print('a b ') #comment\n" fixed = "print('a b ') # comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e262_hash_in_string(self): line = "print('a b #string') #comment\n" fixed = "print('a b #string') # comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e262_hash_in_string_and_multiple_hashes(self): line = "print('a b #string') #comment #comment\n" fixed = "print('a b #string') # comment #comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e262_more_complex(self): line = "print('a b ') #comment\n123\n" fixed = "print('a b ') # comment\n123\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e265(self): line = "#A comment\n123\n" fixed = "# A comment\n123\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e265_ignores_special_comments(self): line = "#!python\n456\n" with autopep8_context(line) as result: self.assertEqual(line, result) def test_e265_ignores_special_comments_in_middle_of_file(self): line = "123\n\n#!python\n456\n" with autopep8_context(line) as result: self.assertEqual(line, result) def test_e265_only(self): line = "##A comment\n#B comment\n123\n" fixed = "## A comment\n# B comment\n123\n" with autopep8_context(line, options=['--select=E265']) as result: self.assertEqual(fixed, result) def test_e265_issue662(self): line = "#print(\" \")\n" fixed = "# print(\" \")\n" with autopep8_context(line, options=['--select=E265']) as result: self.assertEqual(fixed, result) def test_ignore_e265(self): line = "## A comment\n#B comment\n123\n" fixed = "# A comment\n#B comment\n123\n" with autopep8_context(line, options=['--ignore=E265']) as result: self.assertEqual(fixed, result) def test_e266(self): line = "## comment\n123\n" fixed = "# comment\n123\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e266_only(self): line = "## A comment\n#B comment\n123\n" fixed = "# A comment\n#B comment\n123\n" with autopep8_context(line, options=['--select=E266']) as result: self.assertEqual(fixed, result) def test_e266_issue662(self): line = "## comment\n" fixed = "# comment\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_ignore_e266(self): line = "##A comment\n#B comment\n123\n" fixed = "## A comment\n# B comment\n123\n" with autopep8_context(line, options=['--ignore=E266']) as result: self.assertEqual(fixed, result) def test_e271(self): line = 'True and False\n' fixed = 'True and False\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e271_with_multiline(self): line = 'if True and False \\\n True:\n pass\n' fixed = 'if True and False \\\n True:\n pass\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e271_and_w504_with_affects_another_result_line(self): line = """\ cm_opts = ([1] + [d for d in [3,4]]) """ fixed = """\ cm_opts = ([1] + [d for d in [3,4]]) """ with autopep8_context(line, options=["--select=E271,W504"]) as result: self.assertEqual(fixed, result) def test_e272(self): line = 'True and False\n' fixed = 'True and False\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e273(self): line = 'True and\tFalse\n' fixed = 'True and False\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e274(self): line = 'True\tand False\n' fixed = 'True and False\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) class SystemTestsE3(unittest.TestCase): def test_e306(self): line = """ def test_descriptors(self): class descriptor(object): def __init__(self, fn): self.fn = fn def __get__(self, obj, owner): if obj is not None: return self.fn(obj, obj) else: return self def method(self): return 'method' """ fixed = """ def test_descriptors(self): class descriptor(object): def __init__(self, fn): self.fn = fn def __get__(self, obj, owner): if obj is not None: return self.fn(obj, obj) else: return self def method(self): return 'method' """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e301(self): line = 'class k:\n s = 0\n def f():\n print(1)\n' fixed = 'class k:\n s = 0\n\n def f():\n print(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e301_extended_with_docstring(self): line = '''\ class Foo(object): """Test.""" def foo(self): """Test.""" def bar(): pass ''' fixed = '''\ class Foo(object): """Test.""" def foo(self): """Test.""" def bar(): pass ''' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_not_e301_extended_with_comment(self): line = '''\ class Foo(object): """Test.""" # A comment. def foo(self): pass ''' with autopep8_context(line) as result: self.assertEqual(line, result) def test_e302(self): line = 'def f():\n print(1)\n\ndef ff():\n print(2)\n' fixed = 'def f():\n print(1)\n\n\ndef ff():\n print(2)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e302_bug(self): """Avoid creating bad syntax.""" line = r"""def repeatable_expr(): return [bracketed_choice, simple_match, rule_ref],\ Optional(repeat_operator) # def match(): return [simple_match , mixin_rule_match] TODO def simple_match(): return [str_match, re_match] """ self.assertTrue(autopep8.check_syntax(line)) with autopep8_context(line) as result: self.assertTrue(autopep8.check_syntax(result)) def test_e303(self): line = '\n\n\n# alpha\n\n1\n' fixed = '\n\n# alpha\n\n1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e303_extended(self): line = '''\ def foo(): """Document.""" ''' fixed = '''\ def foo(): """Document.""" ''' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e303_with_e305(self): line = """\ def foo(): pass # comment (E303) a = 1 # (E305) """ fixed = """\ def foo(): pass # comment (E303) a = 1 # (E305) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e304(self): line = '@contextmanager\n\ndef f():\n print(1)\n' fixed = '@contextmanager\ndef f():\n print(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e304_with_comment(self): line = '@contextmanager\n# comment\n\ndef f():\n print(1)\n' fixed = '@contextmanager\n# comment\ndef f():\n print(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e305(self): line = 'def a():\n pass\na()\n' fixed = 'def a():\n pass\n\n\na()\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) class SystemTestsE4(unittest.TestCase): def test_e401(self): line = 'import os, sys\n' fixed = 'import os\nimport sys\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e401_with_indentation(self): line = 'def a():\n import os, sys\n' fixed = 'def a():\n import os\n import sys\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e401_should_ignore_commented_comma(self): line = 'import bdist_egg, egg # , not a module, neither is this\n' fixed = 'import bdist_egg\nimport egg # , not a module, neither is this\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e401_should_ignore_commented_comma_with_indentation(self): line = 'if True:\n import bdist_egg, egg # , not a module, neither is this\n' fixed = 'if True:\n import bdist_egg\n import egg # , not a module, neither is this\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e401_should_ignore_false_positive(self): line = 'import bdist_egg; bdist_egg.write_safety_flag(cmd.egg_info, safe)\n' with autopep8_context(line, options=['--select=E401']) as result: self.assertEqual(line, result) def test_e401_with_escaped_newline_case(self): line = 'import foo, \\\n bar\n' fixed = 'import foo\nimport \\\n bar\n' with autopep8_context(line, options=['--select=E401']) as result: self.assertEqual(fixed, result) def test_e402(self): line = 'a = 1\nimport os\n' fixed = 'import os\na = 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_duplicate_module(self): line = 'a = 1\nimport os\nprint(os)\nimport os\n' fixed = 'import os\na = 1\nprint(os)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_with_future_import(self): line = 'from __future__ import print_function\na = 1\nimport os\n' fixed = 'from __future__ import print_function\nimport os\na = 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e401_with_multiline_from_import(self): line = """\ from os import ( chroot ) def f(): pass from a import b from b import c from c import d """ fixed = """\ from a import b from c import d from b import c from os import ( chroot ) def f(): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_with_multiline_from_future_import(self): line = """\ from __future__ import ( absolute_import, print_function ) def f(): pass import os """ fixed = """\ from __future__ import ( absolute_import, print_function ) import os def f(): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_with_module_doc(self): line1 = '"""\nmodule doc\n"""\na = 1\nimport os\n' fixed1 = '"""\nmodule doc\n"""\nimport os\na = 1\n' line2 = '# comment\nr"""\nmodule doc\n"""\na = 1\nimport os\n' fixed2 = '# comment\nr"""\nmodule doc\n"""\nimport os\na = 1\n' line3 = "u'''one line module doc'''\na = 1\nimport os\n" fixed3 = "u'''one line module doc'''\nimport os\na = 1\n" line4 = "'''\n\"\"\"\ndoc'''\na = 1\nimport os\n" fixed4 = "'''\n\"\"\"\ndoc'''\nimport os\na = 1\n" for line, fixed in [(line1, fixed1), (line2, fixed2), (line3, fixed3), (line4, fixed4)]: with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_import_some_modules(self): line = """\ a = 1 from csv import ( reader, writer, ) import os print(os, reader, writer) import os """ fixed = """\ import os from csv import ( reader, writer, ) a = 1 print(os, reader, writer) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_with_dunder(self): line = """\ __all__ = ["a", "b"] def f(): pass import os """ fixed = """\ import os __all__ = ["a", "b"] def f(): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e402_with_dunder_lines(self): line = """\ __all__ = [ "a", "b", ] def f(): pass import os """ fixed = """\ import os __all__ = [ "a", "b", ] def f(): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) class SystemTestsE5(unittest.TestCase): def test_e501_basic(self): line = """\ print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_dictionary(self): line = """\ myDict = { 'kg': 1, 'tonnes': tonne, 't/y': tonne / year, 'Mt/y': 1e6 * tonne / year} """ fixed = """\ myDict = { 'kg': 1, 'tonnes': tonne, 't/y': tonne / year, 'Mt/y': 1e6 * tonne / year} """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_in(self): line = """\ if True: if True: if True: if True: if True: if True: if True: if True: if k_left in ('any', k_curr) and k_right in ('any', k_curr): pass """ fixed = """\ if True: if True: if True: if True: if True: if True: if True: if True: if k_left in ('any', k_curr) and k_right in ('any', k_curr): pass """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_commas_and_colons(self): line = """\ foobar = {'aaaaaaaaaaaa': 'bbbbbbbbbbbbbbbb', 'dddddd': 'eeeeeeeeeeeeeeee', 'ffffffffffff': 'gggggggg'} """ fixed = """\ foobar = {'aaaaaaaaaaaa': 'bbbbbbbbbbbbbbbb', 'dddddd': 'eeeeeeeeeeeeeeee', 'ffffffffffff': 'gggggggg'} """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_inline_comments(self): line = """\ ' ' # Long inline comments should be moved above. if True: ' ' # Long inline comments should be moved above. """ fixed = """\ # Long inline comments should be moved above. ' ' if True: # Long inline comments should be moved above. ' ' """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_inline_comments_should_skip_multiline(self): line = """\ '''This should be left alone. ----------------------------------------------------- ''' # foo '''This should be left alone. ----------------------------------------------------- ''' \\ # foo '''This should be left alone. ----------------------------------------------------- ''' \\ \\ # foo """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(line, result) def test_e501_with_inline_comments_should_skip_keywords(self): line = """\ ' ' # noqa Long inline comments should be moved above. if True: ' ' # pylint: disable-msgs=E0001 ' ' # pragma: no cover ' ' # pragma: no cover """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(line, result) def test_e501_with_inline_comments_should_skip_keywords_without_aggressive( self): line = """\ ' ' # noqa Long inline comments should be moved above. if True: ' ' # pylint: disable-msgs=E0001 ' ' # pragma: no cover ' ' # pragma: no cover """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_with_inline_comments_should_skip_edge_cases(self): line = """\ if True: x = \\ ' ' # Long inline comments should be moved above. """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_basic_should_prefer_balanced_brackets(self): line = """\ if True: reconstructed = iradon(radon(image), filter="ramp", interpolation="nearest") """ fixed = """\ if True: reconstructed = iradon(radon(image), filter="ramp", interpolation="nearest") """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_very_long_line(self): line = """\ x = [3244234243234, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243] """ fixed = """\ x = [ 3244234243234, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243] """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_lambda(self): line = """\ self.mock_group.modify_state.side_effect = lambda *_: defer.fail(NoSuchScalingGroupError(1, 2)) """ fixed = """\ self.mock_group.modify_state.side_effect = lambda *_: defer.fail( NoSuchScalingGroupError(1, 2)) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_shorten_with_backslash(self): line = """\ class Bar(object): def bar(self, position): if 0 <= position <= self._blocks[-1].position + len(self._blocks[-1].text): pass """ fixed = """\ class Bar(object): def bar(self, position): if 0 <= position <= self._blocks[-1].position + \\ len(self._blocks[-1].text): pass """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_shorten_at_commas_skip(self): line = """\ parser.add_argument('source_corpus', help='corpus name/path relative to an nltk_data directory') parser.add_argument('target_corpus', help='corpus name/path relative to an nltk_data directory') """ fixed = """\ parser.add_argument( 'source_corpus', help='corpus name/path relative to an nltk_data directory') parser.add_argument( 'target_corpus', help='corpus name/path relative to an nltk_data directory') """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_shorter_length(self): line = "foooooooooooooooooo('abcdefghijklmnopqrstuvwxyz')\n" fixed = "foooooooooooooooooo(\n 'abcdefghijklmnopqrstuvwxyz')\n" with autopep8_context(line, options=['--max-line-length=40']) as result: self.assertEqual(fixed, result) def test_e501_with_indent(self): line = """\ def d(): print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ def d(): print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_alone_with_indentation(self): line = """\ if True: print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ if True: print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line, options=['--select=E501']) as result: self.assertEqual(fixed, result) def test_e501_alone_with_tuple(self): line = """\ fooooooooooooooooooooooooooooooo000000000000000000000000 = [1, ('TransferTime', 'FLOAT') ] """ fixed = """\ fooooooooooooooooooooooooooooooo000000000000000000000000 = [1, ('TransferTime', 'FLOAT') ] """ with autopep8_context(line, options=['--select=E501']) as result: self.assertEqual(fixed, result) def test_e501_should_not_try_to_break_at_every_paren_in_arithmetic(self): line = """\ term3 = w6 * c5 * (8.0 * psi4 * (11.0 - 24.0 * t2) - 28 * psi3 * (1 - 6.0 * t2) + psi2 * (1 - 32 * t2) - psi * (2.0 * t2) + t4) / 720.0 this_should_be_shortened = (' ', ' ') """ fixed = """\ term3 = w6 * c5 * (8.0 * psi4 * (11.0 - 24.0 * t2) - 28 * psi3 * (1 - 6.0 * t2) + psi2 * (1 - 32 * t2) - psi * (2.0 * t2) + t4) / 720.0 this_should_be_shortened = ( ' ', ' ') """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_arithmetic_operator_with_indent(self): line = """\ def d(): 111 + 111 + 111 + 111 + 111 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 333 + 333 + 333 + 333 """ fixed = r"""def d(): 111 + 111 + 111 + 111 + 111 + 222 + 222 + 222 + 222 + \ 222 + 222 + 222 + 222 + 222 + 333 + 333 + 333 + 333 """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_more_complicated(self): line = """\ blahblah = os.environ.get('blahblah') or os.environ.get('blahblahblah') or os.environ.get('blahblahblahblah') """ fixed = """\ blahblah = os.environ.get('blahblah') or os.environ.get( 'blahblahblah') or os.environ.get('blahblahblahblah') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_skip_even_more_complicated(self): line = """\ if True: if True: if True: blah = blah.blah_blah_blah_bla_bl(blahb.blah, blah.blah, blah=blah.label, blah_blah=blah_blah, blah_blah2=blah_blah) """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_avoid_breaking_at_empty_parentheses_if_possible(self): line = """\ someverylongindenttionwhatnot().foo().bar().baz("and here is a long string 123456789012345678901234567890") """ fixed = """\ someverylongindenttionwhatnot().foo().bar().baz( "and here is a long string 123456789012345678901234567890") """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_logical_fix(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_logical_fix_and_physical_fix(self): line = """\ # ------------------------------------ ------------------------------------------ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ # ------------------------------------ ----------------------------------- xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_logical_fix_and_adjacent_strings(self): line = """\ print('a-----------------------' 'b-----------------------' 'c-----------------------' 'd-----------------------''e'"f"r"g") """ fixed = """\ print( 'a-----------------------' 'b-----------------------' 'c-----------------------' 'd-----------------------' 'e' "f" r"g") """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_multiple_lines(self): line = """\ foo_bar_zap_bing_bang_boom(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333) """ fixed = """\ foo_bar_zap_bing_bang_boom( 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_multiple_lines_and_quotes(self): line = """\ if True: xxxxxxxxxxx = xxxxxxxxxxxxxxxxx(xxxxxxxxxxx, xxxxxxxxxxxxxxxx={'xxxxxxxxxxxx': 'xxxxx', 'xxxxxxxxxxx': xx, 'xxxxxxxx': False, }) """ fixed = """\ if True: xxxxxxxxxxx = xxxxxxxxxxxxxxxxx( xxxxxxxxxxx, xxxxxxxxxxxxxxxx={ 'xxxxxxxxxxxx': 'xxxxx', 'xxxxxxxxxxx': xx, 'xxxxxxxx': False, }) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_do_not_break_on_keyword(self): # We don't want to put a newline after equals for keywords as this # violates PEP 8. line = """\ if True: long_variable_name = tempfile.mkstemp(prefix='abcdefghijklmnopqrstuvwxyz0123456789') """ fixed = """\ if True: long_variable_name = tempfile.mkstemp( prefix='abcdefghijklmnopqrstuvwxyz0123456789') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_do_not_begin_line_with_comma(self): # This fix is incomplete. (The line is still too long.) But it is here # just to confirm that we do not put a comma at the beginning of a # line. line = """\ def dummy(): if True: if True: if True: object = ModifyAction( [MODIFY70.text, OBJECTBINDING71.text, COLON72.text], MODIFY70.getLine(), MODIFY70.getCharPositionInLine() ) """ fixed = """\ def dummy(): if True: if True: if True: object = ModifyAction([MODIFY70.text, OBJECTBINDING71.text, COLON72.text], MODIFY70.getLine( ), MODIFY70.getCharPositionInLine()) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_should_not_break_on_dot(self): line = """\ if True: if True: raise xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx('xxxxxxxxxxxxxxxxx "{d}" xxxxxxxxxxxxxx'.format(d='xxxxxxxxxxxxxxx')) """ fixed = """\ if True: if True: raise xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( 'xxxxxxxxxxxxxxxxx "{d}" xxxxxxxxxxxxxx'.format(d='xxxxxxxxxxxxxxx')) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_comment(self): line = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. pass # http://foo.bar/abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc- # The following is ugly commented-out code and should not be touched. #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx = 1 """ fixed = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will # wrap it using textwrap to be within 72 characters. pass # http://foo.bar/abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc- # The following is ugly commented-out code and should not be touched. # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx = 1 """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_comment_should_not_modify_docstring(self): line = '''\ def foo(): """ # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. """ ''' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(line, result) def test_e501_should_only_modify_last_comment(self): line = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 1. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 2. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 3. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. """ fixed = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 1. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 2. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 3. This is a long comment that should be wrapped. I # will wrap it using textwrap to be within 72 # characters. """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_should_not_interfere_with_non_comment(self): line = ''' """ # not actually a comment %d. 12345678901234567890, 12345678901234567890, 12345678901234567890. """ % (0,) ''' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(line, result) def test_e501_should_cut_comment_pattern(self): line = """123 # -- Useless lines ---------------------------------------------------------------------- 321 """ fixed = """123 # -- Useless lines ------------------------------------------------------- 321 """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_function_should_not_break_on_colon(self): line = r""" class Useless(object): def _table_field_is_plain_widget(self, widget): if widget.__class__ == Widget or\ (widget.__class__ == WidgetMeta and Widget in widget.__bases__): return True return False """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_should_break_before_tuple_start(self): line = """\ xxxxxxxxxxxxx(aaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbb, cccccccccc, (dddddddddddddddddddddd, eeeeeeeeeeee, fffffffffff, gggggggggg)) """ fixed = """\ xxxxxxxxxxxxx(aaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbb, cccccccccc, (dddddddddddddddddddddd, eeeeeeeeeeee, fffffffffff, gggggggggg)) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive(self): line = """\ models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, } """ fixed = """\ models = { 'auth.group': { 'Meta': { 'object_name': 'Group'}, 'permissions': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})}, 'auth.permission': { 'Meta': { 'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'name': ( 'django.db.models.fields.CharField', [], { 'max_length': '50'})}, } """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_multiple_logical_lines(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_multiple_logical_lines_with_math(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx([-1 + 5 / 10, 100, -3 - 4]) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( [-1 + 5 / 10, 100, -3 - 4]) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_import(self): line = """\ from . import (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy) """ fixed = """\ from . import ( xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_massive_number_of_logical_lines(self): """We do not care about results here. We just want to know that it doesn't take a ridiculous amount of time. Caching is currently required to avoid repeately trying the same line. """ line = """\ # encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from provider.compat import user_model_label class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Client' db.create_table('oauth2_client', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])), ('url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('redirect_uri', self.gf('django.db.models.fields.URLField')(max_length=200)), ('client_id', self.gf('django.db.models.fields.CharField')(default='37b581bdc702c732aa65', max_length=255)), ('client_secret', self.gf('django.db.models.fields.CharField')(default='5cf90561f7566aa81457f8a32187dcb8147c7b73', max_length=255)), ('client_type', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal('oauth2', ['Client']) # Adding model 'Grant' db.create_table('oauth2_grant', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])), ('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])), ('code', self.gf('django.db.models.fields.CharField')(default='f0cda1a5f4ae915431ff93f477c012b38e2429c4', max_length=255)), ('expires', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 2, 8, 10, 43, 45, 620301))), ('redirect_uri', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('scope', self.gf('django.db.models.fields.IntegerField')(default=0)), )) db.send_create_signal('oauth2', ['Grant']) # Adding model 'AccessToken' db.create_table('oauth2_accesstoken', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])), ('token', self.gf('django.db.models.fields.CharField')(default='b10b8f721e95117cb13c', max_length=255)), ('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])), ('expires', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2013, 2, 7, 10, 33, 45, 618854))), ('scope', self.gf('django.db.models.fields.IntegerField')(default=0)), )) db.send_create_signal('oauth2', ['AccessToken']) # Adding model 'RefreshToken' db.create_table('oauth2_refreshtoken', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])), ('token', self.gf('django.db.models.fields.CharField')(default='84035a870dab7c820c2c501fb0b10f86fdf7a3fe', max_length=255)), ('access_token', self.gf('django.db.models.fields.related.OneToOneField')(related_name='refresh_token', unique=True, to=orm['oauth2.AccessToken'])), ('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])), ('expired', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('oauth2', ['RefreshToken']) def backwards(self, orm): # Deleting model 'Client' db.delete_table('oauth2_client') # Deleting model 'Grant' db.delete_table('oauth2_grant') # Deleting model 'AccessToken' db.delete_table('oauth2_accesstoken') # Deleting model 'RefreshToken' db.delete_table('oauth2_refreshtoken') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, user_model_label: { 'Meta': {'object_name': user_model_label.split('.')[-1]}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'oauth2.accesstoken': { 'Meta': {'object_name': 'AccessToken'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}), 'expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 7, 10, 33, 45, 624553)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'scope': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'token': ('django.db.models.fields.CharField', [], {'default': "'d5c1f65020ebdc89f20c'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label}) }, 'oauth2.client': { 'Meta': {'object_name': 'Client'}, 'client_id': ('django.db.models.fields.CharField', [], {'default': "'306fb26cbcc87dd33cdb'", 'max_length': '255'}), 'client_secret': ('django.db.models.fields.CharField', [], {'default': "'7e5785add4898448d53767f15373636b918cf0e3'", 'max_length': '255'}), 'client_type': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'redirect_uri': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label}) }, 'oauth2.grant': { 'Meta': {'object_name': 'Grant'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}), 'code': ('django.db.models.fields.CharField', [], {'default': "'310b2c63e27306ecf5307569dd62340cc4994b73'", 'max_length': '255'}), 'expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 2, 8, 10, 43, 45, 625956)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'redirect_uri': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'scope': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label}) }, 'oauth2.refreshtoken': { 'Meta': {'object_name': 'RefreshToken'}, 'access_token': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'refresh_token'", 'unique': 'True', 'to': "orm['oauth2.AccessToken']"}), 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}), 'expired': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'default': "'ef0ab76037f17769ab2975a816e8f41a1c11d25e'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label}) } } complete_apps = ['oauth2'] """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(''.join(line.split()), ''.join(result.split())) def test_e501_shorten_comment_with_aggressive(self): line = """\ # --------- ---------------------------------------------------------------------- """ fixed = """\ # --------- -------------------------------------------------------------- """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_shorten_comment_without_aggressive(self): """Do nothing without aggressive.""" line = """\ def foo(): pass # --------- ---------------------------------------------------------------------- """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_with_aggressive_and_escaped_newline(self): line = """\ if True or \\ False: # test test test test test test test test test test test test test test pass """ fixed = """\ if True or \\ False: # test test test test test test test test test test test test test test pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_multiline_string(self): line = """\ print('---------------------------------------------------------------------', ('================================================', '====================='), '''-------------------------------------------------------------------------------- ''') """ fixed = """\ print( '---------------------------------------------------------------------', ('================================================', '====================='), '''-------------------------------------------------------------------------------- ''') """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_multiline_string_with_addition(self): line = '''\ def f(): email_text += """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""" ''' fixed = '''\ def f(): email_text += """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """ + despot["Nicholas"] + """
Minion: """ + serf["Dmitri"] + """
Residence: """ + palace["Winter"] + """
""" ''' with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_multiline_string_in_parens(self): line = '''\ def f(): email_text += ("""This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""") ''' fixed = '''\ def f(): email_text += ( """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """ + despot["Nicholas"] + """
Minion: """ + serf["Dmitri"] + """
Residence: """ + palace["Winter"] + """
""") ''' with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_indentation(self): line = """\ if True: # comment here print(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,cccccccccccccccccccccccccccccccccccccccccc) """ fixed = """\ if True: # comment here print(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccccccccccccccccc) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_multiple_keys_and_aggressive(self): line = """\ one_two_three_four_five_six = {'one two three four five': 12345, 'asdfsdflsdkfjl sdflkjsdkfkjsfjsdlkfj sdlkfjlsfjs': '343', 1: 1} """ fixed = """\ one_two_three_four_five_six = { 'one two three four five': 12345, 'asdfsdflsdkfjl sdflkjsdkfkjsfjsdlkfj sdlkfjlsfjs': '343', 1: 1} """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_with_aggressive_and_carriage_returns_only(self): """Make sure _find_logical() does not crash.""" line = 'if True:\r from aaaaaaaaaaaaaaaa import bbbbbbbbbbbbbbbbbbb\r \r ccccccccccc = None\r' fixed = 'if True:\r from aaaaaaaaaaaaaaaa import bbbbbbbbbbbbbbbbbbb\r\r ccccccccccc = None\r' with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_should_ignore_imports(self): line = """\ import logging, os, bleach, commonware, urllib2, json, time, requests, urlparse, re """ with autopep8_context(line, options=['--select=E501']) as result: self.assertEqual(line, result) def test_e501_should_not_do_useless_things(self): line = """\ foo(' ') """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e501_aggressive_with_percent(self): line = """\ raise MultiProjectException("Ambiguous workspace: %s=%s, %s" % ( varname, varname_path, os.path.abspath(config_filename))) """ fixed = """\ raise MultiProjectException( "Ambiguous workspace: %s=%s, %s" % (varname, varname_path, os.path.abspath(config_filename))) """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_with_def(self): line = """\ def foo(sldfkjlsdfsdf, kksdfsdfsf,sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf,sdfsdfsfd, sdfsdfdsf): pass """ fixed = """\ def foo(sldfkjlsdfsdf, kksdfsdfsf, sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf, sdfsdfsfd, sdfsdfdsf): pass """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_with_async_def(self): line = """\ async def foo(sldfkjlsdfsdf, kksdfsdfsf,sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf,sdfsdfsfd, sdfsdfdsf): pass """ fixed = """\ async def foo(sldfkjlsdfsdf, kksdfsdfsf, sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf, sdfsdfsfd, sdfsdfdsf): pass """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_more_aggressive_with_def(self): line = """\ def foobar(sldfkjlsdfsdf, kksdfsdfsf,sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf,sdfsdfsfd, sdfsdfdsf): pass """ fixed = """\ def foobar( sldfkjlsdfsdf, kksdfsdfsf, sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf, sdfsdfsfd, sdfsdfdsf): pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_more_aggressive_with_async_def(self): line = """\ async def foobar(sldfkjlsdfsdf, kksdfsdfsf,sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf,sdfsdfsfd, sdfsdfdsf): pass """ fixed = """\ async def foobar( sldfkjlsdfsdf, kksdfsdfsf, sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf, sdfsdfsfd, sdfsdfdsf): pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_with_tuple(self): line = """\ def f(): man_this_is_a_very_long_function_name(an_extremely_long_variable_name, ('a string that is long: %s'%'bork')) """ fixed = """\ def f(): man_this_is_a_very_long_function_name( an_extremely_long_variable_name, ('a string that is long: %s' % 'bork')) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_with_tuple_in_list(self): line = """\ def f(self): self._xxxxxxxx(aaaaaa, bbbbbbbbb, cccccccccccccccccc, [('mmmmmmmmmm', self.yyyyyyyyyy.zzzzzzz/_DDDDD)], eee, 'ff') """ fixed = """\ def f(self): self._xxxxxxxx(aaaaaa, bbbbbbbbb, cccccccccccccccccc, [ ('mmmmmmmmmm', self.yyyyyyyyyy.zzzzzzz / _DDDDD)], eee, 'ff') """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_decorator(self): line = """\ @foo(('xxxxxxxxxxxxxxxxxxxxxxxxxx', users.xxxxxxxxxxxxxxxxxxxxxxxxxx), ('yyyyyyyyyyyy', users.yyyyyyyyyyyy), ('zzzzzzzzzzzzzz', users.zzzzzzzzzzzzzz)) """ fixed = """\ @foo(('xxxxxxxxxxxxxxxxxxxxxxxxxx', users.xxxxxxxxxxxxxxxxxxxxxxxxxx), ('yyyyyyyyyyyy', users.yyyyyyyyyyyy), ('zzzzzzzzzzzzzz', users.zzzzzzzzzzzzzz)) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_long_class_name(self): line = """\ class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA(BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB): pass """ fixed = """\ class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA( BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB): pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_long_comment_and_long_line(self): line = """\ def foo(): # This is not a novel to be tossed aside lightly. It should be throw with great force. self.xxxxxxxxx(_('yyyyyyyyyyyyy yyyyyyyyyyyy yyyyyyyy yyyyyyyy y'), 'zzzzzzzzzzzzzzzzzzz', bork='urgent') """ fixed = """\ def foo(): # This is not a novel to be tossed aside lightly. It should be throw with # great force. self.xxxxxxxxx( _('yyyyyyyyyyyyy yyyyyyyyyyyy yyyyyyyy yyyyyyyy y'), 'zzzzzzzzzzzzzzzzzzz', bork='urgent') """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_aggressive_intermingled_comments(self): line = """\ A = [ # A comment ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccccc'] ] """ fixed = """\ A = [ # A comment ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccccc'] ] """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_if_line_over_limit(self): line = """\ if not xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): return 1 """ fixed = """\ if not xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): return 1 """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_for_line_over_limit(self): line = """\ for aaaaaaaaa in xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ fixed = """\ for aaaaaaaaa in xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_while_line_over_limit(self): line = """\ while xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ fixed = """\ while xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e501_avoid_breaking_at_opening_slice(self): """Prevents line break on slice notation, dict access in this example: GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw[ 'abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME) """ line = """\ GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME) """ fixed = """\ GYakymOSMc = GYakymOSMW(GYakymOSMJ, GYakymOSMA, GYakymOSMr, GYakymOSMw['abc'], GYakymOSMU, GYakymOSMq, GYakymOSMH, GYakymOSMl, svygreNveyvarf=GYakymOSME) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_avoid_breaking_at_multi_level_slice(self): """Prevents line break on slice notation, dict access in this example: GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'][ 'def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME) """ line = """\ GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc']['def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME) """ fixed = """\ GYakymOSMc = GYakymOSMW(GYakymOSMJ, GYakymOSMA, GYakymOSMr, GYakymOSMw['abc']['def'], GYakymOSMU, GYakymOSMq, GYakymOSMH, GYakymOSMl, svygreNveyvarf=GYakymOSME) """ with autopep8_context(line) as result: self.assertEqual(fixed, result) @unittest.skipIf( (sys.version_info.major >= 3 and sys.version_info.minor < 8) or sys.version_info.major < 3, "syntax error in Python3.7 and lower version", ) def test_e501_with_pep572_assignment_expressions(self): line = """\ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1 if bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb := aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: print(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) """ with autopep8_context(line, options=['-aa']) as result: self.assertEqual(line, result) def test_e501_effected_with_fstring(self): line = """\ def foo(): logger.info(f"some string padding some string padding some string padd {somedict['key1']}, more padding more paddin #: {somedict['dictkey2']}") """ fixed = """\ def foo(): logger.info( f"some string padding some string padding some string padd {somedict['key1']}, more padding more paddin #: {somedict['dictkey2']}") """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e501_not_effected_with_fstring(self): line = """\ connector = f"socks5://{user}:{password}:{url}:{port}" """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_e502(self): line = "print('abc'\\\n 'def')\n" fixed = "print('abc'\n 'def')\n" with autopep8_context(line) as result: self.assertEqual(fixed, result) class SystemTestsE7(unittest.TestCase): def test_e701(self): line = 'if True: print(True)\n' fixed = 'if True:\n print(True)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e701_with_escaped_newline(self): line = 'if True:\\\nprint(True)\n' fixed = 'if True:\n print(True)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) @unittest.skipIf(sys.version_info >= (3, 12), 'not detect in Python3.12+') def test_e701_with_escaped_newline_and_spaces(self): line = 'if True: \\ \nprint(True)\n' fixed = 'if True:\n print(True)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702(self): line = 'print(1); print(2)\n' fixed = 'print(1)\nprint(2)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_after_colon_should_be_untouched(self): # https://docs.python.org/2/reference/compound_stmts.html line = 'def foo(): print(1); print(2)\n' with autopep8_context(line) as result: self.assertEqual(line, result) def test_e702_with_semicolon_at_end(self): line = 'print(1);\n' fixed = 'print(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_semicolon_and_space_at_end(self): line = 'print(1); \n' fixed = 'print(1)\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_whitespace(self): line = 'print(1) ; print(2)\n' fixed = 'print(1)\nprint(2)\n' with autopep8_context(line, options=['--select=E702']) as result: self.assertEqual(fixed, result) def test_e702_with_non_ascii_file(self): line = """\ # -*- coding: utf-8 -*- # French comment with accent é # Un commentaire en français avec un accent é import time time.strftime('%d-%m-%Y'); """ fixed = """\ # -*- coding: utf-8 -*- # French comment with accent é # Un commentaire en français avec un accent é import time time.strftime('%d-%m-%Y') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_escaped_newline(self): line = '1; \\\n2\n' fixed = '1\n2\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_escaped_newline_with_indentation(self): line = '1; \\\n 2\n' fixed = '1\n2\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_more_complicated(self): line = """\ def foo(): if bar : bar+=1; bar=bar*bar ; return bar """ fixed = """\ def foo(): if bar: bar += 1 bar = bar * bar return bar """ with autopep8_context(line, options=['--select=E,W']) as result: self.assertEqual(fixed, result) def test_e702_with_semicolon_in_string(self): line = 'print(";");\n' fixed = 'print(";")\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_semicolon_in_string_to_the_right(self): line = 'x = "x"; y = "y;y"\n' fixed = 'x = "x"\ny = "y;y"\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_indent_correctly(self): line = """\ ( 1, 2, 3); 4; 5; 5 # pyflakes """ fixed = """\ ( 1, 2, 3) 4 5 5 # pyflakes """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_triple_quote(self): line = '"""\n hello\n """; 1\n' fixed = '"""\n hello\n """\n1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_triple_quote_and_indent(self): line = 'def f():\n """\n hello\n """; 1\n' fixed = 'def f():\n """\n hello\n """\n 1\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_semicolon_after_string(self): line = """\ raise IOError('abc ' 'def.'); """ fixed = """\ raise IOError('abc ' 'def.') """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_dict_semicolon(self): line = """\ MY_CONST = [ {'A': 1}, {'B': 2} ]; """ fixed = """\ MY_CONST = [ {'A': 1}, {'B': 2} ] """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e702_with_e701_and_only_select_e702_option(self): line = """\ for i in range(3): if i == 1: print(i); continue print(i) """ with autopep8_context(line, options=["--select=E702"]) as result: self.assertEqual(line, result) def test_e703_with_inline_comment(self): line = 'a = 5; # inline comment\n' fixed = 'a = 5 # inline comment\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e703_in_example_of_readme(self): line = """\ def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True}; """ fixed = """\ def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True} """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e704(self): line = 'def f(x): return 2*x\n' fixed = 'def f(x):\n return 2 * x\n' with autopep8_context(line, options=['-aaa']) as result: self.assertEqual(fixed, result) def test_e704_not_work_with_aa_option(self): line = 'def f(x): return 2*x\n' with autopep8_context(line, options=['-aa', '--select=E704']) as result: self.assertEqual(line, result) def test_e711(self): line = 'foo == None\n' fixed = 'foo is None\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) line = 'None == foo\n' fixed = 'None is foo\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e711_in_conditional(self): line = 'if foo == None and None == foo:\npass\n' fixed = 'if foo is None and None is foo:\npass\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e711_in_conditional_with_multiple_instances(self): line = 'if foo == None and bar == None:\npass\n' fixed = 'if foo is None and bar is None:\npass\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e711_with_not_equals_none(self): line = 'foo != None\n' fixed = 'foo is not None\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e712(self): line = 'foo == True\n' fixed = 'foo\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_in_conditional_with_multiple_instances(self): line = 'if foo == True and bar == True:\npass\n' fixed = 'if foo and bar:\npass\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_with_false(self): line = 'foo != False\n' fixed = 'foo\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_with_special_case_equal_not_true(self): line = 'if foo != True:\n pass\n' fixed = 'if not foo:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_with_special_case_equal_false(self): line = 'if foo == False:\n pass\n' fixed = 'if not foo:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_with_dict_value(self): line = 'if d["key"] != True:\n pass\n' fixed = 'if not d["key"]:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E712']) as result: self.assertEqual(fixed, result) def test_e712_only_if_aggressive_level_2(self): line = 'foo == True\n' with autopep8_context(line, options=['-a']) as result: self.assertEqual(line, result) def test_e711_and_e712(self): line = 'if (foo == None and bar == True) or (foo != False and bar != None):\npass\n' fixed = 'if (foo is None and bar) or (foo and bar is not None):\npass\n' with autopep8_context(line, options=['-aa']) as result: self.assertEqual(fixed, result) def test_e713(self): line = 'if not x in y:\n pass\n' fixed = 'if x not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_more(self): line = 'if not "." in y:\n pass\n' fixed = 'if "." not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_with_in(self): line = 'if not "." in y and "," in y:\n pass\n' fixed = 'if "." not in y and "," in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_with_tuple(self): line = """ if not role in ("domaincontroller_master", "domaincontroller_backup", "domaincontroller_slave", "memberserver", ): pass """ fixed = """ if role not in ("domaincontroller_master", "domaincontroller_backup", "domaincontroller_slave", "memberserver", ): pass """ with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_chain(self): line = 'if "@" not in x or not "/" in y:\n pass\n' fixed = 'if "@" not in x or "/" not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_chain2(self): line = 'if "@" not in x or "[" not in x or not "/" in y:\n pass\n' fixed = 'if "@" not in x or "[" not in x or "/" not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_chain3(self): line = 'if not "@" in x or "[" not in x or not "/" in y:\n pass\n' fixed = 'if "@" not in x or "[" not in x or "/" not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e713_chain4(self): line = 'if not "." in y and not "," in y:\n pass\n' fixed = 'if "." not in y and "," not in y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E713']) as result: self.assertEqual(fixed, result) def test_e714(self): line = 'if not x is y:\n pass\n' fixed = 'if x is not y:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E714']) as result: self.assertEqual(fixed, result) def test_e714_with_is(self): line = 'if not x is y or x is z:\n pass\n' fixed = 'if x is not y or x is z:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E714']) as result: self.assertEqual(fixed, result) def test_e714_chain(self): line = 'if not x is y or not x is z:\n pass\n' fixed = 'if x is not y or x is not z:\n pass\n' with autopep8_context(line, options=['-aa', '--select=E714']) as result: self.assertEqual(fixed, result) def test_e713_and_e714(self): line = """ if not x is y: pass if not role in ("domaincontroller_master", "domaincontroller_backup", "domaincontroller_slave", "memberserver", ): pass """ fixed = """ if x is not y: pass if role not in ("domaincontroller_master", "domaincontroller_backup", "domaincontroller_slave", "memberserver", ): pass """ with autopep8_context(line, options=['-aa', '--select=E713,E714']) as result: self.assertEqual(fixed, result) def test_e713_with_single_quote(self): line = "if not 'DC IP' in info:\n" fixed = "if 'DC IP' not in info:\n" with autopep8_context(line, options=['-aa', '--select=E713,E714']) as result: self.assertEqual(fixed, result) def test_e714_with_single_quote(self): line = "if not 'DC IP' is info:\n" fixed = "if 'DC IP' is not info:\n" with autopep8_context(line, options=['-aa', '--select=E713,E714']) as result: self.assertEqual(fixed, result) def test_e721(self): line = "type('') == type('')\n" fixed = "isinstance('', type(''))\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e721_with_str(self): line = "str == type('')\n" fixed = "isinstance('', str)\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e721_in_conditional(self): line = "if str == type(''):\n pass\n" fixed = "if isinstance('', str):\n pass\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e721_in_conditional_pat2(self): line = "if type(res) == type(42):\n pass\n" fixed = "if isinstance(res, type(42)):\n pass\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e721_in_not_conditional(self): line = "if type(res) != type(''):\n pass\n" fixed = "if not isinstance(res, type('')):\n pass\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e721_in_not_conditional_pat2(self): line = "if type(a) != type(b) or type(a) == type(ccc):\n pass\n" fixed = "if not isinstance(a, type(b)) or isinstance(a, type(ccc)):\n pass\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e722(self): line = "try:\n print(a)\nexcept:\n pass\n" fixed = "try:\n print(a)\nexcept BaseException:\n pass\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e722_with_if_else_stmt(self): line = "try:\n print(a)\nexcept:\n if a==b:\n print(a)\n else:\n print(b)\n" fixed = "try:\n print(a)\nexcept BaseException:\n if a == b:\n print(a)\n else:\n print(b)\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_e722_non_aggressive(self): line = "try:\n print(a)\nexcept:\n pass\n" with autopep8_context(line, options=[]) as result: self.assertEqual(line, result) def test_e731(self): line = 'a = lambda x: x * 2\n' fixed = 'def a(x): return x * 2\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e731_no_arg(self): line = 'a = lambda: x * 2\n' fixed = 'def a(): return x * 2\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e731_with_tuple_arg(self): line = 'a = lambda (x, y), z: x * 2\n' fixed = 'def a((x, y), z): return x * 2\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e731_with_args(self): line = 'a = lambda x, y: x * 2 + y\n' fixed = 'def a(x, y): return x * 2 + y\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_e731_with_select_option(self): line = 'a = lambda x: x * 2\n' fixed = 'def a(x): return x * 2\n' with autopep8_context(line, options=['--select=E731']) as result: self.assertEqual(fixed, result) def test_e731_with_default_arguments(self): line = 'a = lambda k, d=None: bar.get("%s/%s" % (prefix, k), d)\n' fixed = 'def a(k, d=None): return bar.get("%s/%s" % (prefix, k), d)\n' with autopep8_context(line, options=['--select=E731']) as result: self.assertEqual(fixed, result) class SystemTestsE9(unittest.TestCase): @unittest.skipIf(sys.version_info >= (3, 12), 'not detect in Python3.12+') def test_e901_should_cause_indentation_screw_up(self): line = """\ def tmp(g): g(4))) if not True: pass pass """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_should_preserve_vertical_tab(self): line = """\ #Memory Bu\vffer Register: """ fixed = """\ # Memory Bu\vffer Register: """ with autopep8_context(line) as result: self.assertEqual(fixed, result) class SystemTestsW1(unittest.TestCase): def test_w191_should_ignore_multiline_strings(self): line = """\ print(3 != 4, ''' while True: if True: \t1 \t''', 4 != 5) if True: \t123 """ fixed = """\ print(3 != 4, ''' while True: if True: \t1 \t''', 4 != 5) if True: 123 """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w191_should_ignore_tabs_in_strings(self): line = """\ if True: \tx = ''' \t\tblah \tif True: \t1 \t''' if True: \t123 else: \t32 """ fixed = """\ if True: x = ''' \t\tblah \tif True: \t1 \t''' if True: 123 else: 32 """ with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) class SystemTestsW2(unittest.TestCase): def test_w291(self): line = "print('a b ')\t \n" fixed = "print('a b ')\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w291_with_comment(self): line = "print('a b ') # comment\t \n" fixed = "print('a b ') # comment\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w292(self): line = '1\n2' fixed = '1\n2\n' with autopep8_context(line, options=['--aggressive', '--select=W292']) as result: self.assertEqual(fixed, result) def test_w292_ignore(self): line = "1\n2" with autopep8_context(line, options=['--aggressive', '--ignore=W292']) as result: self.assertEqual(line, result) def test_w293(self): line = '1\n \n2\n' fixed = '1\n\n2\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) class SystemTestsW3(unittest.TestCase): def test_w391(self): line = ' \n' fixed = '' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w391_more_complex(self): line = '123\n456\n \n' fixed = '123\n456\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) class SystemTestsW5(unittest.TestCase): def test_w503(self): line = '(width == 0\n + height == 0)\n' fixed = '(width == 0 +\n height == 0)\n' with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_ignore_w504(self): line = '(width == 0\n + height == 0)\n' fixed = '(width == 0 +\n height == 0)\n' with autopep8_context(line, options=['--ignore=E,W504']) as result: self.assertEqual(fixed, result) def test_w504_with_ignore_w503(self): line = '(width == 0 +\n height == 0)\n' fixed = '(width == 0\n + height == 0)\n' with autopep8_context(line, options=['--ignore=E,W503']) as result: self.assertEqual(fixed, result) def test_w503_w504_none_ignored(self): line = '(width == 0 +\n height == 0\n+ depth == 0)\n' fixed = '(width == 0 +\n height == 0\n+ depth == 0)\n' with autopep8_context(line, options=['--ignore=E']) as result: self.assertEqual(fixed, result) def test_w503_w504_both_ignored(self): line = '(width == 0 +\n height == 0\n+ depth == 0)\n' fixed = '(width == 0 +\n height == 0\n+ depth == 0)\n' with autopep8_context( line, options=['--ignore=E,W503, W504'], ) as result: self.assertEqual(fixed, result) def test_w503_skip_default(self): line = '(width == 0\n + height == 0)\n' with autopep8_context(line) as result: self.assertEqual(line, result) def test_w503_and_or(self): line = '(width == 0\n and height == 0\n or name == "")\n' fixed = '(width == 0 and\n height == 0 or\n name == "")\n' with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_comment(self): line = '(width == 0 # this is comment\n + height == 0)\n' fixed = '(width == 0 + # this is comment\n height == 0)\n' with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_comment_into_point_out_line(self): line = """\ def test(): return ( True not in [] and False # comment required ) """ fixed = """\ def test(): return ( True not in [] and False # comment required ) """ with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_comment_double(self): line = """\ ( 1111 # C1 and 22222222 # C2 and 333333333333 # C3 ) """ fixed = """\ ( 1111 and # C1 22222222 and # C2 333333333333 # C3 ) """ with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_comment_with_only_comment_block_charactor(self): line = """\ if (True # and True and True): print(1) """ fixed = """\ if (True and # True and True): print(1) """ with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_over_5lines(self): line = """\ X = ( 1 # 1 + 2 # 2 + 3 # 3 + 4 # 4 + 5 # 5 + 6 # 6 + 7 # 7 ) """ fixed = """\ X = ( 1 + # 1 2 + # 2 3 + # 3 4 + # 4 5 + # 5 6 + # 6 7 # 7 ) """ with autopep8_context(line, options=['--select=W503']) as result: self.assertEqual(fixed, result) def test_w503_with_line_comment(self): line = '(width == 0\n # this is comment\n + height == 0)\n' fixed = '(width == 0 +\n # this is comment\n height == 0)\n' with autopep8_context(line, options=['--select=W503', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w503_with_empty_line(self): line = """\ # this is comment a = 2 b = (1 + 2 + 3) / 2.0 """ fixed = """\ # this is comment a = 2 b = (1 + 2 + 3) / 2.0 """ with autopep8_context(line, options=['--ignore=E721']) as result: self.assertEqual(fixed, result) def test_w503_with_line_comments(self): line = '(width == 0\n # this is comment\n # comment2\n + height == 0)\n' fixed = '(width == 0 +\n # this is comment\n # comment2\n height == 0)\n' with autopep8_context(line, options=['--select=W503', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_ignore_only_w503_with_select_w(self): line = """\ a = ( 11 + 22 + 33 + 44 + 55 ) """ fixed = """\ a = ( 11 + 22 + 33 + 44 + 55 ) """ with autopep8_context(line, options=['--select=W', '--ignore=W503']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['--select=W5', '--ignore=W503']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['--select=W50', '--ignore=W503']) as result: self.assertEqual(fixed, result) def test_ignore_only_w504_with_select_w(self): line = """\ a = ( 11 + 22 + 33 + 44 + 55 ) """ fixed = """\ a = ( 11 + 22 + 33 + 44 + 55 ) """ with autopep8_context(line, options=['--select=W', '--ignore=W504']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['--select=W5', '--ignore=W504']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['--select=W50', '--ignore=W504']) as result: self.assertEqual(fixed, result) def test_ignore_w503_and_w504_with_select_w(self): line = """\ a = ( 11 + 22 + 33 + 44 + 55 ) """ with autopep8_context(line, options=['--select=W', '--ignore=W503,W504']) as result: self.assertEqual(line, result) with autopep8_context(line, options=['--select=W5', '--ignore=W503,W504']) as result: self.assertEqual(line, result) with autopep8_context(line, options=['--select=W50', '--ignore=W503,W504']) as result: self.assertEqual(line, result) def test_w504(self): line = '(width == 0 +\n height == 0)\n' fixed = '(width == 0\n + height == 0)\n' with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w504_comment_on_first_line(self): line = 'x = (1 | # test\n2)\n' fixed = 'x = (1 # test\n| 2)\n' with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w504_comment_on_second_line(self): line = 'x = (1 |\n2) # test\n' fixed = 'x = (1\n| 2) # test\n' with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w504_comment_on_each_lines(self): line = 'x = (1 |# test\n2 |# test\n3) # test\n' fixed = 'x = (1# test\n| 2# test\n| 3) # test\n' with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w504_with_e265_ignore_option(self): line = '(width == 0 +\n height == 0)\n' with autopep8_context(line, options=['--ignore=E265']) as result: self.assertEqual(line, result) def test_w504_with_e265_ignore_option_regression(self): line = """\ if True: if True: if ( link.is_wheel and isinstance(link.comes_from, HTMLPage) and link.comes_from.url.startswith(index_url) ): _store_wheel_in_cache(file_path, index_url) """ with autopep8_context(line, options=['--ignore=E265']) as result: self.assertEqual(line, result) def test_w504_with_line_comment(self): line = '(width == 0 +\n # this is comment\n height == 0)\n' fixed = '(width == 0\n # this is comment\n + height == 0)\n' with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result: self.assertEqual(fixed, result) def test_w504_not_applied_by_default_when_modifying_with_ignore(self): line = """\ q = 1 def x(y, z): if ( y and z ): pass """ fixed = line.replace('\n\n\n\n', '\n\n') with autopep8_context(line, options=['--ignore=E265']) as result: self.assertEqual(fixed, result) def test_w503_and_w504_conflict(self): line = """\ if True: if True: assert_equal(self.nodes[0].getbalance( ), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx """ fixed = """\ if True: if True: assert_equal( self.nodes[0].getbalance(), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx """ with autopep8_context(line, options=['-aa', '--select=E,W']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['-aa', '--select=E,W5']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['-aa', '--select=E,W50']) as result: self.assertEqual(fixed, result) class SystemTestsW6(unittest.TestCase): def test_w605_simple(self): line = "escape = '\\.jpg'\n" fixed = "escape = '\\\\.jpg'\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w605_identical_token(self): # ***NOTE***: The --pep8-passes option is required to prevent an infinite loop in # the old, failing code. DO NOT REMOVE. line = "escape = foo('\\.bar', '\\.kilroy')\n" fixed = "escape = foo('\\\\.bar', '\\\\.kilroy')\n" with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result: self.assertEqual(fixed, result, "Two tokens get r added") line = "escape = foo('\\.bar', '\\\\.kilroy')\n" fixed = "escape = foo('\\\\.bar', '\\\\.kilroy')\n" with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result: self.assertEqual(fixed, result, "r not added if already there") # Test Case to catch bad behavior reported in Issue #449 line = "escape = foo('\\.bar', '\\.bar')\n" fixed = "escape = foo('\\\\.bar', '\\\\.bar')\n" with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result: self.assertEqual(fixed, result) def test_w605_with_invalid_syntax(self): line = "escape = rr'\\.jpg'\n" fixed = "escape = rr'\\\\.jpg'\n" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_w605_with_multilines(self): line = """\ regex = '\\d+(\\.\\d+){3}$' foo = validators.RegexValidator( regex='\\d+(\\.\\d+){3}$')\n""" # noqa fixed = """\ regex = '\\\\d+(\\\\.\\\\d+){3}$' foo = validators.RegexValidator( regex='\\\\d+(\\\\.\\\\d+){3}$')\n""" with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_trailing_whitespace_in_multiline_string(self): line = 'x = """ \nhello""" \n' fixed = 'x = """ \nhello"""\n' with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_trailing_whitespace_in_multiline_string_aggressive(self): line = 'x = """ \nhello""" \n' fixed = 'x = """\nhello"""\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(fixed, result) def test_execfile_in_lambda_should_not_be_modified(self): """Modifying this to the exec() form is invalid in Python 2.""" line = 'lambda: execfile("foo.py")\n' with autopep8_context(line, options=['--aggressive']) as result: self.assertEqual(line, result) # FIXME: These tests should use multiline strings for readability. def test_range(self): line = 'print( 1 )\nprint( 2 )\n print( 3 )\n' fixed = 'print( 1 )\nprint(2)\n print( 3 )\n' with autopep8_context(line, options=['--line-range', '2', '2']) as result: self.assertEqual(fixed, result) def test_range_line_number_changes_from_one_line(self): line = 'a=12\na=1; b=2;c=3\nd=4;\n\ndef f(a = 1):\n pass\n' fixed = 'a=12\na = 1\nb = 2\nc = 3\nd=4;\n\ndef f(a = 1):\n pass\n' with autopep8_context(line, options=['--line-range', '2', '2']) as result: self.assertEqual(fixed, result) def test_range_indent_changes_small_range(self): line = '\nif True:\n (1, \n 2,\n3)\nelif False:\n a = 1\nelse:\n a = 2\n\nc = 1\nif True:\n c = 2\n a = (1,\n2)\n' fixed2_5 = '\nif True:\n (1,\n 2,\n 3)\nelif False:\n a = 1\nelse:\n a = 2\n\nc = 1\nif True:\n c = 2\n a = (1,\n2)\n' with autopep8_context(line, options=['--line-range', '2', '5']) as result: self.assertEqual(fixed2_5, result) def test_range_indent_deep_if_blocks_first_block(self): line = '\nif a:\n if a = 1:\n b = 1\n else:\n b = 2\nelif a == 0:\n b = 3\nelse:\n b = 4\n' with autopep8_context(line, options=['--line-range', '2', '5']) as result: self.assertEqual(line, result) def test_range_indent_deep_if_blocks_second_block(self): line = '\nif a:\n if a = 1:\n b = 1\n else:\n b = 2\nelif a == 0:\n b = 3\nelse:\n b = 4\n' with autopep8_context(line, options=['--line-range', '6', '9']) as result: self.assertEqual(line, result) def test_range_indent_continued_statements_partial(self): line = '\nif a == 1:\n\ttry:\n\t foo\n\texcept AttributeError:\n\t pass\n\telse:\n\t "nooo"\n\tb = 1\n' with autopep8_context(line, options=['--line-range', '2', '6']) as result: self.assertEqual(line, result) def test_range_indent_continued_statements_last_block(self): line = '\nif a == 1:\n\ttry:\n\t foo\n\texcept AttributeError:\n\t pass\n\telse:\n\t "nooo"\n\tb = 1\n' with autopep8_context(line, options=['--line-range', '6', '9']) as result: self.assertEqual(line, result) def test_range_with_broken_syntax(self): line = """\ if True: if True: pass else: pass """ with autopep8_context(line, options=['--line-range', '1', '1']) as result: self.assertEqual(line, result) def test_long_import_line(self): line = """\ s from t import a, \ bbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ccccccccccccccccccccccccccccccc, ddddddddddddddddddddddddddddddddddd """ fixed = """\ from t import a, \ bbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ccccccccccccccccccccccccccccccc, ddddddddddddddddddddddddddddddddddd s """ with autopep8_context(line) as result: self.assertEqual(fixed, result) def test_exchange_multiple_imports_with_def(self): line = """\ def f(n): return n from a import fa from b import fb from c import fc """ with autopep8_context(line) as result: self.assertEqual(result[:4], 'from') @unittest.skipIf( (sys.version_info.major >= 3 and sys.version_info.minor < 8) or sys.version_info.major < 3, "syntax error in Python3.7 and lower version", ) def test_with_walrus_operator(self): """check pycodestyle 2.6.0+""" line = """\ sql_stmt = "" with open(filename) as f: while line := f.readline(): sql_stmt += line """ with autopep8_context(line) as result: self.assertEqual(line, result) def test_autopep8_disable(self): test_code = """\ # autopep8: off def f(): aaaaaaaaaaa.bbbbbbb([ ('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) # autopep8: on """ expected_output = """\ # autopep8: off def f(): aaaaaaaaaaa.bbbbbbb([ ('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) # autopep8: on """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_autopep8_disable_multi(self): test_code = """\ fix=1 # autopep8: off skip=1 # autopep8: on fix=2 # autopep8: off skip=2 # autopep8: on fix=3 """ expected_output = """\ fix = 1 # autopep8: off skip=1 # autopep8: on fix = 2 # autopep8: off skip=2 # autopep8: on fix = 3 """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_disable(self): test_code = """\ # fmt: off def f(): aaaaaaaaaaa.bbbbbbb([ ('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) # fmt: on """ expected_output = """\ # fmt: off def f(): aaaaaaaaaaa.bbbbbbb([ ('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) # fmt: on """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_disable_without_reenable(self): test_code = """\ # fmt: off print(123) """ expected_output = """\ # fmt: off print(123) """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_disable_with_double_reenable(self): test_code = """\ # fmt: off print( 123 ) # fmt: on print( 123 ) # fmt: on print( 123 ) """ expected_output = """\ # fmt: off print( 123 ) # fmt: on print(123) # fmt: on print(123) """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_double_disable_and_reenable(self): test_code = """\ # fmt: off print( 123 ) # fmt: off print( 123 ) # fmt: on print( 123 ) """ expected_output = """\ # fmt: off print( 123 ) # fmt: off print( 123 ) # fmt: on print(123) """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_multi_disable_and_reenable(self): test_code = """\ fix=1 # fmt: off skip=1 # fmt: on fix=2 # fmt: off skip=2 # fmt: on fix=3 """ expected_output = """\ fix = 1 # fmt: off skip=1 # fmt: on fix = 2 # fmt: off skip=2 # fmt: on fix = 3 """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_multi_disable_complex(self): test_code = """\ fix=1 # fmt: off skip=1 # fmt: off fix=2 # fmt: off skip=2 # fmt: on fix=3 """ expected_output = """\ fix = 1 # fmt: off skip=1 # fmt: off fix=2 # fmt: off skip=2 # fmt: on fix = 3 """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_fmt_multi_disable_complex_multi(self): test_code = """\ fix=1 # fmt: off skip=1 # fmt: off fix=2 # fmt: on fix=22 # fmt: on fix=222 # fmt: off skip=2 # fmt: on fix=3 """ expected_output = """\ fix = 1 # fmt: off skip=1 # fmt: off fix=2 # fmt: on fix = 22 # fmt: on fix = 222 # fmt: off skip=2 # fmt: on fix = 3 """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) def test_general_disable(self): test_code = """\ # fmt: off import math, sys; def example1(): # This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key( {'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): # Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = ''' Indentation in multiline strings should not be touched. Only actual code should be reindented. ''' return (sys.path, some_string) # fmt: on import math, sys; def example1(): # This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key( {'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): # Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = ''' Indentation in multiline strings should not be touched. Only actual code should be reindented. ''' return (sys.path, some_string) """ expected_output = """\ # fmt: off import sys import math import math, sys; def example1(): # This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key( {'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): # Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = ''' Indentation in multiline strings should not be touched. Only actual code should be reindented. ''' return (sys.path, some_string) # fmt: on def example1(): # This is a long comment. This should be wrapped to fit within 72 characters. some_tuple = (1, 2, 3, 'a') some_variable = {'long': 'Long code lines should be wrapped within 79 characters.', 'other': [math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'], 'more': {'inner': 'This whole logical line should be wrapped.', some_tuple: [1, 20, 300, 40000, 500000000, 60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated': True}.has_key( {'f': 2}.has_key('')) class Example3(object): def __init__(self, bar): # Comments should have a space after the hash. if bar: bar += 1 bar = bar * bar return bar else: some_string = ''' Indentation in multiline strings should not be touched. Only actual code should be reindented. ''' return (sys.path, some_string) """ with autopep8_context(test_code) as result: self.assertEqual(expected_output, result) class UtilityFunctionTests(unittest.TestCase): def test_get_module_imports(self): line = """\ import os import sys if True: print(1) """ target_line_index = 8 result = get_module_imports_on_top_of_file(line.splitlines(), target_line_index) self.assertEqual(result, 0) def test_get_module_imports_case_of_autopep8(self): line = """\ #!/usr/bin/python # comment # comment '''this module ... this module ... ''' import os import sys if True: print(1) """ target_line_index = 11 result = get_module_imports_on_top_of_file(line.splitlines(), target_line_index) self.assertEqual(result, 10) class CommandLineTests(unittest.TestCase): def test_e122_and_e302_with_backslash(self): line = """\ import sys \\ def f(): pass """ fixed = """\ import sys \\ def f(): pass """ with autopep8_subprocess(line, [], timeout=3) as (result, retcode): self.assertEqual(fixed, result) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_diff(self): line = "'abc' \n" fixed = "-'abc' \n+'abc'\n" with autopep8_subprocess(line, ['--diff']) as (result, retcode): self.assertEqual(fixed, '\n'.join(result.split('\n')[3:])) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_diff_with_exit_code_option(self): line = "'abc' \n" fixed = "-'abc' \n+'abc'\n" with autopep8_subprocess(line, ['--diff', '--exit-code']) as (result, retcode): self.assertEqual(fixed, '\n'.join(result.split('\n')[3:])) self.assertEqual(retcode, autopep8.EXIT_CODE_EXISTS_DIFF) def test_non_diff_with_exit_code_option(self): line = "'abc'\n" with autopep8_subprocess(line, ['--diff', '--exit-code']) as (result, retcode): self.assertEqual('', '\n'.join(result.split('\n')[3:])) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_non_diff_with_exit_code_and_jobs_options(self): line = "'abc'\n" with autopep8_subprocess(line, ['-j0', '--diff', '--exit-code']) as (result, retcode): self.assertEqual('', '\n'.join(result.split('\n')[3:])) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_diff_with_empty_file(self): with autopep8_subprocess('', ['--diff']) as (result, retcode): self.assertEqual('\n'.join(result.split('\n')[3:]), '') self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_diff_with_nonexistent_file(self): p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--diff', 'non_existent_file'], stdout=PIPE, stderr=PIPE) error = p.communicate()[1].decode('utf-8') self.assertIn('non_existent_file', error) def test_diff_with_standard_in(self): p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--diff', '-'], stdout=PIPE, stderr=PIPE) error = p.communicate()[1].decode('utf-8') self.assertIn('cannot', error) def test_indent_size_is_zero(self): line = "'abc'\n" p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--indent-size=0', '-'], stdout=PIPE, stderr=PIPE) _, _err = p.communicate(line.encode('utf-8')) self.assertEqual(p.returncode, autopep8.EXIT_CODE_ARGPARSE_ERROR) self.assertIn('indent-size must be greater than 0\n', _err.decode('utf-8')) self.assertIn('usage: autopep8', _err.decode('utf-8')) def test_exit_code_with_io_error(self): line = "import sys\ndef a():\n print(1)\n" with readonly_temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--in-place', filename], stdout=PIPE, stderr=PIPE) p.communicate() self.assertEqual(p.returncode, autopep8.EXIT_CODE_ERROR) def test_pep8_passes(self): line = "'abc' \n" fixed = "'abc'\n" with autopep8_subprocess(line, ['--pep8-passes', '0']) as (result, retcode): self.assertEqual(fixed, result) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_pep8_ignore(self): line = "'abc' \n" with autopep8_subprocess(line, ['--ignore=E,W']) as (result, retcode): self.assertEqual(line, result) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_pep8_ignore_should_handle_trailing_comma_gracefully(self): line = "'abc' \n" fixed = "'abc'\n" with autopep8_subprocess(line, ['--ignore=,']) as (result, retcode): self.assertEqual(fixed, result) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_help(self): p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['-h'], stdout=PIPE) self.assertIn('usage:', p.communicate()[0].decode('utf-8').lower()) @unittest.skipIf(sys.version_info >= (3, 12), 'not detect in Python3.12+') def test_verbose(self): line = 'bad_syntax)' with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '-vvv'], stdout=PIPE, stderr=PIPE) verbose_error = p.communicate()[1].decode('utf-8') self.assertIn("'fix_e901' is not defined", verbose_error) def test_verbose_diff(self): line = '+'.join(100 * ['323424234234']) with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '-vvvv', '--diff'], stdout=PIPE, stderr=PIPE) verbose_error = p.communicate()[1].decode('utf-8') self.assertIn('------------', verbose_error) def test_verbose_with_select_e702(self): line = """\ for i in range(3): if i == 1: print(i); continue print(i) """ with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '-vvv', '--select=E702'], stdout=PIPE, stderr=PIPE) verbose_error = p.communicate()[1].decode('utf-8') self.assertIn(" with other compound statements", verbose_error) def test_in_place(self): line = "'abc' \n" fixed = "'abc'\n" with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place']) p.wait() with open(filename) as f: self.assertEqual(fixed, f.read()) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_in_place_no_modifications_no_writes(self): with temporary_file_context('import os\n') as filename: # ensure that noops do not do writes by making writing an error os.chmod(filename, 0o444) p = Popen( list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place'], stderr=PIPE, ) _, err = p.communicate() self.assertEqual(err, b'') self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_in_place_no_modifications_no_writes_with_empty_file(self): with temporary_file_context('') as filename: # ensure that noops do not do writes by making writing an error os.chmod(filename, 0o444) p = Popen( list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place'], stderr=PIPE, ) _, err = p.communicate() self.assertEqual(err, b'') self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_in_place_with_w292(self): line = "import os" fixed = "import os\n" with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place']) p.wait() with open(filename) as f: self.assertEqual(fixed, f.read()) def test_in_place_with_exit_code_option(self): line = "'abc' \n" fixed = "'abc'\n" with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place', '--exit-code']) p.wait() with open(filename) as f: self.assertEqual(fixed, f.read()) self.assertEqual(p.returncode, autopep8.EXIT_CODE_EXISTS_DIFF) def test_in_place_with_exit_code_option_with_w391(self): line = "\n\n\n" fixed = "" with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place', '--exit-code']) p.wait() with open(filename) as f: self.assertEqual(fixed, f.read()) self.assertEqual(p.returncode, autopep8.EXIT_CODE_EXISTS_DIFF) def test_parallel_jobs(self): line = "'abc' \n" fixed = "'abc'\n" with temporary_file_context(line) as filename_a: with temporary_file_context(line) as filename_b: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename_a, filename_b, '--jobs=3', '--in-place']) p.wait() with open(filename_a) as f: self.assertEqual(fixed, f.read()) with open(filename_b) as f: self.assertEqual(fixed, f.read()) def test_parallel_jobs_with_diff_option(self): line = "'abc' \n" with temporary_file_context(line) as filename_a: with temporary_file_context(line) as filename_b: files = list({filename_a, filename_b}) p = Popen(list(AUTOPEP8_CMD_TUPLE) + files + ['--jobs=3', '--diff'], stdout=PIPE) p.wait() output = p.stdout.read().decode() output = output.replace("\r\n","\n") # windows compatibility p.stdout.close() actual_diffs = [] for filename in files: actual_diffs.append("""\ --- original/{filename} +++ fixed/{filename} @@ -1 +1 @@ -'abc' {blank} +'abc' """.format(filename=filename, blank="")) # in case the users IDE trims leaning whitespace self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) for actual_diff in actual_diffs: self.assertIn(actual_diff, output) def test_parallel_jobs_with_inplace_option_and_io_error(self): temp_directory = mkdtemp(dir='.') try: file_a = os.path.join(temp_directory, 'a.py') with open(file_a, 'w') as output: output.write("'abc' \n") os.chmod(file_a, stat.S_IRUSR) # readonly os.mkdir(os.path.join(temp_directory, 'd')) file_b = os.path.join(temp_directory, 'd', 'b.py') with open(file_b, 'w') as output: output.write('123 \n') os.chmod(file_b, stat.S_IRUSR) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [temp_directory, '--recursive', '--in-place'], stdout=PIPE, stderr=PIPE) p.communicate()[0].decode('utf-8') self.assertEqual(p.returncode, autopep8.EXIT_CODE_ERROR) finally: shutil.rmtree(temp_directory) def test_parallel_jobs_with_automatic_cpu_count(self): line = "'abc' \n" fixed = "'abc'\n" with temporary_file_context(line) as filename_a: with temporary_file_context(line) as filename_b: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename_a, filename_b, '--jobs=0', '--in-place']) p.wait() with open(filename_a) as f: self.assertEqual(fixed, f.read()) with open(filename_b) as f: self.assertEqual(fixed, f.read()) def test_in_place_with_empty_file(self): line = '' with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place']) p.wait() self.assertEqual(0, p.returncode) with open(filename) as f: self.assertEqual(f.read(), line) def test_in_place_and_diff(self): line = "'abc' \n" with temporary_file_context(line) as filename: p = Popen( list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place', '--diff'], stderr=PIPE) result = p.communicate()[1].decode('utf-8') self.assertIn('--in-place and --diff are mutually exclusive', result) def test_recursive(self): temp_directory = mkdtemp(dir='.') try: with open(os.path.join(temp_directory, 'a.py'), 'w') as output: output.write("'abc' \n") os.mkdir(os.path.join(temp_directory, 'd')) with open(os.path.join(temp_directory, 'd', 'b.py'), 'w') as output: output.write('123 \n') p = Popen(list(AUTOPEP8_CMD_TUPLE) + [temp_directory, '--recursive', '--diff'], stdout=PIPE) result = p.communicate()[0].decode('utf-8') self.assertEqual( "-'abc' \n+'abc'", '\n'.join(result.split('\n')[3:5])) self.assertEqual( '-123 \n+123', '\n'.join(result.split('\n')[8:10])) finally: shutil.rmtree(temp_directory) def test_recursive_should_not_crash_on_unicode_filename(self): temp_directory = mkdtemp(dir='.') try: for filename in ['x.py', 'é.py', 'é.txt']: with open(os.path.join(temp_directory, filename), 'w'): pass p = Popen(list(AUTOPEP8_CMD_TUPLE) + [temp_directory, '--recursive', '--diff'], stdout=PIPE) self.assertFalse(p.communicate()[0]) self.assertEqual(0, p.returncode) finally: shutil.rmtree(temp_directory) def test_recursive_should_ignore_hidden(self): temp_directory = mkdtemp(dir='.') temp_subdirectory = mkdtemp(prefix='.', dir=temp_directory) try: with open(os.path.join(temp_subdirectory, 'a.py'), 'w') as output: output.write("'abc' \n") p = Popen(list(AUTOPEP8_CMD_TUPLE) + [temp_directory, '--recursive', '--diff'], stdout=PIPE) result = p.communicate()[0].decode('utf-8') self.assertEqual(0, p.returncode) self.assertEqual('', result) finally: shutil.rmtree(temp_directory) def test_exclude(self): temp_directory = mkdtemp(dir='.') try: with open(os.path.join(temp_directory, 'a.py'), 'w') as output: output.write("'abc' \n") os.mkdir(os.path.join(temp_directory, 'd')) with open(os.path.join(temp_directory, 'd', 'b.py'), 'w') as output: output.write('123 \n') p = Popen(list(AUTOPEP8_CMD_TUPLE) + [temp_directory, '--recursive', '--exclude=a*', '--diff'], stdout=PIPE) result = p.communicate()[0].decode('utf-8') self.assertNotIn('abc', result) self.assertIn('123', result) finally: shutil.rmtree(temp_directory) def test_exclude_with_directly_file_args(self): temp_directory = mkdtemp(dir='.') try: filepath_a = os.path.join(temp_directory, 'a.py') with open(filepath_a, 'w') as output: output.write("'abc' \n") os.mkdir(os.path.join(temp_directory, 'd')) filepath_b = os.path.join(temp_directory, 'd', 'b.py') with open(os.path.join(filepath_b), 'w') as output: output.write('123 \n') p = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--exclude=*/a.py', '--diff', filepath_a, filepath_b], stdout=PIPE) result = p.communicate()[0].decode('utf-8') self.assertNotIn('abc', result) self.assertIn('123', result) finally: shutil.rmtree(temp_directory) def test_invalid_option_combinations(self): line = "'abc' \n" with temporary_file_context(line) as filename: for options in [['--recursive', filename], # without --diff ['--jobs=2', filename], # without --diff ['--max-line-length=0', filename], [], # no argument ['-', '--in-place'], ['-', '--recursive'], ['-', filename], ['--line-range', '0', '2', filename], ['--line-range', '2', '1', filename], ['--line-range', '-1', '-1', filename], ]: p = Popen(list(AUTOPEP8_CMD_TUPLE) + options, stderr=PIPE) result = p.communicate()[1].decode('utf-8') self.assertNotEqual(0, p.returncode, msg=str(options)) self.assertTrue(len(result)) def test_list_fixes(self): with autopep8_subprocess('', options=['--list-fixes']) as (result, retcode): self.assertIn('E121', result) self.assertEqual(retcode, autopep8.EXIT_CODE_OK) def test_fixpep8_class_constructor(self): line = 'print(1)\nprint(2)\n' with temporary_file_context(line) as filename: pep8obj = autopep8.FixPEP8(filename, None) self.assertEqual(''.join(pep8obj.source), line) def test_inplace_with_multi_files(self): exception = None with disable_stderr(): try: autopep8.parse_args(['test.py', 'dummy.py']) except SystemExit as e: exception = e self.assertTrue(exception) self.assertEqual(exception.code, autopep8.EXIT_CODE_ARGPARSE_ERROR) def test_standard_out_should_use_native_line_ending(self): line = '1\r\n2\r\n3\r\n' with temporary_file_context(line) as filename: process = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename], stdout=PIPE) self.assertEqual( os.linesep.join(['1', '2', '3', '']), process.communicate()[0].decode('utf-8')) def test_standard_out_should_use_native_line_ending_with_cr_input(self): line = '1\r2\r3\r' with temporary_file_context(line) as filename: process = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename], stdout=PIPE) self.assertEqual( os.linesep.join(['1', '2', '3', '']), process.communicate()[0].decode('utf-8')) def test_standard_in(self): line = 'print( 1 )\n' fixed = 'print(1)' + os.linesep process = Popen(list(AUTOPEP8_CMD_TUPLE) + ['-'], stdout=PIPE, stdin=PIPE) self.assertEqual( fixed, process.communicate(line.encode('utf-8'))[0].decode('utf-8')) def test_exit_code_should_be_set_when_standard_in(self): line = 'print( 1 )\n' process = Popen(list(AUTOPEP8_CMD_TUPLE) + ['--exit-code', '-'], stdout=PIPE, stdin=PIPE) process.communicate(line.encode('utf-8'))[0].decode('utf-8') self.assertEqual( process.returncode, autopep8.EXIT_CODE_EXISTS_DIFF) def test_non_args(self): process = Popen(list(AUTOPEP8_CMD_TUPLE) + [], stderr=PIPE, stdout=PIPE, stdin=PIPE) _output, _error = process.communicate() self.assertEqual( process.returncode, autopep8.EXIT_CODE_ARGPARSE_ERROR) self.assertEqual(_output.decode("utf-8"), "") self.assertIn( "incorrect number of arguments\n", _error.decode("utf-8"), ) class ConfigurationTests(unittest.TestCase): def test_local_config(self): args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(os.devnull), '-vvv'], apply_config=True) self.assertEqual(args.indent_size, 2) def test_config_override(self): args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--indent-size=7'], apply_config=True) self.assertEqual(args.indent_size, 7) def test_config_false_with_local(self): args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config=False'], apply_config=True) self.assertEqual(args.global_config, 'False') self.assertEqual(args.indent_size, 2) def test_config_false_with_local_space(self): args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config', 'False'], apply_config=True) self.assertEqual(args.global_config, 'False') self.assertEqual(args.indent_size, 2) def test_local_pycodestyle_config_line_length(self): args = autopep8.parse_args( [os.path.join(FAKE_PYCODESTYLE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(os.devnull)], apply_config=True) self.assertEqual(args.max_line_length, 40) def test_config_false_with_local_autocomplete(self): args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--g', 'False'], apply_config=True) self.assertEqual(args.global_config, 'False') self.assertEqual(args.indent_size, 2) def test_config_false_without_local(self): args = autopep8.parse_args(['/nowhere/foo.py', '--global-config={}'.format(os.devnull)], apply_config=True) self.assertEqual(args.indent_size, 4) def test_global_config_with_locals(self): with temporary_file_context('[pep8]\nindent-size=3\n') as filename: args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(filename)], apply_config=True) self.assertEqual(args.indent_size, 2) def test_global_config_ignore_locals(self): with temporary_file_context('[pep8]\nindent-size=3\n') as filename: args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(filename), '--ignore-local-config'], apply_config=True) self.assertEqual(args.indent_size, 3) def test_global_config_without_locals(self): with temporary_file_context('[pep8]\nindent-size=3\n') as filename: args = autopep8.parse_args( ['/nowhere/foo.py', '--global-config={}'.format(filename)], apply_config=True) self.assertEqual(args.indent_size, 3) def test_config_local_int_value(self): with temporary_file_context('[pep8]\naggressive=1\n') as filename: args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(filename)], apply_config=True) self.assertEqual(args.aggressive, 1) def test_config_local_inclue_invalid_key(self): configstr = """\ [pep8] count=True aggressive=1 """ with temporary_file_context(configstr) as filename: args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--global-config={}'.format(filename)], apply_config=True) self.assertEqual(args.aggressive, 1) def test_pyproject_toml_config_local_int_value(self): with temporary_file_context('[tool.autopep8]\naggressive=2\n') as filename: args = autopep8.parse_args( [os.path.join(FAKE_CONFIGURATION, 'foo.py'), '--ignore-local-config', '--global-config={}'.format(filename)], apply_config=True) self.assertEqual(args.aggressive, 2) class ConfigurationFileTests(unittest.TestCase): def test_pyproject_toml_with_flake8_config(self): """override to flake8 config""" line = "a = 1\n" dot_flake8 = """[pep8]\naggressive=0\n""" pyproject_toml = """[tool.autopep8]\naggressvie=2\nignore="E,W"\n""" with temporary_project_directory() as dirname: with open(os.path.join(dirname, "pyproject.toml"), "w") as fp: fp.write(pyproject_toml) with open(os.path.join(dirname, ".flake8"), "w") as fp: fp.write(dot_flake8) target_filename = os.path.join(dirname, "foo.py") with open(target_filename, "w") as fp: fp.write(line) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [target_filename], stdout=PIPE) self.assertEqual(p.communicate()[0].decode("utf-8"), line) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_pyproject_toml_with_verbose_option(self): """override to flake8 config""" line = "a = 1\n" verbose_line = "enable pyproject.toml config: key=ignore, value=E,W\n" pyproject_toml = """[tool.autopep8]\naggressvie=2\nignore="E,W"\n""" with temporary_project_directory() as dirname: with open(os.path.join(dirname, "pyproject.toml"), "w") as fp: fp.write(pyproject_toml) target_filename = os.path.join(dirname, "foo.py") with open(target_filename, "w") as fp: fp.write(line) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [target_filename, "-vvv"], stdout=PIPE) output = p.communicate()[0].decode("utf-8") self.assertTrue(line in output) self.assertTrue(verbose_line in output) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_pyproject_toml_with_iterable_value(self): line = "a = 1\n" pyproject_toml = """[tool.autopep8]\naggressvie=2\nignore=["E","W"]\n""" with temporary_project_directory() as dirname: with open(os.path.join(dirname, "pyproject.toml"), "w") as fp: fp.write(pyproject_toml) target_filename = os.path.join(dirname, "foo.py") with open(target_filename, "w") as fp: fp.write(line) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [target_filename, ], stdout=PIPE) output = p.communicate()[0].decode("utf-8") self.assertTrue(line in output) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_setupcfg_with_flake8_config(self): line = "a = 1\n" fixed = "a = 1\n" setupcfg_flake8 = """[flake8]\njobs=auto\n""" with temporary_project_directory() as dirname: with open(os.path.join(dirname, "setup.cfg"), "w") as fp: fp.write(setupcfg_flake8) target_filename = os.path.join(dirname, "foo.py") with open(target_filename, "w") as fp: fp.write(line) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [target_filename, "-v"], stdout=PIPE) output = p.communicate()[0].decode("utf-8") self.assertTrue(fixed in output) self.assertTrue("ignore config: jobs=auto" in output) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) def test_setupcfg_with_pycodestyle_config(self): line = "a = 1\n" fixed = "a = 1\n" setupcfg_flake8 = """[pycodestyle]\ndiff=True\nignore="E,W"\n""" with temporary_project_directory() as dirname: with open(os.path.join(dirname, "setup.cfg"), "w") as fp: fp.write(setupcfg_flake8) target_filename = os.path.join(dirname, "foo.py") with open(target_filename, "w") as fp: fp.write(line) p = Popen(list(AUTOPEP8_CMD_TUPLE) + [target_filename, "-v"], stdout=PIPE) output = p.communicate()[0].decode("utf-8") self.assertTrue(fixed in output) self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK) class ExperimentalSystemTests(unittest.TestCase): def test_e501_experimental_basic(self): line = """\ print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_commas_and_colons(self): line = """\ foobar = {'aaaaaaaaaaaa': 'bbbbbbbbbbbbbbbb', 'dddddd': 'eeeeeeeeeeeeeeee', 'ffffffffffff': 'gggggggg'} """ fixed = """\ foobar = {'aaaaaaaaaaaa': 'bbbbbbbbbbbbbbbb', 'dddddd': 'eeeeeeeeeeeeeeee', 'ffffffffffff': 'gggggggg'} """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_inline_comments(self): line = """\ ' ' # Long inline comments should be moved above. if True: ' ' # Long inline comments should be moved above. """ fixed = """\ # Long inline comments should be moved above. ' ' if True: # Long inline comments should be moved above. ' ' """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_inline_comments_should_skip_multiline( self): line = """\ '''This should be left alone. ----------------------------------------------------- ''' # foo '''This should be left alone. ----------------------------------------------------- ''' \\ # foo '''This should be left alone. ----------------------------------------------------- ''' \\ \\ # foo """ fixed = """\ '''This should be left alone. ----------------------------------------------------- ''' # foo '''This should be left alone. ----------------------------------------------------- ''' # foo '''This should be left alone. ----------------------------------------------------- ''' # foo """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_inline_comments_should_skip_keywords(self): line = """\ ' ' # noqa Long inline comments should be moved above. if True: ' ' # pylint: disable-msgs=E0001 ' ' # pragma: no cover ' ' # pragma: no cover """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(line, result) def test_e501_experimental_with_inline_comments_should_skip_edge_cases( self): line = """\ if True: x = \\ ' ' # Long inline comments should be moved above. """ fixed = """\ if True: # Long inline comments should be moved above. x = ' ' """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_basic_should_prefer_balanced_brackets(self): line = """\ if True: reconstructed = iradon(radon(image), filter="ramp", interpolation="nearest") """ fixed = """\ if True: reconstructed = iradon( radon(image), filter="ramp", interpolation="nearest") """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_very_long_line(self): line = """\ x = [3244234243234, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243] """ fixed = """\ x = [3244234243234, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243, 234234234324, 234234324, 23424234, 234234234, 234234, 234243, 234243] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_shorten_at_commas_skip(self): line = """\ parser.add_argument('source_corpus', help='corpus name/path relative to an nltk_data directory') parser.add_argument('target_corpus', help='corpus name/path relative to an nltk_data directory') """ fixed = """\ parser.add_argument( 'source_corpus', help='corpus name/path relative to an nltk_data directory') parser.add_argument( 'target_corpus', help='corpus name/path relative to an nltk_data directory') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_shorter_length(self): line = """\ foooooooooooooooooo('abcdefghijklmnopqrstuvwxyz') """ fixed = """\ foooooooooooooooooo( 'abcdefghijklmnopqrstuvwxyz') """ with autopep8_context(line, options=['--max-line-length=40', '--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_indent(self): line = """\ def d(): print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ def d(): print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_alone_with_indentation(self): line = """\ if True: print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ if True: print(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line, options=['--select=E501', '--experimental']) as result: self.assertEqual(fixed, result) @unittest.skip('Not sure why space is not removed anymore') def test_e501_experimental_alone_with_tuple(self): line = """\ fooooooooooooooooooooooooooooooo000000000000000000000000 = [1, ('TransferTime', 'FLOAT') ] """ fixed = """\ fooooooooooooooooooooooooooooooo000000000000000000000000 = [ 1, ('TransferTime', 'FLOAT')] """ with autopep8_context(line, options=['--select=E501', '--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_should_not_try_to_break_at_every_paren_in_arithmetic( self): line = """\ term3 = w6 * c5 * (8.0 * psi4 * (11.0 - 24.0 * t2) - 28 * psi3 * (1 - 6.0 * t2) + psi2 * (1 - 32 * t2) - psi * (2.0 * t2) + t4) / 720.0 this_should_be_shortened = (' ', ' ') """ fixed = """\ term3 = w6 * c5 * (8.0 * psi4 * (11.0 - 24.0 * t2) - 28 * psi3 * (1 - 6.0 * t2) + psi2 * (1 - 32 * t2) - psi * (2.0 * t2) + t4) / 720.0 this_should_be_shortened = ( ' ', ' ') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_arithmetic_operator_with_indent(self): line = """\ def d(): 111 + 111 + 111 + 111 + 111 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 222 + 333 + 333 + 333 + 333 """ fixed = """\ def d(): 111 + 111 + 111 + 111 + 111 + 222 + 222 + 222 + 222 + \\ 222 + 222 + 222 + 222 + 222 + 333 + 333 + 333 + 333 """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_more_complicated(self): line = """\ blahblah = os.environ.get('blahblah') or os.environ.get('blahblahblah') or os.environ.get('blahblahblahblah') """ fixed = """\ blahblah = os.environ.get('blahblah') or os.environ.get( 'blahblahblah') or os.environ.get('blahblahblahblah') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_skip_even_more_complicated(self): line = """\ if True: if True: if True: blah = blah.blah_blah_blah_bla_bl(blahb.blah, blah.blah, blah=blah.label, blah_blah=blah_blah, blah_blah2=blah_blah) """ fixed = """\ if True: if True: if True: blah = blah.blah_blah_blah_bla_bl( blahb.blah, blah.blah, blah=blah.label, blah_blah=blah_blah, blah_blah2=blah_blah) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_logical_fix(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_logical_fix_and_physical_fix(self): line = """\ # ------ ------------------------------------------------------------------------ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ # ------ ----------------------------------------------------------------- xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_logical_fix_and_adjacent_strings(self): line = """\ print('a-----------------------' 'b-----------------------' 'c-----------------------' 'd-----------------------''e'"f"r"g") """ fixed = """\ print( 'a-----------------------' 'b-----------------------' 'c-----------------------' 'd-----------------------' 'e' "f" r"g") """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_multiple_lines(self): line = """\ foo_bar_zap_bing_bang_boom(111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333) """ fixed = """\ foo_bar_zap_bing_bang_boom( 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333, 111, 111, 111, 111, 222, 222, 222, 222, 222, 222, 222, 222, 222, 333, 333) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_do_not_break_on_keyword(self): # We don't want to put a newline after equals for keywords as this # violates PEP 8. line = """\ if True: long_variable_name = tempfile.mkstemp(prefix='abcdefghijklmnopqrstuvwxyz0123456789') """ fixed = """\ if True: long_variable_name = tempfile.mkstemp( prefix='abcdefghijklmnopqrstuvwxyz0123456789') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_do_not_begin_line_with_comma(self): line = """\ def dummy(): if True: if True: if True: object = ModifyAction( [MODIFY70.text, OBJECTBINDING71.text, COLON72.text], MODIFY70.getLine(), MODIFY70.getCharPositionInLine() ) """ fixed = """\ def dummy(): if True: if True: if True: object = ModifyAction( [MODIFY70.text, OBJECTBINDING71.text, COLON72.text], MODIFY70.getLine(), MODIFY70.getCharPositionInLine()) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_should_not_break_on_dot(self): line = """\ if True: if True: raise xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx('xxxxxxxxxxxxxxxxx "{d}" xxxxxxxxxxxxxx'.format(d='xxxxxxxxxxxxxxx')) """ fixed = """\ if True: if True: raise xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( 'xxxxxxxxxxxxxxxxx "{d}" xxxxxxxxxxxxxx'.format( d='xxxxxxxxxxxxxxx')) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_comment(self): line = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. pass # http://foo.bar/abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc- # The following is ugly commented-out code and should not be touched. #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx = 1 """ fixed = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will # wrap it using textwrap to be within 72 characters. pass # http://foo.bar/abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc-abc- # The following is ugly commented-out code and should not be touched. # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx = 1 """ with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_comment_should_not_modify_docstring(self): line = '''\ def foo(): """ # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. """ ''' with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(line, result) def test_e501_experimental_should_only_modify_last_comment(self): line = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 1. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 2. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 3. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. """ fixed = """123 if True: if True: if True: if True: if True: if True: # This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 1. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 2. This is a long comment that should be wrapped. I will wrap it using textwrap to be within 72 characters. # 3. This is a long comment that should be wrapped. I # will wrap it using textwrap to be within 72 # characters. """ with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_experimental_should_not_interfere_with_non_comment(self): line = ''' """ # not actually a comment %d. 12345678901234567890, 12345678901234567890, 12345678901234567890. """ % (0,) ''' with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(line, result) def test_e501_experimental_should_cut_comment_pattern(self): line = """123 # -- Useless lines ---------------------------------------------------------------------- 321 """ fixed = """123 # -- Useless lines ------------------------------------------------------- 321 """ with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_function_should_not_break_on_colon(self): line = r""" class Useless(object): def _table_field_is_plain_widget(self, widget): if widget.__class__ == Widget or\ (widget.__class__ == WidgetMeta and Widget in widget.__bases__): return True return False """ fixed = r""" class Useless(object): def _table_field_is_plain_widget(self, widget): if widget.__class__ == Widget or ( widget.__class__ == WidgetMeta and Widget in widget.__bases__): return True return False """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental(self): line = """\ models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, } """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(line, result) def test_e501_experimental_and_multiple_logical_lines(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) xxxxxxxxxxxxxxxxxxxxxxxxxxxx(aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) xxxxxxxxxxxxxxxxxxxxxxxxxxxx( aaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccc, dddddddddddddddddddddddd) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_and_multiple_logical_lines_with_math(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx([-1 + 5 / -10, 100, -3 - 4]) """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( [-1 + 5 / -10, 100, -3 - 4]) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_and_import(self): line = """\ from . import (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy) """ fixed = """\ from . import ( xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_shorten_comment_with_experimental(self): line = """\ # ------ ------------------------------------------------------------------------- """ fixed = """\ # ------ ----------------------------------------------------------------- """ with autopep8_context(line, options=['--experimental', '--aggressive']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_escaped_newline(self): line = """\ if True or \\ False: # test test test test test test test test test test test test test test pass """ fixed = """\ if True or \\ False: # test test test test test test test test test test test test test test pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_multiline_string(self): line = """\ print('---------------------------------------------------------------------', ('================================================', '====================='), '''-------------------------------------------------------------------------------- ''') """ fixed = """\ print( '---------------------------------------------------------------------', ('================================================', '====================='), '''-------------------------------------------------------------------------------- ''') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_multiline_string_with_addition(self): line = '''\ def f(): email_text += """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""" ''' fixed = '''\ def f(): email_text += """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""" ''' with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_multiline_string_in_parens(self): line = '''\ def f(): email_text += ("""This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""") ''' fixed = '''\ def f(): email_text += ( """This is a really long docstring that goes over the column limit and is multi-line.

Czar: """+despot["Nicholas"]+"""
Minion: """+serf["Dmitri"]+"""
Residence: """+palace["Winter"]+"""
""") ''' with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_indentation(self): line = """\ if True: # comment here print(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,cccccccccccccccccccccccccccccccccccccccccc) """ fixed = """\ if True: # comment here print(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccccccccccccccccc) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_multiple_keys_and_experimental(self): line = """\ one_two_three_four_five_six = {'one two three four five': 12345, 'asdfsdflsdkfjl sdflkjsdkfkjsfjsdlkfj sdlkfjlsfjs': '343', 1: 1} """ fixed = """\ one_two_three_four_five_six = { 'one two three four five': 12345, 'asdfsdflsdkfjl sdflkjsdkfkjsfjsdlkfj sdlkfjlsfjs': '343', 1: 1} """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_with_experimental_and_carriage_returns_only(self): """Make sure _find_logical() does not crash.""" line = 'if True:\r from aaaaaaaaaaaaaaaa import bbbbbbbbbbbbbbbbbbb\r \r ccccccccccc = None\r' fixed = 'if True:\r from aaaaaaaaaaaaaaaa import bbbbbbbbbbbbbbbbbbb\r\r ccccccccccc = None\r' with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_should_ignore_imports(self): line = """\ import logging, os, bleach, commonware, urllib2, json, time, requests, urlparse, re """ with autopep8_context(line, options=['--select=E501', '--experimental']) as result: self.assertEqual(line, result) def test_e501_experimental_should_not_do_useless_things(self): line = """\ foo(' ') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(line, result) def test_e501_experimental_with_percent(self): line = """\ raise MultiProjectException("Ambiguous workspace: %s=%s, %s" % ( varname, varname_path, os.path.abspath(config_filename))) """ fixed = """\ raise MultiProjectException( "Ambiguous workspace: %s=%s, %s" % (varname, varname_path, os.path.abspath(config_filename))) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_def(self): line = """\ def foobar(sldfkjlsdfsdf, kksdfsdfsf,sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf,sdfsdfsfd, sdfsdfdsf): pass """ fixed = """\ def foobar(sldfkjlsdfsdf, kksdfsdfsf, sdfsdfsdf, sdfsdfkdk, szdfsdfsdf, sdfsdfsdfsdlkfjsdlf, sdfsdfddf, sdfsdfsfd, sdfsdfdsf): pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_tuple(self): line = """\ def f(): man_this_is_a_very_long_function_name(an_extremely_long_variable_name, ('a string that is long: %s'%'bork')) """ fixed = """\ def f(): man_this_is_a_very_long_function_name( an_extremely_long_variable_name, ('a string that is long: %s' % 'bork')) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_tuple_in_list(self): line = """\ def f(self): self._xxxxxxxx(aaaaaa, bbbbbbbbb, cccccccccccccccccc, [('mmmmmmmmmm', self.yyyyyyyyyy.zzzzzzzz/_DDDDDD)], eee, 'ff') """ fixed = """\ def f(self): self._xxxxxxxx( aaaaaa, bbbbbbbbb, cccccccccccccccccc, [('mmmmmmmmmm', self.yyyyyyyyyy.zzzzzzzz / _DDDDDD)], eee, 'ff') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_complex_reformat(self): line = """\ bork(111, 111, 111, 111, 222, 222, 222, { 'foo': 222, 'qux': 222 }, ((['hello', 'world'], ['yo', 'stella', "how's", 'it'], ['going']), {str(i): i for i in range(10)}, {'bork':((x, x**x) for x in range(10))}), 222, 222, 222, 222, 333, 333, 333, 333) """ fixed = """\ bork( 111, 111, 111, 111, 222, 222, 222, {'foo': 222, 'qux': 222}, ((['hello', 'world'], ['yo', 'stella', "how's", 'it'], ['going']), {str(i): i for i in range(10)}, {'bork': ((x, x ** x) for x in range(10))}), 222, 222, 222, 222, 333, 333, 333, 333) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_dot_calls(self): line = """\ if True: logging.info('aaaaaa bbbbb dddddd ccccccc eeeeeee fffffff gg: %s', xxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyyyyy(zzzzzzzzzzzzzzzzz.jjjjjjjjjjjjjjjjj())) """ fixed = """\ if True: logging.info( 'aaaaaa bbbbb dddddd ccccccc eeeeeee fffffff gg: %s', xxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyyyyy( zzzzzzzzzzzzzzzzz.jjjjjjjjjjjjjjjjj())) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_avoid_breaking_at_empty_parentheses_if_possible( self): line = """\ someverylongindenttionwhatnot().foo().bar().baz("and here is a long string 123456789012345678901234567890") """ fixed = """\ someverylongindenttionwhatnot().foo().bar().baz( "and here is a long string 123456789012345678901234567890") """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_unicode(self): line = """\ someverylongindenttionwhatnot().foo().bar().baz("and here is a l안녕하세요 123456789012345678901234567890") """ fixed = """\ someverylongindenttionwhatnot().foo().bar().baz( "and here is a l안녕하세요 123456789012345678901234567890") """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_tuple_assignment(self): line = """\ if True: (xxxxxxx,) = xxxx.xxxxxxx.xxxxx(xxxxxxxxxxxx.xx).xxxxxx(xxxxxxxxxxxx.xxxx == xxxx.xxxx).xxxxx() """ fixed = """\ if True: (xxxxxxx,) = xxxx.xxxxxxx.xxxxx(xxxxxxxxxxxx.xx).xxxxxx( xxxxxxxxxxxx.xxxx == xxxx.xxxx).xxxxx() """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) @unittest.skip('To do') def test_e501_experimental_tuple_on_line(self): line = """\ def f(): self.aaaaaaaaa(bbbbbb, ccccccccc, dddddddddddddddd, ((x, y/eeeeeee) for x, y in self.outputs.total.iteritems()), fff, 'GG') """ fixed = """\ def f(): self.aaaaaaaaa( bbbbbb, ccccccccc, dddddddddddddddd, ((x, y / eeeeeee) for x, y in self.outputs.total.iteritems()), fff, 'GG') """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_tuple_on_line_two_space_indent(self): line = """\ def f(): self.aaaaaaaaa(bbbbbb, ccccccccc, dddddddddddddddd, ((x, y/eeeeeee) for x, y in self.outputs.total.iteritems()), fff, 'GG') """ fixed = """\ def f(): self.aaaaaaaaa(bbbbbb, ccccccccc, dddddddddddddddd, ((x, y/eeeeeee) for x, y in self.outputs.total.iteritems()), fff, 'GG') """ with autopep8_context(line, options=['--experimental', '--indent-size=2']) as result: self.assertEqual(fixed, result) def test_e501_experimental_oversized_default_initializer(self): line = """\ aaaaaaaaaaaaaaaaaaaaa(lllll,mmmmmmmm,nnn,fffffffffff,ggggggggggg,hhh,ddddddddddddd=eeeeeeeee,bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=ccccccccccccccccccccccccccccccccccccccccccccccccc,bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=cccccccccccccccccccccccccccccccccccccccccccccccc) """ fixed = """\ aaaaaaaaaaaaaaaaaaaaa( lllll, mmmmmmmm, nnn, fffffffffff, ggggggggggg, hhh, ddddddddddddd=eeeeeeeee, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=ccccccccccccccccccccccccccccccccccccccccccccccccc, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=cccccccccccccccccccccccccccccccccccccccccccccccc) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_decorator(self): line = """\ @foo(('xxxxxxxxxxxxxxxxxxxxxxxxxx', users.xxxxxxxxxxxxxxxxxxxxxxxxxx), ('yyyyyyyyyyyy', users.yyyyyyyyyyyy), ('zzzzzzzzzzzzzz', users.zzzzzzzzzzzzzz)) """ fixed = """\ @foo(('xxxxxxxxxxxxxxxxxxxxxxxxxx', users.xxxxxxxxxxxxxxxxxxxxxxxxxx), ('yyyyyyyyyyyy', users.yyyyyyyyyyyy), ('zzzzzzzzzzzzzz', users.zzzzzzzzzzzzzz)) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_long_class_name(self): line = """\ class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA(BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB): pass """ fixed = """\ class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA( BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB): pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_no_line_change(self): line = """\ def f(): return 'Copy Link' % url """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(line, result) def test_e501_experimental_splitting_small_arrays(self): line = """\ def foo(): unspecified[service] = ('# The %s brown fox jumped over the lazy, good for nothing ' 'dog until it grew tired and set its sights upon the cat!' % adj) """ fixed = """\ def foo(): unspecified[service] = ( '# The %s brown fox jumped over the lazy, good for nothing ' 'dog until it grew tired and set its sights upon the cat!' % adj) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_no_splitting_in_func_call(self): line = """\ def foo(): if True: if True: function.calls('%r (%s): aaaaaaaa bbbbbbbbbb ccccccc ddddddd eeeeee (%d, %d)', xxxxxx.yy, xxxxxx.yyyy, len(mmmmmmmmmmmmm['fnord']), len(mmmmmmmmmmmmm['asdfakjhdsfkj'])) """ fixed = """\ def foo(): if True: if True: function.calls( '%r (%s): aaaaaaaa bbbbbbbbbb ccccccc ddddddd eeeeee (%d, %d)', xxxxxx.yy, xxxxxx.yyyy, len(mmmmmmmmmmmmm['fnord']), len(mmmmmmmmmmmmm['asdfakjhdsfkj'])) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_no_splitting_at_dot(self): line = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx = [yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.MMMMMM_NNNNNNN_OOOOO, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.PPPPPP_QQQQQQQ_RRRRR, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.SSSSSS_TTTTTTT_UUUUU] """ fixed = """\ xxxxxxxxxxxxxxxxxxxxxxxxxxxx = [ yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.MMMMMM_NNNNNNN_OOOOO, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.PPPPPP_QQQQQQQ_RRRRR, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.SSSSSS_TTTTTTT_UUUUU] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_no_splitting_before_arg_list(self): line = """\ xxxxxxxxxxxx = [yyyyyy['yyyyyy'].get('zzzzzzzzzzz') for yyyyyy in x.get('aaaaaaaaaaa') if yyyyyy['yyyyyy'].get('zzzzzzzzzzz')] """ fixed = """\ xxxxxxxxxxxx = [yyyyyy['yyyyyy'].get('zzzzzzzzzzz') for yyyyyy in x.get('aaaaaaaaaaa') if yyyyyy['yyyyyy'].get('zzzzzzzzzzz')] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_dont_split_if_looks_bad(self): line = """\ def f(): if True: BAD(('xxxxxxxxxxxxx', 42), 'I died for beauty, but was scarce / Adjusted in the tomb %s', yyyyyyyyyyyyy) """ fixed = """\ def f(): if True: BAD(('xxxxxxxxxxxxx', 42), 'I died for beauty, but was scarce / Adjusted in the tomb %s', yyyyyyyyyyyyy) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_list_comp(self): line = """\ xxxxxxxxxxxs = [xxxxxxxxxxx for xxxxxxxxxxx in xxxxxxxxxxxs if not yyyyyyyyyyyy[xxxxxxxxxxx] or not yyyyyyyyyyyy[xxxxxxxxxxx].zzzzzzzzzz] """ fixed = """\ xxxxxxxxxxxs = [ xxxxxxxxxxx for xxxxxxxxxxx in xxxxxxxxxxxs if not yyyyyyyyyyyy[xxxxxxxxxxx] or not yyyyyyyyyyyy[xxxxxxxxxxx].zzzzzzzzzz] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) line = """\ def f(): xxxxxxxxxx = [f for f in yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.zzzzzzzzzzzzzzzzzzzzzzzz.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] """ fixed = """\ def f(): xxxxxxxxxx = [ f for f in yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.zzzzzzzzzzzzzzzzzzzzzzzz.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_dict(self): line = """\ def f(): zzzzzzzzzzzzz = { 'aaaaaa/bbbbbb/ccccc/dddddddd/eeeeeeeee/fffffffffff/ggggggggg/hhhhhhhh.py': yyyyyyyyyyy.xxxxxxxxxxx( 'aa/bbbbbbb/cc/ddddddd/eeeeeeeeeee/fffffffffff/ggggggggg/hhhhhhh/ggggg.py', '00000000', yyyyyyyyyyy.xxxxxxxxx.zzzz), } """ fixed = """\ def f(): zzzzzzzzzzzzz = { 'aaaaaa/bbbbbb/ccccc/dddddddd/eeeeeeeee/fffffffffff/ggggggggg/hhhhhhhh.py': yyyyyyyyyyy.xxxxxxxxxxx( 'aa/bbbbbbb/cc/ddddddd/eeeeeeeeeee/fffffffffff/ggggggggg/hhhhhhh/ggggg.py', '00000000', yyyyyyyyyyy.xxxxxxxxx.zzzz), } """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_indentation(self): line = """\ class Klass(object): '''Class docstring.''' def Quote(self, parameter_1, parameter_2, parameter_3, parameter_4, parameter_5): pass """ fixed = """\ class Klass(object): '''Class docstring.''' def Quote( self, parameter_1, parameter_2, parameter_3, parameter_4, parameter_5): pass """ with autopep8_context(line, options=['--experimental', '--indent-size=2']) as result: self.assertEqual(fixed, result) def test_e501_experimental_long_function_call_elements(self): line = """\ def g(): pppppppppppppppppppppppppp1, pppppppppppppppppppppppp2 = ( zzzzzzzzzzzz.yyyyyyyyyyyyyy(aaaaaaaaa=10, bbbbbbbbbbbbbbbb='2:3', cccccccc='{1:2}', dd=1, eeeee=0), zzzzzzzzzzzz.yyyyyyyyyyyyyy(dd=7, aaaaaaaaa=16, bbbbbbbbbbbbbbbb='2:3', cccccccc='{1:2}', eeeee=xxxxxxxxxxxxxxxxx.wwwwwwwwwwwww.vvvvvvvvvvvvvvvvvvvvvvvvv)) """ fixed = """\ def g(): pppppppppppppppppppppppppp1, pppppppppppppppppppppppp2 = ( zzzzzzzzzzzz.yyyyyyyyyyyyyy( aaaaaaaaa=10, bbbbbbbbbbbbbbbb='2:3', cccccccc='{1:2}', dd=1, eeeee=0), zzzzzzzzzzzz.yyyyyyyyyyyyyy( dd=7, aaaaaaaaa=16, bbbbbbbbbbbbbbbb='2:3', cccccccc='{1:2}', eeeee=xxxxxxxxxxxxxxxxx.wwwwwwwwwwwww.vvvvvvvvvvvvvvvvvvvvvvvvv)) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_long_nested_tuples_in_arrays(self): line = """\ def f(): aaaaaaaaaaa.bbbbbbb([ ('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) """ fixed = """\ def f(): aaaaaaaaaaa.bbbbbbb( [('xxxxxxxxxx', 'yyyyyy', 'Heaven hath no wrath like love to hatred turned. Nor hell a fury like a woman scorned.'), ('xxxxxxx', 'yyyyyyyyyyy', "To the last I grapple with thee. From hell's heart I stab at thee. For hate's sake I spit my last breath at thee!")]) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_func_call_open_paren_not_separated(self): # Don't separate the opening paren of a function call from the # function's name. line = """\ def f(): owned_list = [o for o in owned_list if self.display['zzzzzzzzzzzzzz'] in aaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbb(o.qq, ccccccccccccccccccccccccccc.ddddddddd.eeeeeee)] """ fixed = """\ def f(): owned_list = [ o for o in owned_list if self.display['zzzzzzzzzzzzzz'] in aaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbb( o.qq, ccccccccccccccccccccccccccc.ddddddddd.eeeeeee)] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_long_dotted_object(self): # Don't separate a long dotted object too soon. Otherwise, it may end # up with most of its elements on separate lines. line = """\ def f(self): return self.xxxxxxxxxxxxxxx(aaaaaaa.bbbbb.ccccccc.ddd.eeeeee.fffffffff.ggggg.hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh) """ fixed = """\ def f(self): return self.xxxxxxxxxxxxxxx( aaaaaaa.bbbbb.ccccccc.ddd.eeeeee.fffffffff.ggggg. hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh) """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) @unittest.skipIf(sys.version_info >= (3, 12), 'not detect in Python3.12+') def test_e501_experimental_parsing_dict_with_comments(self): line = """\ self.display['xxxxxxxxxxxx'] = [{'title': _('Library'), #. This is the first comment. 'flag': aaaaaaaaaa.bbbbbbbbb.cccccccccc }, {'title': _('Original'), #. This is the second comment. 'flag': aaaaaaaaaa.bbbbbbbbb.dddddddddd }, {'title': _('Unknown'), #. This is the third comment. 'flag': aaaaaaaaaa.bbbbbbbbb.eeeeeeeeee}] """ fixed = """\ self.display['xxxxxxxxxxxx'] = [{'title': _('Library'), # . This is the first comment. 'flag': aaaaaaaaaa.bbbbbbbbb.cccccccccc # . This is the second comment. }, {'title': _('Original'), 'flag': aaaaaaaaaa.bbbbbbbbb.dddddddddd # . This is the third comment. }, {'title': _('Unknown'), 'flag': aaaaaaaaaa.bbbbbbbbb.eeeeeeeeee}] """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) @unittest.skipIf(sys.version_info >= (3, 12), 'not detect in Python3.12+') def test_e501_experimental_if_line_over_limit(self): line = """\ if not xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): return 1 """ fixed = """\ if not xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): return 1 """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_for_line_over_limit(self): line = """\ for aaaaaaaaa in xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ fixed = """\ for aaaaaaaaa in xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_while_line_over_limit(self): line = """\ while xxxxxxxxxxxx(aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ fixed = """\ while xxxxxxxxxxxx( aaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbb, cccccccccccccc, dddddddddddddddddddddd): pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) def test_e501_experimental_with_in(self): line = """\ if True: if True: if True: if True: if True: if True: if True: if True: if k_left in ('any', k_curr) and k_right in ('any', k_curr): pass """ fixed = """\ if True: if True: if True: if True: if True: if True: if True: if True: if k_left in ( 'any', k_curr) and k_right in ( 'any', k_curr): pass """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(fixed, result) @unittest.skipIf(sys.version_info < (3, 12), 'not support in Python3.11 and lower version') def test_e501_experimental_not_effect_with_fstring(self): line = """\ fstring = {"some_key": f"There is a string value inside of an f string, which itself is a dictionary value {s})"} """ with autopep8_context(line, options=['--experimental']) as result: self.assertEqual(line, result) def fix_e266(source): with autopep8_context(source, options=['--select=E266']) as result: return result def fix_e265_and_e266(source): with autopep8_context(source, options=['--select=E265,E266']) as result: return result @contextlib.contextmanager def autopep8_context(line, options=None): if not options: options = [] with temporary_file_context(line) as filename: options = autopep8.parse_args([filename] + list(options)) yield autopep8.fix_file(filename=filename, options=options) @contextlib.contextmanager def autopep8_subprocess(line, options, timeout=None): with temporary_file_context(line) as filename: p = Popen(list(AUTOPEP8_CMD_TUPLE) + [filename] + options, stdout=PIPE) if timeout is None: _stdout, _ = p.communicate() else: try: _stdout, _ = p.communicate(timeout=timeout) except TypeError: # for Python2 while p.poll() is None and timeout > 0: time.sleep(0.5) timeout -= 0.5 if p.poll() is None: p.kill() raise Exception("subprocess is timed out") _stdout, _ = p.communicate() yield _stdout.decode('utf-8'), p.returncode @contextlib.contextmanager def temporary_file_context(text, suffix='', prefix=''): temporary = mkstemp(suffix=suffix, prefix=prefix) os.close(temporary[0]) with autopep8.open_with_encoding(temporary[1], encoding='utf-8', mode='w') as temp_file: temp_file.write(text) yield temporary[1] os.remove(temporary[1]) @contextlib.contextmanager def readonly_temporary_file_context(text, suffix='', prefix=''): temporary = mkstemp(suffix=suffix, prefix=prefix) os.close(temporary[0]) with autopep8.open_with_encoding(temporary[1], encoding='utf-8', mode='w') as temp_file: temp_file.write(text) os.chmod(temporary[1], stat.S_IRUSR) yield temporary[1] os.remove(temporary[1]) @contextlib.contextmanager def temporary_project_directory(prefix="autopep8test"): temporary = mkdtemp(prefix=prefix) yield temporary shutil.rmtree(temporary) @contextlib.contextmanager def disable_stderr(): sio = StringIO() with capture_stderr(sio): yield @contextlib.contextmanager def capture_stderr(sio): _tmp = sys.stderr sys.stderr = sio try: yield finally: sys.stderr = _tmp if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/test/test_suite.py0000755000175100001770000000557314635727563016447 0ustar00runnerdocker#!/usr/bin/env python """Run autopep8 against test file and check against expected output.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import os import sys ROOT_DIR = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] sys.path.insert(0, ROOT_DIR) import autopep8 if sys.stdout.isatty(): GREEN = '\x1b[32m' RED = '\x1b[31m' END = '\x1b[0m' else: GREEN = '' RED = '' END = '' def check(expected_filename, input_filename, aggressive): """Test and compare output. Return True on success. """ got = autopep8.fix_file( input_filename, options=autopep8.parse_args([''] + aggressive * ['--aggressive'])) try: with autopep8.open_with_encoding(expected_filename) as expected_file: expected = expected_file.read() except IOError: expected = None if expected == got: return True else: got_filename = expected_filename + '.err' encoding = autopep8.detect_encoding(input_filename) with autopep8.open_with_encoding(got_filename, encoding=encoding, mode='w') as got_file: got_file.write(got) print( '{begin}{got} does not match expected {expected}{end}'.format( begin=RED, got=got_filename, expected=expected_filename, end=END), file=sys.stdout) return False def run(filename, aggressive): """Test against a specific file. Return True on success. Expected output should have the same base filename, but live in an "out" directory: foo/bar.py foo/out/bar.py Failed output will go to: foo/out/bar.py.err """ return check( expected_filename=os.path.join( os.path.dirname(filename), 'out', os.path.basename(filename) ), input_filename=filename, aggressive=aggressive ) def suite(aggressive): """Run against pep8 test suite.""" result = True path = os.path.join(os.path.dirname(__file__), 'suite') for filename in os.listdir(path): filename = os.path.join(path, filename) if filename.endswith('.py'): print(filename, file=sys.stderr) result = run(filename, aggressive=aggressive) and result if result: print(GREEN + 'Okay' + END) return result def main(): parser = argparse.ArgumentParser() parser.add_argument('--aggression-level', default=2, type=int, help='run autopep8 in aggression level') args = parser.parse_args() return int(not suite(aggressive=args.aggression_level)) if __name__ == '__main__': sys.exit(main()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1719119731.0 autopep8-2.3.1/tox.ini0000644000175100001770000000043714635727563014230 0ustar00runnerdocker[tox] envlist=py38,py39,py310,py311,py312 skip_missing_interpreters=True [testenv] commands= python test/test_autopep8.py python test/acid.py --aggressive test/example.py python test/acid.py --compare-bytecode test/example.py deps= pycodestyle>=2.12.0 pydiff>=0.1.2