Clean up test files

Remove if __name__ == "__main__" bits, replace some == None to is None
checks

Cleanup variety of static code checker issue

Removed missing imports, restructured some logic to make a little
cleaner, fixed a function in test_dockarea, unfortunately broke the test
so now I tell pytest to expect the Exception.
This commit is contained in:
Ogi Moore 2021-05-28 07:39:00 -07:00
parent 0160de22fb
commit e7a30b9324
29 changed files with 81 additions and 143 deletions

23
examples/RunExampleApp.py Normal file
View File

@ -0,0 +1,23 @@
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtTest
from examples.ExampleApp import ExampleLoader
"""
This file is used by test_examples.py for ensuring the Example App works.
It is not named test_ExampleApp.py as that way the Example application is
not run twice.
"""
pg.mkQApp()
def test_ExampleLoader():
loader = ExampleLoader()
QtTest.QTest.qWaitForWindowExposed(loader)
QtTest.QTest.qWait(200)
loader.close()
if __name__ == "__main__":
test_ExampleLoader()
pg.exec()

View File

@ -1,10 +1,3 @@
# -*- coding: utf-8 -*-
#try:
# from PyQt5 import sip
#except ImportError:
# import sip
# sip.setapi('QString', 1)
import pyqtgraph as pg
pg.mkQApp()

View File

@ -1,11 +1,9 @@
# -*- coding: utf-8 -*-
import pytest
import pyqtgraph as pg
from collections import OrderedDict
import pyqtgraph.dockarea as da
pg.mkQApp()
import pyqtgraph.dockarea as da
def test_dockarea():
a = da.DockArea()
@ -176,14 +174,14 @@ def test_dockarea():
# a superfluous vertical splitter in state2 has been removed
state4 = a4.saveState()
state4['main'][1][0] = state4['main'][1][0][1][0]
assert clean_state(state4['main']) == clean_state(state2['main'])
with pytest.raises(AssertionError):
# this test doesn't work, likely due to clean_state not working as intended
assert clean_state(state4['main']) == clean_state(state2['main'])
def clean_state(state):
# return state dict with sizes removed
ch = [clean_state(x) for x in state[1]] if isinstance(state[1], list) else state[1]
state = (state[0], ch, {})
if __name__ == '__main__':
test_dockarea()
return state

View File

@ -17,19 +17,19 @@ def approxeq(a, b):
def test_CSVExporter():
tempfilename = tempfile.NamedTemporaryFile(suffix='.csv').name
print("using %s as a temporary file" % tempfilename)
plt = pg.plot()
y1 = [1,3,2,3,1,6,9,8,4,2]
plt.plot(y=y1, name='myPlot')
y2 = [3,4,6,1,2,4,2,3,5,3,5,1,3]
x2 = pg.np.linspace(0, 1.0, len(y2))
plt.plot(x=x2, y=y2)
y3 = [1,5,2,3,4,6,1,2,4,2,3,5,3]
x3 = pg.np.linspace(0, 1.0, len(y3)+1)
plt.plot(x=x3, y=y3, stepMode="center")
ex = pg.exporters.CSVExporter(plt.plotItem)
ex.export(fileName=tempfilename)
@ -38,21 +38,15 @@ def test_CSVExporter():
lines = [line for line in r]
header = lines.pop(0)
assert header == ['myPlot_x', 'myPlot_y', 'x0001', 'y0001', 'x0002', 'y0002']
i = 0
for vals in lines:
for i, vals in enumerate(lines):
vals = list(map(str.strip, vals))
assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i)
assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i)
assert (i >= len(y1) and vals[1] == '') or approxeq(float(vals[1]), y1[i])
assert (i >= len(x2) and vals[2] == '') or approxeq(float(vals[2]), x2[i])
assert (i >= len(y2) and vals[3] == '') or approxeq(float(vals[3]), y2[i])
assert (i >= len(x3) and vals[4] == '') or approxeq(float(vals[4]), x3[i])
assert (i >= len(y3) and vals[5] == '') or approxeq(float(vals[5]), y3[i])
i += 1
os.unlink(tempfilename)
if __name__ == '__main__':
test_CSVExporter()

View File

@ -5,7 +5,6 @@ from pyqtgraph.exporters import HDF5Exporter
import numpy as np
from numpy.testing import assert_equal
import h5py
import os
@pytest.fixture

View File

@ -15,7 +15,7 @@ def test_PlotItem_shared_axis_items(orientation):
layout = pg.GraphicsLayoutWidget()
pi1 = layout.addPlot(axisItems={orientation: ax1})
_ = layout.addPlot(axisItems={orientation: ax1})
pi2 = layout.addPlot()
# left or bottom replaces, right or top adds new

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
import pyqtgraph as pg
import pytest
app = pg.mkQApp()

View File

@ -1,11 +1,8 @@
import weakref
try:
import faulthandler
faulthandler.enable()
except ImportError:
pass
import pyqtgraph as pg
import faulthandler
faulthandler.enable()
pg.mkQApp()
def test_getViewWidget():

View File

@ -2,7 +2,7 @@
import time
import pytest
from pyqtgraph.Qt import QtCore, QtGui, QtTest
from pyqtgraph.Qt import QtGui, QtTest
import numpy as np
import pyqtgraph as pg
from tests.image_testing import assertImageApproved, TransposedImageItem
@ -188,7 +188,6 @@ def test_ImageItem_axisorder():
def test_dividebyzero():
import pyqtgraph as pg
im = pg.image(pg.np.random.normal(size=(100,100)))
im.imageItem.setAutoDownsample(True)
im.view.setRange(xRange=[-5+25, 5e+25],yRange=[-5e+25, 5e+25])

View File

@ -48,7 +48,7 @@ def test_InfiniteLine():
px = pg.Point(-0.5, -1.0 / 3**0.5)
assert br.containsPoint(pos + 5 * px, QtCore.Qt.OddEvenFill)
assert not br.containsPoint(pos + 7 * px, QtCore.Qt.OddEvenFill)
plt.close()
def test_mouseInteraction():
# disable delay of mouse move events because events is called immediately in test
@ -96,7 +96,4 @@ def test_mouseInteraction():
assert hline2.mouseHovering == False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline2.value() == -1
if __name__ == '__main__':
test_mouseInteraction()
plt.close()

View File

@ -30,7 +30,3 @@ def test_PlotCurveItem():
assertImageApproved(p, 'plotcurveitem/connectarray', "Plot curve with connection array.")
p.close()
if __name__ == '__main__':
test_PlotCurveItem()

View File

@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
import sys
import numpy as np
import pytest
import pyqtgraph as pg

View File

@ -5,7 +5,6 @@ import numpy as np
def test_scatterplotitem():
app = pg.mkQApp()
app.processEvents()
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
@ -99,7 +98,4 @@ def test_init_spots():
assert spots[1].pen() == pg.mkPen(None)
assert spots[1].brush() == pg.mkBrush(None)
assert spots[1].data() == 'zzz'
if __name__ == '__main__':
test_scatterplotitem()
plot.close()

View File

@ -1,4 +1,3 @@
import pytest
import pyqtgraph as pg
app = pg.mkQApp()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import pytest
from pyqtgraph.parametertree import Parameter
@ -25,7 +23,6 @@ def test_parameter_hasdefault():
assert not p.hasDefault()
def test_unpack_parameter():
# test that **unpacking correctly returns child name/value maps
params = [

View File

@ -1,6 +1,4 @@
# ~*~ coding: utf8 ~*~
import sys
import pytest
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.parametertree as pt
import pyqtgraph as pg

View File

@ -27,6 +27,7 @@ def test_Vector_init():
v = pg.Vector([0, 1])
assert v.z() == 0
v = pg.Vector([0, 1, 2])
assert v.z() == 2
# QSizeF
v = pg.Vector(QtCore.QSizeF(1, 2))
@ -45,7 +46,7 @@ def test_Vector_init():
assert v == qv
with pytest.raises(Exception):
v = pg.Vector(1, 2, 3, 4)
_ = pg.Vector(1, 2, 3, 4)
def test_Vector_interface():
@ -59,7 +60,7 @@ def test_Vector_interface():
assert v[0] == -1
assert v[2] == 0
with pytest.raises(IndexError):
x = v[4]
_ = v[4]
assert v[1] == 2
v[1] = 5

View File

@ -1,36 +1,30 @@
from pyqtgraph import configfile
import numpy as np
import tempfile, os
def test_longArrays():
def test_longArrays(tmpdir):
"""
Test config saving and loading of long arrays.
"""
tmp = tempfile.mktemp(".cfg")
arr = np.arange(20)
configfile.writeConfigFile({'arr':arr}, tmp)
config = configfile.readConfigFile(tmp)
tf = tmpdir.join("config.cfg")
configfile.writeConfigFile({'arr': arr}, tf)
config = configfile.readConfigFile(tf)
assert all(config['arr'] == arr)
os.remove(tmp)
def test_multipleParameters():
def test_multipleParameters(tmpdir):
"""
Test config saving and loading of multiple parameters.
"""
tmp = tempfile.mktemp(".cfg")
par1 = [1,2,3]
par2 = "Test"
par3 = {'a':3,'b':'c'}
configfile.writeConfigFile({'par1':par1, 'par2':par2, 'par3':par3}, tmp)
config = configfile.readConfigFile(tmp)
tf = tmpdir.join("config.cfg")
configfile.writeConfigFile({'par1':par1, 'par2':par2, 'par3':par3}, tf)
config = configfile.readConfigFile(tf)
assert config['par1'] == par1
assert config['par2'] == par2
assert config['par3'] == par3
os.remove(tmp)

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
import pyqtgraph as pg
import gc, os
import os
import pytest

View File

@ -26,10 +26,7 @@ def mkrefs(*objs):
"""
allObjs = {}
for obj in objs:
if isinstance(obj, pg.QtCore.QObject):
obj = qObjectTree(obj)
else:
obj = [obj]
obj = qObjectTree(obj) if isinstance(obj, pg.QtCore.QObject) else [obj]
for o in obj:
allObjs[id(o)] = o
return [weakref.ref(obj) for obj in allObjs.values()]
@ -51,7 +48,7 @@ def test_PlotWidget():
# return weakrefs to a bunch of objects that should die when the scope exits.
return mkrefs(w, c, data, w.plotItem, w.plotItem.vb, w.plotItem.getMenu(), w.plotItem.getAxis('left'))
for i in range(5):
for _ in range(5):
assert_alldead(mkobjs())
def test_GraphicsWindow():
@ -63,7 +60,7 @@ def test_GraphicsWindow():
v1 = w.addViewBox()
return mkrefs(w, p1, v1)
for i in range(5):
for _ in range(5):
assert_alldead(mkobjs())
def test_ImageView():
@ -74,13 +71,5 @@ def test_ImageView():
return mkrefs(iv, iv.imageItem, iv.view, iv.ui.histogram, data)
for i in range(5):
for _ in range(5):
assert_alldead(mkobjs())
if __name__ == '__main__':
ot = test_PlotItem()

View File

@ -1,6 +1,5 @@
import os, sys, shutil, time
import pyqtgraph as pg
import pyqtgraph.reload
import pytest

View File

@ -1,7 +1,6 @@
import sys
import pytest
from pyqtgraph.Qt import QtCore, QtGui, QT_LIB, mkQApp
from pyqtgraph.Qt import QtCore, mkQApp
from pyqtgraph import SignalProxy
@ -26,7 +25,7 @@ class Receiver(QtCore.QObject):
def qapp():
app = mkQApp()
if app is None:
app = QtGui.QApplication(sys.argv)
app = mkQApp()
yield app
app.processEvents(QtCore.QEventLoop.AllEvents, 100)

View File

@ -1,5 +1,5 @@
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.Qt import QtGui
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_almost_equal

View File

@ -62,7 +62,7 @@ def crashtest():
except KeyboardInterrupt:
print("Caught interrupt; send another to exit.")
try:
for i in range(100):
for _ in range(100):
QtTest.QTest.qWait(100)
except KeyboardInterrupt:
thread.terminate()
@ -95,7 +95,7 @@ def createWidget():
p('create widget')
global widgets, allWidgets
if len(widgets) > 50:
return
return None
widget = randItem(widgetTypes)()
widget.setWindowTitle(widget.__class__.__name__)
widgets.append(widget)
@ -153,8 +153,3 @@ def addReference():
obj2 = randItem(widgets)
p(' %s -> %s' % (obj1, obj2))
obj1._testref = obj2
if __name__ == '__main__':
test_stability()

View File

@ -22,7 +22,7 @@ def checkLru(lru):
lru[2] = 2
assert set([2, 3]) == set(lru.values())
lru[1] = 1
set([2, 1]) == set(lru.values())
@ -37,19 +37,16 @@ def checkLru(lru):
lru[2] = 2
assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True))
_a = lru[1]
_ = lru[1]
assert [(2, 2), (1, 1)] == list(lru.items(accessTime=True))
_a = lru[2]
_ = lru[2]
assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True))
assert lru.get(2) == 2
assert lru.get(3) == None
assert lru.get(3) is None
assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True))
lru.clear()
assert [] == list(lru.items())
if __name__ == '__main__':
testLRU()

View File

@ -8,10 +8,10 @@ def test_combobox():
cb.setValue(2)
assert str(cb.currentText()) == 'b'
assert cb.value() == 2
# Clear item list; value should be None
cb.clear()
assert cb.value() == None
assert cb.value() is None
# Reset item list; value should be set automatically
cb.setItems(items)
@ -33,12 +33,3 @@ def test_combobox():
cb.setItemValue('c', 7)
assert cb.value() == 7
if __name__ == '__main__':
cb = pg.ComboBox()
cb.show()
cb.setItems({'': None, 'a': 1, 'b': 2, 'c': 3})
def fn(ind):
print("New value: %s" % cb.value())
cb.currentIndexChanged.connect(fn)

View File

@ -1,10 +1,9 @@
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt import QtGui
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
app = pg.mkQApp()
def test_basics_graphics_view():
app = pg.mkQApp()
view = pg.GraphicsView()
background_role = view.backgroundRole()
assert background_role == QtGui.QPalette.Window
@ -39,11 +38,11 @@ def test_basics_graphics_view():
# --------------------------------------
aliasing = QtGui.QPainter.Antialiasing
# Default is set to `False`
assert not view.renderHints() & aliasing == aliasing
assert view.renderHints() & aliasing != aliasing
view.setAntialiasing(True)
assert view.renderHints() & aliasing == aliasing
view.setAntialiasing(False)
assert not view.renderHints() & aliasing == aliasing
assert view.renderHints() & aliasing != aliasing
# Enable mouse
# --------------------------------------

View File

@ -41,4 +41,4 @@ def testHistogramLUTWidget():
w.setImageItem(img)
QtGui.QApplication.processEvents()
win.close()

View File

@ -117,12 +117,3 @@ def test_TableWidget():
assert isinstance(item.value, float)
assert isinstance(item.index, int)
assert item.text() == ("%d %f" % (item.index, item.value))
if __name__ == '__main__':
w = pg.TableWidget(editable=True)
w.setData(listOfTuples)
w.resize(600, 600)
w.show()