test_uic.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import os
  2. import sys
  3. import contextlib
  4. import pytest
  5. from qtpy import PYSIDE2, QtWidgets
  6. from qtpy.QtWidgets import QComboBox
  7. from qtpy import uic
  8. from qtpy.uic import loadUi
  9. QCOMBOBOX_SUBCLASS = """
  10. from qtpy.QtWidgets import QComboBox
  11. class _QComboBoxSubclass(QComboBox):
  12. pass
  13. """
  14. @contextlib.contextmanager
  15. def enabled_qcombobox_subclass(tmpdir):
  16. """
  17. Context manager that sets up a temporary module with a QComboBox subclass
  18. and then removes it once we are done.
  19. """
  20. with open(tmpdir.join('qcombobox_subclass.py').strpath, 'w') as f:
  21. f.write(QCOMBOBOX_SUBCLASS)
  22. sys.path.insert(0, tmpdir.strpath)
  23. yield
  24. sys.path.pop(0)
  25. def get_qapp(icon_path=None):
  26. """
  27. Helper function to return a QApplication instance
  28. """
  29. qapp = QtWidgets.QApplication.instance()
  30. if qapp is None:
  31. qapp = QtWidgets.QApplication([''])
  32. return qapp
  33. @pytest.mark.skipif((PYSIDE2 and os.environ.get('CI', None) is not None),
  34. reason="It segfaults in our CIs with PYSIDE2")
  35. def test_load_ui():
  36. """
  37. Make sure that the patched loadUi function behaves as expected with a
  38. simple .ui file.
  39. """
  40. app = get_qapp()
  41. ui = loadUi(os.path.join(os.path.dirname(__file__), 'test.ui'))
  42. assert isinstance(ui.pushButton, QtWidgets.QPushButton)
  43. assert isinstance(ui.comboBox, QComboBox)
  44. @pytest.mark.skipif((PYSIDE2 and os.environ.get('CI', None) is not None),
  45. reason="It segfaults in our CIs with PYSIDE2")
  46. def test_load_ui_custom_auto(tmpdir):
  47. """
  48. Test that we can load a .ui file with custom widgets without having to
  49. explicitly specify a dictionary of custom widgets, even in the case of
  50. PySide.
  51. """
  52. app = get_qapp()
  53. with enabled_qcombobox_subclass(tmpdir):
  54. from qcombobox_subclass import _QComboBoxSubclass
  55. ui = loadUi(os.path.join(os.path.dirname(__file__), 'test_custom.ui'))
  56. assert isinstance(ui.pushButton, QtWidgets.QPushButton)
  57. assert isinstance(ui.comboBox, _QComboBoxSubclass)
  58. def test_load_full_uic():
  59. """Test that we load the full uic objects for PyQt5 and PyQt4."""
  60. QT_API = os.environ.get('QT_API', '').lower()
  61. if QT_API.startswith('pyside'):
  62. assert hasattr(uic, 'loadUi')
  63. assert not hasattr(uic, 'loadUiType')
  64. else:
  65. objects = ['compileUi', 'compileUiDir', 'loadUi', 'loadUiType',
  66. 'widgetPluginPath']
  67. assert all([hasattr(uic, o) for o in objects])