def _create_report(self): """ Create an exception report. """ openlp_version = get_version() description = self.description_text_edit.toPlainText() traceback = self.exception_text_edit.toPlainText() system = translate( 'OpenLP.ExceptionForm', 'Platform: {platform}\n').format(platform=platform.platform()) library_versions = get_library_versions() library_versions['PyUNO'] = self._get_pyuno_version() libraries = '\n'.join([ '{}: {}'.format(library, version) for library, version in library_versions.items() ]) if is_linux(): if os.environ.get('KDE_FULL_SESSION') == 'true': system += 'Desktop: KDE SC\n' elif os.environ.get('GNOME_DESKTOP_SESSION_ID'): system += 'Desktop: GNOME\n' elif os.environ.get('DESKTOP_SESSION') == 'xfce': system += 'Desktop: Xfce\n' # NOTE: Keys match the expected input for self.report_text.format() return { 'version': openlp_version, 'description': description, 'traceback': traceback, 'system': system, 'libs': libraries }
def _create_report(self): """ Create an exception report. """ openlp_version = get_application_version() description = self.description_text_edit.toPlainText() traceback = self.exception_text_edit.toPlainText() system = translate('OpenLP.ExceptionForm', 'Platform: %s\n') % platform.platform() libraries = 'Python: %s\n' % platform.python_version() + \ 'Qt4: %s\n' % Qt.qVersion() + \ 'Phonon: %s\n' % PHONON_VERSION + \ 'PyQt4: %s\n' % Qt.PYQT_VERSION_STR + \ 'QtWebkit: %s\n' % WEBKIT_VERSION + \ 'SQLAlchemy: %s\n' % sqlalchemy.__version__ + \ 'SQLAlchemy Migrate: %s\n' % MIGRATE_VERSION + \ 'BeautifulSoup: %s\n' % bs4.__version__ + \ 'lxml: %s\n' % etree.__version__ + \ 'Chardet: %s\n' % CHARDET_VERSION + \ 'PyEnchant: %s\n' % ENCHANT_VERSION + \ 'Mako: %s\n' % MAKO_VERSION + \ 'pyICU: %s\n' % ICU_VERSION + \ 'pyUNO bridge: %s\n' % self._pyuno_import() + \ 'VLC: %s\n' % VLC_VERSION if is_linux(): if os.environ.get('KDE_FULL_SESSION') == 'true': system += 'Desktop: KDE SC\n' elif os.environ.get('GNOME_DESKTOP_SESSION_ID'): system += 'Desktop: GNOME\n' elif os.environ.get('DESKTOP_SESSION') == 'xfce': system += 'Desktop: Xfce\n' return openlp_version, description, traceback, system, libraries
def test_is_linux(self): """ Test the is_linux() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch('openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectivly mocked_os.name = 'posix' mocked_sys.platform = 'linux3' # THEN: The three platform functions should perform properly self.assertTrue(is_linux(), 'is_linux() should return True') self.assertFalse(is_win(), 'is_win() should return False') self.assertFalse(is_macosx(), 'is_macosx() should return False')
def test_is_macosx(self): """ Test the is_macosx() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch( 'openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'darwin' repectivly mocked_os.name = 'posix' mocked_sys.platform = 'darwin' # THEN: The three platform functions should perform properly assert is_macosx() is True, 'is_macosx() should return True' assert is_win() is False, 'is_win() should return False' assert is_linux() is False, 'is_linux() should return False'
def is_linux_test(self): """ Test the is_linux() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch( 'openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectivly mocked_os.name = 'posix' mocked_sys.platform = 'linux3' # THEN: The three platform functions should perform properly self.assertTrue(is_linux(), 'is_linux() should return True') self.assertFalse(is_win(), 'is_win() should return False') self.assertFalse(is_macosx(), 'is_macosx() should return False')
def get_screen_resolution(): """ Get the screen resolution """ if is_macosx(): from AppKit import NSScreen screen_size = NSScreen.mainScreen().frame().size return screen_size.width, screen_size.height elif is_win(): from win32api import GetSystemMetrics return GetSystemMetrics(0), GetSystemMetrics(1) elif is_linux(): from Xlib.display import Display resolution = Display().screen().root.get_geometry() return resolution.width, resolution.height else: return 1024, 768
def _create_report(self): """ Create an exception report. """ openlp_version = get_version() description = self.description_text_edit.toPlainText() traceback = self.exception_text_edit.toPlainText() system = translate( 'OpenLP.ExceptionForm', 'Platform: {platform}\n').format(platform=platform.platform()) libraries = ( 'Python: {python}\nQt5: {qt5}\nPyQt5: {pyqt5}\nQtWebkit: {qtwebkit}\nSQLAlchemy: {sqalchemy}\n' 'SQLAlchemy Migrate: {migrate}\nBeautifulSoup: {soup}\nlxml: {etree}\nChardet: {chardet}\n' 'PyEnchant: {enchant}\nMako: {mako}\npyICU: {icu}\npyUNO bridge: {uno}\n' 'VLC: {vlc}\n').format(python=platform.python_version(), qt5=Qt.qVersion(), pyqt5=Qt.PYQT_VERSION_STR, qtwebkit=WEBKIT_VERSION, sqalchemy=sqlalchemy.__version__, migrate=MIGRATE_VERSION, soup=bs4.__version__, etree=etree.__version__, chardet=CHARDET_VERSION, enchant=ENCHANT_VERSION, mako=MAKO_VERSION, icu=ICU_VERSION, uno=self._pyuno_import(), vlc=VLC_VERSION) if is_linux(): if os.environ.get('KDE_FULL_SESSION') == 'true': system += 'Desktop: KDE SC\n' elif os.environ.get('GNOME_DESKTOP_SESSION_ID'): system += 'Desktop: GNOME\n' elif os.environ.get('DESKTOP_SESSION') == 'xfce': system += 'Desktop: Xfce\n' # NOTE: Keys match the expected input for self.report_text.format() return { 'version': openlp_version, 'description': description, 'traceback': traceback, 'system': system, 'libs': libraries }
def bootstrap_initialise(self): """ Check to see if we have any media Player's available. """ self.setup() self.vlc_player = VlcPlayer(self) State().add_service('mediacontroller', 0) State().add_service('media_live', 0) has_vlc = get_vlc() if has_vlc and pymediainfo_available: State().update_pre_conditions('mediacontroller', True) State().update_pre_conditions('media_live', True) else: if hasattr(self.main_window, 'splash') and self.main_window.splash.isVisible(): self.main_window.splash.hide() generic_message = translate( 'OpenLP.MediaController', 'OpenLP requires the following libraries in order to show videos and other ' 'media, but they are not installed. Please install these libraries to enable ' 'media playback in OpenLP.') fedora_rpmfusion = translate( 'OpenLP.MediaController', 'To install these libraries, you will need to enable the RPMFusion ' 'repository: https://rpmfusion.org/') if is_macosx(): message = translate( 'OpenLP.MediaController', 'macOS is missing VLC. Please download and install from the VLC web site: ' 'https://www.videolan.org/vlc/') else: packages = [] if not has_vlc: packages.append('python3-vlc') if not pymediainfo_available: packages.append('python3-pymediainfo') message = generic_message + '\n\n' + ', '.join(packages) if not has_vlc and is_linux(distro='fedora'): message += '\n\n' + fedora_rpmfusion State().missing_text('media_live', message) return True
def test_is_linux_distro(self): """ Test the is_linux() function for a particular Linux distribution """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, \ patch('openlp.core.common.sys') as mocked_sys, \ patch('openlp.core.common.distro_id') as mocked_distro_id: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectively # and the distro is Fedora mocked_os.name = 'posix' mocked_sys.platform = 'linux3' mocked_distro_id.return_value = 'fedora' # THEN: The three platform functions should perform properly assert is_linux( distro='fedora' ) is True, 'is_linux(distro="fedora") should return True' assert is_win() is False, 'is_win() should return False' assert is_macosx() is False, 'is_macosx() should return False'
""" import datetime import logging import os from PyQt4 import QtCore, QtGui from openlp.core.common import ThemeLevel, SlideLimits, UiStrings, is_win, is_linux log = logging.getLogger(__name__) # Fix for bug #1014422. X11_BYPASS_DEFAULT = True if is_linux(): # Default to False on Gnome. X11_BYPASS_DEFAULT = bool(not os.environ.get('GNOME_DESKTOP_SESSION_ID')) # Default to False on Xfce. if os.environ.get('DESKTOP_SESSION') == 'xfce': X11_BYPASS_DEFAULT = False def recent_files_conv(value): """ If the value is not a list convert it to a list :param value: Value to convert :return: value as a List """ if isinstance(value, list): return value
return None # Verify that VLC is also loadable is_vlc_available = False try: is_vlc_available = bool(sys.modules['vlc'].get_default_instance()) except Exception: pass if is_vlc_available: return sys.modules['vlc'] return None # On linux we need to initialise X threads, but not when running tests. # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... if is_linux() and 'pytest' not in sys.argv[0] and get_vlc(): try: try: x11 = ctypes.cdll.LoadLibrary('libX11.so.6') except OSError: # If libx11.so.6 was not found, fallback to more generic libx11.so x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except Exception: log.exception( 'Failed to run XInitThreads(), VLC might not work properly!') class VlcPlayer(MediaPlayer): """ A specialised version of the MediaPlayer class, which provides a VLC display.
# http://bugs.python.org/issue14894 if LooseVersion(VERSION.split()[0]) < LooseVersion('1.1.0'): is_vlc_available = False log.debug( 'VLC could not be loaded, because the vlc version is too old: %s' % VERSION) if is_vlc_available: return vlc else: return None # On linux we need to initialise X threads, but not when running tests. # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... if get_vlc() and is_linux() and 'nose' not in sys.argv[0]: import ctypes try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: log.exception( 'Failed to run XInitThreads(), VLC might not work properly!') class VlcPlayer(MediaPlayer): """ A specialised version of the MediaPlayer class, which provides a VLC display. """ def __init__(self, parent): """
log = logging.getLogger(__name__) __version__ = 2 class ProxyMode(IntEnum): NO_PROXY = 1 SYSTEM_PROXY = 2 MANUAL_PROXY = 3 TODAY = QtCore.QDate.currentDate() # Fix for bug #1014422. X11_BYPASS_DEFAULT = True if is_linux(): # pragma: no cover # Default to False on Gnome. X11_BYPASS_DEFAULT = bool(not os.environ.get('GNOME_DESKTOP_SESSION_ID')) # Default to False on Xfce. if os.environ.get('DESKTOP_SESSION') == 'xfce': X11_BYPASS_DEFAULT = False def media_players_conv(string): """ If phonon is in the setting string replace it with system :param string: String to convert :return: Converted string """ values = string.split(',') for index, value in enumerate(values):
def find_optical_devices(self): """ Attempt to autodetect optical devices on the computer, and add them to the media-dropdown :return: """ # Clear list first self.media_path_combobox.clear() if is_win(): # use win api to find optical drives fso = Dispatch('scripting.filesystemobject') for drive in fso.Drives: log.debug('Drive {drive} has type {types:d}'.format( drive=drive.DriveLetter, types=drive.DriveType)) # if type is 4, it is a cd-rom drive if drive.DriveType == 4: self.media_path_combobox.addItem( '{drive}:\\'.format(drive=drive.DriveLetter)) elif is_linux(): # Get disc devices from dbus and find the ones that are optical bus = dbus.SystemBus() try: udev_manager_obj = bus.get_object('org.freedesktop.UDisks', '/org/freedesktop/UDisks') udev_manager = dbus.Interface(udev_manager_obj, 'org.freedesktop.UDisks') for dev in udev_manager.EnumerateDevices(): device_obj = bus.get_object("org.freedesktop.UDisks", dev) device_props = dbus.Interface(device_obj, dbus.PROPERTIES_IFACE) if device_props.Get('org.freedesktop.UDisks.Device', 'DeviceIsDrive'): drive_props = device_props.Get( 'org.freedesktop.UDisks.Device', 'DriveMediaCompatibility') if any('optical' in prop for prop in drive_props): self.media_path_combobox.addItem( device_props.Get( 'org.freedesktop.UDisks.Device', 'DeviceFile')) return except dbus.exceptions.DBusException: log.debug('could not use udisks, will try udisks2') udev_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') udev_manager = dbus.Interface( udev_manager_obj, 'org.freedesktop.DBus.ObjectManager') for k, v in udev_manager.GetManagedObjects().items(): drive_info = v.get('org.freedesktop.UDisks2.Drive', {}) drive_props = drive_info.get('MediaCompatibility') if drive_props and any('optical' in prop for prop in drive_props): for device in udev_manager.GetManagedObjects().values(): if dbus.String( 'org.freedesktop.UDisks2.Block') in device: if device[dbus.String( 'org.freedesktop.UDisks2.Block')][ dbus.String('Drive')] == k: block_file = '' for c in device[dbus.String( 'org.freedesktop.UDisks2.Block')][ dbus.String('PreferredDevice')]: if chr(c) != '\x00': block_file += chr(c) self.media_path_combobox.addItem(block_file) elif is_macosx(): # Look for DVD folders in devices to find optical devices volumes = os.listdir('/Volumes') for volume in volumes: if volume.startswith('.'): continue dirs = os.listdir('/Volumes/' + volume) # Detect DVD if 'VIDEO_TS' in dirs: self.media_path_combobox.addItem('/Volumes/' + volume) # Detect audio cd files = [f for f in dirs if os.path.isfile(f)] for file in files: if file.endswith('aiff'): self.media_path_combobox.addItem('/Volumes/' + volume) break
from time import sleep from PyQt5 import QtCore, QtWidgets from openlp.core.common import is_linux, is_macosx, is_win from openlp.core.common.i18n import translate from openlp.core.common.mixins import RegistryProperties from openlp.core.lib.ui import critical_error_message_box from openlp.core.ui.icons import UiIcons from openlp.core.ui.media.vlcplayer import get_vlc from openlp.plugins.media.forms.mediaclipselectordialog import Ui_MediaClipSelector if is_win(): from win32com.client import Dispatch if is_linux(): import dbus log = logging.getLogger(__name__) class MediaClipSelectorForm(QtWidgets.QDialog, Ui_MediaClipSelector, RegistryProperties): """ Class to manage the clip selection """ log.info('{name} MediaClipSelectorForm loaded'.format(name=__name__)) def __init__(self, media_item, parent, manager): """ Constructor
def dump_valentina_to_xml(self): """ Load the LiveWorship database using the Valentina DB ADK for C and dump the DB content to a XML file. """ self.import_wizard.increment_progress_bar(translate('SongsPlugin.LiveWorshipImport', 'Extracting data from database'), 0) # Based on OS and bitness, try to load the dll libVCSDK = None if is_win(): # The DLL path must be set depending on the bitness of the OpenLP/Python instance if is_64bit_instance(): vcdk_install_folder = 'VCDK_x64_{adkver}' dll_name = '/vcsdk_release_x64.dll' else: vcdk_install_folder = 'VCDK_{adkver}' dll_name = '/vcsdk_release_x86.dll' dll_path = '{pf}\\Paradigma Software\\{vcdk}'.format(pf=os.getenv('PROGRAMFILES'), vcdk=vcdk_install_folder) dll_path2 = '{pf}\\Paradigma Software\\vcomponents_win_vc'.format(pf=os.getenv('PROGRAMFILES')) os.environ['PATH'] = ';'.join([os.environ['PATH'], dll_path, dll_path2]) libVCSDK_path = dll_path + dll_name elif is_linux(): libVCSDK_path = '/opt/VCSDK/libVCSDK.so' elif is_macosx(): # The DLL path must be set depending on the bitness of the OpenLP/Python instance if is_64bit_instance(): vcdk_install_folder = 'VCDK_x64_{adkver}' dll_name = '/vcsdk_x64.dylib' else: vcdk_install_folder = 'VCDK_{adkver}' dll_name = '/vcsdk_x86.dylib' libVCSDK_path = '/Users/Shared/Paradigma Software/{folder}/{dll}'.format(folder=vcdk_install_folder, dll=dll_name) # Try to make this somewhat future proof by trying versions 9 to 15 found_dll = False if '{adkver}' in libVCSDK_path: for i in range(9, 16): if os.path.exists(libVCSDK_path.format(adkver=i)): found_dll = True libVCSDK_path = libVCSDK_path.format(adkver=i) break if not found_dll: libVCSDK_path = libVCSDK_path.format(adkver=9) elif os.path.exists(libVCSDK_path): found_dll = True if not found_dll: adk_name = "Valentina DB ADK for C, {bitness} bit" if is_64bit_instance(): adk_name = adk_name.format(bitness=64) else: adk_name = adk_name.format(bitness=32) critical_error_message_box(translate('SongsPlugin.LiveWorshipImport', 'Could not find Valentina DB ADK libraries '), translate('SongsPlugin.LiveWorshipImport', 'Could not find "{dllpath}", please install "{adk}"' .format(dllpath=libVCSDK_path, adk=adk_name))) return False libVCSDK = ctypes.CDLL(libVCSDK_path) # cache size set to 1024, got no idea what this means... # serial numbers set to None - only 10 minutes access, should be enough :) libVCSDK.Valentina_Init(1024, None, None, None) # Create a DB instance Database_New = libVCSDK.Database_New Database_New.argtypes = [ctypes.c_int] Database_New.restype = ctypes.c_void_p database = Database_New(EVStorageType_kDisk) database_ptr = ctypes.c_void_p(database) # Load the file into our instance libVCSDK.Database_Open(database_ptr, ctypes.c_char_p(str(self.import_source).encode())) # Dump the database to XML libVCSDK.Database_Dump(database_ptr, ctypes.c_char_p(str(self.dump_file).encode()), EVDumpType_kXML, EVDataKind_kStructureAndRecords, pretty_print, ctypes.c_char_p(b'utf-8')) # Close the DB libVCSDK.Database_Close(database_ptr) # Shutdown Valentina libVCSDK.Valentina_Shutdown() return True
# http://bugs.python.org/issue14894 if LooseVersion(VERSION.split()[0]) < LooseVersion('1.1.0'): is_vlc_available = False log.debug( 'VLC could not be loaded, because the vlc version is too old: %s' % VERSION) if is_vlc_available: return vlc else: return None # On linux we need to initialise X threads, but not when running tests. # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... if is_linux() and 'nose' not in sys.argv[0] and get_vlc(): import ctypes try: try: x11 = ctypes.cdll.LoadLibrary('libX11.so.6') except OSError: # If libx11.so.6 was not found, fallback to more generic libx11.so x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: log.exception( 'Failed to run XInitThreads(), VLC might not work properly!') class VlcPlayer(MediaPlayer): """
VERSION = '0.0.0' # LooseVersion does not work when a string contains letter and digits (e. g. 2.0.5 Twoflower). # http://bugs.python.org/issue14894 if LooseVersion(VERSION.split()[0]) < LooseVersion('1.1.0'): is_vlc_available = False log.debug('VLC could not be loaded, because the vlc version is too old: %s' % VERSION) if is_vlc_available: return vlc else: return None # On linux we need to initialise X threads, but not when running tests. # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... if get_vlc() and is_linux() and 'nose' not in sys.argv[0]: import ctypes try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: log.exception('Failed to run XInitThreads(), VLC might not work properly!') class VlcPlayer(MediaPlayer): """ A specialised version of the MediaPlayer class, which provides a VLC display. """ def __init__(self, parent): """
VERSION = '0.0.0' # LooseVersion does not work when a string contains letter and digits (e. g. 2.0.5 Twoflower). # http://bugs.python.org/issue14894 if LooseVersion(VERSION.split()[0]) < LooseVersion('1.1.0'): is_vlc_available = False log.debug('VLC could not be loaded, because the vlc version is too old: %s' % VERSION) if is_vlc_available: return vlc else: return None # On linux we need to initialise X threads, but not when running tests. # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... if is_linux() and 'nose' not in sys.argv[0] and get_vlc(): try: try: x11 = ctypes.cdll.LoadLibrary('libX11.so.6') except OSError: # If libx11.so.6 was not found, fallback to more generic libx11.so x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: log.exception('Failed to run XInitThreads(), VLC might not work properly!') class VlcPlayer(MediaPlayer): """ A specialised version of the MediaPlayer class, which provides a VLC display. """
class TestCommonFunctions(TestCase): """ A test suite to test out various functions in the openlp.core.common module. """ def test_extension_loader_no_files_found(self): """ Test the `extension_loader` function when no files are found """ # GIVEN: A mocked `Path.glob` method which does not match any files with patch('openlp.core.common.applocation.AppLocation.get_directory', return_value=Path('/', 'app', 'dir', 'openlp')), \ patch.object(Path, 'glob', return_value=[]), \ patch('openlp.core.common.importlib.import_module') as mocked_import_module: # WHEN: Calling `extension_loader` extension_loader('glob', ['file2.py', 'file3.py']) # THEN: `extension_loader` should not try to import any files assert mocked_import_module.called is False def test_extension_loader_files_found(self): """ Test the `extension_loader` function when it successfully finds and loads some files """ # GIVEN: A mocked `Path.glob` method which returns a list of files with patch('openlp.core.common.applocation.AppLocation.get_directory', return_value=Path('/', 'app', 'dir', 'openlp')), \ patch.object(Path, 'glob', return_value=[ Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file1.py'), Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file2.py'), Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file3.py'), Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file4.py')]), \ patch('openlp.core.common.importlib.import_module') as mocked_import_module: # WHEN: Calling `extension_loader` with a list of files to exclude extension_loader('glob', ['file2.py', 'file3.py']) # THEN: `extension_loader` should only try to import the files that are matched by the blob, excluding the # files listed in the `excluded_files` argument mocked_import_module.assert_has_calls([ call('openlp.import_dir.file1'), call('openlp.import_dir.file4') ]) def test_extension_loader_import_error(self): """ Test the `extension_loader` function when `SourceFileLoader` raises a `ImportError` """ # GIVEN: A mocked `import_module` which raises an `ImportError` with patch('openlp.core.common.applocation.AppLocation.get_directory', return_value=Path('/', 'app', 'dir', 'openlp')), \ patch.object(Path, 'glob', return_value=[ Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file1.py')]), \ patch('openlp.core.common.importlib.import_module', side_effect=ImportError()), \ patch('openlp.core.common.log') as mocked_logger: # WHEN: Calling `extension_loader` extension_loader('glob') # THEN: The `ImportError` should be caught and logged assert mocked_logger.exception.called def test_extension_loader_os_error(self): """ Test the `extension_loader` function when `import_module` raises a `ImportError` """ # GIVEN: A mocked `SourceFileLoader` which raises an `OSError` with patch('openlp.core.common.applocation.AppLocation.get_directory', return_value=Path('/', 'app', 'dir', 'openlp')), \ patch.object(Path, 'glob', return_value=[ Path('/', 'app', 'dir', 'openlp', 'import_dir', 'file1.py')]), \ patch('openlp.core.common.importlib.import_module', side_effect=OSError()), \ patch('openlp.core.common.log') as mocked_logger: # WHEN: Calling `extension_loader` extension_loader('glob') # THEN: The `OSError` should be caught and logged assert mocked_logger.exception.called def test_de_hump_conversion(self): """ Test the de_hump function with a class name """ # GIVEN: a Class name in Camel Case string = "MyClass" # WHEN: we call de_hump new_string = de_hump(string) # THEN: the new string should be converted to python format assert new_string == "my_class", 'The class name should have been converted' def test_de_hump_static(self): """ Test the de_hump function with a python string """ # GIVEN: a Class name in Camel Case string = "my_class" # WHEN: we call de_hump new_string = de_hump(string) # THEN: the new string should be converted to python format assert new_string == "my_class", 'The class name should have been preserved' def test_path_to_module(self): """ Test `path_to_module` when supplied with a `Path` object """ # GIVEN: A `Path` object path = Path('core', 'ui', 'media', 'vlcplayer.py') # WHEN: Calling path_to_module with the `Path` object result = path_to_module(path) # THEN: path_to_module should return the module name assert result == 'openlp.core.ui.media.vlcplayer' def test_trace_error_handler(self): """ Test the trace_error_handler() method """ # GIVEN: Mocked out objects with patch('openlp.core.common.traceback') as mocked_traceback: mocked_traceback.extract_stack.return_value = [ ('openlp.fake', 56, None, 'trace_error_handler_test') ] mocked_logger = MagicMock() # WHEN: trace_error_handler() is called trace_error_handler(mocked_logger) # THEN: The mocked_logger.error() method should have been called with the correct parameters mocked_logger.error.assert_called_with( 'OpenLP Error trace\n File openlp.fake at line 56 \n\t called trace_error_handler_test' ) def test_singleton_metaclass_multiple_init(self): """ Test that a class using the Singleton Metaclass is only initialised once despite being called several times and that the same instance is returned each time.. """ # GIVEN: The Singleton Metaclass and a test class using it class SingletonClass(metaclass=Singleton): def __init__(self): pass with patch.object(SingletonClass, '__init__', return_value=None) as patched_init: # WHEN: Initialising the class multiple times inst_1 = SingletonClass() inst_2 = SingletonClass() # THEN: The __init__ method of the SingletonClass should have only been called once, and both returned values # should be the same instance. assert inst_1 is inst_2 assert patched_init.call_count == 1 def test_singleton_metaclass_multiple_classes(self): """ Test that multiple classes using the Singleton Metaclass return the different an appropriate instances. """ # GIVEN: Two different classes using the Singleton Metaclass class SingletonClass1(metaclass=Singleton): def __init__(self): pass class SingletonClass2(metaclass=Singleton): def __init__(self): pass # WHEN: Initialising both classes s_c1 = SingletonClass1() s_c2 = SingletonClass2() # THEN: The instances should be an instance of the appropriate class assert isinstance(s_c1, SingletonClass1) assert isinstance(s_c2, SingletonClass2) def test_is_win(self): """ Test the is_win() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch( 'openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'nt' and 'win32' repectivly mocked_os.name = 'nt' mocked_sys.platform = 'win32' # THEN: The three platform functions should perform properly assert is_win() is True, 'is_win() should return True' assert is_macosx() is False, 'is_macosx() should return False' assert is_linux() is False, 'is_linux() should return False' def test_is_macosx(self): """ Test the is_macosx() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch( 'openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'darwin' repectivly mocked_os.name = 'posix' mocked_sys.platform = 'darwin' # THEN: The three platform functions should perform properly assert is_macosx() is True, 'is_macosx() should return True' assert is_win() is False, 'is_win() should return False' assert is_linux() is False, 'is_linux() should return False' def test_is_linux(self): """ Test the is_linux() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, patch( 'openlp.core.common.sys') as mocked_sys: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectively mocked_os.name = 'posix' mocked_sys.platform = 'linux3' # THEN: The three platform functions should perform properly assert is_linux() is True, 'is_linux() should return True' assert is_win() is False, 'is_win() should return False' assert is_macosx() is False, 'is_macosx() should return False' @skipUnless(is_linux(), 'This can only run on Linux') def test_is_linux_distro(self): """ Test the is_linux() function for a particular Linux distribution """ # GIVEN: Mocked out objects with patch('openlp.core.common.os') as mocked_os, \ patch('openlp.core.common.sys') as mocked_sys, \ patch('openlp.core.common.distro_id') as mocked_distro_id: # WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectively # and the distro is Fedora mocked_os.name = 'posix' mocked_sys.platform = 'linux3' mocked_distro_id.return_value = 'fedora' # THEN: The three platform functions should perform properly assert is_linux( distro='fedora' ) is True, 'is_linux(distro="fedora") should return True' assert is_win() is False, 'is_win() should return False' assert is_macosx() is False, 'is_macosx() should return False' def test_is_64bit_instance(self): """ Test the is_64bit_instance() function """ # GIVEN: Mocked out objects with patch('openlp.core.common.sys') as mocked_sys: # WHEN: The mocked sys.maxsize is set to 32-bit mocked_sys.maxsize = 2**32 # THEN: The result should be False assert is_64bit_instance( ) is False, 'is_64bit_instance() should return False' def test_normalize_str_leaves_newlines(self): # GIVEN: a string containing newlines string = 'something\nelse' # WHEN: normalize is called normalized_string = normalize_str(string) # THEN: string is unchanged assert normalized_string == string def test_normalize_str_removes_null_byte(self): # GIVEN: a string containing a null byte string = 'somet\x00hing' # WHEN: normalize is called normalized_string = normalize_str(string) # THEN: nullbyte is removed assert normalized_string == 'something' def test_normalize_str_replaces_crlf_with_lf(self): # GIVEN: a string containing crlf string = 'something\r\nelse' # WHEN: normalize is called normalized_string = normalize_str(string) # THEN: crlf is replaced with lf assert normalized_string == 'something\nelse' def test_clean_button_text(self): """ Test the clean_button_text() function. """ # GIVEN: Button text input_text = '&Next >' expected_text = 'Next' # WHEN: The button caption is sent through the clean_button_text function actual_text = clean_button_text(input_text) # THEN: The text should have been cleaned assert expected_text == actual_text, 'The text should be clean'
def find_optical_devices(self): """ Attempt to autodetect optical devices on the computer, and add them to the media-dropdown :return: """ # Clear list first self.media_path_combobox.clear() if is_win(): # use win api to find optical drives fso = Dispatch('scripting.filesystemobject') for drive in fso.Drives: log.debug('Drive %s has type %d' % (drive.DriveLetter, drive.DriveType)) # if type is 4, it is a cd-rom drive if drive.DriveType == 4: self.media_path_combobox.addItem('%s:\\' % drive.DriveLetter) elif is_linux(): # Get disc devices from dbus and find the ones that are optical bus = dbus.SystemBus() try: udev_manager_obj = bus.get_object('org.freedesktop.UDisks', '/org/freedesktop/UDisks') udev_manager = dbus.Interface(udev_manager_obj, 'org.freedesktop.UDisks') for dev in udev_manager.EnumerateDevices(): device_obj = bus.get_object("org.freedesktop.UDisks", dev) device_props = dbus.Interface(device_obj, dbus.PROPERTIES_IFACE) if device_props.Get('org.freedesktop.UDisks.Device', 'DeviceIsDrive'): drive_props = device_props.Get('org.freedesktop.UDisks.Device', 'DriveMediaCompatibility') if any('optical' in prop for prop in drive_props): self.media_path_combobox.addItem(device_props.Get('org.freedesktop.UDisks.Device', 'DeviceFile')) return except dbus.exceptions.DBusException: log.debug('could not use udisks, will try udisks2') udev_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') udev_manager = dbus.Interface(udev_manager_obj, 'org.freedesktop.DBus.ObjectManager') for k, v in udev_manager.GetManagedObjects().items(): drive_info = v.get('org.freedesktop.UDisks2.Drive', {}) drive_props = drive_info.get('MediaCompatibility') if drive_props and any('optical' in prop for prop in drive_props): for device in udev_manager.GetManagedObjects().values(): if dbus.String('org.freedesktop.UDisks2.Block') in device: if device[dbus.String('org.freedesktop.UDisks2.Block')][dbus.String('Drive')] == k: block_file = '' for c in device[dbus.String('org.freedesktop.UDisks2.Block')][ dbus.String('PreferredDevice')]: if chr(c) != '\x00': block_file += chr(c) self.media_path_combobox.addItem(block_file) elif is_macosx(): # Look for DVD folders in devices to find optical devices volumes = os.listdir('/Volumes') candidates = list() for volume in volumes: if volume.startswith('.'): continue dirs = os.listdir('/Volumes/' + volume) # Detect DVD if 'VIDEO_TS' in dirs: self.media_path_combobox.addItem('/Volumes/' + volume) # Detect audio cd files = [f for f in dirs if os.path.isfile(f)] for file in files: if file.endswith('aiff'): self.media_path_combobox.addItem('/Volumes/' + volume) break