Pathlib refactors and test fixes

This commit is contained in:
Phill Ridout 2017-11-18 11:23:15 +00:00
parent 71eaccb547
commit 9196db5af0
21 changed files with 143 additions and 139 deletions

View File

@ -22,7 +22,6 @@
""" """
Download and "install" the remote web client Download and "install" the remote web client
""" """
import os
from zipfile import ZipFile from zipfile import ZipFile
from openlp.core.common.applocation import AppLocation from openlp.core.common.applocation import AppLocation
@ -30,18 +29,18 @@ from openlp.core.common.registry import Registry
from openlp.core.common.httputils import url_get_file, get_web_page, get_url_file_size from openlp.core.common.httputils import url_get_file, get_web_page, get_url_file_size
def deploy_zipfile(app_root, zip_name): def deploy_zipfile(app_root_path, zip_name):
""" """
Process the downloaded zip file and add to the correct directory Process the downloaded zip file and add to the correct directory
:param zip_name: the zip file to be processed :param str zip_name: the zip file name to be processed
:param app_root: the directory where the zip get expanded to :param openlp.core.common.path.Path app_root_path: The directory to expand the zip to
:return: None :return: None
""" """
zip_file = os.path.join(app_root, zip_name) zip_path = app_root_path / zip_name
web_zip = ZipFile(zip_file) web_zip = ZipFile(str(zip_path))
web_zip.extractall(app_root) web_zip.extractall(str(app_root_path))
def download_sha256(): def download_sha256():
@ -67,4 +66,4 @@ def download_and_check(callback=None):
if url_get_file(callback, 'https://get.openlp.org/webclient/site.zip', if url_get_file(callback, 'https://get.openlp.org/webclient/site.zip',
AppLocation.get_section_data_path('remotes') / 'site.zip', AppLocation.get_section_data_path('remotes') / 'site.zip',
sha256=sha256): sha256=sha256):
deploy_zipfile(str(AppLocation.get_section_data_path('remotes')), 'site.zip') deploy_zipfile(AppLocation.get_section_data_path('remotes'), 'site.zip')

View File

@ -28,6 +28,7 @@ import json
from openlp.core.api.http.endpoint import Endpoint from openlp.core.api.http.endpoint import Endpoint
from openlp.core.api.http import requires_auth from openlp.core.api.http import requires_auth
from openlp.core.common.applocation import AppLocation from openlp.core.common.applocation import AppLocation
from openlp.core.common.path import Path
from openlp.core.common.registry import Registry from openlp.core.common.registry import Registry
from openlp.core.common.settings import Settings from openlp.core.common.settings import Settings
from openlp.core.lib import ItemCapabilities, create_thumb from openlp.core.lib import ItemCapabilities, create_thumb
@ -66,12 +67,12 @@ def controller_text(request):
elif current_item.is_image() and not frame.get('image', '') and Settings().value('api/thumbnails'): elif current_item.is_image() and not frame.get('image', '') and Settings().value('api/thumbnails'):
item['tag'] = str(index + 1) item['tag'] = str(index + 1)
thumbnail_path = os.path.join('images', 'thumbnails', frame['title']) thumbnail_path = os.path.join('images', 'thumbnails', frame['title'])
full_thumbnail_path = str(AppLocation.get_data_path() / thumbnail_path) full_thumbnail_path = AppLocation.get_data_path() / thumbnail_path
# Create thumbnail if it doesn't exists # Create thumbnail if it doesn't exists
if not os.path.exists(full_thumbnail_path): if not full_thumbnail_path.exists():
create_thumb(current_item.get_frame_path(index), full_thumbnail_path, False) create_thumb(Path(current_item.get_frame_path(index)), full_thumbnail_path, False)
Registry().get('image_manager').add_image(full_thumbnail_path, frame['title'], None, 88, 88) Registry().get('image_manager').add_image(str(full_thumbnail_path), frame['title'], None, 88, 88)
item['img'] = urllib.request.pathname2url(os.path.sep + thumbnail_path) item['img'] = urllib.request.pathname2url(os.path.sep + str(thumbnail_path))
item['text'] = str(frame['title']) item['text'] = str(frame['title'])
item['html'] = str(frame['title']) item['html'] = str(frame['title'])
else: else:

View File

@ -19,7 +19,6 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 # # with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
import os
import json import json
import re import re
import urllib import urllib
@ -103,7 +102,7 @@ def display_thumbnails(request, controller_name, log, dimensions, file_name, sli
:param controller_name: which controller is requesting the image :param controller_name: which controller is requesting the image
:param log: the logger object :param log: the logger object
:param dimensions: the image size eg 88x88 :param dimensions: the image size eg 88x88
:param file_name: the file name of the image :param str file_name: the file name of the image
:param slide: the individual image name :param slide: the individual image name
:return: :return:
""" """
@ -124,12 +123,10 @@ def display_thumbnails(request, controller_name, log, dimensions, file_name, sli
if controller_name and file_name: if controller_name and file_name:
file_name = urllib.parse.unquote(file_name) file_name = urllib.parse.unquote(file_name)
if '..' not in file_name: # no hacking please if '..' not in file_name: # no hacking please
full_path = AppLocation.get_section_data_path(controller_name) / 'thumbnails' / file_name
if slide: if slide:
full_path = str(AppLocation.get_section_data_path(controller_name) / 'thumbnails' / file_name / slide) full_path = full_path / slide
else: if full_path.exists():
full_path = str(AppLocation.get_section_data_path(controller_name) / 'thumbnails' / file_name) Registry().get('image_manager').add_image(full_path, full_path.name, None, width, height)
if os.path.exists(full_path): image = Registry().get('image_manager').get_image(full_path, full_path.name, width, height)
path, just_file_name = os.path.split(full_path)
Registry().get('image_manager').add_image(full_path, just_file_name, None, width, height)
image = Registry().get('image_manager').get_image(full_path, just_file_name, width, height)
return Response(body=image_to_byte(image, False), status=200, content_type='image/png', charset='utf8') return Response(body=image_to_byte(image, False), status=200, content_type='image/png', charset='utf8')

View File

@ -22,8 +22,6 @@
""" """
The Endpoint class, which provides plugins with a way to serve their own portion of the API The Endpoint class, which provides plugins with a way to serve their own portion of the API
""" """
import os
from mako.template import Template from mako.template import Template
from openlp.core.common.applocation import AppLocation from openlp.core.common.applocation import AppLocation
@ -67,13 +65,17 @@ class Endpoint(object):
def render_template(self, filename, **kwargs): def render_template(self, filename, **kwargs):
""" """
Render a mako template Render a mako template
:param str filename: The file name of the template to render.
:return: The rendered template object.
:rtype: mako.template.Template
""" """
root = str(AppLocation.get_section_data_path('remotes')) root_path = AppLocation.get_section_data_path('remotes')
if not self.template_dir: if not self.template_dir:
raise Exception('No template directory specified') raise Exception('No template directory specified')
path = os.path.join(root, self.template_dir, filename) path = root_path / self.template_dir / filename
if self.static_dir: if self.static_dir:
kwargs['static_url'] = '/{prefix}/static'.format(prefix=self.url_prefix) kwargs['static_url'] = '/{prefix}/static'.format(prefix=self.url_prefix)
kwargs['static_url'] = kwargs['static_url'].replace('//', '/') kwargs['static_url'] = kwargs['static_url'].replace('//', '/')
kwargs['assets_url'] = '/assets' kwargs['assets_url'] = '/assets'
return Template(filename=path, input_encoding='utf-8').render(**kwargs) return Template(filename=str(path), input_encoding='utf-8').render(**kwargs)

View File

@ -25,7 +25,6 @@ App stuff
""" """
import json import json
import logging import logging
import os
import re import re
from webob import Request, Response from webob import Request, Response
@ -138,12 +137,11 @@ class WSGIApplication(object):
Add a static directory as a route Add a static directory as a route
""" """
if route not in self.static_routes: if route not in self.static_routes:
root = str(AppLocation.get_section_data_path('remotes')) static_path = AppLocation.get_section_data_path('remotes') / static_dir
static_path = os.path.abspath(os.path.join(root, static_dir)) if not static_path.exists():
if not os.path.exists(static_path):
log.error('Static path "%s" does not exist. Skipping creating static route/', static_path) log.error('Static path "%s" does not exist. Skipping creating static route/', static_path)
return return
self.static_routes[route] = DirectoryApp(static_path) self.static_routes[route] = DirectoryApp(str(static_path.resolve()))
def dispatch(self, request): def dispatch(self, request):
""" """

View File

@ -69,6 +69,9 @@ class Path(PathVariant):
path = path.relative_to(base_path) path = path.relative_to(base_path)
return {'__Path__': path.parts} return {'__Path__': path.parts}
def rmtree(self, *args, **kwargs):
shutil.rmtree(str(self), *args, **kwargs)
def replace_params(args, kwargs, params): def replace_params(args, kwargs, params):
""" """

View File

@ -198,6 +198,7 @@ class Renderer(RegistryBase, LogMixin, RegistryProperties):
:param theme_data: The theme to generated a preview for. :param theme_data: The theme to generated a preview for.
:param force_page: Flag to tell message lines per page need to be generated. :param force_page: Flag to tell message lines per page need to be generated.
:rtype: QtGui.QPixmap
""" """
# save value for use in format_slide # save value for use in format_slide
self.force_page = force_page self.force_page = force_page
@ -222,8 +223,7 @@ class Renderer(RegistryBase, LogMixin, RegistryProperties):
self.display.build_html(service_item) self.display.build_html(service_item)
raw_html = service_item.get_rendered_frame(0) raw_html = service_item.get_rendered_frame(0)
self.display.text(raw_html, False) self.display.text(raw_html, False)
preview = self.display.preview() return self.display.preview()
return preview
self.force_page = False self.force_page = False
def format_slide(self, text, item): def format_slide(self, text, item):

View File

@ -179,8 +179,9 @@ def create_thumb(image_path, thumb_path, return_icon=True, size=None):
height of 88 is used. height of 88 is used.
:return: The final icon. :return: The final icon.
""" """
ext = os.path.splitext(thumb_path)[1].lower() # TODO: To path object
reader = QtGui.QImageReader(image_path) thumb_path = Path(thumb_path)
reader = QtGui.QImageReader(str(image_path))
if size is None: if size is None:
# No size given; use default height of 88 # No size given; use default height of 88
if reader.size().isEmpty(): if reader.size().isEmpty():
@ -207,10 +208,10 @@ def create_thumb(image_path, thumb_path, return_icon=True, size=None):
# Invalid; use default height of 88 # Invalid; use default height of 88
reader.setScaledSize(QtCore.QSize(int(ratio * 88), 88)) reader.setScaledSize(QtCore.QSize(int(ratio * 88), 88))
thumb = reader.read() thumb = reader.read()
thumb.save(thumb_path, ext[1:]) thumb.save(str(thumb_path), thumb_path.suffix[1:].lower())
if not return_icon: if not return_icon:
return return
if os.path.exists(thumb_path): if thumb_path.exists():
return build_icon(thumb_path) return build_icon(thumb_path)
# Fallback for files with animation support. # Fallback for files with animation support.
return build_icon(image_path) return build_icon(image_path)

View File

@ -139,10 +139,6 @@ class Plugin(QtCore.QObject, RegistryProperties):
self.text_strings = {} self.text_strings = {}
self.set_plugin_text_strings() self.set_plugin_text_strings()
self.name_strings = self.text_strings[StringContent.Name] self.name_strings = self.text_strings[StringContent.Name]
if version:
self.version = version
else:
self.version = get_version()['version']
self.settings_section = self.name self.settings_section = self.name
self.icon = None self.icon = None
self.media_item_class = media_item_class self.media_item_class = media_item_class
@ -162,6 +158,19 @@ class Plugin(QtCore.QObject, RegistryProperties):
Settings.extend_default_settings(default_settings) Settings.extend_default_settings(default_settings)
Registry().register_function('{name}_add_service_item'.format(name=self.name), self.process_add_service_event) Registry().register_function('{name}_add_service_item'.format(name=self.name), self.process_add_service_event)
Registry().register_function('{name}_config_updated'.format(name=self.name), self.config_update) Registry().register_function('{name}_config_updated'.format(name=self.name), self.config_update)
self._setup(version)
def _setup(self, version):
"""
Run some initial setup. This method is separate from __init__ in order to mock it out in tests.
:param version: Defaults to *None*, which means that the same version number is used as OpenLP's version number.
:rtype: None
"""
if version:
self.version = version
else:
self.version = get_version()['version']
def check_pre_conditions(self): def check_pre_conditions(self):
""" """

View File

@ -398,6 +398,8 @@ class MainDisplay(Display, LogMixin, RegistryProperties):
def preview(self): def preview(self):
""" """
Generates a preview of the image displayed. Generates a preview of the image displayed.
:rtype: QtGui.QPixmap
""" """
was_visible = self.isVisible() was_visible = self.isVisible()
self.application.process_events() self.application.process_events()

View File

@ -296,10 +296,9 @@ class Ui_MainWindow(object):
# Give QT Extra Hint that this is an About Menu Item # Give QT Extra Hint that this is an About Menu Item
self.about_item.setMenuRole(QtWidgets.QAction.AboutRole) self.about_item.setMenuRole(QtWidgets.QAction.AboutRole)
if is_win(): if is_win():
self.local_help_file = os.path.join(str(AppLocation.get_directory(AppLocation.AppDir)), 'OpenLP.chm') self.local_help_file = AppLocation.get_directory(AppLocation.AppDir) / 'OpenLP.chm'
elif is_macosx(): elif is_macosx():
self.local_help_file = os.path.join(str(AppLocation.get_directory(AppLocation.AppDir)), self.local_help_file = AppLocation.get_directory(AppLocation.AppDir) / '..' / 'Resources' / 'OpenLP.help'
'..', 'Resources', 'OpenLP.help')
self.user_manual_item = create_action(main_window, 'userManualItem', icon=':/system/system_help_contents.png', self.user_manual_item = create_action(main_window, 'userManualItem', icon=':/system/system_help_contents.png',
can_shortcuts=True, category=UiStrings().Help, can_shortcuts=True, category=UiStrings().Help,
triggers=self.on_help_clicked) triggers=self.on_help_clicked)
@ -760,7 +759,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
Use the Online manual in other cases. (Linux) Use the Online manual in other cases. (Linux)
""" """
if is_macosx() or is_win(): if is_macosx() or is_win():
QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(self.local_help_file)) QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(str(self.local_help_file)))
else: else:
import webbrowser import webbrowser
webbrowser.open_new('http://manual.openlp.org/') webbrowser.open_new('http://manual.openlp.org/')

View File

@ -497,12 +497,12 @@ class ThemeManager(QtWidgets.QWidget, RegistryBase, Ui_ThemeManager, LogMixin, R
name = translate('OpenLP.ThemeManager', '{name} (default)').format(name=text_name) name = translate('OpenLP.ThemeManager', '{name} (default)').format(name=text_name)
else: else:
name = text_name name = text_name
thumb = self.thumb_path / '{name}.png'.format(name=text_name) thumb_path = self.thumb_path / '{name}.png'.format(name=text_name)
item_name = QtWidgets.QListWidgetItem(name) item_name = QtWidgets.QListWidgetItem(name)
if validate_thumb(theme_path, thumb): if validate_thumb(theme_path, thumb_path):
icon = build_icon(thumb) icon = build_icon(thumb_path)
else: else:
icon = create_thumb(str(theme_path), str(thumb)) icon = create_thumb(theme_path, thumb_path)
item_name.setIcon(icon) item_name.setIcon(icon)
item_name.setData(QtCore.Qt.UserRole, text_name) item_name.setData(QtCore.Qt.UserRole, text_name)
self.theme_list_widget.addItem(item_name) self.theme_list_widget.addItem(item_name)
@ -692,7 +692,7 @@ class ThemeManager(QtWidgets.QWidget, RegistryBase, Ui_ThemeManager, LogMixin, R
sample_path_name.unlink() sample_path_name.unlink()
frame.save(str(sample_path_name), 'png') frame.save(str(sample_path_name), 'png')
thumb_path = self.thumb_path / '{name}.png'.format(name=theme_name) thumb_path = self.thumb_path / '{name}.png'.format(name=theme_name)
create_thumb(str(sample_path_name), str(thumb_path), False) create_thumb(sample_path_name, thumb_path, False)
def update_preview_images(self): def update_preview_images(self):
""" """
@ -710,7 +710,8 @@ class ThemeManager(QtWidgets.QWidget, RegistryBase, Ui_ThemeManager, LogMixin, R
Call the renderer to build a Sample Image Call the renderer to build a Sample Image
:param theme_data: The theme to generated a preview for. :param theme_data: The theme to generated a preview for.
:param force_page: Flag to tell message lines per page need to be generated. :param force_page: Flag to tell message lines per page need to be generated.7
:rtype: QtGui.QPixmap
""" """
return self.renderer.generate_preview(theme_data, force_page) return self.renderer.generate_preview(theme_data, force_page)

View File

@ -23,7 +23,6 @@
The :mod:`openlp.core.version` module downloads the version details for OpenLP. The :mod:`openlp.core.version` module downloads the version details for OpenLP.
""" """
import logging import logging
import os
import platform import platform
import sys import sys
import time import time
@ -176,18 +175,12 @@ def get_version():
full_version = '{tag}-bzr{tree}'.format(tag=tag_version.strip(), tree=tree_revision.strip()) full_version = '{tag}-bzr{tree}'.format(tag=tag_version.strip(), tree=tree_revision.strip())
else: else:
# We're not running the development version, let's use the file. # We're not running the development version, let's use the file.
file_path = str(AppLocation.get_directory(AppLocation.VersionDir)) file_path = AppLocation.get_directory(AppLocation.VersionDir) / '.version'
file_path = os.path.join(file_path, '.version')
version_file = None
try: try:
version_file = open(file_path, 'r') full_version = file_path.read_text().rstrip()
full_version = str(version_file.read()).rstrip()
except OSError: except OSError:
log.exception('Error in version file.') log.exception('Error in version file.')
full_version = '0.0.0-bzr000' full_version = '0.0.0-bzr000'
finally:
if version_file:
version_file.close()
bits = full_version.split('-') bits = full_version.split('-')
APPLICATION_VERSION = { APPLICATION_VERSION = {
'full': full_version, 'full': full_version,

View File

@ -377,7 +377,7 @@ class ImageMediaItem(MediaManagerItem):
if validate_thumb(image.file_path, thumbnail_path): if validate_thumb(image.file_path, thumbnail_path):
icon = build_icon(thumbnail_path) icon = build_icon(thumbnail_path)
else: else:
icon = create_thumb(str(image.file_path), str(thumbnail_path)) icon = create_thumb(image.file_path,thumbnail_path)
item_name = QtWidgets.QTreeWidgetItem([file_name]) item_name = QtWidgets.QTreeWidgetItem([file_name])
item_name.setText(0, file_name) item_name.setText(0, file_name)
item_name.setIcon(0, icon) item_name.setIcon(0, icon)

View File

@ -198,10 +198,10 @@ class PresentationMediaItem(MediaManagerItem):
if not (preview_path and preview_path.exists()): if not (preview_path and preview_path.exists()):
icon = build_icon(':/general/general_delete.png') icon = build_icon(':/general/general_delete.png')
else: else:
if validate_thumb(Path(preview_path), Path(thumbnail_path)): if validate_thumb(preview_path, thumbnail_path):
icon = build_icon(thumbnail_path) icon = build_icon(thumbnail_path)
else: else:
icon = create_thumb(str(preview_path), str(thumbnail_path)) icon = create_thumb(preview_path, thumbnail_path)
else: else:
if initial_load: if initial_load:
icon = build_icon(':/general/general_delete.png') icon = build_icon(':/general/general_delete.png')

View File

@ -267,7 +267,7 @@ class PresentationDocument(object):
return return
if image_path.is_file(): if image_path.is_file():
thumb_path = self.get_thumbnail_path(index, False) thumb_path = self.get_thumbnail_path(index, False)
create_thumb(str(image_path), str(thumb_path), False, QtCore.QSize(-1, 360)) create_thumb(image_path, thumb_path, False, QtCore.QSize(-1, 360))
def get_thumbnail_path(self, slide_no, check_exists=False): def get_thumbnail_path(self, slide_no, check_exists=False):
""" """

View File

@ -19,15 +19,13 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 # # with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
import os
import shutil
from tempfile import mkdtemp from tempfile import mkdtemp
from unittest import TestCase from unittest import TestCase
from openlp.core.api.deploy import deploy_zipfile from openlp.core.api.deploy import deploy_zipfile
from openlp.core.common.path import Path, copyfile
TEST_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'resources')) TEST_PATH = (Path(__file__).parent / '..' / '..' / '..' / 'resources').resolve()
class TestRemoteDeploy(TestCase): class TestRemoteDeploy(TestCase):
@ -39,25 +37,25 @@ class TestRemoteDeploy(TestCase):
""" """
Setup for tests Setup for tests
""" """
self.app_root = mkdtemp() self.app_root_path = Path(mkdtemp())
def tearDown(self): def tearDown(self):
""" """
Clean up after tests Clean up after tests
""" """
shutil.rmtree(self.app_root) self.app_root_path.rmtree()
def test_deploy_zipfile(self): def test_deploy_zipfile(self):
""" """
Remote Deploy tests - test the dummy zip file is processed correctly Remote Deploy tests - test the dummy zip file is processed correctly
""" """
# GIVEN: A new downloaded zip file # GIVEN: A new downloaded zip file
aa = TEST_PATH zip_path = TEST_PATH / 'remotes' / 'site.zip'
zip_file = os.path.join(TEST_PATH, 'remotes', 'site.zip') app_root_path = self.app_root_path / 'site.zip'
app_root = os.path.join(self.app_root, 'site.zip') copyfile(zip_path, app_root_path)
shutil.copyfile(zip_file, app_root)
# WHEN: I process the zipfile
deploy_zipfile(self.app_root, 'site.zip')
# THEN test if www directory has been created # WHEN: I process the zipfile
self.assertTrue(os.path.isdir(os.path.join(self.app_root, 'www')), 'We should have a www directory') deploy_zipfile(self.app_root_path, 'site.zip')
# THEN: test if www directory has been created
self.assertTrue((self.app_root_path / 'www').is_dir(), 'We should have a www directory')

View File

@ -274,32 +274,32 @@ class TestLib(TestCase):
Test the create_thumb() function with a given size. Test the create_thumb() function with a given size.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
thumb_size = QtCore.QSize(10, 20) thumb_size = QtCore.QSize(10, 20)
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
# Only continue when the thumb does not exist. # Only continue when the thumb does not exist.
self.assertFalse(os.path.exists(thumb_path), 'Test was not run, because the thumb already exists.') self.assertFalse(thumb_path.exists(), 'Test was not run, because the thumb already exists.')
# WHEN: Create the thumb. # WHEN: Create the thumb.
icon = create_thumb(image_path, thumb_path, size=thumb_size) icon = create_thumb(image_path, thumb_path, size=thumb_size)
# THEN: Check if the thumb was created and scaled to the given size. # THEN: Check if the thumb was created and scaled to the given size.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(thumb_size, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(thumb_size, QtGui.QImageReader(str(thumb_path)).size(), 'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -308,14 +308,14 @@ class TestLib(TestCase):
Test the create_thumb() function with no size specified. Test the create_thumb() function with no size specified.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
expected_size = QtCore.QSize(63, 88) expected_size = QtCore.QSize(63, 88)
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -326,14 +326,15 @@ class TestLib(TestCase):
icon = create_thumb(image_path, thumb_path) icon = create_thumb(image_path, thumb_path)
# THEN: Check if the thumb was created, retaining its aspect ratio. # THEN: Check if the thumb was created, retaining its aspect ratio.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size, QtGui.QImageReader(str(thumb_path)).size(),
'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -342,33 +343,34 @@ class TestLib(TestCase):
Test the create_thumb() function with invalid size specified. Test the create_thumb() function with invalid size specified.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
thumb_size = QtCore.QSize(-1, -1) thumb_size = QtCore.QSize(-1, -1)
expected_size = QtCore.QSize(63, 88) expected_size = QtCore.QSize(63, 88)
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
# Only continue when the thumb does not exist. # Only continue when the thumb does not exist.
self.assertFalse(os.path.exists(thumb_path), 'Test was not run, because the thumb already exists.') self.assertFalse(thumb_path.exists(), 'Test was not run, because the thumb already exists.')
# WHEN: Create the thumb. # WHEN: Create the thumb.
icon = create_thumb(image_path, thumb_path, size=thumb_size) icon = create_thumb(image_path, thumb_path, size=thumb_size)
# THEN: Check if the thumb was created, retaining its aspect ratio. # THEN: Check if the thumb was created, retaining its aspect ratio.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size, QtGui.QImageReader(str(thumb_path)).size(),
'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -377,33 +379,33 @@ class TestLib(TestCase):
Test the create_thumb() function with a size of only width specified. Test the create_thumb() function with a size of only width specified.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
thumb_size = QtCore.QSize(100, -1) thumb_size = QtCore.QSize(100, -1)
expected_size = QtCore.QSize(100, 137) expected_size = QtCore.QSize(100, 137)
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
# Only continue when the thumb does not exist. # Only continue when the thumb does not exist.
self.assertFalse(os.path.exists(thumb_path), 'Test was not run, because the thumb already exists.') self.assertFalse(thumb_path.exists(), 'Test was not run, because the thumb already exists.')
# WHEN: Create the thumb. # WHEN: Create the thumb.
icon = create_thumb(image_path, thumb_path, size=thumb_size) icon = create_thumb(image_path, thumb_path, size=thumb_size)
# THEN: Check if the thumb was created, retaining its aspect ratio. # THEN: Check if the thumb was created, retaining its aspect ratio.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size, QtGui.QImageReader(str(thumb_path)).size(), 'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -412,33 +414,33 @@ class TestLib(TestCase):
Test the create_thumb() function with a size of only height specified. Test the create_thumb() function with a size of only height specified.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
thumb_size = QtCore.QSize(-1, 100) thumb_size = QtCore.QSize(-1, 100)
expected_size = QtCore.QSize(72, 100) expected_size = QtCore.QSize(72, 100)
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
# Only continue when the thumb does not exist. # Only continue when the thumb does not exist.
self.assertFalse(os.path.exists(thumb_path), 'Test was not run, because the thumb already exists.') self.assertFalse(thumb_path.exists(), 'Test was not run, because the thumb already exists.')
# WHEN: Create the thumb. # WHEN: Create the thumb.
icon = create_thumb(image_path, thumb_path, size=thumb_size) icon = create_thumb(image_path, thumb_path, size=thumb_size)
# THEN: Check if the thumb was created, retaining its aspect ratio. # THEN: Check if the thumb was created, retaining its aspect ratio.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size, QtGui.QImageReader(str(thumb_path)).size(), 'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
@ -447,8 +449,8 @@ class TestLib(TestCase):
Test the create_thumb() function with a size of only height specified. Test the create_thumb() function with a size of only height specified.
""" """
# GIVEN: An image to create a thumb of. # GIVEN: An image to create a thumb of.
image_path = os.path.join(TEST_PATH, 'church.jpg') image_path = Path(TEST_PATH, 'church.jpg')
thumb_path = os.path.join(TEST_PATH, 'church_thumb.jpg') thumb_path = Path(TEST_PATH, 'church_thumb.jpg')
thumb_size = QtCore.QSize(-1, 100) thumb_size = QtCore.QSize(-1, 100)
expected_size_1 = QtCore.QSize(88, 88) expected_size_1 = QtCore.QSize(88, 88)
expected_size_2 = QtCore.QSize(100, 100) expected_size_2 = QtCore.QSize(100, 100)
@ -456,12 +458,12 @@ class TestLib(TestCase):
# Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the # Remove the thumb so that the test actually tests if the thumb will be created. Maybe it was not deleted in the
# last test. # last test.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass
# Only continue when the thumb does not exist. # Only continue when the thumb does not exist.
self.assertFalse(os.path.exists(thumb_path), 'Test was not run, because the thumb already exists.') self.assertFalse(thumb_path.exists(), 'Test was not run, because the thumb already exists.')
# WHEN: Create the thumb. # WHEN: Create the thumb.
with patch('openlp.core.lib.QtGui.QImageReader.size') as mocked_size: with patch('openlp.core.lib.QtGui.QImageReader.size') as mocked_size:
@ -469,10 +471,10 @@ class TestLib(TestCase):
icon = create_thumb(image_path, thumb_path, size=None) icon = create_thumb(image_path, thumb_path, size=None)
# THEN: Check if the thumb was created with aspect ratio of 1. # THEN: Check if the thumb was created with aspect ratio of 1.
self.assertTrue(os.path.exists(thumb_path), 'Test was not ran, because the thumb already exists') self.assertTrue(thumb_path.exists(), 'Test was not ran, because the thumb already exists')
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size_1, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size_1, QtGui.QImageReader(str(thumb_path)).size(), 'The thumb should have the given size')
# WHEN: Create the thumb. # WHEN: Create the thumb.
with patch('openlp.core.lib.QtGui.QImageReader.size') as mocked_size: with patch('openlp.core.lib.QtGui.QImageReader.size') as mocked_size:
@ -482,11 +484,11 @@ class TestLib(TestCase):
# THEN: Check if the thumb was created with aspect ratio of 1. # THEN: Check if the thumb was created with aspect ratio of 1.
self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon') self.assertIsInstance(icon, QtGui.QIcon, 'The icon should be a QIcon')
self.assertFalse(icon.isNull(), 'The icon should not be null') self.assertFalse(icon.isNull(), 'The icon should not be null')
self.assertEqual(expected_size_2, QtGui.QImageReader(thumb_path).size(), 'The thumb should have the given size') self.assertEqual(expected_size_2, QtGui.QImageReader(str(thumb_path)).size(), 'The thumb should have the given size')
# Remove the thumb so that the test actually tests if the thumb will be created. # Remove the thumb so that the test actually tests if the thumb will be created.
try: try:
os.remove(thumb_path) thumb_path.unlink()
except: except:
pass pass

View File

@ -199,16 +199,16 @@ class TestThemeManager(TestCase):
theme_manager._create_theme_from_xml = MagicMock() theme_manager._create_theme_from_xml = MagicMock()
theme_manager.generate_and_save_image = MagicMock() theme_manager.generate_and_save_image = MagicMock()
theme_manager.theme_path = None theme_manager.theme_path = None
folder = Path(mkdtemp()) folder_path = Path(mkdtemp())
theme_file = Path(TEST_RESOURCES_PATH, 'themes', 'Moss_on_tree.otz') theme_file = Path(TEST_RESOURCES_PATH, 'themes', 'Moss_on_tree.otz')
# WHEN: We try to unzip it # WHEN: We try to unzip it
theme_manager.unzip_theme(theme_file, folder) theme_manager.unzip_theme(theme_file, folder_path)
# THEN: Files should be unpacked # THEN: Files should be unpacked
self.assertTrue((folder / 'Moss on tree' / 'Moss on tree.xml').exists()) self.assertTrue((folder_path / 'Moss on tree' / 'Moss on tree.xml').exists())
self.assertEqual(mocked_critical_error_message_box.call_count, 0, 'No errors should have happened') self.assertEqual(mocked_critical_error_message_box.call_count, 0, 'No errors should have happened')
shutil.rmtree(str(folder)) folder_path.rmtree()
def test_unzip_theme_invalid_version(self): def test_unzip_theme_invalid_version(self):
""" """

View File

@ -67,10 +67,10 @@ class TestPdfController(TestCase, TestMixin):
self.desktop.screenGeometry.return_value = SCREEN['size'] self.desktop.screenGeometry.return_value = SCREEN['size']
self.screens = ScreenList.create(self.desktop) self.screens = ScreenList.create(self.desktop)
Settings().extend_default_settings(__default_settings__) Settings().extend_default_settings(__default_settings__)
self.temp_folder = Path(mkdtemp()) self.temp_folder_path = Path(mkdtemp())
self.thumbnail_folder = Path(mkdtemp()) self.thumbnail_folder_path = Path(mkdtemp())
self.mock_plugin = MagicMock() self.mock_plugin = MagicMock()
self.mock_plugin.settings_section = self.temp_folder self.mock_plugin.settings_section = self.temp_folder_path
def tearDown(self): def tearDown(self):
""" """
@ -78,8 +78,8 @@ class TestPdfController(TestCase, TestMixin):
""" """
del self.screens del self.screens
self.destroy_settings() self.destroy_settings()
shutil.rmtree(str(self.thumbnail_folder)) self.thumbnail_folder_path.rmtree()
shutil.rmtree(str(self.temp_folder)) self.temp_folder_path.rmtree()
def test_constructor(self): def test_constructor(self):
""" """
@ -105,8 +105,8 @@ class TestPdfController(TestCase, TestMixin):
controller = PdfController(plugin=self.mock_plugin) controller = PdfController(plugin=self.mock_plugin)
if not controller.check_available(): if not controller.check_available():
raise SkipTest('Could not detect mudraw or ghostscript, so skipping PDF test') raise SkipTest('Could not detect mudraw or ghostscript, so skipping PDF test')
controller.temp_folder = self.temp_folder controller.temp_folder = self.temp_folder_path
controller.thumbnail_folder = self.thumbnail_folder controller.thumbnail_folder = self.thumbnail_folder_path
document = PdfDocument(controller, test_file) document = PdfDocument(controller, test_file)
loaded = document.load_presentation() loaded = document.load_presentation()
@ -125,14 +125,14 @@ class TestPdfController(TestCase, TestMixin):
controller = PdfController(plugin=self.mock_plugin) controller = PdfController(plugin=self.mock_plugin)
if not controller.check_available(): if not controller.check_available():
raise SkipTest('Could not detect mudraw or ghostscript, so skipping PDF test') raise SkipTest('Could not detect mudraw or ghostscript, so skipping PDF test')
controller.temp_folder = self.temp_folder controller.temp_folder = self.temp_folder_path
controller.thumbnail_folder = self.thumbnail_folder controller.thumbnail_folder = self.thumbnail_folder_path
document = PdfDocument(controller, test_file) document = PdfDocument(controller, test_file)
loaded = document.load_presentation() loaded = document.load_presentation()
# THEN: The load should succeed and pictures should be created and have been scales to fit the screen # THEN: The load should succeed and pictures should be created and have been scales to fit the screen
self.assertTrue(loaded, 'The loading of the PDF should succeed.') self.assertTrue(loaded, 'The loading of the PDF should succeed.')
image = QtGui.QImage(os.path.join(str(self.temp_folder), 'pdf_test1.pdf', 'mainslide001.png')) image = QtGui.QImage(os.path.join(str(self.temp_folder_path), 'pdf_test1.pdf', 'mainslide001.png'))
# Based on the converter used the resolution will differ a bit # Based on the converter used the resolution will differ a bit
if controller.gsbin: if controller.gsbin:
self.assertEqual(760, image.height(), 'The height should be 760') self.assertEqual(760, image.height(), 'The height should be 760')

View File

@ -23,7 +23,6 @@
Package to test the openlp.core.lib.pluginmanager package. Package to test the openlp.core.lib.pluginmanager package.
""" """
import sys import sys
import shutil
import gc import gc
from tempfile import mkdtemp from tempfile import mkdtemp
from unittest import TestCase from unittest import TestCase
@ -50,8 +49,8 @@ class TestPluginManager(TestCase, TestMixin):
""" """
self.setup_application() self.setup_application()
self.build_settings() self.build_settings()
self.temp_dir = Path(mkdtemp('openlp')) self.temp_dir_path = Path(mkdtemp('openlp'))
Settings().setValue('advanced/data path', self.temp_dir) Settings().setValue('advanced/data path', self.temp_dir_path)
Registry.create() Registry.create()
Registry().register('service_list', MagicMock()) Registry().register('service_list', MagicMock())
self.main_window = QtWidgets.QMainWindow() self.main_window = QtWidgets.QMainWindow()
@ -64,7 +63,7 @@ class TestPluginManager(TestCase, TestMixin):
# On windows we need to manually garbage collect to close sqlalchemy files # On windows we need to manually garbage collect to close sqlalchemy files
# to avoid errors when temporary files are deleted. # to avoid errors when temporary files are deleted.
gc.collect() gc.collect()
shutil.rmtree(str(self.temp_dir)) self.temp_dir_path.rmtree()
@patch('openlp.plugins.songusage.lib.db.init_schema') @patch('openlp.plugins.songusage.lib.db.init_schema')
@patch('openlp.plugins.songs.lib.db.init_schema') @patch('openlp.plugins.songs.lib.db.init_schema')