forked from mottosso/Qt.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1400 lines (1083 loc) · 38.7 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
"""Tests that run once"""
import io
import os
import sys
import imp
import shutil
import tempfile
import subprocess
import contextlib
import datetime
import json
# Third-party dependency
import six
try:
# Try importing assert_raises from nose.tools
from nose.tools import assert_raises
except ImportError:
# Fallback: Define assert_raises using unittest if the import fails
import unittest
def assert_raises(expected_exception, callable_obj=None, *args, **kwargs):
"""
Custom implementation of assert_raises using unittest.
Parameters:
- expected_exception: The exception type that is expected to be raised.
- callable_obj: The callable object that is expected to raise the exception.
- *args, **kwargs: Arguments and keyword arguments to pass to the callable object.
Usage example:
with assert_raises(SomeException):
function_that_raises_some_exception()
"""
context = unittest.TestCase().assertRaises(expected_exception)
# If callable_obj is provided, directly call the function with the context manager
if callable_obj:
with context:
callable_obj(*args, **kwargs)
else:
# Otherwise, return the context manager to be used with a 'with' statement
return context
PYTHON = sys.version_info[0] # e.g. 2 or 3
try:
long
except NameError:
# Python 3 compatibility
long = int
def _pyside2_commit_date():
"""Return the commit date of PySide2"""
import PySide2
if hasattr(PySide2, '__build_commit_date__'):
commit_date = PySide2.__build_commit_date__
datetime_object = datetime.datetime.strptime(
commit_date[: commit_date.rfind('+')], '%Y-%m-%dT%H:%M:%S'
)
return datetime_object
else:
# Returns None if no __build_commit_date__ is available
return None
@contextlib.contextmanager
def captured_output():
new_out, new_err = six.StringIO(), six.StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
def CustomWidget(parent=None):
"""
Wrap CustomWidget class into a function to avoid global Qt import
"""
from Qt import QtWidgets
class Widget(QtWidgets.QWidget):
pass
return Widget(parent)
self = sys.modules[__name__]
qwidget_ui = 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>507</width>
<height>394</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>
<item row="1" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLineEdit" name="lineEdit_2"/>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>lineEdit</sender>
<signal>textChanged(QString)</signal>
<receiver>label</receiver>
<slot>setText(QString)</slot>
<hints>
<hint type="sourcelabel">
<x>228</x>
<y>23</y>
</hint>
<hint type="destinationlabel">
<x>37</x>
<y>197</y>
</hint>
</hints>
</connection>
</connections>
</ui>
"""
qmainwindow_ui = u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>238</width>
<height>44</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
"""
qdialog_ui = u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>186</width>
<height>38</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
"""
qdockwidget_ui = u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DockWidget</class>
<widget class="QDockWidget" name="DockWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>169</width>
<height>60</height>
</rect>
</property>
<property name="windowTitle">
<string>DockWidget</string>
</property>
<widget class="QWidget" name="dockWidgetContents">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
"""
qcustomwidget_ui = u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>238</width>
<height>44</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="CustomWidget" name="customwidget">
</widget>
</widget>
<customwidgets>
<customwidget>
<class>CustomWidget</class>
<extends>QWidget</extends>
<header>tests.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
"""
qpycustomwidget_ui = u"""\
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>238</width>
<height>44</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="CustomWidget" name="customwidget">
</widget>
</widget>
<customwidgets>
<customwidget>
<class>CustomWidget</class>
<extends>QWidget</extends>
<header>custom.customwidget.customwidget</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
"""
python_custom_widget = u'''
def CustomWidget(parent=None):
"""
Wrap CustomWidget class into a function to avoid global Qt import
"""
from Qt import QtWidgets
class Widget(QtWidgets.QWidget):
pass
return Widget(parent)
'''
def setup():
"""Module-wide initialisation
This function runs once, followed by teardown() below once
all tests have completed.
"""
self.tempdir = tempfile.mkdtemp()
def saveUiFile(filename, ui_template):
filename = os.path.join(self.tempdir, filename)
with io.open(filename, "w", encoding="utf-8") as f:
f.write(ui_template)
return filename
self.ui_qwidget = saveUiFile("qwidget.ui", qwidget_ui)
self.ui_qmainwindow = saveUiFile("qmainwindow.ui", qmainwindow_ui)
self.ui_qdialog = saveUiFile("qdialog.ui", qdialog_ui)
self.ui_qdockwidget = saveUiFile("qdockwidget.ui", qdockwidget_ui)
self.ui_qpycustomwidget = saveUiFile("qcustomwidget.ui", qcustomwidget_ui)
def setUpModule():
"""Module-wide initialisation
This function runs once, followed by tearDownModule() below once
all tests have completed.
"""
setup()
def teardown():
shutil.rmtree(self.tempdir)
def tearDownModule():
teardown()
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
@contextlib.contextmanager
def ignoreQtMessageHandler(msgs):
"""A context that ignores specific qMessages for all bindings
Args:
msgs: list of message strings to ignore
"""
from Qt import QtCompat
def messageOutputHandler(msgType, logContext, msg):
if msg in msgs:
return
sys.stderr.write("{0}\n".format(msg))
QtCompat.qInstallMessageHandler(messageOutputHandler)
try:
yield
finally:
QtCompat.qInstallMessageHandler(None)
def test_environment():
"""Tests require all bindings to be installed (except PySide on py3.5+)"""
if sys.version_info < (3, 5):
# PySide is not available for Python > 3.4
imp.find_module("PySide")
elif os.environ.get("QT_PREFERRED_BINDING") == "PySide6":
imp.find_module("PySide6")
else:
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
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
obj = QtCompat.loadUi(self.ui_qwidget)
assert isinstance(obj, QtCore.QObject)
app.exit()
def test_load_ui_baseinstance():
"""Tests to see if the baseinstance loading loads a QWidget on properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QWidget()
QtCompat.loadUi(self.ui_qwidget, win)
assert hasattr(win, 'lineEdit'), "loadUi could not load instance to win"
app.exit()
def test_load_ui_signals():
"""Tests to see if the baseinstance connects signals properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QWidget()
QtCompat.loadUi(self.ui_qwidget, win)
win.lineEdit.setText('Hello')
assert str(win.label.text()) == 'Hello', "lineEdit signal did not fire"
app.exit()
def test_load_ui_mainwindow():
"""Tests to see if the baseinstance loading loads a QMainWindow properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QMainWindow()
QtCompat.loadUi(self.ui_qmainwindow, win)
assert hasattr(win, 'lineEdit'), \
"loadUi could not load instance to main window"
app.exit()
def test_load_ui_dialog():
"""Tests to see if the baseinstance loading loads a QDialog properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QDialog()
QtCompat.loadUi(self.ui_qdialog, win)
assert hasattr(win, 'lineEdit'), \
"loadUi could not load instance to main window"
app.exit()
def test_load_ui_dockwidget():
"""Tests to see if the baseinstance loading loads a QDockWidget properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QDockWidget()
QtCompat.loadUi(self.ui_qdockwidget, win)
assert hasattr(win, 'lineEdit'), \
"loadUi could not load instance to main window"
app.exit()
def test_load_ui_customwidget():
"""Tests to see if loadUi loads a custom widget properly"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QMainWindow()
QtCompat.loadUi(self.ui_qpycustomwidget, win)
# Ensure that the derived class was properly created
# and not the base class (in case of failure)
custom_class_name = getattr(win, "customwidget", None).__class__.__name__
excepted_class_name = CustomWidget(win).__class__.__name__
assert custom_class_name == excepted_class_name, \
"loadUi could not load custom widget to main window"
app.exit()
def test_load_ui_pycustomwidget():
"""Tests to see if loadUi loads a custom widget properly"""
import sys
from Qt import QtWidgets, QtCompat
# create a python file for the custom widget in a directory relative to the tempdir
filename = os.path.join(
self.tempdir,
"custom",
"customwidget",
"customwidget.py"
)
os.makedirs(os.path.dirname(filename))
with io.open(filename, "w", encoding="utf-8") as f:
f.write(self.python_custom_widget)
# Python 2.7 requires that each folder be a package
with io.open(os.path.join(self.tempdir, "custom/__init__.py"), "w", encoding="utf-8") as f:
f.write(u"")
with io.open(os.path.join(self.tempdir, "custom/customwidget/__init__.py"), "w", encoding="utf-8") as f:
f.write(u"")
# append the path to ensure the future import can be loaded 'relative' to the tempdir
sys.path.append(self.tempdir)
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QMainWindow()
QtCompat.loadUi(self.ui_qpycustomwidget, win)
# Ensure that the derived class was properly created
# and not the base class (in case of failure)
custom_class_name = getattr(win, "customwidget", None).__class__.__name__
excepted_class_name = CustomWidget(win).__class__.__name__
assert custom_class_name == excepted_class_name, \
"loadUi could not load custom widget to main window"
app.exit()
def test_load_ui_invalidpath():
"""Tests to see if loadUi successfully fails on invalid paths"""
import sys
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
assert_raises(IOError, QtCompat.loadUi, 'made/up/path')
app.exit()
def test_load_ui_invalidxml():
"""Tests to see if loadUi successfully fails on invalid ui files"""
import sys
invalid_xml = os.path.join(self.tempdir, "invalid.ui")
with io.open(invalid_xml, "w", encoding="utf-8") as f:
f.write(u"""
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0" garbage
</ui>
""")
from xml.etree import ElementTree
from Qt import QtWidgets, QtCompat
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
assert_raises(ElementTree.ParseError, QtCompat.loadUi, invalid_xml)
app.exit()
def test_load_ui_existingLayoutOnDialog():
"""Tests to see if loading a ui onto a layout in a Dialog works"""
import sys
from Qt import QtWidgets, QtCompat
msgs = 'QLayout: Attempting to add QLayout "" to QDialog ' \
'"Dialog", which already has a layout'
with ignoreQtMessageHandler([msgs]):
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QDialog()
QtWidgets.QComboBox(win)
QtWidgets.QHBoxLayout(win)
QtCompat.loadUi(self.ui_qdialog, win)
app.exit()
def test_load_ui_existingLayoutOnMainWindow():
"""Tests to see if loading a ui onto a layout in a MainWindow works"""
import sys
from Qt import QtWidgets, QtCompat
msgs = 'QLayout: Attempting to add QLayout "" to QMainWindow ' \
'"", which already has a layout'
with ignoreQtMessageHandler([msgs]):
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QMainWindow()
QtWidgets.QComboBox(win)
QtWidgets.QHBoxLayout(win)
QtCompat.loadUi(self.ui_qmainwindow, win)
app.exit()
def test_load_ui_existingLayoutOnDockWidget():
"""Tests to see if loading a ui onto a layout in a DockWidget works"""
import sys
from Qt import QtWidgets, QtCompat
msgs = 'QLayout: Attempting to add QLayout "" to QDockWidget ' \
'"", which already has a layout'
with ignoreQtMessageHandler([msgs]):
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QDockWidget()
QtWidgets.QComboBox(win)
QtWidgets.QHBoxLayout(win)
QtCompat.loadUi(self.ui_qdockwidget, win)
app.exit()
def test_load_ui_existingLayoutOnWidget():
"""Tests to see if loading a ui onto a layout in a Widget works"""
import sys
from Qt import QtWidgets, QtCompat
msgs = 'QLayout: Attempting to add QLayout "" to QWidget ' \
'"Form", which already has a layout'
with ignoreQtMessageHandler([msgs]):
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
win = QtWidgets.QWidget()
QtWidgets.QComboBox(win)
QtWidgets.QHBoxLayout(win)
QtCompat.loadUi(self.ui_qwidget, win)
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"))
# Copy real Qt.py into the root folder
shutil.copy(os.path.join(os.path.dirname(__file__), "Qt.py"),
os.path.join(self.tempdir, "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
#
# Test invalid json data
print("Testing invalid json data..")
env = os.environ.copy()
env["QT_PREFERRED_BINDING_JSON"] = '{"Qt":["PyQt5","PyQt4"],}'
cmd = "import myproject.vendor.Qt;"
cmd += "import Qt;"
cmd += "assert myproject.vendor.Qt.__binding__ != None, 'vendor';"
cmd += "assert Qt.__binding__ != None, 'Qt';"
popen = subprocess.Popen(
[sys.executable, "-c", cmd],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.tempdir,
env=env
)
out, err = popen.communicate()
if popen.returncode != 0:
print(out)
msg = "An exception was raised"
assert popen.returncode == 0, msg
error_check = b"Qt.py [warning]:"
assert err.startswith(error_check), err
print('out------------------')
print(out)
print('err ------------------')
print(err)
# Check QT_PREFERRED_BINDING_JSON works as expected
print("Testing QT_PREFERRED_BINDING_JSON is respected..")
cmd = "import myproject.vendor.Qt;"
# Check that the "None" binding was set for `import myproject.vendor.Qt`
cmd += "assert myproject.vendor.Qt.__binding__ == 'None', 'vendor';"
cmd += "import Qt;"
# Check that the "None" binding was not set for `import Qt`.
# This should be PyQt5 or PyQt4 depending on the test environment.
cmd += "assert Qt.__binding__ != 'None', 'Qt'"
# If the module name is "Qt" use PyQt5 or PyQt4, otherwise use None binding
env = os.environ.copy()
env["QT_PREFERRED_BINDING_JSON"] = json.dumps(
{
"Qt": ["PySide6", "PyQt5", "PyQt4"],
"default": ["None"]
}
)
assert subprocess.call(
[sys.executable, "-c", cmd],
stdout=subprocess.PIPE,
cwd=self.tempdir,
env=env
) == 0
print("Testing QT_PREFERRED_BINDING_JSON and QT_PREFERRED_BINDING work..")
env["QT_PREFERRED_BINDING_JSON"] = '{"Qt":["PySide6","PyQt5","PyQt4"]}'
env["QT_PREFERRED_BINDING"] = "None"
assert subprocess.call(
[sys.executable, "-c", cmd],
stdout=subprocess.PIPE,
cwd=self.tempdir,
env=env
) == 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 QtCompat, QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
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 QtCompat, QtCore, QtGui, QtWidgets
class Ui_uic(object):
def setupUi(self, uic):
self.retranslateUi(uic)
def retranslateUi(self, uic):
self.pushButton_2.setText(
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_import_from_qtcompat():
""" `from Qt.QtCompat import XXX` works """
from Qt.QtCompat import loadUi
assert loadUi.__name__ == "_loadUi", loadUi
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_binding_states():
"""Tests to see if the Qt binding enum states are set properly"""
import Qt
assert Qt.IsPySide == binding("PySide")
assert Qt.IsPySide2 == binding("PySide2")
assert Qt.IsPySide6 == binding("PySide6")
assert Qt.IsPyQt5 == binding("PyQt5")
assert Qt.IsPyQt4 == binding("PyQt4")
def test_qtcompat_base_class():
"""Tests to ensure the QtCompat namespace object works as expected"""
import sys
import Qt
from Qt import QtWidgets
from Qt import QtCompat