Changed preferences to use JSON for v3

pull/91/head
Luc Charland 2015-04-28 11:02:43 -04:00 committed by Francis Lachapelle
parent f49610f058
commit 243726f096
4 changed files with 173 additions and 149 deletions

View File

@ -7,6 +7,9 @@ import simplejson
import sogoLogin
DEBUG=False
#DEBUG=True
# must be kept in sync with SoObjects/SOGo/SOGoDefaults.plist
# this should probably be fetched magically...
@ -18,122 +21,128 @@ SOGoSupportedLanguages = [ "Arabic", "Basque", "Catalan", "Czech", "Dutch", "Dan
daysBetweenResponseList=[1,2,3,5,7,14,21,30]
class HTTPPreferencesPOST (webdavlib.HTTPPOST):
cookie = None
def prepare_headers (self):
headers = webdavlib.HTTPPOST.prepare_headers(self)
if self.cookie:
headers["Cookie"] = self.cookie
return headers
cookie = None
def prepare_headers (self):
headers = webdavlib.HTTPPOST.prepare_headers(self)
if self.cookie:
headers["Cookie"] = self.cookie
return headers
class HTTPPreferencesGET (webdavlib.HTTPGET):
cookie = None
cookie = None
def prepare_headers (self):
headers = webdavlib.HTTPGET.prepare_headers(self)
if self.cookie:
headers["Cookie"] = self.cookie
return headers
def prepare_headers (self):
headers = webdavlib.HTTPGET.prepare_headers(self)
if self.cookie:
headers["Cookie"] = self.cookie
return headers
class preferences:
login = username
passw = password
login = username
passw = password
def __init__(self, otherLogin = None, otherPassword = None):
if otherLogin and otherPassword:
self.login = otherLogin
self.passw = otherPassword
def __init__(self, otherLogin = None, otherPassword = None):
if otherLogin and otherPassword:
self.login = otherLogin
self.passw = otherPassword
self.client = webdavlib.WebDAVClient(hostname, port)
self.client = webdavlib.WebDAVClient(hostname, port)
authCookie = sogoLogin.getAuthCookie(hostname, port, self.login, self.passw)
self.cookie = authCookie
authCookie = sogoLogin.getAuthCookie(hostname, port, self.login, self.passw)
self.cookie = authCookie
# map between preferences/jsonDefaults and the webUI names
# should probably be unified...
self.preferencesMap = {
"SOGoLanguage": "language",
"SOGoTimeZone": "timezone",
"SOGoSieveFilters": "sieveFilters",
#- If this is not set, we CAN'T save preferences
self.preferences = None
# Vacation stuff
"Vacation": "enableVacation", # to disable, don't specify it
"autoReplyText": "autoReplyText", # string
"autoReplyEmailAddresses": "autoReplyEmailAddresses", # LIST
"daysBetweenResponse": "daysBetweenResponsesList",
"ignoreLists": "ignoreLists", #bool
def find_key(self, d, key):
if key in d:
return d
subdicts = [a[1] for a in d.iteritems() if type(a[1]) == dict]
for subd in subdicts:
ret = self.find_key(subd, key)
if ret:
return ret
return None
# forward stuff
"Forward": "enableForward", # to disable, don't specify it
"forwardAddress": "forwardAddress",
"keepCopy": "forwardKeepCopy",
def load_preferences(self):
defaults = self.get_defaults()
settings = self.get_settings()
self.preferences = {'defaults': defaults, 'settings': settings}
#print "LOAD PREFS:", self.preferences
# Calendar stuff
"enablePreventInvitations": "preventInvitations",
"PreventInvitations": "PreventInvitations",
"whiteList": "whiteList",
}
def get(self, preference=None):
if not self.preferences:
self.load_preferences()
#- Want the whole thing
if not preference:
return self.preferences
else:
tmpdict = self.find_key(self.preferences, preference)
return tmpdict[preference]
def _get(self, subtype='jsonDefault', preference=None):
url = "/SOGo/so/%s/%s" % (self.login, subtype)
get = HTTPPreferencesGET(url)
get.cookie = self.cookie
self.client.execute(get)
if DEBUG: print "LUC (url):", url
if DEBUG: print "LUC (status):", get.response["status"]
if DEBUG: print "LUC (body):", get.response['body']
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
def set(self, preference, value=None):
# if preference is a dict, set all prefs found in the dict
content=""
if isinstance(preference, dict):
for k,v in preference.items():
content+="%s=%s&" % (self.preferencesMap[k], urllib.quote(v))
else:
# assume it is a str
formKey = self.preferencesMap[preference]
content = "%s=%s&hasChanged=1" % (formKey, urllib.quote(value))
def get_defaults(self, preference=None):
return self._get('jsonDefaults', preference)
def get_settings(self, preference=None):
return self._get('jsonSettings', preference)
url = "/SOGo/so/%s/preferences" % self.login
def set_nosave(self, preference, value=None):
# First check if we did a get, if not, must get first
if not self.preferences:
self.load_preferences()
post = HTTPPreferencesPOST (url, content)
post.content_type = "application/x-www-form-urlencoded"
post.cookie = self.cookie
# Get the right sub-dict and change the key/value
subdict = self.find_key(self.preferences, preference)
if not subdict:
print "LUC(nosubdict):", preference, self.preferences
subdict[preference] = value
self.client.execute (post)
def set(self, preference, value=None):
self.set_nosave(preference, value)
self.save()
# Raise an exception if the pref wasn't properly set
if post.response["status"] != 200:
raise Exception ("failure setting prefs, (code = %d)" \
def set_multiple(self, preferences={}):
for key, value in preferences.iteritems():
self.set_nosave(key, value)
self.save()
def save(self):
url = "/SOGo/so/%s/Preferences/save" % self.login
post = HTTPPreferencesPOST(url, simplejson.dumps(self.preferences))
post.content_type = "application/json"
post.cookie = self.cookie
self.client.execute(post)
# Raise an exception if the pref wasn't properly set
if post.response["status"] != 200:
raise Exception ("failure setting prefs, (code = %d)" \
% post.response["status"])
def get(self, preference=None):
url = "/SOGo/so/%s/preferences/jsonDefaults" % self.login
get = HTTPPreferencesGET (url)
get.cookie = self.cookie
self.client.execute (get)
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
def get_settings(self, preference=None):
url = "/SOGo/so/%s/preferences/jsonSettings" % self.login
get = HTTPPreferencesGET (url)
get.cookie = self.cookie
self.client.execute (get)
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
# Simple main to test this class
if __name__ == "__main__":
p = preferences ()
print p.get ("SOGoLanguage")
p.set ("SOGoLanguage", SOGoSupportedLanguages.index("French"))
print p.get ("SOGoLanguage")
p = preferences ()
print p.get ("SOGoLanguage")
p.set ("SOGoLanguage", SOGoSupportedLanguages.index("French"))
print p.get ("SOGoLanguage")

View File

@ -9,6 +9,12 @@ import utilities
class preferencesTest(unittest.TestCase):
def setUp(self):
self.prefs = preferences.preferences()
def tearDown(self):
self.prefs.set("autoReplyText", "")
def _setTextPref(self, prefText = None ):
""" set a text preference to a known value """
self.prefs.set("autoReplyText", prefText)
@ -19,15 +25,8 @@ class preferencesTest(unittest.TestCase):
self.assertEqual(prefData["autoReplyText"], prefText,
"%s != %s" % (prefData["autoReplyText"], prefText))
def setUp(self):
self.prefs = preferences.preferences()
def tearDown(self):
self.prefs.set("autoReplyText", "")
def testSetTextPreferences(self):
""" Set/get a text preference - normal characters"""
self._setTextPref("defaultText")
def testSetTextPreferencesWeirdChars(self):
@ -37,17 +36,17 @@ class preferencesTest(unittest.TestCase):
def testSetPreventInvitation(self):
""" Set/get the PreventInvitation pref"""
self.prefs.set('PreventInvitations', '0')
notset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.prefs.set('PreventInvitations', 0)
notset = self.prefs.get('Calendar')['PreventInvitations']
self.assertEqual(notset, 0)
self.prefs.set('enablePreventInvitations', '0')
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get('Calendar')['PreventInvitations']
self.assertEqual(isset, 1)
def testPreventInvitationsWhiteList(self):
"""Add to the PreventInvitations Whitelist"""
self.prefs.set("whiteList", simplejson.dumps(white_listed_attendee))
whitelist = self.prefs.get_settings('Calendar')['PreventInvitationsWhitelist']
self.prefs.set("PreventInvitationsWhitelist", white_listed_attendee)
whitelist = self.prefs.get('Calendar')['PreventInvitationsWhitelist']
self.assertEqual(whitelist, white_listed_attendee)

View File

@ -26,18 +26,26 @@ class preventInvitationsTest(unittest.TestCase):
def setUp(self):
self.prefs = preferences.preferences(attendee1, attendee1_password)
self.caldav = CalDAVSchedulingTest(self)
cal = self.prefs.get("Calendar")
if "PreventInvitationsWhitelist" not in cal:
#print "LUC (cal):", cal
cal["PreventInvitationsWhitelist"] = None
self.prefs.set("PreventInvitationsWhitelist", None)
def tearDown(self):
self.prefs.set("autoReplyText", "")
self.prefs.set('PreventInvitations', '0')
self.prefs.set("whiteList", "")
self.prefs.set('PreventInvitations', 0)
self.prefs.set("PreventInvitationsWhitelist", None)
#- Manual Cleanup, not called because classs is not derived from unittest
self.caldav.tearDown()
def not_test_empty_string_instead_of_null(self):
self.prefs.set('PreventInvitationsWhitelist', "")
def testDontPreventInvitation(self):
""" Set/get the PreventInvitation pref"""
#- First accept the invitation
self.prefs.set('PreventInvitations', '0')
self.prefs.set('PreventInvitations', 0)
notset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(notset, 0)
self.caldav.AddAttendee()
@ -46,7 +54,7 @@ class preventInvitationsTest(unittest.TestCase):
def testPreventInvitation(self):
""" Set PreventInvitation and don't accept the Invitation"""
#- Second, enable PreventInviation and refuse it
self.prefs.set('enablePreventInvitations', '0')
self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(isset, 1)
self.caldav.AddAttendee(409)
@ -55,13 +63,13 @@ class preventInvitationsTest(unittest.TestCase):
def testPreventInvitationWhiteList(self):
""" Set PreventInvitation add to WhiteList and accept the Invitation"""
#- First, add the Organiser to the Attendee's whitelist
self.prefs.set('enablePreventInvitations', '0')
self.prefs.set("whiteList", simplejson.dumps(white_listed_attendee))
self.prefs.set('PreventInvitations', 1)
self.prefs.set("PreventInvitationsWhitelist", simplejson.dumps(white_listed_attendee))
whitelist = self.prefs.get_settings('Calendar')['PreventInvitationsWhitelist']
self.assertEqual(whitelist, white_listed_attendee)
#- Second, try again to invite, it should work
self.prefs.set('enablePreventInvitations', '0')
self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(isset, 1)
self.caldav.AddAttendee()

74
Tests/Integration/test-sieve.py 100644 → 100755
View File

@ -16,17 +16,14 @@ sieve_simple_filter="""require ["fileinto"];\r\nif anyof (header :contains "subj
class sieveTest(unittest.TestCase):
def _killFilters(self):
filtersKill={}
# kill existing filters
filtersKill["SOGoSieveFilters"]= "[]"
# vacation filters
filtersKill["autoReplyText"] = ""
filtersKill["autoReplyEmailAddresses"] = ""
# forwarding filters
filtersKill["forwardAddress"] = ""
self.prefs=preferences.preferences()
self.prefs.set(filtersKill)
# kill existing filters
self.prefs.set("SOGoSieveFilters", [{}])
# vacation filters
self.prefs.set("autoReplyText", "")
self.prefs.set("autoReplyEmailAddresses", "")
# forwarding filters
self.prefs.set("forwardAddress", "")
def setUp(self):
ret = ""
@ -73,13 +70,16 @@ class sieveTest(unittest.TestCase):
"days": preferences.daysBetweenResponseList[daysSelect],
}
filterAdd = {"Vacation":"1",
"autoReplyText": vacation_msg,
"daysBetweenResponse": "%d" % daysSelect,
"autoReplyEmailAddresses": self.user_email,
}
# Enabling Vacation now is an 'enabled' setting in the subdict Vacation
# We need to get that subdict first -- next save/set will also save this
vacation = self.prefs.get("Vacation")
vacation['enabled'] = 1
self.prefs.set_nosave("autoReplyText", vacation_msg)
self.prefs.set_nosave("daysBetweenResponse", "%d" % daysSelect)
self.prefs.set_nosave("autoReplyEmailAddresses", self.user_email)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript=self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript)
@ -94,14 +94,17 @@ class sieveTest(unittest.TestCase):
"days": preferences.daysBetweenResponseList[daysSelect],
}
filterAdd = {"Vacation":"1",
"autoReplyText": vacation_msg,
"daysBetweenResponse": "%d" % daysSelect,
"autoReplyEmailAddresses": self.user_email,
"ignoreLists": "1",
}
# Enabling Vacation now is an 'enabled' setting in the subdict Vacation
# We need to get that subdict first -- next save/set will also save this
vacation = self.prefs.get("Vacation")
vacation['enabled'] = 1
self.prefs.set_nosave("autoReplyText", vacation_msg)
self.prefs.set_nosave("daysBetweenResponse", "%d" % daysSelect)
self.prefs.set_nosave("autoReplyEmailAddresses", self.user_email)
self.prefs.set_nosave("ignoreLists", 1)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript=self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript)
@ -112,11 +115,13 @@ class sieveTest(unittest.TestCase):
sieveScript = sieve_simple_forward % { "redirect_mailaddr": redirect_mailaddr }
filterAdd = { "Forward": "1",
"forwardAddress": redirect_mailaddr,
}
# Enabling Forward now is an 'enabled' setting in the subdict Forward
# We need to get that subdict first -- next save/set will also save this
forward = self.prefs.get("Forward")
forward['enabled'] = 1
self.prefs.set("forwardAddress", redirect_mailaddr)
self.prefs.set(filterAdd)
createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript)
@ -126,12 +131,15 @@ class sieveTest(unittest.TestCase):
sieveScript = sieve_forward_keep % { "redirect_mailaddr": redirect_mailaddr }
filterAdd = { "Forward": "1",
"forwardAddress": redirect_mailaddr,
"keepCopy": "1",
}
# Enabling Forward now is an 'enabled' setting in the subdict Forward
# We need to get that subdict first -- next save/set will also save this
forward = self.prefs.get("Forward")
forward['enabled'] = 1
self.prefs.set_nosave("forwardAddress", redirect_mailaddr)
self.prefs.set_nosave("keepCopy", 1)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript)
@ -145,7 +153,7 @@ class sieveTest(unittest.TestCase):
filterAdd = { "SOGoSieveFilters": """[{"active": true, "actions": [{"method": "fileinto", "argument": "Sent"}], "rules": [{"operator": "contains", "field": "subject", "value": "%s"}], "match": "any", "name": "%s"}]""" % (subject, folderName)
}
self.prefs.set(filterAdd)
self.prefs.set_multiple(filterAdd)
createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript)