def pep8(args):
"""Check code for PEP8 violations
"""
try:
import pep8
except:
error('pep8 not found! Run "paver install_devtools".')
sys.exit(1)
# Errors to ignore
ignore = ['E203', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127',
'E128', 'E402']
styleguide = pep8.StyleGuide(ignore=ignore,
exclude=['*/extlibs/*', '*/ext-src/*'],
repeat=True, max_line_length=79,
parse_argv=args)
styleguide.input_dir(options.plugin.source_dir)
info('===== PEP8 SUMMARY =====')
styleguide.options.report.print_statistics()
python类StyleGuide()的实例源码
def pep8(args):
"""Check code for PEP8 violations
"""
try:
import pep8
except:
error('pep8 not found! Run "paver install_devtools".')
sys.exit(1)
# Errors to ignore
ignore = ['E203', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127',
'E128', 'E402']
styleguide = pep8.StyleGuide(ignore=ignore,
exclude=['*/extlibs/*', '*/ext-src/*'],
repeat=True, max_line_length=79,
parse_argv=args)
styleguide.input_dir(options.plugin.source_dir)
info('===== PEP8 SUMMARY =====')
styleguide.options.report.print_statistics()
def test_pep8_conformance(self):
# Tests the nc-time-axis code base against the "pep8" tool.
#
# Users can add their own excluded files (should files exist in the
# local directory which is not in the repository) by adding a
# ".pep8_test_exclude.txt" file in the same directory as this test.
# The file should be a line separated list of filenames/directories
# as can be passed to the "pep8" tool's exclude list.
pep8style = pep8.StyleGuide(quiet=False)
pep8style.options.exclude.extend(['*/_version.py'])
# Allow users to add their own exclude list.
extra_exclude_file = os.path.join(os.path.dirname(__file__),
'.pep8_test_exclude.txt')
if os.path.exists(extra_exclude_file):
with open(extra_exclude_file, 'r') as fhandle:
extra_exclude = [line.strip()
for line in fhandle if line.strip()]
pep8style.options.exclude.extend(extra_exclude)
root = os.path.abspath(nc_time_axis.__file__)
result = pep8style.check_files([os.path.dirname(root)])
self.assertEqual(result.total_errors, 0, "Found code syntax "
"errors (and warnings).")
def test_pep8(self):
style = pep8.StyleGuide(quiet=False)
style.options.ignore += ('E111',) # 4-spacing is just too much
style.options.ignore += ('E501',)
style.options.ignore += ('E114',)
style.options.ignore += ('E121',)
style.options.ignore += ('E122',)
style.options.ignore += ('E126',)
style.options.ignore += ('E127',)
style.options.ignore += ('E128',)
# style.options.max_line_length = 100 # because it isn't 1928 anymore
errors = 0
for dir in ['wxgen/', 'wxgen/tests/']:
for root, _, files in os.walk(dir):
if ignore(root):
continue
python_files = [os.path.join(root, f) for f in files if f.endswith('.py')]
report = style.check_files(python_files)
errors += report.total_errors
if errors > 0:
warnings.warn('Warning: There are %d PEP8 style errors in the source files' % errors)
def pep8(args):
"""Check code for PEP8 violations
"""
try:
import pep8
except:
error('pep8 not found! Run "paver install_devtools".')
sys.exit(1)
# Errors to ignore
ignore = ['E203', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127',
'E128', 'E402']
styleguide = pep8.StyleGuide(ignore=ignore,
exclude=['*/extlibs/*', '*/ext-src/*'],
repeat=True, max_line_length=79,
parse_argv=args)
styleguide.input_dir(options.plugin.source_dir)
info('===== PEP8 SUMMARY =====')
styleguide.options.report.print_statistics()
def test_pep8_conformance(self):
"""Test that we conform to PEP8."""
pep8style = pep8.StyleGuide(quiet=False)
result = pep8style.check_files(['Builder.py',
'Building.py',
'Clips.py',
'Entities.py',
'Farmer.py',
'GameEntity.py',
'Image_funcs.py',
'Lumberjack.py',
'New_Icon.py',
'NewVillagerSim.py',
'StateMachine.py',
'Tile.py',
'Villager.py',
'World.py',
'Tests/test_pep8.py',
'Tests/animation_test.py'])
self.assertEqual(result.total_errors, 0,
"Found code style errors (and warnings).")
def pep8(args):
"""Check code for PEP8 violations
"""
try:
import pep8
except:
error('pep8 not found! Run "paver install_devtools".')
sys.exit(1)
# Errors to ignore
ignore = ['E203', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127',
'E128', 'E402']
styleguide = pep8.StyleGuide(ignore=ignore,
exclude=['*/extlibs/*', '*/ext-src/*'],
repeat=True, max_line_length=79,
parse_argv=args)
styleguide.input_dir(options.plugin.source_dir)
info('===== PEP8 SUMMARY =====')
styleguide.options.report.print_statistics()
def check_files(dir):
style = pep8.StyleGuide()
style.options.max_line_length = 100
python_files = []
for root, _, files in os.walk(dir):
python_files += [os.path.join(root, f) for f in files if f.endswith('.py')]
for file in python_files:
report = style.check_files([os.path.join(BASE_PATH, file)])
report.print_statistics()
nose.tools.assert_equal(report.total_errors, 0,
"File %s has some PEP8 errors: %d" % (file, report.total_errors))
def test_pycodestyle():
style = pycodestyle.StyleGuide()
base_path = os.path.dirname(os.path.dirname(__file__))
report = style.check_files([
os.path.join(base_path, 'script', 'control_team_blue'),
os.path.join(base_path, 'script', 'control_team_gold'),
os.path.join(base_path, 'script', 'rqt_uctf'),
os.path.join(base_path, 'script', 'spawn_blue'),
os.path.join(base_path, 'script', 'spawn_gold'),
os.path.join(base_path, 'src'),
os.path.join(base_path, 'test'),
])
assert not report.total_errors
def test_pep8_conformance():
"""
Test for pep8 conformance
"""
pattern = re.compile(r'.*({0}.*\.py)'.format('jsone'))
base = os.path.dirname(os.path.abspath(__file__))
dirname = os.path.abspath(os.path.join(base, '../jsone'))
sources = [
os.path.join(root, pyfile) for root, _, files in os.walk(dirname)
for pyfile in files
if pyfile.endswith('.py')]
pep8style = pep8.StyleGuide(reporter=CustomReport, paths=[dirname])
report = pep8style.init_report()
pep8style.check_files(sources)
for error in report.results:
msg = "{path}: {code} {row}, {col} - {text}"
match = pattern.match(error['path'])
if match:
rel_path = match.group(1)
else:
rel_path = error['path']
def fail():
raise AssertionError(msg.format(
path=rel_path,
code=error['code'],
row=error['row'],
col=error['col'],
text=error['text']
))
yield fail
def test_pep8():
pep8style = pep8.StyleGuide(config_file='linter.cfg', exclude=get_excluded_files())
result = pep8style.check_files(CHECKED_DIRS)
assert result.total_errors == 0
def test_pep8():
"""All source files should comply with PEP 8."""
file_paths = itertools.chain(
glob.iglob('automata/*/*.py'),
glob.iglob('tests/*.py'))
for file_path in file_paths:
style_guide = pep8.StyleGuide(quiet=True)
total_errors = style_guide.input_file(file_path)
fail_msg = '{} does not comply with PEP 8'.format(file_path)
yield nose.assert_equal, total_errors, 0, fail_msg
def test_pep8(self):
def match(*p):
s = list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(
match('examples') +
match('test') +
match('theanets') +
match('theanets', 'layers'))
assert result.total_errors == 0
def test_pep8(self):
def match(*p):
s = ['downhill'] + list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(match())
assert result.total_errors == 0
def test_pep8(self):
pep8style = pep8.StyleGuide([['statistics', True],
['show-sources', True],
['repeat', True],
['ignore', "E501"],
['paths', [os.path.dirname(
os.path.abspath(__file__))]]],
parse_argv=False)
report = pep8style.check_files()
assert report.total_errors == 0
def _pep8_annotations(text, ignore=None, max_line_length=None):
import pep8
class _Pep8AnnotationReport(pep8.BaseReport):
def __init__(self, options):
super().__init__(options)
self.annotations = []
def error(self, line_number, offset, text, check):
# If super doesn't return code, this one is ignored
if not super().error(line_number, offset, text, check):
return
annotation = _AnalyzerAnnotation(self.line_offset + line_number, text, _Source.pep8, Style.warning)
self.annotations.append(annotation)
# pep8 requires you to include \n at the end of lines
lines = text.splitlines(True)
style_guide = pep8.StyleGuide(reporter=_Pep8AnnotationReport, )
options = style_guide.options
if ignore:
options.ignore = tuple(ignore)
else:
options.ignore = tuple()
if max_line_length:
options.max_line_length = max_line_length
checker = pep8.Checker(None, lines, options, None)
checker.check_all()
return checker.report.annotations
#
# pyflakes
#
def test_pep8_conformance(self):
"""Test that we conform to PEP8."""
if pep8 is not None:
ignore_error_codes = []
base_path = self.get_package_path()
test_cases = ["",
"test",
]
for directory in test_cases:
path = os.path.join(base_path, directory)
if os.path.exists(path):
files = self.get_files(path)
results = []
# Need to check if pep8 is installed before running
for f in sorted(files):
pep8_style = pep8.StyleGuide(quiet=True,
ignore=ignore_error_codes)
result = pep8_style.check_files([f])
if result.total_errors != 0:
results.append("Found code style errors (and warnings)\
Run 'pep8 --show-source {0}'.".format(f))
self.assertEqual(0, len(results),
"results {0}".format(results))
else:
print("PEP8 module is not installed skipping test.")
def run(self, settings, **options):
output = open(os.path.join(options[CI.OUTPUT_DIR], Reports.PEP8_REPORT), 'w')
class JenkinsReport(pep8.BaseReport):
def error(self, line_number, offset, text, check):
code = super(JenkinsReport, self).error(line_number, offset, text, check)
if code:
source_line = self.line_offset + line_number
output.write('%s:%s:%s: %s\n' % (self.filename, source_line, offset + 1, text))
pep8_options = {}
config_file = self.get_config_path(settings, options)
if config_file is not None:
pep8_options[Pep8.CONFIG_FILE] = config_file
pep8_options[Pep8.MAX_LINE_LENGTH] = options[Pep8.PEP8_MAX_LINE_LENGTH]
pep8style = pep8.StyleGuide(
parse_argv=False,
reporter=JenkinsReport,
**pep8_options)
pep8style.options.report.start()
for location in getattr(settings, Settings.PROJECT_APPS, []):
pep8style.input_dir(os.path.relpath(location))
pep8style.options.report.stop()
output.close()
def test_pep8_conformance(self):
"""Test for pep8 conformance."""
pep8style = pep8.StyleGuide(quiet=False)
# pep8style.options.ignore += ('E501',)
pep8style.options.max_line_length = 150
errors = 0
for root, _, files in os.walk('.'):
if not ignore(root):
python_files = [root + '/' + f for f in files if f.endswith('.py')]
errors += pep8style.check_files(python_files).total_errors
self.assertEqual(errors, 0, 'PEP8 style errors: %d' % errors)
def run(path, code=None, params=None, **meta):
"""Check code with PEP8.
:return list: List of errors.
"""
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
if not isinstance(value, str):
continue
params[option.dest] = option.convert_value(option, params[option.dest])
P8Style = StyleGuide(reporter=_PEP8Report, **params)
buf = StringIO(code)
return P8Style.input_file(path, lines=buf.readlines())
def test_pep8_conformance_views(self):
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files([self.path])
error_message = ""
if result.total_errors != 0:
error_message = "Style errors in: " + self.path + "\n" + "\n".join(result.get_statistics())
self.assertEqual(result.total_errors, 0, error_message)
def test_pep8_conformance_views(self):
file_path = self.path + 'views.py'
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files([file_path])
self._validate(result, file_path)
def test_pep8_conformance_urls(self):
file_path = self.path + 'urls.py'
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files([file_path])
self._validate(result, file_path)
def test_pep8_conformance_init(self):
file_path = self.path + '__init__.py'
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files([file_path])
self._validate(result, file_path)
# Helper method to validate whether or not there are pep8 errors in the code specified by the path
def test_pep8(self):
pep8style = pep8.StyleGuide()
result = pep8style.check_files([
'tests/test_ark.py',
'tests/test_arktypes.py',
'arkpy/binary.py',
'arkpy/utils.py',
'arkpy/ark.py',
'arkpy/arktypes.py',
])
assert result.total_errors == 0
test_code_format_pep8.py 文件源码
项目:tm-librarian
作者: FabricAttachedMemory
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def test_pep8_conformance(self):
"""Test that we conform to PEP8."""
pep8style = pep8.StyleGuide(
ignore=['E121', 'E123', 'E126', 'E133', 'E226',
'E241', 'E242', 'E704', 'E265', 'E201','E202'],
# show_pep8=True,
show_source=True
)
result = pep8style.check_files([
'backend_sqlite3.py',
'book_shelf_bos.py',
'function_chain.py',
'librarian_chain.py',
'repl_client.py',
'sqlassist.py',
'cmdproto.py',
'genericobj.py',
'librarian.py',
'sqlbackend.py',
'lfs_fuse.py',
'book_register.py',
'engine.py',
'lfs_shadow.py',
'socket_handling.py'])
self.assertEqual(result.total_errors, 0,
"Found code style errors (and warnings).")
def do_run(self):
if type(self.filelist) == type('a'):
ph_out = self.filelist
self.detail = []
warning = 0
l = ph_out.split('\n')
for x in l:
if x[:6] == '[WARN]':
warning += 1
self.detail.append(x)
self.score = 100.0 - warning * self.errcost
if self.score < 0.0:
self.score = 0.0
total_file = 1
if warning > 0:
self.brief = lazy_gettext(
'%(trouble)d problem(s) found in %(file)d file(s)',
trouble=warning, file=total_file
)
else:
self.brief = lazy_gettext('All files passed Google code style check')
if self.logs != None:
self.logs.saveCodeStyle(str(self.score) + '\n' + str(self.brief) + '\n' + GetTextStringList(self.detail))
return
guide = pep8.StyleGuide()
guide.options.show_source = True
guide.options.report = Pep8DetailReport(guide.options)
result = guide.check_files(self.filelist)
# Each error consumes 1 point.
errcount = result.count_errors()
self.score = 100.0 - errcount * self.errcost
if self.score < 0.0:
self.score = 0.0
# format the brief report
total_file = len(self.filelist)
if errcount > 0:
self.brief = lazy_gettext(
'%(trouble)d problem(s) found in %(file)d file(s)',
trouble=errcount, file=total_file
)
else:
self.brief = lazy_gettext('All files passed PEP8 code style check')
# format detailed reports
self.detail = result.build_report()
if self.logs != None:
self.logs.saveCodeStyle(str(self.score) + '\n' + str(self.brief) + '\n' + GetTextStringList(self.detail))