forked from mottosso/Qt.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
392 lines (282 loc) · 10 KB
/
tests.py
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""Tests that run once"""
import io
import os
import sys
import imp
import shutil
import tempfile
import subprocess
from nose.tools import (
assert_raises,
)
PYTHON = sys.version_info[0] # e.g. 2 or 3
self = sys.modules[__name__]
def setup():
"""Module-wide initialisation
This function runs once, followed by teardown() below once
all tests have completed.
"""
self.tempdir = tempfile.mkdtemp()
self.ui_qwidget = os.path.join(self.tempdir, "qwidget.ui")
with io.open(self.ui_qwidget, "w", encoding="utf-8") as f:
f.write(u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>235</width>
<height>149</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
""")
def teardown():
shutil.rmtree(self.tempdir)
def binding(binding):
"""Isolate test to a particular binding
When used, tests inside the if-statement are run independently
with the given binding.
Without this function, a test is run once for each binding.
"""
return os.getenv("QT_PREFERRED_BINDING") == binding
def test_environment():
"""Tests require all bindings to be installed"""
imp.find_module("PySide")
imp.find_module("PySide2")
imp.find_module("PyQt4")
imp.find_module("PyQt5")
def test_load_ui_returntype():
"""load_ui returns an instance of QObject"""
import sys
from Qt import QtWidgets, QtCore, QtCompat
app = QtWidgets.QApplication(sys.argv)
obj = QtCompat.load_ui(self.ui_qwidget)
assert isinstance(obj, QtCore.QObject)
app.exit()
def test_preferred_none():
"""Preferring None shouldn't import anything"""
os.environ["QT_PREFERRED_BINDING"] = "None"
import Qt
assert Qt.__name__ == "Qt", Qt
def test_vendoring():
"""Qt.py may be bundled along with another library/project
Create toy project
from project.vendor import Qt # Absolute
from .vendor import Qt # Relative
project/
vendor/
__init__.py
__init__.py
"""
project = os.path.join(self.tempdir, "myproject")
vendor = os.path.join(project, "vendor")
os.makedirs(vendor)
# Make packages out of folders
with open(os.path.join(project, "__init__.py"), "w") as f:
f.write("from .vendor.Qt import QtWidgets")
with open(os.path.join(vendor, "__init__.py"), "w") as f:
f.write("\n")
# Copy real Qt.py into myproject
shutil.copy(os.path.join(os.path.dirname(__file__), "Qt.py"),
os.path.join(vendor, "Qt.py"))
print("Testing relative import..")
assert subprocess.call(
[sys.executable, "-c", "import myproject"],
cwd=self.tempdir,
stdout=subprocess.PIPE, # With nose process isolation, buffer can
stderr=subprocess.STDOUT, # easily get full and throw an error.
) == 0
print("Testing absolute import..")
assert subprocess.call(
[sys.executable, "-c", "from myproject.vendor.Qt import QtWidgets"],
cwd=self.tempdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) == 0
print("Testing direct import..")
assert subprocess.call(
[sys.executable, "-c", "import myproject.vendor.Qt"],
cwd=self.tempdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) == 0
def test_convert_simple():
"""python -m Qt --convert works in general"""
before = """\
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
QtWidgets.QApplication.translate("uic", "NOT Ok", None, -1))
""".split("\n")
after = """\
from Qt import QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
Qt.QtCompat.translate("uic", "NOT Ok", None, -1))
""".split("\n")
from Qt import QtCompat
assert QtCompat._convert(before) == after, after
def test_convert_idempotency():
"""Converting a converted file produces an identical file"""
before = """\
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
QtWidgets.QApplication.translate("uic", "NOT Ok", None, -1))
"""
after = """\
from Qt import QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
Qt.QtCompat.translate("uic", "NOT Ok", None, -1))
"""
fname = os.path.join(self.tempdir, "idempotency.py")
with open(fname, "w") as f:
f.write(before)
from Qt import QtCompat
os.chdir(self.tempdir)
QtCompat._cli(args=["--convert", "idempotency.py"])
with open(fname) as f:
assert f.read() == after
QtCompat._cli(args=["--convert", "idempotency.py"])
with open(fname) as f:
assert f.read() == after
def test_convert_backup():
"""Converting produces a backup"""
fname = os.path.join(self.tempdir, "idempotency.py")
with open(fname, "w") as f:
f.write("")
from Qt import QtCompat
os.chdir(self.tempdir)
QtCompat._cli(args=["--convert", "idempotency.py"])
assert os.path.exists(
os.path.join(self.tempdir, "%s_backup%s" % os.path.splitext(fname))
)
def test_import_from_qtwidgets():
"""Fix #133, `from Qt.QtWidgets import XXX` works"""
from Qt.QtWidgets import QPushButton
assert QPushButton.__name__ == "QPushButton", QPushButton
def test_i158_qtcore_direct_import():
"""import Qt.QtCore works on all bindings
This addresses issue #158
"""
import Qt.QtCore
assert hasattr(Qt.QtCore, "Signal")
def test_translate_arguments():
"""Arguments of QtCompat.translate are correct
QtCompat.translate is a shim over the PySide, PyQt4 and PyQt5
equivalent with an interface like the one found in PySide2.
Reference: https://doc.qt.io/qt-5/qcoreapplication.html#translate
"""
import Qt
# This will run on each binding
result = Qt.QtCompat.translate("CustomDialog", # context
"Status", # sourceText
None, # disambiguation
-1) # n
assert result == u'Status', result
def test_binding_and_qt_version():
"""Qt's __binding_version__ and __qt_version__ populated"""
import Qt
assert Qt.__binding_version__ != "0.0.0", ("Binding version was not "
"populated")
assert Qt.__qt_version__ != "0.0.0", ("Qt version was not populated")
def test_strict():
"""QT_STRICT exposes only a subset of PySide2"""
os.environ["QT_STRICT"] = "1"
from Qt import QtGui
assert not hasattr(QtGui, "QWidget")
def test_cli():
"""Qt.py is available from the command-line"""
os.environ.pop("QT_VERBOSE")
popen = subprocess.Popen([sys.executable, "Qt.py", "--help"],
stdout=subprocess.PIPE)
out, err = popen.communicate()
assert out.startswith(b"usage: Qt.py")
if binding("PyQt4"):
def test_preferred_pyqt4():
"""QT_PREFERRED_BINDING = PyQt4 properly forces the binding"""
import Qt
assert Qt.__binding__ == "PyQt4", (
"PyQt4 should have been picked, "
"instead got %s" % Qt.__binding__)
def test_sip_api_qtpy():
"""Preferred binding PyQt4 should have sip version 2"""
__import__("Qt") # Bypass linter warning
import sip
assert sip.getapi("QString") == 2, (
"PyQt4 API version should be 2, "
"instead is %s" % sip.getapi("QString"))
if PYTHON == 2:
def test_sip_api_already_set():
"""Raise ImportError if sip API v1 was already set"""
__import__("PyQt4.QtCore") # Bypass linter warning
import sip
sip.setapi("QString", 1)
assert_raises(ImportError, __import__, "Qt")
if binding("PyQt5"):
def test_preferred_pyqt5():
"""QT_PREFERRED_BINDING = PyQt5 properly forces the binding"""
import Qt
assert Qt.__binding__ == "PyQt5", (
"PyQt5 should have been picked, "
"instead got %s" % Qt.__binding__)
if binding("PySide"):
def test_preferred_pyside():
"""QT_PREFERRED_BINDING = PySide properly forces the binding"""
import Qt
assert Qt.__binding__ == "PySide", (
"PySide should have been picked, "
"instead got %s" % Qt.__binding__)
if binding("PySide2"):
def test_preferred_pyside2():
"""QT_PREFERRED_BINDING = PySide2 properly forces the binding"""
import Qt
assert Qt.__binding__ == "PySide2", (
"PySide2 should have been picked, "
"instead got %s" % Qt.__binding__)
def test_coexistence():
"""Qt.py may be use alongside the actual binding"""
from Qt import QtCore
import PySide.QtGui
# Qt remaps QStringListModel
assert QtCore.QStringListModel
# But does not delete the original
assert PySide.QtGui.QStringListModel
if binding("PySide") or binding("PySide2"):
def test_multiple_preferred():
"""QT_PREFERRED_BINDING = more than one binding excludes others"""
# PySide is the more desirable binding
os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(
["PySide", "PySide2"])
import Qt
assert Qt.__binding__ == "PySide", (
"PySide should have been picked, "
"instead got %s" % Qt.__binding__)