Merge pull request #1743 from j9ac9k/cleanup-some-static-code-checks

Cleanup some static code checks
This commit is contained in:
Ogi Moore 2021-04-25 22:01:06 -07:00 committed by GitHub
commit 2cbc86bee1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 80 additions and 128 deletions

View File

@ -369,7 +369,8 @@ class ExampleLoader(QtGui.QMainWindow):
return return
if os.path.isdir(fn): if os.path.isdir(fn):
fn = os.path.join(fn, '__main__.py') fn = os.path.join(fn, '__main__.py')
text = open(fn).read() with open(fn, "r") as currentFile:
text = currentFile.read()
self.ui.codeView.setPlainText(text) self.ui.codeView.setPlainText(text)
self.ui.loadedFileLabel.setText(fn) self.ui.loadedFileLabel.setText(fn)
self.codeBtn.hide() self.codeBtn.hide()

View File

@ -172,7 +172,6 @@ def _generateItemSvg(item, nodes=None, root=None, options={}):
## Generate SVG text for just this item (exclude its children; we'll handle them later) ## Generate SVG text for just this item (exclude its children; we'll handle them later)
tr = QtGui.QTransform()
if isinstance(item, QtGui.QGraphicsScene): if isinstance(item, QtGui.QGraphicsScene):
xmlStr = "<g>\n</g>\n" xmlStr = "<g>\n</g>\n"
doc = xml.parseString(xmlStr) doc = xml.parseString(xmlStr)

View File

@ -163,7 +163,6 @@ class RegionSelectNode(CtrlNode):
sliced = data[mask] sliced = data[mask]
else: else:
sliced = None sliced = None
return {'selected': sliced, 'widget': self.items, 'region': region} return {'selected': sliced, 'widget': self.items, 'region': region}

View File

@ -21,6 +21,7 @@ class FillBetweenItem(QtGui.QGraphicsPathItem):
self.updatePath() self.updatePath()
def setBrush(self, *args, **kwds): def setBrush(self, *args, **kwds):
"""Change the fill brush. Acceps the same arguments as pg.mkBrush()"""
QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds)) QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds))
def setPen(self, *args, **kwds): def setPen(self, *args, **kwds):
@ -50,10 +51,6 @@ class FillBetweenItem(QtGui.QGraphicsPathItem):
self.setZValue(min(curve1.zValue(), curve2.zValue())-1) self.setZValue(min(curve1.zValue(), curve2.zValue())-1)
self.curveChanged() self.curveChanged()
def setBrush(self, *args, **kwds):
"""Change the fill brush. Acceps the same arguments as pg.mkBrush()"""
QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds))
def curveChanged(self): def curveChanged(self):
self.updatePath() self.updatePath()

View File

@ -193,8 +193,3 @@ def test_zoom_ratio_with_limits_out_of_range():
assert viewRange[1][0] >= -5 assert viewRange[1][0] >= -5
assert viewRange[1][1] <= 5 assert viewRange[1][1] <= 5
assert viewWidth == 2 * viewHeight assert viewWidth == 2 * viewHeight
if __name__ == "__main__":
setup_module(None)
test_zoom_ratio()

View File

@ -45,7 +45,7 @@ def reloadAll(prefix=None, debug=False):
failed = [] failed = []
changed = [] changed = []
ret = {} ret = {}
for modName, mod in list(sys.modules.items()): ## don't use iteritems; size may change during reload for modName, mod in list(sys.modules.items()):
if not inspect.ismodule(mod): if not inspect.ismodule(mod):
ret[modName] = (False, 'not a module') ret[modName] = (False, 'not a module')
continue continue
@ -331,10 +331,6 @@ if __name__ == '__main__':
btn = Btn() btn = Btn()
except: except:
raise raise
print("Error; skipping Qt tests")
doQtTest = False
import os import os
if not os.path.isdir('test1'): if not os.path.isdir('test1'):

View File

@ -0,0 +1,10 @@
import pytest
import os
import sys
@pytest.fixture
def tmp_module(tmp_path):
module_path = os.fsdecode(tmp_path)
sys.path.insert(0, module_path)
yield module_path
sys.path.remove(module_path)

View File

@ -15,7 +15,13 @@ def test_Vector_init():
# separate values with 3 args # separate values with 3 args
v = pg.Vector(0, 1, 2) v = pg.Vector(0, 1, 2)
assert v.x() == 0
assert v.y() == 1
assert v.z() == 2
v = pg.Vector(0.0, 1.0, 2.0) v = pg.Vector(0.0, 1.0, 2.0)
assert v.x() == 0
assert v.y() == 1
assert v.z() == 2
# all in a list # all in a list
v = pg.Vector([0, 1]) v = pg.Vector([0, 1])

View File

@ -98,19 +98,6 @@ def check_interpolateArray(order):
assert_array_almost_equal(r1, r2) assert_array_almost_equal(r1, r2)
def test_subArray():
a = np.array([0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221, 222, 223, 0, 0, 0, 0])
b = pg.subArray(a, offset=2, shape=(2,2,3), stride=(10,4,1))
c = np.array([[[111,112,113], [121,122,123]], [[211,212,213], [221,222,223]]])
assert np.all(b == c)
# operate over first axis; broadcast over the rest
aa = np.vstack([a, a/100.]).T
cc = np.empty(c.shape + (2,))
cc[..., 0] = c
cc[..., 1] = c / 100.
bb = pg.subArray(aa, offset=2, shape=(2,2,3), stride=(10,4,1))
assert np.all(bb == cc)
def test_subArray(): def test_subArray():
a = np.array([0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221, 222, 223, 0, 0, 0, 0]) a = np.array([0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221, 222, 223, 0, 0, 0, 0])

View File

@ -1,4 +1,4 @@
import tempfile, os, sys, shutil, time import os, sys, shutil, time
import pyqtgraph as pg import pyqtgraph as pg
import pyqtgraph.reload import pyqtgraph.reload
import pytest import pytest
@ -7,21 +7,6 @@ import pytest
pgpath = os.path.join(os.path.dirname(pg.__file__), '..') pgpath = os.path.join(os.path.dirname(pg.__file__), '..')
pgpath_repr = repr(pgpath) pgpath_repr = repr(pgpath)
# make temporary directory to write module code
path = None
def setup_module():
# make temporary directory to write module code
global path
path = tempfile.mkdtemp()
sys.path.insert(0, path)
def teardown_module():
global path
shutil.rmtree(path)
sys.path.remove(path)
code = """ code = """
import sys import sys
sys.path.append({path_repr}) sys.path.append({path_repr})
@ -50,13 +35,13 @@ def remove_cache(mod):
or (sys.version_info >= (3, 10)), or (sys.version_info >= (3, 10)),
reason="Unknown Issue" reason="Unknown Issue"
) )
def test_reload(): @pytest.mark.usefixtures("tmp_module")
py3 = sys.version_info >= (3,) def test_reload(tmp_module):
# write a module # write a module
mod = os.path.join(path, 'reload_test_mod.py') mod = os.path.join(tmp_module, 'reload_test_mod.py')
print("\nRELOAD FILE:", mod) print("\nRELOAD FILE:", mod)
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version1")) with open(mod, "w") as file_:
file_.write(code.format(path_repr=pgpath_repr, msg="C.fn() Version1"))
# import the new module # import the new module
import reload_test_mod import reload_test_mod
@ -64,61 +49,37 @@ def test_reload():
c = reload_test_mod.C() c = reload_test_mod.C()
c.sig.connect(c.fn) c.sig.connect(c.fn)
if py3:
v1 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__) v1 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v1 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
# write again and reload # write again and reload
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version2")) with open(mod, "w") as file_:
file_.write(code.format(path_repr=pgpath_repr, msg="C.fn() Version 2"))
time.sleep(1.1) time.sleep(1.1)
#remove_cache(mod) #remove_cache(mod)
result1 = pg.reload.reloadAll(path, debug=True) _ = pg.reload.reloadAll(tmp_module, debug=True)
if py3:
v2 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__) v2 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v2 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
if not py3:
assert c.fn.im_class is v2[0]
oldcfn = pg.reload.getPreviousVersion(c.fn) oldcfn = pg.reload.getPreviousVersion(c.fn)
if oldcfn is None: if oldcfn is None:
# Function did not reload; are we using pytest's assertion rewriting? # Function did not reload; are we using pytest's assertion rewriting?
raise Exception("Function did not reload. (This can happen when using py.test" raise Exception("Function did not reload. (This can happen when using py.test"
" with assertion rewriting; use --assert=plain for this test.)") " with assertion rewriting; use --assert=plain for this test.)")
if py3:
assert oldcfn.__func__ is v1[2] assert oldcfn.__func__ is v1[2]
else:
assert oldcfn.im_class is v1[0]
assert oldcfn.__func__ is v1[2].__func__
assert oldcfn.__self__ is c assert oldcfn.__self__ is c
# write again and reload # write again and reload
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version2")) with open(mod, "w") as file_:
file_.write(code.format(path_repr=pgpath_repr, msg="C.fn() Version2"))
time.sleep(1.1) time.sleep(1.1)
# remove_cache(mod) # remove_cache(mod)
result2 = pg.reload.reloadAll(path, debug=True) _ = pg.reload.reloadAll(tmp_module, debug=True)
if py3: _ = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
v3 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v3 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
#for i in range(len(old)):
#print id(old[i]), id(new1[i]), id(new2[i]), old[i], new1[i]
cfn1 = pg.reload.getPreviousVersion(c.fn) cfn1 = pg.reload.getPreviousVersion(c.fn)
cfn2 = pg.reload.getPreviousVersion(cfn1) cfn2 = pg.reload.getPreviousVersion(cfn1)
if py3:
assert cfn1.__func__ is v2[2] assert cfn1.__func__ is v2[2]
assert cfn2.__func__ is v1[2] assert cfn2.__func__ is v1[2]
else:
assert cfn1.__func__ is v2[2].__func__
assert cfn2.__func__ is v1[2].__func__
assert cfn1.im_class is v2[0]
assert cfn2.im_class is v1[0]
assert cfn1.__self__ is c assert cfn1.__self__ is c
assert cfn2.__self__ is c assert cfn2.__self__ is c

View File

@ -229,8 +229,6 @@ class EnumColorMapItem(ptree.types.GroupParameter):
vals = opts.get('values', []) vals = opts.get('values', [])
if isinstance(vals, list): if isinstance(vals, list):
vals = OrderedDict([(v,str(v)) for v in vals]) vals = OrderedDict([(v,str(v)) for v in vals])
childs = [{'name': v, 'type': 'color'} for v in vals]
childs = [] childs = []
for val,vname in vals.items(): for val,vname in vals.items():
ch = ptree.Parameter.create(name=vname, type='color') ch = ptree.Parameter.create(name=vname, type='color')

View File

@ -81,7 +81,7 @@ class Build(build.build):
if os.path.isdir(buildPath): if os.path.isdir(buildPath):
distutils.dir_util.remove_tree(buildPath) distutils.dir_util.remove_tree(buildPath)
ret = build.build.run(self) build.build.run(self)
class Install(install.install): class Install(install.install):
@ -110,8 +110,10 @@ class Install(install.install):
try: try:
initfile = os.path.join(path, '__init__.py') initfile = os.path.join(path, '__init__.py')
data = open(initfile, 'r').read() with open(initfile, "r") as file_:
open(initfile, 'w').write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data)) data = file_.read()
with open(initfile, "w") as file_:
file_.write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data))
installVersion = version installVersion = version
except: except:
sys.stderr.write("Warning: Error occurred while setting version string in build path. " sys.stderr.write("Warning: Error occurred while setting version string in build path. "

View File

@ -28,7 +28,8 @@ def generateDebianChangelog(package, logFile, version, maintainer):
current_version = None current_version = None
current_log = None current_log = None
current_date = None current_date = None
for line in open(logFile).readlines(): with open(logFile) as file_:
for line in file_.readlines():
match = re.match(package+r'-(\d+\.\d+\.\d+(\.\d+)?)\s*(\d+-\d+-\d+)\s*$', line) match = re.match(package+r'-(\d+\.\d+\.\d+(\.\d+)?)\s*(\d+-\d+-\d+)\s*$', line)
if match is None: if match is None:
if current_log is not None: if current_log is not None:

View File

@ -7,7 +7,7 @@ import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
from distutils.core import Command from distutils import core
from typing import Dict, Any from typing import Dict, Any
from generateChangelog import generateDebianChangelog from generateChangelog import generateDebianChangelog
@ -149,7 +149,7 @@ def checkStyle():
if os.path.splitext(f)[1] not in ('.py', '.rst'): if os.path.splitext(f)[1] not in ('.py', '.rst'):
continue continue
filename = os.path.join(path, f) filename = os.path.join(path, f)
fh = open(filename, 'U') with open(filename, 'U') as fh:
_ = fh.readlines() _ = fh.readlines()
endings = set( endings = set(
fh.newlines fh.newlines
@ -503,7 +503,7 @@ DEFAULT_ASV: Dict[str, Any] = {
} }
class ASVConfigCommand(Command): class ASVConfigCommand(core.Command):
description = "Setup the ASV benchmarking config for this system" description = "Setup the ASV benchmarking config for this system"
user_options = [] user_options = []
@ -526,7 +526,7 @@ class ASVConfigCommand(Command):
conf_file.write(json.dumps(config, indent=2)) conf_file.write(json.dumps(config, indent=2))
class DebCommand(Command): class DebCommand(core.Command):
description = "build .deb package using `debuild -us -uc`" description = "build .deb package using `debuild -us -uc`"
maintainer = "Luke Campagnola <luke.campagnola@gmail.com>" maintainer = "Luke Campagnola <luke.campagnola@gmail.com>"
debTemplate = "debian" debTemplate = "debian"
@ -584,7 +584,7 @@ class DebCommand(Command):
raise Exception("Error during debuild.") raise Exception("Error during debuild.")
class DebugCommand(Command): class DebugCommand(core.Command):
"""Just for learning about distutils.""" """Just for learning about distutils."""
description = "" description = ""
user_options = [] user_options = []
@ -599,7 +599,7 @@ class DebugCommand(Command):
print(self.distribution.version) print(self.distribution.version)
class TestCommand(Command): class TestCommand(core.Command):
description = "Run all package tests and exit immediately with ", \ description = "Run all package tests and exit immediately with ", \
"informative return code." "informative return code."
user_options = [] user_options = []
@ -614,7 +614,7 @@ class TestCommand(Command):
pass pass
class StyleCommand(Command): class StyleCommand(core.Command):
description = "Check all code for style, exit immediately with ", \ description = "Check all code for style, exit immediately with ", \
"informative return code." "informative return code."
user_options = [] user_options = []
@ -629,7 +629,7 @@ class StyleCommand(Command):
pass pass
class MergeTestCommand(Command): class MergeTestCommand(core.Command):
description = "Run all tests needed to determine whether the current ",\ description = "Run all tests needed to determine whether the current ",\
"code is suitable for merge." "code is suitable for merge."
user_options = [] user_options = []