1.. currentmodule:: pycodestyle 2 3============== 4Advanced usage 5============== 6 7 8Automated tests 9--------------- 10 11You can also execute ``pycodestyle`` tests from Python code. For example, this 12can be highly useful for automated testing of coding style conformance 13in your project:: 14 15 import unittest 16 import pycodestyle 17 18 19 class TestCodeFormat(unittest.TestCase): 20 21 def test_conformance(self): 22 """Test that we conform to PEP-8.""" 23 style = pycodestyle.StyleGuide(quiet=True) 24 result = style.check_files(['file1.py', 'file2.py']) 25 self.assertEqual(result.total_errors, 0, 26 "Found code style errors (and warnings).") 27 28There's also a shortcut for checking a single file:: 29 30 import pycodestyle 31 32 fchecker = pycodestyle.Checker('testsuite/E27.py', show_source=True) 33 file_errors = fchecker.check_all() 34 35 print("Found %s errors (and warnings)" % file_errors) 36 37 38Configuring tests 39----------------- 40 41You can configure automated ``pycodestyle`` tests in a variety of ways. 42 43For example, you can pass in a path to a configuration file that ``pycodestyle`` 44should use:: 45 46 import pycodestyle 47 48 style = pycodestyle.StyleGuide(config_file='/path/to/tox.ini') 49 50You can also set specific options explicitly:: 51 52 style = pycodestyle.StyleGuide(ignore=['E501']) 53 54 55Skip file header 56---------------- 57 58Another example is related to the `feature request #143 59<https://github.com/pycqa/pycodestyle/issues/143>`_: skip a number of lines 60at the beginning and the end of a file. This use case is easy to implement 61through a custom wrapper for the PEP 8 library:: 62 63 #!python 64 import pycodestyle 65 66 LINES_SLICE = slice(14, -20) 67 68 class StyleGuide(pycodestyle.StyleGuide): 69 """This subclass of pycodestyle.StyleGuide will skip the first and last lines 70 of each file.""" 71 72 def input_file(self, filename, lines=None, expected=None, line_offset=0): 73 if lines is None: 74 assert line_offset == 0 75 line_offset = LINES_SLICE.start or 0 76 lines = pycodestyle.readlines(filename)[LINES_SLICE] 77 return super(StyleGuide, self).input_file( 78 filename, lines=lines, expected=expected, line_offset=line_offset) 79 80 if __name__ == '__main__': 81 style = StyleGuide(parse_argv=True, config_file=True) 82 report = style.check_files() 83 if report.total_errors: 84 raise SystemExit(1) 85 86This module declares a lines' window which skips 14 lines at the beginning 87and 20 lines at the end. If there's no line to skip at the end, it could be 88changed with ``LINES_SLICE = slice(14, None)`` for example. 89 90You can save it in a file and use it with the same options as the 91original ``pycodestyle``. 92