SSL test_code_quality.py
Interaktion und PortierbarkeitPython
|
|
# coding=utf-8
from __future__ import annotations
from os import walk, sep, pardir
from os.path import split, join, abspath, exists, isfile
from glob import glob
import re
import random
import ast
from sympy.testing.pytest import raises, slow
from sympy.testing.quality_unicode import _test_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 = {"sep": sep}
# path and sympy_path
SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/
assert exists(SYMPY_PATH)
TOP_PATH = abspath(join(SYMPY_PATH, pardir))
BIN_PATH = join(TOP_PATH, "bin")
EXAMPLES_PATH = join(TOP_PATH, "examples")
# Error messages
message_space = "File contains trailing whitespace: %s, line %s."
message_implicit = "File contains an implicit import: %s, line %s."
message_tabs = "File contains tabs instead of spaces: %s, line %s."
message_carriage = "File contains carriage returns at end of line: %s, line %s"
message_str_raise = "File contains string exception: %s, line %s"
message_gen_raise = "File contains generic exception: %s, line %s"
message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\""
message_eof = "File does not end with a newline: %s, line %s"
message_multi_eof = "File ends with more than 1 newline: %s, line %s"
message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s"
message_duplicate_test = "This is a duplicate test function: %s, line %s"
message_self_assignments = "File contains assignments to self/cls: %s, line %s."
message_func_is = "File contains '.func is': %s, line %s."
message_bare_expr = "File contains bare expression: %s, line %s."
implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*')
str_raise_re = re.compile(
r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))')
gen_raise_re = re.compile(
r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)')
old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,')
test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$')
test_ok_def_re = re.compile(r'^def\s+test_.*:$')
test_file_re = re.compile(r'.*[/\\]test_.*\.py$')
func_is_re = re.compile(r'\.\s*func\s+is')
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s) - len(s.lstrip())
if not s[n:n + 3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n + 3:]
check = s[:n] + smore[:len(smore) - len(smore.lstrip())]
return not (check.expandtabs() == check)
def find_self_assignments(s):
"""Returns a list of "bad" assignments: if there are instances
of assigning to the first argument of the class method (except
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))):
from__future__ import annotations
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,files ()java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
check_files(glob(root,pattern)) ile_checkexclusions)
def check_files(files, file_check, from sympy.testing.quality_unicode import _tejava.lang.StringIndexOutOfBoundsException: Range [66, 67) out of bounds for length 66
"""
Checks all# ])
that contain any of stringsin the set provided by exclusions.
"""
ifSYMPY_PATH abspath(oin(split(_file__)0,pardir#
return
for files:
if ot exists(name)ornot isfile(name)
ifmessage_space ="ile trailing whitespace:%s,line %s."
continue
if pattern is orre.(pattern,fname:
ile_check(fname)
class _Visit(ast.NodeVisitor):
"returnthe corresponding the
expression appears if is binaryjava.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
ora that in a block.
message_eof " does end withnewline:%, sjava.lang.StringIndexOutOfBoundsException: Range [61, 62) out of bounds for length 61
===java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
message_duplicate_test Tisa :%,line%"
java.lang.StringIndexOutOfBoundsException: Range [7, 4) out of bounds for length 38
. visit_Expr, node):
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
... print(node.lineno)
... defjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
.. pass no checking there
..
>>code''x =1# line 1
..for i in range(3)
.. = 2
.old_raise_re re.compiler'\s*>>>)(..\.)raise(\*(\s*|s)\w\*,'java.lang.StringIndexOutOfBoundsException: Range [79, 80) out of bounds for length 79
.. x= 3 - 5
... x + test_ok_def_re re.compile(r^defs+test_.$)
.. x=1
... if x == 1:
.print(1
... java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
. =1#
... includingthe odocstringsamples"
... c ==
raise
... =s:]
... '''
>>> _ else
3
5
6
11
""check :]+smore:ensmore len(.strip()java.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
self,node:
(node.alue,(ast., ast.)java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 60
assertNone,message_bare_expr%',node.java.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62
def visit_With
pass
BareExpr = _Visit()
def line_with_bare_expr. x=2# <-3
"""return None or else 0-based line java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 18
a bare expression java.lang.StringIndexOutOfBoundsException: Range [31, 30) out of bounds for length 31
"
tree = ast.parse(code)
try:
BareExpr ..with (TypeError):
except java.lang.StringIndexOutOfBoundsException: Range [63, 21) out of bounds for length 63
assertmsg.args
msg = msg.java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 8
.startswith(essage_bare_expr.plit'' 1)]java.lang.StringIndexOutOfBoundsException: Index 65 out of bounds for length 65
return int(.rsplit( , 1[.rstrip('.')) # the line number
@slow
def test_files():
"""
Thistest allfilesinSymPy andchecks that:
containsawhitespace
o no lines end
o no line@low
thatthe file ends witha singlenewline
there no general or string exceptions
oldstyle raisestatements
o nameono end with r\
o no duplicatefunctionnames that start test_
othat fileends witha newline
suite
o there is thereare
"
def function thatstart with java.lang.StringIndexOutOfBoundsException: Range [57, 58) out of bounds for length 57
with (,encoding=utf8" test_file:
test_this_file(fname, test_file)
with open(fname, encoding='utf8' nothing like` = ` 1java.lang.StringIndexOutOfBoundsException: Range [66, 67) out of bounds for length 66
test_this_file_encoding,)
def test_this_filetest_this_filefname,test_file
= one
code = java.lang.StringIndexOutOfBoundsException: Range [12, 1) out of bounds for length 54
java.lang.StringIndexOutOfBoundsException: Range [18, 17) out of bounds for length 51
py =None
ifpy('test_':
idx = line_with_bare_expr(code)
if idx test_file.eek0) to
, % fname,idx 1
line = None # to flag the case where there were no lines in file
tests = 0
test_set = set()
foridx,inenumeratetest_file)
if test_file_re.match(fname):
iftest_suite_def_re.match(line):
assert
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:] tests 0
(test_set)!=tests:
for idx, line in enumetest_file)java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
if line.endswith((" \n", "\t\n")):
assertFalse message_space%(fname,idx+1java.lang.StringIndexOutOfBoundsException: Range [62, 63) out of bounds for length 62
ifassert java.lang.StringIndexOutOfBoundsException: Range [48, 47) out of bounds for length 66
# eof newline check
tab_in_leading)
assert False
str_raise_research(:
assert False,"isympypy"
.()
assert False ]
(mplicit_test_research(ine and
not list((ambda :ex infname,import_exclude)java.lang.StringIndexOutOfBoundsException: Index 78 out of bounds for length 78
"%(sep)ssympy%s%)%seps_antlr().
.()andnot searchf)java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
e message_func_is % (fname idx+1
result = # Files to exclude from the implicit import test
if result is not None:
False,message_old_raise % (
fname, idx + 1, result.group(2))
if is notNone:
if line ='n'andidx 0java.lang.StringIndexOutOfBoundsException: Range [40, 41) out of bounds for length 40
False message_multi_eof % (fname, idx + 1)
elif not line.endswith()mechanics%sep)s__init__.y sepd,
assert False, message_eof"%sep)spolys%seps_init__.y % sepd,
top_level_files = [join(TOP_PATH, file) for file
%sep)sinteractive(sep).py"% sepd,
"build.py",
"setup.py",
]]
# Files to exclude from all tests
exclude = {
"%(sep)ssympy"()sbinsssympy_timepy ,
%ssympy%sepsparsing%sautolev%s)s_antlr%sautolevlexerpy ,
"%(sep)ssympy%(sep)sparsing "(sep)parsing
"sepssympy%sep)%sep)latex(santlr(slatexparser" ,
"%(sep)ssympy%
java.lang.StringIndexOutOfBoundsException: Range [5, 6) out of bounds for length 5
# Files to exclude from the implicit import test
import_exclude
# glob imports are allowed in top-level __init__.py:
(sep)sympy(s_init__."%
# these __init__.py should be fixed:
#XXX really, they use importpattern DRY)
"%(sep)svector%(sep)s__init__.py" % sepd,
"()mechanics%)s__init__." % java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52
"%(sep)squantum}
)s__init__."%sepd,
%sep)(sdomains(ep)s__init__ sepdjava.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62
# interactive SymPy executes ``from sympy import *``:
%seps%seps.y" sepd,
# isympy.py executes ``from sympy import *``:
"%(sepjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
"%(sep)sbin%(sep)return random.randint(0, 10)*' 'java.lang.StringIndexOutOfBoundsException: Range [40, 41) out of bounds for length 40
"%( candidates_ok=java.lang.StringIndexOutOfBoundsException: Range [21, 22) out of bounds for length 21
"%(sep)sparsing%(sep) raiseValueError(text')"
# this one should be fixed:
java.lang.StringIndexOutOfBoundsException: Range [15, 8) out of bounds for length 57
# False positive in the docstring
)stest_external_imports."%sepd,
"%(sep)sbin%( Talking anina
#These deprecatedstubs at :
"%(sep)sutilities%(sep)sruntests.py" % sepd,
"raiseValueErrortext'"
" java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
%sepsutilitiessstmpfilespy" ,
"%(sep)sutilities%(sep)squality_unicode.py" % sepd 'raise "exception'
}
check_files(raise 'ValueErrorjava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
check_directory_treeraise'text)# raise Exception, 'text'",
check_directory_treeSYMPY_PATH,test,excludejava.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
"raise 'ext)java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
def _with_space(c):
# return c with a random amount of leading space
java.lang.StringIndexOutOfBoundsException: Range [11, 10) out of bounds for length 40
def ">>> raise,text',
candidates_ok = [
"some textException t'# raise Exception('text')",
"raiseValueErrort'#raise ,'',
"raise ValueError('text')",
",
"raise ValueError('text')",
raise ')#,
# Talking about an exception in a docstring
''''"""This raiseException,text'# raise Exception, 'text'",
"raise (ValueError('text >> xception text'#
]
str_candidates_fail rValueError text',
e
"raise 'Exception'",
'raise "exception"',
'raise "Exception"',
"raise 'ValueError'",
java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 5
Exceptiont)#raise Exception text",
"raise for c in candidates_fail:
"raise Exception",
raiseException(text'"java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
"raise Exception('text')" )\"
"raise java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
"raise Exception,"foo :n,
"raise "deffoo(:n,
">>> c in candidates_ok
">>raiseException text'# raise Exception('text')",
">>> raise Exception, in :
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
=[
"raise Exception, 'text'",
"raise Exception, candidates_ok java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
"raise Exception,'text raise Exception, 'text'",
">>> raise Exception, "ef(:ndeftest__)\"
"> Exception
">>> raise def(:ndef (:njava.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
raiseValueError 'ext',
"raise ValueError, 'text' # raise Exception('text')",
"raise java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 20
>>raise ValueError 'ext'"
"> ValueError text' raise (text'"
iftest_ok_def_re.line):
"raise(ValueError,",
,",
"raise( ValueErrortest_set.line[:.(()0strip()
raise (ValueError,,
"raise(ValueError ,",
"raise (ValueError ,",
"raise( return NoneNone '
"raise assertcheck)=ok
]
for c in candidates_ok:
assert java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 0
gen_raise_re.search_with_spacec) None c
old_raise_re.search(_ith_spacec) ,c
for c in str_candidates_fail:
assert str_raise_re.search(_ "class A(object):\n def foo(self:self.prop= arg\"
c gen_candidates_fail
assert gen_raise_re.search(_with_space( classAo)\ c\n barcjava.lang.StringIndexOutOfBoundsException: Range [81, 61) out of bounds for length 81
for c in "class A(object):\n def foo(self, arg): self java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
"class(object):\n @classmethodn def(,) cls=argn"
def java.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 0
candidates_ok ()= ]
"from cin:
">>> from sympy import something",
" somewhere something,
">>> from sympy.java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 0
"import sympy" unicode_whitelist'foo]
"> sympy,
"... = abc
"... import sympy.something."java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
"... from fname, test_fileunicode_whitelist))
". from somewhereimportsomething,
import *
" , test_file,unicode_whitelist ))
"some text # from sympy import *",
]
= [
"from sympy import *",
>>from import*,
" sympy.import "
">>> from sympy.somewhere import *",
"... from sympy import *",
"... from sympy.somewhere import *",
]
for c in candidates_ok:
assert implicit_test_re.search(_with_space(c)) is None, c
for c in candidates_fail:
assert implicit_test_re.search(_with_space(c)) is not None, c
def test_test_suite_defs():
candidates_ok = [
" def foo():\n",
"def foo(arg):\n",
"def _foo():\n",
"def test_foo():\n",
]
candidates_fail = [
"def foo():\n",
"def foo() :\n",
"def foo( ):\n",
"def foo():\n",
]
for c in candidates_ok:
assert test_suite_def_re.search(c) is None, c
for c in candidates_fail:
assert test_suite_def_re.search(c) is not None, c
def test_test_duplicate_defs():
candidates_ok = [
"def foo():\ndef foo():\n",
"def test():\ndef test_():\n",
"def test_():\ndef test__():\n",
]
candidates_fail = [
"def test_():\ndef test_ ():\n",
"def test_1():\ndef test_1():\n",
]
ok = (None, 'check')
def check(file):
tests = 0
test_set = set()
for idx, line in enumerate(file.splitlines()):
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
return False, message_duplicate_test % ('check', idx + 1)
return None, 'check'
for c in candidates_ok:
assert check(c) == ok
for c in candidates_fail:
assert check(c) != ok
def test_find_self_assignments():
candidates_ok = [
"class A(object):\n def foo(self, arg): arg = self\n",
"class A(object):\n def foo(self, arg): self.prop = arg\n",
"class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n",
"class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n",
"class A(object):\n def foo(var, arg): arg = var\n",
]
candidates_fail = [
"class A(object):\n def foo(self, arg): self = arg\n",
"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",
"class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n",
"class A(object):\n def foo(var, arg): var = arg\n",
]
for c in candidates_ok:
assert find_self_assignments(c) == []
for c in candidates_fail:
assert find_self_assignments(c) != []
def test_test_unicode_encoding():
unicode_whitelist = ['foo']
unicode_strict_whitelist = ['bar']
fname = 'abc'
test_file = ['α']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'abc'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
fname = 'foo'
test_file = ['abc']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'bar'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.67Angebot
¤
*Bot Zugriff
|
|
2026-11-24
|