Impl a bit more. Switched to use py.test

bzr-revno: 59
This commit is contained in:
Carsten Tinggaard 2008-10-30 11:36:11 +00:00
parent bf9b1c50fc
commit fd05e8c6fe
6 changed files with 215 additions and 145 deletions

View File

@ -15,4 +15,4 @@ 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
"""
from song import Song
from song import Song, SongTitleError

View File

@ -16,88 +16,18 @@ this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
"""
import platform
ver = platform.python_version()
if ver >= '2.5':
from xml.etree.ElementTree import ElementTree, XML
else:
from elementtree import ElementTree, XML
import sys
import os
sys.path.append(os.path.abspath("./../.."))
from openlp.core.xmlrootclass import XmlRootClass
# borrowed from theme - can be common
DelphiColors={"clRed":0xFF0000,
"clBlack":0x000000,
"clWhite":0xFFFFFF}
class SongException(Exception):
pass
class RootClass(object):
"""Root class for themes, songs etc
class SongTitleError(SongException):
pass
provides interface for parsing xml files into object attributes
"""
def _setFromXml(self, xml, rootTag):
"""Set song properties from given xml content
xml (string) -- formatted as xml tags and values
rootTag -- main tag of the xml
"""
root=ElementTree(element=XML(xml))
iter=root.getiterator()
for element in iter:
if element.tag != rootTag:
t=element.text
#print element.tag, t, type(t)
if type(t) == type(None): # easy!
val=t
if type(t) == type(" "): # strings need special handling to sort the colours out
#print "str",
if t[0] == "$": # might be a hex number
#print "hex",
try:
val=int(t[1:], 16)
except ValueError: # nope
#print "nope",
pass
elif DelphiColors.has_key(t):
#print "colour",
val=DelphiColors[t]
else:
#print "last chance",
try:
val=int(t)
#print "int",
except ValueError:
#print "give up",
val=t
if (element.tag.find("Color") > 0 or
(element.tag.find("BackgroundParameter") == 0 and type(val) == type(0))):
# convert to a QtGui.Color
val= QtGui.QColor((val>>16) & 0xFF, (val>>8)&0xFF, val&0xFF)
#print [val]
setattr(self,element.tag, val)
pass
def __str__(self):
"""Return string with all public attributes
The string is formatted with one attribute per line
If the string is split on newline then the length of the
list is equal to the number of attributes
"""
l = []
for k in dir(self):
if not k.startswith("_"):
l.append("%30s : %s" %(k,getattr(self,k)))
return "\n".join(l)
def _get_as_string(self):
"""Return one string with all public attributes"""
s=""
for k in dir(self):
if not k.startswith("_"):
s+= "_%s_" %(getattr(self,k))
return s
blankSongXml = \
'''<?xml version="1.0" encoding="iso-8859-1"?>
<Song>
@ -120,7 +50,7 @@ blankSongXml = \
</Song>
'''
class Song(RootClass) :
class Song(XmlRootClass) :
"""Class for handling song properties"""
def __init__(self, xmlContent = None):
@ -144,9 +74,65 @@ class Song(RootClass) :
songNumber -- number of the song, related to a songbook
comments -- free comment
verseOrder -- presentation order of the slides
lyrics -- simple or xml formatted (tbd)
lyrics -- simple or formatted (tbd)
"""
super(Song, self).__init__()
self._reset()
def _reset(self):
"""Reset all song attributes"""
global blankSongXml
self._setFromXml(blankSongXml, "Song")
def _RemovePunctuation(self, title):
"""Remove the puntuation chars from title
chars are: .,:;!?&%#/\@`$'|"^~*
"""
punctuation = ".,:;!?&%#'\"/\\@`$|^~*"
s = title
for c in punctuation :
s = s.replace(c, '')
return s
def SetTitle(self, title):
"""Set the song title
title (string)
"""
self.title = title.strip()
self.searchableTitle = self._RemovePunctuation(title).strip()
if len(self.title) < 1 :
raise SongTitleError("The title is empty")
if len(self.searchableTitle) < 1 :
raise SongTitleError("The searchable title is empty")
def GetTitle(self):
"""Return title value"""
return self.title
def GetSearchableTitle(self):
"""Return searchableTitle"""
return self.searchableTitle
def FromTextList(self, textList):
"""Create song from a list of texts (strings) - CCLI text format expected
textList (list of strings) -- the song
"""
self._reset()
# TODO: Implement CCLI text parse
def FromTextFile(self, textFileName):
"""Create song from a list of texts read from given file
textFileName -- path to text file
"""
textList = []
f = open(textFileName, 'r')
for line in f :
textList.append(line)
f.close()
self.FromText(textList)

View File

@ -1,64 +0,0 @@
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 Carsten Tinggaard
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
"""
import unittest
import os
import sys
mypath=os.path.split(os.path.abspath(__file__))[0]
sys.path.insert(0,(os.path.join(mypath, '..' ,'..', '..')))
from openlp.song import Song
class SongTest_Init(unittest.TestCase):
"""Class for first initialization check"""
def testCreation(self):
"""Init: Create as empty"""
s = Song()
self.assertTrue(True)
def test_str(self):
"""Init: Empty, use __str__ to count attributes"""
s = Song()
r = s.__str__()
l = r.split("\n")
#print r
self.assertEqual(len(l), 16)
def test_asString(self):
"""Init: Empty asString"""
s = Song()
r = s._get_as_string()
#print r
self.assertEqual(len(r), 89)
class SongTest_ParseText(unittest.TestCase):
"""Test cases for converting from text format to Song"""
def testSimple(self):
"""Text: Simply return True"""
self.failUnless(True)
if "__main__" == __name__:
suite1 = unittest.TestLoader().loadTestsFromTestCase(SongTest_ParseText)
suite2 = unittest.TestLoader().loadTestsFromTestCase(SongTest_Init)
alltests = unittest.TestSuite([suite1, suite2])
unittest.TextTestRunner(verbosity=2).run(alltests)

View File

@ -0,0 +1,86 @@
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 Carsten Tinggaard
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
"""
import py.test
import os
import sys
sys.path.append(os.path.abspath("./../../.."))
from openlp.song import *
class Test_Basic(object):
"""Class for first initialization check
set-get functions
"""
def test_Creation(self):
"""Init: Create as empty"""
s = Song()
assert(True)
def test_str(self):
"""Init: Empty, use __str__ to count public attributes & methods"""
s = Song()
r = s.__str__()
l = r.split("\n")
#print r
assert(len(l) == 21)
def test_asString(self):
"""Init: Empty asString - initial values"""
s = Song()
r = s._get_as_string()
flag = r.endswith("__None__None__None__None__None__None__1__1__1__1__None__None__None__None__BlankSong__None_")
assert(flag)
def test_Title1(self):
"""Set an empty title - raises an exception"""
s = Song()
py.test.raises(SongTitleError, s.SetTitle, "")
def test_Title2(self):
"""Set a normal title"""
s = Song()
t = "A normal title"
s.SetTitle(t)
assert(s.GetTitle() == t)
assert(s.GetSearchableTitle() == t)
def test_Title2(self):
"""Set a titel with punctuation 1"""
s = Song()
t1 = "Hey! Come on, ya programmers*"
t2 = "Hey Come on ya programmers"
s.SetTitle(t1)
assert(s.GetTitle() == t1)
assert(s.GetSearchableTitle() == t2)
def test_Title3(self):
"""Set a titel with punctuation 2"""
s = Song()
t1 = "??#Hey! Come on, ya programmers*"
t2 = "Hey Come on ya programmers"
s.SetTitle(t1)
assert(s.GetTitle() == t1)
assert(s.GetSearchableTitle() == t2)
def test_Title4(self):
"""Set a title, where searchable title becomes empty - raises an exception"""
s = Song()
py.test.raises(SongTitleError, s.SetTitle, ",*")

View File

@ -0,0 +1,31 @@
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 Carsten Tinggaard
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
"""
import os
import sys
sys.path.append(os.path.abspath("./../../.."))
from openlp.song import Song
class Test_OpenSong(object):
"""Test cases for converting from OpenSong xml format to Song"""
def test_Simple(self):
"""OpenSong: Simply return True"""
assert(True)

View File

@ -0,0 +1,31 @@
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 Carsten Tinggaard
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
"""
import os
import sys
sys.path.append(os.path.abspath("./../../.."))
from openlp.song import Song
class Test_Text(object):
"""Test cases for converting from text format to Song"""
def test_Simple(self):
"""Text: Simply return True"""
assert(True)