1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
|
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the MIT License
# Copyright (c) 2015 Pierre Raybaut
# (see LICENSE file for more details)
"""
PythonQwt test utilities
------------------------
"""
import argparse
import inspect
import os
import os.path as osp
import platform
import subprocess
import sys
from qtpy import QtCore as QC
from qtpy import QtGui as QG
from qtpy import QtWidgets as QW
import qwt
from qwt import QwtPlot
from qwt import qthelpers as qth
QT_API = os.environ["QT_API"]
if QT_API.startswith("pyside"):
from qtpy import PYSIDE_VERSION
PYTHON_QT_API = "PySide v" + PYSIDE_VERSION
else:
from qtpy import PYQT_VERSION
PYTHON_QT_API = "PyQt v" + PYQT_VERSION
TEST_PATH = osp.abspath(osp.dirname(__file__))
class TestEnvironment:
UNATTENDED_ARG = "unattended"
SCREENSHOTS_ARG = "screenshots"
UNATTENDED_ENV = "PYTHONQWT_UNATTENDED_TESTS"
SCREENSHOTS_ENV = "PYTHONQWT_TAKE_SCREENSHOTS"
def __init__(self):
self.parse_args()
@property
def unattended(self):
return os.environ.get(self.UNATTENDED_ENV) is not None
@property
def screenshots(self):
return os.environ.get(self.SCREENSHOTS_ENV) is not None
def parse_args(self):
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description="Run PythonQwt tests")
parser.add_argument(
"--mode",
choices=[self.UNATTENDED_ARG, self.SCREENSHOTS_ARG],
required=False,
)
args, _unknown = parser.parse_known_args()
if args.mode is not None:
self.set_env_from_args(args)
def set_env_from_args(self, args):
"""Set appropriate environment variables"""
for name in (self.UNATTENDED_ENV, self.SCREENSHOTS_ENV):
if name in os.environ:
os.environ.pop(name)
if args.mode == self.UNATTENDED_ARG:
os.environ[self.UNATTENDED_ENV] = "1"
if args.mode == self.SCREENSHOTS_ARG:
os.environ[self.SCREENSHOTS_ENV] = os.environ[self.UNATTENDED_ENV] = "1"
def get_tests(package):
"""Return list of test filenames"""
test_package_name = "%s.tests" % package.__name__
_temp = __import__(test_package_name)
test_package = sys.modules[test_package_name]
tests = []
test_path = osp.dirname(osp.realpath(test_package.__file__))
for fname in sorted(
[
name
for name in os.listdir(test_path)
if name.endswith((".py", ".pyw")) and not name.startswith(("_", "conftest"))
]
):
module_name = osp.splitext(fname)[0]
_temp = __import__(test_package.__name__, fromlist=[module_name])
module = getattr(_temp, module_name)
if hasattr(module, "SHOW") and module.SHOW:
tests.append(osp.abspath(osp.join(test_path, fname)))
return tests
def run_test(fname, wait=True):
"""Run test"""
os.environ["PYTHONPATH"] = os.pathsep.join(sys.path)
args = " ".join([sys.executable, '"' + fname + '"'])
if TestEnvironment().unattended:
print(" " + args)
(subprocess.call if wait else subprocess.Popen)(args, shell=True)
def run_all_tests(wait=True):
"""Run all PythonQwt tests"""
for fname in get_tests(qwt):
run_test(fname, wait=wait)
def get_lib_versions():
"""Return string containing Python-Qt versions"""
from qtpy.QtCore import __version__ as qt_version
return "Python %s, Qt %s, %s on %s" % (
platform.python_version(),
qt_version,
PYTHON_QT_API,
platform.system(),
)
class TestLauncher(QW.QMainWindow):
"""PythonQwt Test Launcher main window"""
COLUMNS = 5
def __init__(self, parent=None):
super(TestLauncher, self).__init__(parent)
self.setObjectName("TestLauncher")
icon = QG.QIcon(osp.join(TEST_PATH, "data", "PythonQwt.svg"))
self.setWindowIcon(icon)
self.setWindowTitle("PythonQwt %s - Test Launcher" % qwt.__version__)
self.setCentralWidget(QW.QWidget())
self.grid_layout = QW.QGridLayout()
self.centralWidget().setLayout(self.grid_layout)
self.test_nb = None
self.fill_layout()
self.statusBar().show()
self.setStatusTip("Click on any button to run a test")
def get_std_icon(self, name):
"""Return Qt standard icon"""
return self.style().standardIcon(getattr(QW.QStyle, "SP_" + name))
def fill_layout(self):
"""Fill grid layout"""
for fname in get_tests(qwt):
self.add_test(fname)
toolbar = QW.QToolBar(self)
all_act = QW.QAction(self.get_std_icon("DialogYesButton"), "", self)
all_act.setIconText("Run all tests")
all_act.triggered.connect(lambda checked: run_all_tests(wait=False))
folder_act = QW.QAction(self.get_std_icon("DirOpenIcon"), "", self)
folder_act.setIconText("Open tests folder")
def open_test_folder(checked):
return os.startfile(TEST_PATH)
folder_act.triggered.connect(open_test_folder)
about_act = QW.QAction(self.get_std_icon("FileDialogInfoView"), "", self)
about_act.setIconText("About")
about_act.triggered.connect(self.about)
for action in (all_act, folder_act, None, about_act):
if action is None:
toolbar.addSeparator()
else:
toolbar.addAction(action)
toolbar.setToolButtonStyle(QC.Qt.ToolButtonTextBesideIcon)
self.addToolBar(toolbar)
def add_test(self, fname):
"""Add new test"""
if self.test_nb is None:
self.test_nb = 0
self.test_nb += 1
column = (self.test_nb - 1) % self.COLUMNS
row = (self.test_nb - 1) // self.COLUMNS
bname = osp.basename(fname)
button = QW.QToolButton(self)
button.setToolButtonStyle(QC.Qt.ToolButtonTextUnderIcon)
shot = osp.join(
TEST_PATH, "data", bname.replace(".py", ".png").replace("test_", "")
)
if osp.isfile(shot):
button.setIcon(QG.QIcon(shot))
else:
button.setIcon(self.get_std_icon("DialogYesButton"))
button.setText(bname)
button.setToolTip(fname)
button.setIconSize(QC.QSize(130, 80))
button.clicked.connect(lambda checked=None, fname=fname: run_test(fname))
self.grid_layout.addWidget(button, row, column)
def about(self):
"""About test launcher"""
QW.QMessageBox.about(
self,
"About " + self.windowTitle(),
"""<b>%s</b><p>Developped by Pierre Raybaut
<br>Copyright © 2020 Pierre Raybaut
<p>%s"""
% (self.windowTitle(), get_lib_versions()),
)
class TestOptions(QW.QGroupBox):
"""Test options groupbox"""
def __init__(self, parent=None):
super(TestOptions, self).__init__("Test options", parent)
self.setLayout(QW.QFormLayout())
self.hide()
def add_checkbox(self, title, label, slot):
"""Add new checkbox to option panel"""
widget = QW.QCheckBox(label, self)
widget.stateChanged.connect(slot)
self.layout().addRow(title, widget)
self.show()
return widget
class TestCentralWidget(QW.QWidget):
"""Test central widget"""
def __init__(self, widget_name, parent=None):
super(TestCentralWidget, self).__init__(parent)
self.widget_name = widget_name
self.plots = None
self.widget_of_interest = self.parent()
self.setLayout(QW.QVBoxLayout())
self.options = TestOptions(self)
self.add_widget(self.options)
def add_widget(self, widget):
"""Add new sub-widget"""
self.layout().addWidget(widget)
if isinstance(widget, QwtPlot):
self.plots = [widget]
else:
self.plots = widget.findChildren(QwtPlot)
for index, plot in enumerate(self.plots):
plot_name = plot.objectName()
if not plot_name:
plot_name = "Plot #%d" % (index + 1)
widget = self.options.add_checkbox(
plot_name, "Enable new flat style option", plot.setFlatStyle
)
widget.setChecked(plot.flatStyle())
if len(self.plots) == 1:
self.widget_of_interest = self.plots[0]
def take_screenshot(widget):
"""Take screenshot and save it to the data folder"""
bname = (widget.objectName().lower() + ".png").replace("window", "")
bname = bname.replace("plot", "").replace("widget", "")
qth.take_screenshot(widget, osp.join(TEST_PATH, "data", bname), quit=True)
def close_widgets_and_quit() -> None:
"""Close Qt top level widgets and quit Qt event loop"""
QW.QApplication.processEvents()
for widget in QW.QApplication.instance().topLevelWidgets():
assert widget.close()
QC.QTimer.singleShot(0, QW.QApplication.instance().quit)
def test_widget(widget_class, size=None, title=None, options=True):
"""Test widget"""
widget_name = widget_class.__name__
app = QW.QApplication.instance()
if app is None:
app = QW.QApplication([])
test_env = TestEnvironment()
if inspect.signature(widget_class).parameters.get("unattended") is None:
widget = widget_class()
else:
widget = widget_class(unattended=test_env.unattended)
window = widget
if options:
if isinstance(widget, QW.QMainWindow):
widget = window.centralWidget()
widget.setParent(None)
else:
window = QW.QMainWindow()
central_widget = TestCentralWidget(widget_name, parent=window)
central_widget.add_widget(widget)
window.setCentralWidget(central_widget)
widget_of_interest = central_widget.widget_of_interest
else:
widget_of_interest = window
widget_of_interest.setObjectName(widget_name)
if title is None:
title = 'Test "%s" - PythonQwt %s' % (widget_name, qwt.__version__)
window.setWindowTitle(title)
if size is not None:
width, height = size
window.resize(width, height)
window.show()
if test_env.screenshots:
QC.QTimer.singleShot(1000, lambda: take_screenshot(widget_of_interest))
elif test_env.unattended:
QC.QTimer.singleShot(0, close_widgets_and_quit)
if QT_API == "pyside6":
app.exec()
else:
app.exec_()
return app
|