Clean up exceptions used in error

This commit is contained in:
Tim Bentley 2013-12-13 19:44:17 +00:00
parent 84e90e01d1
commit d684359e59
11 changed files with 166 additions and 26 deletions

View File

@ -30,15 +30,31 @@
The :mod:`common` module contains most of the components and libraries that make
OpenLP work.
"""
import re
import os
import logging
import sys
import traceback
from PyQt4 import QtCore
log = logging.getLogger(__name__)
FIRST_CAMEL_REGEX = re.compile('(.)([A-Z][a-z]+)')
SECOND_CAMEL_REGEX = re.compile('([a-z0-9])([A-Z])')
def trace_error_handler(logger):
"""
Log the calling path of an exception
'logger'
Logger to use so traceback is logged to correct class
"""
for tb in traceback.extract_stack():
logger.error('Called by ' + tb[3] + ' at line ' + str(tb[1]) + ' in ' + tb[0])
def check_directory_exists(directory, do_not_log=False):
"""
Check a theme directory exists and if not create it
@ -103,6 +119,15 @@ class SlideLimits(object):
Wrap = 2
Next = 3
def de_hump(name):
"""
Change any Camel Case string to python string
"""
sub_name = FIRST_CAMEL_REGEX.sub(r'\1_\2', name)
return SECOND_CAMEL_REGEX.sub(r'\1_\2', sub_name).lower()
from .openlpmixin import OpenLPMixin
from .registry import Registry
from .uistrings import UiStrings
from .settings import Settings

View File

@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2013 Raoul Snyman #
# Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan #
# Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, #
# Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. #
# Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, #
# Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, #
# Frode Woldsund, Martin Zibricky, Patrick Zimmermann #
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the Free #
# Software Foundation; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
"""
Provide Error Handling Services
"""
import logging
from openlp.core.common import trace_error_handler
class OpenLPMixin(object):
"""
Base Calling object for OpenLP classes.
"""
def __init__(self, parent=None):
super(OpenLPMixin, self).__init__(parent)
print(self.__class__, self.__module__)
def log_error(self, message):
"""
Common log error handler which prints the calling path
"""
log = logging.getLogger(self.__module__)
trace_error_handler(log)
log.error(message)
def log_exception(self, message):
"""
Common log exception handler which prints the calling path
"""
log = logging.getLogger(self.__module__)
trace_error_handler(log)
log.exception(message)

View File

@ -36,7 +36,7 @@ import json
from xml.dom.minidom import Document
from lxml import etree, objectify
from openlp.core.common import AppLocation
from openlp.core.common import AppLocation, de_hump
from openlp.core.lib import str_to_bool, ScreenList, get_text_file_string
@ -157,9 +157,6 @@ class ThemeXML(object):
"""
A class to encapsulate the Theme XML.
"""
FIRST_CAMEL_REGEX = re.compile('(.)([A-Z][a-z]+)')
SECOND_CAMEL_REGEX = re.compile('([a-z0-9])([A-Z])')
def __init__(self):
"""
Initialise the theme object.
@ -532,7 +529,7 @@ class ThemeXML(object):
reject, master, element, value = self._translate_tags(master, element, value)
if reject:
return
field = self._de_hump(element)
field = de_hump(element)
tag = master + '_' + field
if field in BOOLEAN_LIST:
setattr(self, tag, str_to_bool(value))
@ -557,13 +554,6 @@ class ThemeXML(object):
theme_strings.append('%30s: %s' % (key, getattr(self, key)))
return '\n'.join(theme_strings)
def _de_hump(self, name):
"""
Change Camel Case string to python string
"""
sub_name = ThemeXML.FIRST_CAMEL_REGEX.sub(r'\1_\2', name)
return ThemeXML.SECOND_CAMEL_REGEX.sub(r'\1_\2', sub_name).lower()
def _build_xml_from_attrs(self):
"""
Build the XML from the varables in the object

View File

@ -730,7 +730,7 @@ class ServiceManager(QtGui.QWidget, ServiceManagerDialog):
Settings().setValue('servicemanager/last file', file_name)
else:
critical_error_message_box(message=translate('OpenLP.ServiceManager', 'File is not a valid service.'))
log.exception('File contains no service data')
log.error('File contains no service data')
except (IOError, NameError, zipfile.BadZipfile):
log.exception('Problem loading service file %s' % file_name)
critical_error_message_box(message=translate('OpenLP.ServiceManager',
@ -741,7 +741,7 @@ class ServiceManager(QtGui.QWidget, ServiceManagerDialog):
QtGui.QMessageBox.information(self, translate('OpenLP.ServiceManager', 'Empty File'),
translate('OpenLP.ServiceManager', 'This service file does not contain any data.'))
else:
log.exception('Service file is cannot be extracted as zip: '
log.error('Service file is cannot be extracted as zip: '
'%s' % file_name)
QtGui.QMessageBox.information(self, translate('OpenLP.ServiceManager', 'Corrupt File'),
translate('OpenLP.ServiceManager',

View File

@ -490,7 +490,7 @@ class ThemeManager(QtGui.QWidget, ThemeManagerHelper):
theme_zip = zipfile.ZipFile(file_name)
xml_file = [name for name in theme_zip.namelist() if os.path.splitext(name)[1].lower() == '.xml']
if len(xml_file) != 1:
log.exception('Theme contains "%s" XML files' % len(xml_file))
log.error('Theme contains "%s" XML files' % len(xml_file))
raise Exception('validation')
xml_tree = ElementTree(element=XML(theme_zip.read(xml_file[0]))).getroot()
theme_name = xml_tree.find('name').text.strip()
@ -543,7 +543,7 @@ class ThemeManager(QtGui.QWidget, ThemeManagerHelper):
critical_error_message_box(
translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager', 'File is not a valid theme.'))
log.exception('Theme file does not contain XML data %s' % file_name)
log.error('Theme file does not contain XML data %s' % file_name)
def check_if_theme_exists(self, theme_name):
"""

View File

@ -93,7 +93,7 @@ class CSVBible(BibleDB):
success = True
language_id = self.get_language(bible_name)
if not language_id:
log.exception('Importing books from "%s" failed' % self.filename)
log.error('Importing books from "%s" failed' % self.filename)
return False
books_file = None
book_list = {}
@ -112,7 +112,7 @@ class CSVBible(BibleDB):
str(line[2], details['encoding']))
book_ref_id = self.get_book_ref_id_by_name(str(line[2], details['encoding']), 67, language_id)
if not book_ref_id:
log.exception('Importing books from "%s" failed' % self.booksfile)
log.error('Importing books from "%s" failed' % self.booksfile)
return False
book_details = BiblesResourcesDB.get_book_by_id(book_ref_id)
self.create_book(str(line[2], details['encoding']), book_ref_id, book_details['testament_id'])

View File

@ -552,7 +552,7 @@ class HTTPBible(BibleDB):
handler = BSExtract(self.proxy_server)
books = handler.get_books_from_http(self.download_name)
if not books:
log.exception('Importing books from %s - download name: "%s" '\
log.error('Importing books from %s - download name: "%s" '\
'failed' % (self.download_source, self.download_name))
return False
self.wizard.progress_bar.setMaximum(len(books) + 2)
@ -564,7 +564,7 @@ class HTTPBible(BibleDB):
else:
language_id = self.get_language(bible_name)
if not language_id:
log.exception('Importing books from %s failed' % self.filename)
log.error('Importing books from %s failed' % self.filename)
return False
for book in books:
if self.stop_import_flag:
@ -573,7 +573,7 @@ class HTTPBible(BibleDB):
'BiblesPlugin.HTTPBible', 'Importing %s...', 'Importing <book name>...') % book)
book_ref_id = self.get_book_ref_id_by_name(book, len(books), language_id)
if not book_ref_id:
log.exception('Importing books from %s - download name: "%s" '\
log.error('Importing books from %s - download name: "%s" '\
'failed' % (self.download_source, self.download_name))
return False
book_details = BiblesResourcesDB.get_book_by_id(book_ref_id)

View File

@ -84,14 +84,14 @@ class OpenSongBible(BibleDB):
bible = opensong.getroot()
language_id = self.get_language(bible_name)
if not language_id:
log.exception('Importing books from "%s" failed' % self.filename)
log.error('Importing books from "%s" failed' % self.filename)
return False
for book in bible.b:
if self.stop_import_flag:
break
book_ref_id = self.get_book_ref_id_by_name(str(book.attrib['n']), len(bible.b), language_id)
if not book_ref_id:
log.exception('Importing books from "%s" failed' % self.filename)
log.error('Importing books from "%s" failed' % self.filename)
return False
book_details = BiblesResourcesDB.get_book_by_id(book_ref_id)
db_book = self.create_book(str(book.attrib['n']), book_ref_id, book_details['testament_id'])

View File

@ -131,7 +131,7 @@ class OSISBible(BibleDB):
if not language_id:
language_id = self.get_language(bible_name)
if not language_id:
log.exception('Importing books from "%s" failed' % self.filename)
log.error('Importing books from "%s" failed' % self.filename)
return False
match_count += 1
book = str(match.group(1))
@ -140,7 +140,7 @@ class OSISBible(BibleDB):
verse_text = match.group(4)
book_ref_id = self.get_book_ref_id_by_name(book, book_count, language_id)
if not book_ref_id:
log.exception('Importing books from "%s" failed' % self.filename)
log.error('Importing books from "%s" failed' % self.filename)
return False
book_details = BiblesResourcesDB.get_book_by_id(book_ref_id)
if not db_book or db_book.name != book_details['name']:

View File

@ -127,7 +127,7 @@ class OooImport(SongImport):
manager = uno_instance.ServiceManager
self.desktop = manager.createInstanceWithContext("com.sun.star.frame.Desktop", uno_instance)
return
raise
raise Exception('Unable to start LibreOffice')
def startOooProcess(self):
try:

View File

@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2013 Raoul Snyman #
# Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan #
# Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, #
# Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. #
# Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, #
# Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, #
# Frode Woldsund, Martin Zibricky, Patrick Zimmermann #
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the Free #
# Software Foundation; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
"""
Functional tests to test the AppLocation class and related methods.
"""
from unittest import TestCase
from openlp.core.common import de_hump
class TestInitFunctions(TestCase):
"""
A test suite to test out various functions in the __init__ class.
"""
def de_hump_conversion_test(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
self.assertTrue(new_string == "my_class", 'The class name should have been converted')
def de_hump_static_test(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
self.assertTrue(new_string == "my_class", 'The class name should have been preserved')