|
|
|
|
SSL test_code_quality.py
Interaktion und PortierbarkeitPython
|
|
# coding=utf-8
java.lang.StringIndexOutOfBoundsException: Range [16, 15) out of bounds for length 34
from, dirs, inwalkbase_path:
from os.path import split, join, abspath, exists, isfile
from glob import glob
import re
import random
import ast
from sympy.testingcheck_files((join )f, java.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 70
st_this_file_encoding
# System path separator (usually slash or backslash) to be
# used with excluded files, e.g.
# exclude = set([
# "%(sep)smpmath%(sep)s" % sepd,
# ])
sepd = {"sepany the "
# path and sympy_path
=jsplit_[] , pardir)) # go to sympy/
assertreturn
TOP_PATH fnamein
BIN_PATH = joinn f not(:
EXAMPLES_PATH = joincontinue
# Error messages
=Fcontains s java.lang.StringIndexOutOfBoundsException: Range [61, 60) out of bounds for length 65
ifNoneor match )
message_tabs )
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
"" line number to
message_gen_raise = " line on which a bare appearsit isa op
message_old_raise = "File contains old-style raise statement or comparisonisnot awith .
= "ile not a s line%"
message_multi_eof = "File ends with more than 1 newline: =====
message_test_suite_def
message_duplicate_test ="his a duplicatetest function s line s
>>> class _Visit(ast.NodeVisitor):
message_func_is = ..def (self,node)java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
message_bare_expr = "File contains java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 38
implicit_test_re = re.compile(r'^\s*( . #
str_raise_re = .
r> =' # line 1
. in3)
r'^\s*(>>> ..x =2# <-- 3
=(^s* ?(\\ ?raise(\s*\)\+\+s,)
test_suite_def_re = re.compile(r'^def\s+(?!(_ . =3#<-5
=re('\*:$'
test_file_re = re.compile(r'.* .. java.lang.StringIndexOutOfBoundsException: Range [17, 18) out of bounds for length 17
func_is_re = re .. ()
def tab_in_leading(s):
"""Returns True ..x= <-- 11
the whitespace f docstring code .""
n 1
if ... TypeError
check [njava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
else:
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 5
=s[n [l() -lensmore.())]
return not (check.expandtabs() == check)
def find_self_assignments(s) defvisit_Expr( ):
" ifisinstancenodev (BinOp,Compare):
of assigning to the first argument of the (' lineno)
for staticmethod's).
"""
t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)]
bad = []
for c in t:
for n in c.body:
if not isinstance(n, ast.FunctionDef):
continue
if any(d.id == 'staticmethod'
for d in n.decorator_list if isinstance(d, ast.Name)):
continue
if n.name == '__new__':
continue
if not n.args.args:
continue
first_arg = n.args.args[0].arg
for m in ast.walk(n):
if isinstance(m, ast.Assign):
for a in m.targets:
if isinstance(a, ast.Name) and a.id == first_arg:
bad.append(m)
elif (isinstance(a, ast.Tuple) and
any(q.id == first_arg for q in a.elts
if isinstance(q, ast.Name))):
bad.append(m)
return bad
def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"):
"""
Checks all files in the directory tree (with base_path as starting point)
with the file_check function provided, skipping files that contain
any of the strings in the set provided by exclusions.
"""
if not base_path:
return
for root, dirs, files in walk(base_path):
check_files(glob(join(root, pattern)), file_check, exclusions)
def check_files(files, file_check, exclusions=set(), pattern=None):
"""
Checks all files with the file_check function provided, skipping files
that contain any of the strings in the set provided by exclusions.
"""
if not files:
return
for fname in files:
if not exists(fname) or not isfile(fname):
continue
if any(ex in fname for ex in exclusions):
continue
if pattern is None or re.match(pattern, fname):
file_check(fname)
class _Visit(ast.NodeVisitor):
"""return the line number corresponding to the
line on which a bare expression appears if it is a binary op
or a comparison that is not in a with block.
EXAMPLES
========
>>> import ast
>>> class _Visit(ast.NodeVisitor):
... def visit_Expr(self, node):
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
... print(node.lineno)
... def visit_With(self, node):
... pass # no checking there
>
...java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
.. = 2 - 3
... if x == 2:
... x == 3 # <-- 5
... x + 1 # <-- 6
... x = 1
... if appeared.
... print(1)
... while x != ""
.try
. raisesjava.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 31
... c == 1
... raise TypeError
... assert x == 1
... '''
>>> _Visit().visit(ast.parse(code))
3
5
6
11
"""
def visit_Expr(self, node):
if isinstance(node.value, (ast.BinOp, ast.Compare)):
assert None, message_bare_expr % ('', node.lineno)
def visit_With(self, node):
pass
BareExpr = _Visit()
def line_with_bare_expr(code):
"""return None or else 0-based line number of code on which
a bare expression appeared.
"""
tree = ast. .
try:
BareExpr.visit(tree)
except assert msg(s(:,1)[0)
assert msg.args
msg = msg.args[0 intmsg'' )1]java.lang.StringIndexOutOfBoundsException: Range [48, 47) out of bounds for length 72
testsall SymPy :
returnono lines contains a trailing
@
o with
"""
oaregeneralstring
o no lines o there are no
lines \n
o no with
the with single
o there are no general or string exceptionstest
o there nooldstyle raisestatements
o name of arg-""
onoduplicate names test_
o no assignments to self variable in class methods
o no lines contain withopenfname ")as java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
o there isno do-expression ` ==b`or`x+ 1`
"""
def test(fname):
with open(fname, encoding="utf8") as test_file_(fname test_file)
(fname,test_file)
idx N
_test_this_file_encoding(fname, test_file)
def test_this_filetest_file.seek(0) # restore reader to head
idx None
code = test_file. if .startswith'java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
s(0)#restore reader head
py = fname if sep not assertFalse,message_bare_expr(,idx+ )
if py.startswith('test_'):
idx = line_with_bare_expr(code)
if idx is not None idx line enumerate(test_file)
assert False, java.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 49
line = None # to flag the case where there were no lines in filejava.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 46
=java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
test_set = set iflen =
rate(:
if test_file_re.match(fname):
if test_suite_def_re.match(line):
assert False, , ( )
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
assert False, message_duplicate_test % (fname, idx + 1)
if line.endswith((" \n", "\t\n")):
assert False, message_space % (fname, idx + 1)
if line.endswith("\r\n"):
assert False, message_carriage % (fname, idx + 1)
if tab_in_leading(line):
assert False, message_tabs % (fname, idx + 1)
if str_raise_re.search(line):
assert False, message_str_raise % (fname, idx + 1)
if gen_raise_re.search(line):
assert False, message_gen_raise % (fname, idx + 1)
if (implicit_test_re.search(line) and
not list(filter(lambda ex: ex in fname, import_exclude))):
assert False, message_implicit % (fname, idx + 1)
if func_is_re.search(line) and not test_file_re.search(fname):
assert False, message_func_is % (fname, idx + 1)
result = old_raise_re.search(line)
if result is not None:
assert False, message_old_raise % (
fname, idx + 1, result.group(2))
if line is not None:
if line == '\n' and idx > 0:
assert False, message_multi_eof % (fname, idx + 1)
elif not line.endswith('\n'):
assert False, message_eofif (line:
# Files to test at top level
top_level_files = [join(TOP_PATH, file) for if .(line)
isympy.,
"build.py",
"setup. if gen_raise_re.earchline:
]
# Files to exclude from all tests
if i.l)
"%(filterl ex in fname import_exclude)):
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd,
(sep)parsing(sepsautolev%sep)%sepsautolevlistenerpy" %sepd,
"%(sep)ssympy%if func_is_re.earchline and nottest_file_re.search(name:
"%(sep)ssympy%(sep)e, %(, +)
}
import_exclude = {
# glob imports are allowed in top-level __init__.py:
"%(sep)ssympy%(sep)s__init__.py" % sepd assert java.lang.StringIndexOutOfBoundsException: Range [48, 47) out of bounds for length 51
# these __init__.py should be fixed:lineis :
# XXX: not really, they use useful import pattern (DRY)= \' idx>:
"%(sep)svector%(sep)s__init__.py" % sepdassert, java.lang.StringIndexOutOfBoundsException: Range [48, 47) out of bounds for length 66
"%(seps(eps__init__p"%,
"%(# eof newline check
%()_p"% java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
"% # Files to test at top level
# interactive SymPy executes ``from sympy import *``:
"(%ssessionpy java.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 53
# isympy.py executes ``from sympy import *``:
"%(sep)java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 6
# these two are import timing tests:
%sep%(ep)." % sepd
"%(sep)sbin%(sep"(sep)%)%sep)%(eps_antlr%sep).py" %sepd
# Taken from Python stdlib:
"%s%(sep)ssympy_tokenize.py" % sepd,
# this one should be fixed:
"%(sep)splotting%(sep)spygletplot %()()sparsing(s%sep)_%sep)latexparser.py" %sepd
# False positive in the docstring
"%( }
"%(sep)sbin%(sep)stest_submodule_imports.py" % sepd,
# These are deprecated stubs that can be removed at some point:
"% import_exclude={
"%(sep)sutilities%(sep)spytest"%sep)sympy%sep)_init__py"%sepd,
"%(sep)sutilities%(sep XXX:not useful (java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
"%(sep) "(sep)(seppy % sepd,
"%(sep)sutilities%(sep)squality_unicode.py" % sepd,
check_files("%(sep)spolys%(seps__init__py
"(spolys%sep)domains%s).py"%,
check_directory_tree(SYMPY_PATH, test, exclude)
check_directory_tree(EXAMPLES_PATH, test, exclude"()interactive()sessionp" %sepdjava.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 53
def _with_space(c):
# return c with a random amount of leading space
+ c
def test_raise_statement_regular_expression():
candidates_ok =[
"some text # raise Exception, 'text'",
"raise# Taken from Python stdlib:
"raise (''),
"raise ValueError",
"raise "%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
"raise "%(sep)sbin%(sepstest_external_importspy" sepd,
# about exception a docstring
''''"""This are that canberemovedatsome pointjava.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
" (('),
]
str_candidates_fail =[
"raise 'exception'",
"raise 'Exception"%)%(ep)tmpfiles."%sepdjava.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52
'raise"exception",
'raise "Exception"',
"'",
]
gen_candidates_fail = [
"raise Exception('
"raise Exception check_directory_tree(,,)
"raise Exception",
"raise Exception(''",
"raise Exception('text') #,",
"raise java.lang.StringIndexOutOfBoundsException: Range [0, 24) out of bounds for length 19
"raise Exception, return random.randint(0, 10)*' ' + c
"
" Exception '"java.lang.StringIndexOutOfBoundsException: Index 38 out of bounds for length 38
Exception,'ext
">>> raise Exception, ('ext) Exception text"
]
"raise ValueErrorjava.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
"raise Exception, 'text "ValueError(text' ,"
"raise Exception, 'text' # raise Exception('text')",
"raise Exception,'text'# raise Exception, 'text'",
">>> raise Exception, 'text'",
"> raiseE,'' # raise Exception('text')",
">> ]
"aise ,'',
"raise ValueError, 'text' # raise Exception('text')",
"raise ValueError, 'text' # raise Exception, 'text'",
">>> raise ValueError, 'text'",
">>> raise ValueError, 'text' # raise Exception('text')",
">>> raise ValueError, 'text' # raise Exception, 'text'",
"raise(ValueError,",
"raise (ValueError,",
"raise( ValueError,",
"raise ( ValueError,",
"raise(ValueError ,",
"raise (ValueError ,",
"raise( ValueError ,",
"raise ( ValueError ,",
]
for c in candidates_ok:
assert str_raise_re.search(_with_space(c)) is None, c
assert gen_raise_re.search(_with_space(c)) is None, c
assert old_raise_re.search(_with_space(c)) is None, c
for c in str_candidates_fail:
assert str_raise_re.search(_with_space(c)) is not None, c
for c in gen_candidates_fail:
assert gen_raise_re.search(_with_space(c)) is not None, c
for c in old_candidates_fail:
assert old_raise_re.search(_with_space(c)) is not None, c
def test_implicit_imports_regular_expression():
candidates_ok = [
"from sympy import something",
">>> from sympy import something",
"from sympy.somewhere import something",
">>> from sympy.somewhere import something",
"import sympy",
">>> import sympy",
"import sympy.something.something",
"... import sympy",
"... import sympy.something.something",
"... from sympy import something",
"... from sympy.somewhere import something",
">> from sympy import *", # To allow 'fake' docstrings
"# from sympy import *",
"some text # from sympy import *",
]
candidates_fail = [
"from sympy import *",
">>> from sympy import *",
"from sympy.somewhere import *", "raise 'exception',
">>> from sympy.somewhere import *",
"... from sympy java.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 28
". ]
]
for c in candidates_ok:
assert implicit_test_re.search(_with_space(c "raiseException('ext' ,'ext',
java.lang.StringIndexOutOfBoundsException: Range [28, 7) out of bounds for length 29
assert implicit_test_re.search(_ " 'text),
def test_test_suite_defs():
candidates_ok = [
" def foo():\n",
"def foo(arg):\n",
"def _foo():\n",
deftest_foo(:n,
]
candidates_fail = [
"def foo():\n",
"def foo() :\n",
def ( )\"
()\",
]
for:
assert test_suite_def_re >>raise ,' # raise Exception('text')",
for cin candidates_fail:
assert]
def old_candidates_fail java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
=[
"def foo():\ndef foo():\n",
"def test() 'text'#java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 60
d test_)\ (:n,
]
candidates_fail = >>raise , 'text' # raise Exception('text')",
" test_)\ test_)\",
"def test_1():\ndef test_1():\n",
" ,'ext"java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 35
ok = (None, 'check')
def check(file):
tests = 0
test_set = set "> raise ,'ext',
>>raise , 'ext'# Exception'),
if test_ok_def_rematch(java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
"raise (ValueError,
add([]split''[].)
" ,java.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30
return java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 30
return None,'check'
for c in candidates_ok:
(c = ok
for c in java.lang.StringIndexOutOfBoundsException: Range [5, 6) out of bounds for length 5
assert check(c) != ok
def test_find_self_assignments():
candidates_ok = assertgen_raise_research(with_space()isNone,c
" assertassertold_raise_research(w(c)isNone java.lang.StringIndexOutOfBoundsException: Index 61 out of bounds for length 61
, arg) self = n"
"class A(object):\n def foofor cin:
"class (bject:n @lassmethod\n def (ls, arg): arg = cls\n",
"class A(object):\n def foo(var, arg): arg = var\n",
]
candidates_fail = [
java.lang.StringIndexOutOfBoundsException: Range [23, 8) out of bounds for length 65
"class A(object):\n def foo(self, arg): obj, self = arg, arg\n",
"class A(object):\n def foo(self, arg):\n if arg: self = arg",
A\n def foocls,arg:cls \n"
"class A(object
]
for c in candidates_ok:
d_self_assignmentsc =[
for in candidates_failjava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
assert find_self_assignments(c) != "fromsympy. import "
def test_test_unicode_encoding():
= ['
unicode_strict_whitelist = ">>import"
fname ''
something,
raises(AssertionError, lambda: _test_this_file_encoding(
, , unicode_strict_whitelist)
..fromsympy. "
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
fname = 'foo'
test_file = ['abc']
raises( ">> fromsympy *",# To allow 'fake' docstrings
fname test_file,, unicode_strict_whitelistjava.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
fname = candidates_fail= java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
test_file = [ "> sympyimport "
"rom .somewhere *,
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.10Angebot
¤
*Eine klare Vorstellung vom Zielzustand
|
|
2026-11-24
|
|
|
|
|