diff --git a/Doxyfile b/Doxyfile index 56ec070..27dca58 100644 --- a/Doxyfile +++ b/Doxyfile @@ -31,7 +31,7 @@ PROJECT_NAME = "Python ChannelFinder Client Library" # This could be handy for archiving the generated documentation or # if some version control system is used. -PROJECT_NUMBER = "1.1.0" +PROJECT_NUMBER = "3.0.0" # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. diff --git a/channelfinder/ChannelFinderClient.py b/channelfinder/ChannelFinderClient.py index 114bec7..a6a1c1c 100644 --- a/channelfinder/ChannelFinderClient.py +++ b/channelfinder/ChannelFinderClient.py @@ -50,7 +50,7 @@ def __init__(self, BaseURL=None, username=None, password=None): self.__auth = None self.__session = requests.Session() self.__session.mount('https://localhost:8181/ChannelFinder/', Ssl3HttpAdapter()) - self.__session.get(self.__baseURL, verify=False, headers=copy(self.__jsonheader)).raise_for_status() + #self.__session.get(self.__baseURL, verify=False, headers=copy(self.__jsonheader)).raise_for_status() except: raise Exception, 'Failed to create client to ' + self.__baseURL @@ -67,9 +67,14 @@ def set(self, **kwds): The operation creates a new entry if none exists and destructively replaces existing entries. set(channel = Channel) >>> set(channel={'name':'channelName', 'owner':'channelOwner'}) - + >>> set(channel={'name':'channelName', + 'owner':'channelOwner', + 'tags':[{'name':'tagName1', 'owner':'tagOwner'}, ...], + 'properties':[{'name':'propName1', 'owner':'propOwner', 'value':'propValue1'}, ...]}) + set(channels = [Channel]) >>> set(channels=[{'name':'chName1','owner':'chOwner'},{'name':'chName2','owner':'chOwner'}]) + >>> set(channels=[{'name':'chName1','owner':'chOwner', 'tags':[...], 'properties':[...]}, {...}]) set(tag = Tag) >>> set(tag={'name':'tagName','owner':'tagOwner'}) @@ -87,25 +92,20 @@ def set(self, **kwds): *** if you simply want to append a tag or property use the update operation*** set(tag=Tag, channelName=String) - >>> set(tag={'name':'tagName','owner':'tagOwner}, channelName='chName') + >>> set(tag={'name':'tagName','owner':'tagOwner'}, channelName='chName') # will create/replace specified Tag # and add it to the channel with the name = channelName set(tag=Tag, channelNames=[String]) - >>> set (tag={'name':'tagName','owner':'tagOwner}, channelNames=['ch1','ch2','ch3']) + >>> set (tag={'name':'tagName','owner':'tagOwner'}, channelNames=['ch1','ch2','ch3']) # will create/replace the specified Tag # and add it to the channels with the names specified in channelNames # and delete it from all other channels - set(property=Property, channelName=String) - >>> set(property={'name':'propName','owner':'propOwner','value':'propValue'}, channelName='channelName') - # will create/replace the specified Property - # and add it to the channel with the name = channelName - set(property=Property, channelNames=[String]) - >>> set(property={'name':'propName','owner':'propOwner','value':'propValue'}, channelNames=[String]) + >>> set(property={'name':'propName','owner':'propOwner','value':'propValue'}, channels=[...]) # will create/replace the specified Property - # and add it to the channels with the names specified in channelNames + # and add it to the channels with the names specified in channels # and delete it from all other channels ''' @@ -118,62 +118,62 @@ def set(self, **kwds): def __hadleSingleAddParameter(self, **kwds): if 'channel' in kwds : - r = self.__session.put(self.__baseURL + self.__channelsResource + '/' + kwds['channel'][u'name'], \ - data=JSONEncoder().encode(kwds['channel']), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__channelsResource + '/' + kwds['channel'][u'name'], + data=JSONEncoder().encode(kwds['channel']), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'channels' in kwds : - r = self.__session.put(self.__baseURL + self.__channelsResource, \ - data=JSONEncoder().encode(kwds['channels']), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__channelsResource, + data=JSONEncoder().encode(kwds['channels']), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'tag' in kwds: - r = self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], \ - data=JSONEncoder().encode(kwds['tag']), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], + data=JSONEncoder().encode(kwds['tag']), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'tags' in kwds: data = JSONEncoder().encode(kwds['tags']) - r = self.__session.put(self.__baseURL + self.__tagsResource, \ - data=data, \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__tagsResource, + data=data, + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'property' in kwds: - r = self.__session.put(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'], \ - data=JSONEncoder().encode(kwds['property']) , \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'], + data=JSONEncoder().encode(kwds['property']) , + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'properties' in kwds: ############################ u'property' may be incorrect data = JSONEncoder().encode(kwds['properties']) - r = self.__session.put(self.__baseURL + self.__propertiesResource, \ - data=data, \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.put(self.__baseURL + self.__propertiesResource, + data=data, + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() else: - raise Exception, 'Incorrect Usage: unknown key' - + raise Exception, 'Incorrect Usage: unknown key' + def __handleMultipleAddParameters(self, **kwds): # set a tag to a channel if 'tag' in kwds and 'channelName' in kwds: channels = [{u'name':kwds['channelName'].strip(), u'owner':self.__userName}] kwds['tag']['channels'] = channels data = kwds['tag'] - self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], \ - data=JSONEncoder().encode(data), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], + data=JSONEncoder().encode(data), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'tag' in kwds and 'channelNames' in kwds: channels = [] @@ -181,22 +181,22 @@ def __handleMultipleAddParameters(self, **kwds): channels.append({u'name':eachChannel, u'owner':self.__userName}) kwds['tag']['channels'] = channels data = kwds['tag'] - self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], \ - data=JSONEncoder().encode(data), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.put(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'], + data=JSONEncoder().encode(data), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'property' in kwds and 'channels' in kwds: data = kwds['property'] data['property']['channels'] = kwds['channels'] - self.__session.put(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'], \ - data=JSONEncoder().encode(data), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.put(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'], + data=JSONEncoder().encode(data), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() else: raise Exception, 'Incorrect Usage: unknown keys' - + def __checkResponseState(self, r): ''' simply checks the return status of the http response @@ -207,48 +207,48 @@ def __checkResponseState(self, r): raise Exception, 'HTTP Error status: ' + r[u'headers']['status'] + \ ' Cause: ' + msg return r - + def find(self, **kwds): ''' Method allows you to query for a channel/s based on name, properties, tags find(name = channelNamePattern) >>> find(name='*') >>> find(name='SR:C01*') - + find(tagName = tagNamePattern) >>> find(tagName = 'myTag') - + find(property = [(propertyName,propertyValuePattern)]) >>> find(property=[('position','*')]) >>> find(property=[('position','*'),('cell','')]) - + returns a _list_ of matching Channels - special pattern matching char + special pattern matching char * for multiple char ? for single char - + Searching with multiple parameters >>> find(name='SR:C01*', tagName = 'myTag', property=[('position','pattern1')]) - return all channels with name matching 'SR:C01*' AND - with tagName = 'mytag' AND + return all channels with name matching 'SR:C01*' AND + with tagName = 'mytag' AND with property 'position' with value matching 'pattern1' - - + + For multiValued searches >>> find(name='pattern1,pattern2') will return all the channels which match either pattern1 OR pattern2 - + >>> find(property=[('propA','pattern1,pattern2')]) - will return all the channels which have the property propA and + will return all the channels which have the property propA and whose values match pattern1 OR pattern2 - + >>> find(property=[('propA', 'pattern1'),('propB', 'pattern2')]) will return all the channels which have properties _propA_ with value matching _pattern1_ AND _propB_ with value matching _pattern2_ - + >>> find(tagName='pattern1,pattern2') will return all the channels which have the tags matching pattern1 AND pattern2 - + To query for the existance of a tag or property use findTag and findProperty. ''' if not self.__baseURL: @@ -273,13 +273,13 @@ def find(self, **kwds): else: raise Exception, 'unknown find argument ' + key return self.findByArgs(args) - + def findByArgs(self, args): url = self.__baseURL + self.__channelsResource - r = self.__session.get(url, \ - params=args, \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.get(url, + params=args, + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) try: r.raise_for_status() @@ -288,8 +288,8 @@ def findByArgs(self, args): if r.status_code == 404: return None else: - r.raise_for_status() - + r.raise_for_status() + def findTag(self, tagName): ''' Searches for the _exact_ tagName and returns a single Tag object if found @@ -307,7 +307,7 @@ def findTag(self, tagName): return None else: r.raise_for_status() - + def findProperty(self, propertyName): ''' Searches for the _exact_ propertyName and return a single Property object if found @@ -322,7 +322,7 @@ def findProperty(self, propertyName): return None else: r.raise_for_status() - + def getAllTags(self): ''' return a list of all the Tags present - even the ones not associated w/t any channel @@ -337,7 +337,7 @@ def getAllTags(self): return None else: r.raise_for_status() - + def getAllProperties(self): ''' return a list of all the Properties present - even the ones not associated w/t any channel @@ -352,33 +352,33 @@ def getAllProperties(self): return None else: r.raise_for_status() - + def delete(self, **kwds): ''' Method to delete a channel, property, tag delete(channelName = String) >>> delete(channelName = 'ch1') - + delete(tagName = String) >>> delete(tagName = 'myTag') # tagName = tag name of the tag to be removed from all channels - + delete(propertyName = String) >>> delete(propertyName = 'position') # propertyName = property name of property to be removed from all channels - + delete(tag = Tag ,channelName = String) - >>> delete(tag={'name':'myTag','owner':'tagOwner'}, channelName = 'chName') + >>> delete(tag={'name':'myTag','owner':'tagOwner'}, channelName = 'chName') # delete the tag from the specified channel _chName_ - + delete(tag = Tag ,channelNames = [String]) >>> delete(tag={'name':'myTag', 'owner':'tagOwner'}, channelNames=['ch1','ch2','ch3']) # delete the tag from all the channels specified in the channelNames list - + delete(property = Property ,channelName = String) >>> delete(property = {'name':'propName','propOwner':'propOwner'} ,channelName = 'chName') # delete the property from the specified channel - + delete(property = Property ,channelNames = [String]) >>> delete(property = {'name':'propName','owner':'propOwner'} ,channelNames = ['ch1','ch2','ch3']) # delete the property from all the channels in the channelNames list @@ -389,54 +389,54 @@ def delete(self, **kwds): self.__handleMultipleDeleteParameters(**kwds) else: raise Exception, 'incorrect usage: Delete a single Channel/tag/property' - + def __handleSingleDeleteParameter(self, **kwds): if 'channelName' in kwds: url = self.__baseURL + self.__channelsResource + '/' + kwds['channelName'].strip() - self.__session.delete(url, \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.delete(url, + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() pass elif 'tagName' in kwds: url = self.__baseURL + self.__tagsResource + '/' + kwds['tagName'].strip() - self.__session.delete(url, \ - verify=False, \ - headers=copy(self.__jsonheader), \ + self.__session.delete(url, + verify=False, + headers=copy(self.__jsonheader), auth=self.__auth).raise_for_status() pass elif 'propertyName' in kwds: url = self.__baseURL + self.__propertiesResource + '/' + kwds['propertyName'].strip() - self.__session.delete(url, \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.delete(url, + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() pass else: raise Exception, ' unkown key use channelName, tagName or proprtyName' - + def __handleMultipleDeleteParameters(self, **kwds): if 'tag' in kwds and 'channelName' in kwds: - self.__session.delete(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'] + '/' + kwds['channelName'].strip(), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.delete(self.__baseURL + self.__tagsResource + '/' + kwds['tag'][u'name'] + '/' + kwds['channelName'].strip(), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'tag' in kwds and 'channelNames' in kwds: # find channels with the tag channelsWithTag = self.find(tagName=kwds['tag'][u'name']) # delete channels from which tag is to be removed - + channelNames = [channel[u'name'] for channel in channelsWithTag if channel[u'name'] not in kwds['channelNames']] self.set(tag=kwds['tag'], channelNames=channelNames) elif 'property' in kwds and 'channelName' in kwds: - self.__session.delete(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'] + '/' + kwds['channelName'], \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.delete(self.__baseURL + self.__propertiesResource + '/' + kwds['property'][u'name'] + '/' + kwds['channelName'], + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'property' in kwds and 'channelNames' in kwds: channelsWithProp = self.find(property=[(kwds['property'][u'name'], '*')]) channels = [channel for channel in channelsWithProp if channel[u'name'] not in kwds['channelNames']] - self.set(property=kwds['property'], channels=channels) + self.set(property=kwds['property'], channels=channels) else: raise Exception, ' unkown keys' @@ -452,51 +452,51 @@ def update(self, **kwds): {'name':'newProp','owner':'propOwner','value':'Val'}, {'name':'existingProp','owner':'propOwner','value':'newVal'}], tags=[{'name':'mytag','owner':'tagOwner'}]}) - # updates the channel 'existingCh' with the new provided properties and tags - # without affecting the other tags and properties of this channel - + # updates the channel 'existingCh' with the new provided properties and tags + # without affecting the other tags and properties of this channel + update(property = Property, channelName = String) - >>> update(property={'name':'propName', 'owner':'propOwner', 'value':'propValue'}, + >>> update(property={'name':'propName', 'owner':'propOwner', 'value':'propValue'}, channelName='ch1') # Add Property to the channel with the name 'ch1' - # without affecting the other channels using this property - - >>>update(property={'name':'propName', 'owner':'propOwner', 'value':'propValue'}, + # without affecting the other channels using this property + + >>>update(property={'name':'propName', 'owner':'propOwner', 'value':'propValue'}, channelNames=['ch1','ch2','ch3']) # Add Property to the channels with the names in the list channelNames - # without affecting the other channels using this property - + # without affecting the other channels using this property + update(tag = Tag, channelName = String) >>> update(tag = {'name':'myTag', 'owner':'tagOwner'}, channelName='chName') # Add tag to channel with name chName # without affecting the other channels using this tag - + update(tag = Tag, channelNames = [String]) >>> update(tag = {'name':'tagName'}, channelNames=['ch1','ch2','ch3']) # Add tag to channels with names in the list channeNames - # without affecting the other channels using this tag + # without affecting the other channels using this tag update(property = Property) update(tag = Tag) - - ## RENAME OPERATIONS ## + + ## RENAME OPERATIONS ## update(channel = Channel, originalChannelName = String) - >>> update(channel = {'name':'newChannelName','owner':'channelOwner}, + >>> update(channel = {'name':'newChannelName','owner':'channelOwner'}, originalChannelName = 'oldChannelName') # rename the channel 'oldChannelName' to 'newChannelName' - + update(property = Property, originalPropertyName = String) - >>> update(property = {'name':'newPropertyName','owner':'propOwner'}, + >>> update(property = {'name':'newPropertyName','owner':'propOwner'}, originalPropertyName = 'oldPropertyName') # rename the property 'oldPropertyName' to 'newPropertyName' # the channels with the old property are also updated - + update(tag = Tag, originalTagName = String) >>> update(tab = {'name':'newTagName','owner':'tagOwner'}, originalTagName = 'oldTagName') # rename the tag 'oldTagName' to 'newTagName' # the channel with the old tag are also updated ''' - + if not self.__baseURL: raise Exception, 'Olog client not configured correctly' if len(kwds) == 1: @@ -505,105 +505,117 @@ def update(self, **kwds): self.__handleMultipleUpdateParameters(**kwds) else: raise Exception, 'incorrect usage: ' - + def __handleSingleUpdateParameter(self, **kwds): if 'channel' in kwds: ch = kwds['channel'] - r = self.__session.post(self.__baseURL + self.__channelsResource + '/' + ch[u'name'], \ - data=JSONEncoder().encode(ch), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.post(self.__baseURL + self.__channelsResource + '/' + ch[u'name'], + data=JSONEncoder().encode(ch), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'property' in kwds: property = kwds['property'] - r = self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], \ - data=JSONEncoder().encode(property), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], + data=JSONEncoder().encode(property), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'tag' in kwds: tag = kwds['tag'] - r = self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag[u'name'], \ - data=JSONEncoder().encode(tag), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag[u'name'], + data=JSONEncoder().encode(tag), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() elif 'tags' in kwds: - r = self.__session.post(self.__baseURL + self.__tagsResource, \ - data=JSONEncoder().encode(kwds['tags']), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + r = self.__session.post(self.__baseURL + self.__tagsResource, + data=JSONEncoder().encode(kwds['tags']), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth) r.raise_for_status() else: raise Exception, ' unkown key ' - + def __handleMultipleUpdateParameters(self, **kwds): if 'tag' in kwds and 'channelName' in kwds: - tag = kwds['tag'] - channels = [{u'name':kwds['channelName'].strip(), u'owner':self.__userName}] - self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag[u'name'], \ - data=JSONEncoder().encode(self.__encodeTag(tag, withChannels=channels)), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + # identity operation performed to prevent side-effects + tag = dict(kwds['tag']) + channels = [{u'name': kwds['channelName'].strip(), u'owner': self.__userName, u'tags': [tag]}] + tag = dict(tag) + tag[u'channels'] = channels + self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag[u'name'], + data=JSONEncoder().encode(tag), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'tag' in kwds and 'channelNames' in kwds: - tag = kwds['tag'] + # identity operation performed to prevent side-effects + tag = dict(kwds['tag']) channels = [] for eachChannel in kwds['channelNames']: - channels.append({u'name':eachChannel, u'owner':self.__userName}) - self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag['name'], \ - data=JSONEncoder().encode(self.__encodeTag(tag, withChannels=channels)), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + channels.append({u'name': eachChannel, u'owner': self.__userName, u'tags': [tag]}) + tag = dict(tag) + tag[u'channels'] = channels + self.__session.post(self.__baseURL + self.__tagsResource + '/' + tag[u'name'], + data=JSONEncoder().encode(tag), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'property' in kwds and 'channelName' in kwds: - property = kwds['property'] - channels = [{u'name':kwds['channelName'].strip(), u'owner':self.__userName, u'properties':[property]}] - self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], \ - data=JSONEncoder().encode(self.__encodeProperty(property, withChannels=channels)), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + # identity operation performed to prevent side-effects + property = dict(kwds['property']) + channels = [{u'name': kwds['channelName'].strip(), u'owner': self.__userName, u'properties': [property]}] + property = dict(property) + property[u'channels'] = channels + self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], + data=JSONEncoder().encode(property), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'property' in kwds and 'channelNames' in kwds: - property = kwds['property'] + # identity operation performed to prevent side-effects + property = dict(kwds['property']) channels = [] for eachChannel in kwds['channelNames']: - channels.append({u'name':eachChannel, u'owner':self.__userName, u'properties':[property]}) - self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], \ - data=JSONEncoder().encode(self.__encodeProperty(property, withChannels=channels)), \ - headers=copy(self.__jsonheader), \ - verify=False, \ - auth=self.__auth).raise_for_status() + channels.append({u'name': eachChannel.strip(), u'owner': self.__userName, u'properties': [property]}) + property = dict(property) + property[u'channels'] = channels + self.__session.post(self.__baseURL + self.__propertiesResource + '/' + property[u'name'], + data=JSONEncoder().encode(property), + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth).raise_for_status() elif 'originalChannelName' in kwds and 'channel' in kwds: ch = kwds['channel'] channelName = kwds['originalChannelName'].strip() - self.__session.post(self.__baseURL + self.__channelsResource + '/' + channelName, \ - data=JSONEncoder().encode(self.__encodeChannel(ch)) , \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.post(self.__baseURL + self.__channelsResource + '/' + channelName, + data=JSONEncoder().encode(ch), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() elif 'originalPropertyName' in kwds and 'property' in kwds: prop = kwds['property'] propName = kwds['originalPropertyName'].strip() - self.__session.post(self.__baseURL + self.__propertiesResource + '/' + propName, \ - data=JSONEncoder().encode(self.__encodeProperty(prop)), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.post(self.__baseURL + self.__propertiesResource + '/' + propName, + data=JSONEncoder().encode(prop), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() - elif 'originalTagName' in kwds and 'tag' in kwds: + elif 'originalTagName' in kwds and 'tag' in kwds: tag = kwds['tag'] tagName = kwds['originalTagName'].strip() - self.__session.post(self.__baseURL + self.__tagsResource + '/' + tagName, \ - data=JSONEncoder().encode(tag), \ - headers=copy(self.__jsonheader), \ - verify=False, \ + self.__session.post(self.__baseURL + self.__tagsResource + '/' + tagName, + data=JSONEncoder().encode(tag), + headers=copy(self.__jsonheader), + verify=False, auth=self.__auth).raise_for_status() else: - raise Exception, ' unkown keys' + raise Exception, ' unknown keys' @@ -614,6 +626,5 @@ def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, - ssl_version=ssl.PROTOCOL_SSLv3) + ssl_version=ssl.PROTOCOL_SSLv23) - diff --git a/channelfinder/cfUpdate/CFUpdateIOC.py b/channelfinder/cfUpdate/CFUpdateIOC.py index fa6c507..ae6612b 100644 --- a/channelfinder/cfUpdate/CFUpdateIOC.py +++ b/channelfinder/cfUpdate/CFUpdateIOC.py @@ -37,10 +37,10 @@ def getPVNames(completeFilePath, pattern=None): try: f = open(completeFilePath) pvNames = f.read().splitlines() - pvNames=map(lambda x: x.strip(), pvNames) - pvNames=filter(lambda x: len(x)>0, pvNames) + pvNames = map(lambda x: x.strip(), pvNames) + pvNames = filter(lambda x: len(x)>0, pvNames) if pattern: - pvNames=[ re.match(pattern,pvName).group() for pvName in pvNames if re.match(pattern, pvName) ] + pvNames = [re.match(pattern, pvName).group() for pvName in pvNames if re.match(pattern, pvName)] return pvNames except IOError: return None @@ -48,7 +48,7 @@ def getPVNames(completeFilePath, pattern=None): if f: f.close() -def updateChannelFinder(pvNames, hostName, iocName, time, owner, \ +def updateChannelFinder(pvNames, hostName, iocName, time, owner, service=None, username=None, password=None): ''' pvNames = list of pvNames @@ -77,50 +77,50 @@ def updateChannelFinder(pvNames, hostName, iocName, time, owner, \ for ch in previousChannelsList: if pvNames != None and ch.Name in pvNames: '''''' - channels.append(updateChannel(ch,\ - owner=owner, \ - hostName=hostName, \ - iocName=iocName, \ - pvStatus=u'Active', \ + channels.append(updateChannel(ch, + owner=owner, + hostName=hostName, + iocName=iocName, + pvStatus=u'Active', time=time)) pvNames.remove(ch.Name) elif pvNames == None or ch.Name not in pvNames: '''Orphan the channel : mark as inactive, keep the old hostName and iocName''' - channels.append(updateChannel(ch, \ - owner=owner, \ - hostName=ch.getProperties()[u'hostName'], \ - iocName=ch.getProperties()[u'iocName'], \ - pvStatus=u'InActive', \ + channels.append(updateChannel(ch, + owner=owner, + hostName=ch.getProperties()[u'hostName'], + iocName=ch.getProperties()[u'iocName'], + pvStatus=u'Inactive', time=ch.getProperties()[u'time'])) # now pvNames contains a list of pv's new on this host/ioc for pv in pvNames: ch = client.findByArgs([('~name',pv)]) if ch == None: '''New channel''' - channels.append(createChannel(pv, \ - chOwner=owner, \ - hostName=hostName, \ - iocName=iocName, \ - pvStatus=u'Active', \ + channels.append(createChannel(pv, + chOwner=owner, + hostName=hostName, + iocName=iocName, + pvStatus=u'Active', time=time)) elif ch[0] != None: '''update existing channel: exists but with a different hostName and/or iocName''' - channels.append(updateChannel(ch[0], \ - owner=owner, \ - hostName=hostName, \ - iocName=iocName, \ - pvStatus=u'Active', \ + channels.append(updateChannel(ch[0], + owner=owner, + hostName=hostName, + iocName=iocName, + pvStatus=u'Active', time=time)) client.set(channels=channels) -def updateChannel(channel, owner, hostName=None, iocName=None, pvStatus='InActive', time=None): +def updateChannel(channel, owner, hostName=None, iocName=None, pvStatus='Inactive', time=None): ''' Helper to update a channel object so as to not affect the existing properties ''' # properties list devoid of hostName and iocName properties if channel[u'properties']: - properties = [property for property in channel[u'properties'] \ + properties = [property for property in channel[u'properties'] if property[u'name'] != u'hostName' and property[u'name'] != u'iocName' and property[u'name'] != u'pvStatus'] else: properties = [] @@ -135,7 +135,7 @@ def updateChannel(channel, owner, hostName=None, iocName=None, pvStatus='InActiv channel[u'properties'] = properties return channel -def createChannel(chName, chOwner, hostName=None, iocName=None, pvStatus=u'InActive', time=None): +def createChannel(chName, chOwner, hostName=None, iocName=None, pvStatus=u'Inactive', time=None): ''' Helper to create a channel object with the required properties ''' @@ -184,26 +184,26 @@ def mainRun(opts, args): fHostName, fIocName = getArgsFromFilename(completeFilePath) ftime = os.path.getctime(completeFilePath) pattern = __getDefaultConfig('pattern', opts.pattern) - updateChannelFinder(getPVNames(completeFilePath, pattern=pattern), \ - ifNoneReturnDefault(opts.hostName, fHostName), \ - ifNoneReturnDefault(opts.iocName, fIocName), \ - ifNoneReturnDefault(opts.time, ftime), \ - ifNoneReturnDefault(opts.owner,__getDefaultConfig('username', opts.username)), \ - service=__getDefaultConfig('BaseURL',opts.serviceURL), \ - username=__getDefaultConfig('username',opts.username), \ + updateChannelFinder(getPVNames(completeFilePath, pattern=pattern), + ifNoneReturnDefault(opts.hostName, fHostName), + ifNoneReturnDefault(opts.iocName, fIocName), + ifNoneReturnDefault(opts.time, ftime), + ifNoneReturnDefault(opts.owner,__getDefaultConfig('username', opts.username)), + service=__getDefaultConfig('BaseURL',opts.serviceURL), + username=__getDefaultConfig('username',opts.username), password=__getDefaultConfig('password',opts.password)) else: completeFilePath = os.path.abspath(filename) fHostName, fIocName = getArgsFromFilename(completeFilePath) ftime = os.path.getctime(completeFilePath) pattern = __getDefaultConfig('pattern', opts.pattern) - updateChannelFinder(getPVNames(completeFilePath, pattern=pattern), \ - ifNoneReturnDefault(opts.hostName, fHostName), \ - ifNoneReturnDefault(opts.iocName, fIocName), \ - ifNoneReturnDefault(opts.time, ftime), \ - ifNoneReturnDefault(opts.owner,__getDefaultConfig('username', opts.username)), \ - service=__getDefaultConfig('BaseURL',opts.serviceURL), \ - username=__getDefaultConfig('username',opts.username), \ + updateChannelFinder(getPVNames(completeFilePath, pattern=pattern), + ifNoneReturnDefault(opts.hostName, fHostName), + ifNoneReturnDefault(opts.iocName, fIocName), + ifNoneReturnDefault(opts.time, ftime), + ifNoneReturnDefault(opts.owner,__getDefaultConfig('username', opts.username)), + service=__getDefaultConfig('BaseURL',opts.serviceURL), + username=__getDefaultConfig('username',opts.username), password=__getDefaultConfig('password',opts.password)) def __getDefaultConfig(arg, value): @@ -218,30 +218,30 @@ def __getDefaultConfig(arg, value): def main(): usage = "usage: %prog [options] filename" parser = OptionParser(usage=usage) - parser.add_option('-H', '--hostname', \ - action='store', type='string', dest='hostName', \ + parser.add_option('-H', '--hostname', + action='store', type='string', dest='hostName', help='the hostname') - parser.add_option('-i', '--iocname', \ - action='store', type='string', dest='iocName', \ + parser.add_option('-i', '--iocname', + action='store', type='string', dest='iocName', help='the iocname') - parser.add_option('-s', '--service', \ - action='store', type='string', dest='serviceURL', \ + parser.add_option('-s', '--service', + action='store', type='string', dest='serviceURL', help='the service URL') - parser.add_option('-o', '--owner', \ - action='store', type='string', dest='owner', \ + parser.add_option('-o', '--owner', + action='store', type='string', dest='owner', help='owner if not specified username will default as owner') - parser.add_option('-r', '--pattern', \ - action='store', type='string', dest='pattern', \ + parser.add_option('-r', '--pattern', + action='store', type='string', dest='pattern', help='pattern to match valid channel names') - parser.add_option('-u', '--username', \ - action='store', type='string', dest='username', \ + parser.add_option('-u', '--username', + action='store', type='string', dest='username', help='username') - parser.add_option('-t', '--time', \ - action='store', type='string', dest='time', \ + parser.add_option('-t', '--time', + action='store', type='string', dest='time', help='time') - parser.add_option('-p', '--password', \ - action='callback', callback=getPassword, \ - dest='password', \ + parser.add_option('-p', '--password', + action='callback', callback=getPassword, + dest='password', help='prompt user for password') opts, args = parser.parse_args() if len(args) == 0 or args == None: diff --git a/test/ChannelFinderClientTest.py b/test/ChannelFinderClientTest.py index 90b0894..71b8326 100644 --- a/test/ChannelFinderClientTest.py +++ b/test/ChannelFinderClientTest.py @@ -77,7 +77,7 @@ def testEncodeChannel(self): # print encodedChannel[u'channels'][u'channel'] print "TEST "+ str(encodedChannel[u'channels'][u'channel']) + " == " + str(self.channel) self.assertTrue(encodedChannel[u'channels'][u'channel'] == self.channel) - + def testEncodeChannels(self): self.assertTrue(self.multiChannels == \ ChannelFinderClient()._ChannelFinderClient__encodeChannels(ChannelFinderClient()._ChannelFinderClient__decodeChannels(self.multiChannels))) @@ -168,24 +168,24 @@ def testSetRemoveTag2Channel(self): try: self.client.set(tag=testTag) self.client.set(tag=testTag, channelName=self.testChannels[0][u'name']) - + self.assertTrue(checkTagOnChannel(self.client, 'pyTestChannel1', testTag) , \ 'Error: Tag-pySetTag not added to the channel-pyTestChannel1') - + self.client.set(tag=testTag, channelName=self.testChannels[1][u'name']) # check if the tag has been added to the new channel and removed from the old channel - self.assertTrue(checkTagOnChannel(self.client, self.testChannels[1][u'name'], testTag) and + self.assertTrue(checkTagOnChannel(self.client, self.testChannels[1][u'name'], testTag) and not checkTagOnChannel(self.client, self.testChannels[0][u'name'], testTag), \ 'Error: Tag-pySetTag not added to the channel-pyTestChannel2') - + self.client.delete(tag=testTag, channelName=self.testChannels[1][u'name']) self.assertTrue(not checkTagOnChannel(self.client, self.testChannels[1][u'name'], testTag), \ 'Error: Failed to delete the tag-pySetTag from channel-pyTestChannel1') finally: self.client.delete(tagName=testTag[u'name']) - + # TODO set a check for removing the tag from a subset of channels which have that tag - + def testSetRemoveTag2Channels(self): ''' Set tags to a set of channels and remove it from all other channels @@ -220,7 +220,7 @@ def testUpdateTag(self): '''Update tag with new channels''' tag['channels'] = [self.testChannels[1], self.testChannels[2]] self.clientTag.update(tag=tag) - + for channel in self.testChannels: self.assertTrue(checkTagOnChannel(self.client, channel['name'], tag), 'Failed to updated tag') finally: @@ -236,7 +236,7 @@ def testUpdateTags(self): tag1['channels'] = [self.testChannels[0]] tag2 = {'name':'pyTestTag2', 'owner':self.tagOwner} tag2['channels'] = [self.testChannels[0]] - + try: '''Create initial tags which are set on the pyTestChannel1''' self.clientTag.set(tags=[tag1,tag2]) @@ -252,7 +252,7 @@ def testUpdateTags(self): checkTagOnChannel(self.client, channel['name'], tag2), \ 'Failed to updated tags') finally: - '''cleanup''' + '''cleanup''' self.client.delete(tagName=tag1['name']) self.client.delete(tagName=tag2['name']) self.assertIsNone(self.client.findTag(tag1['name']), 'failed to delete the test tag:'+tag1['name']) @@ -282,7 +282,7 @@ def testGetAllTags(self): #=============================================================================== class OperationPropertyTest(unittest.TestCase): - + def setUp(self): '''Default Owners''' self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') @@ -395,22 +395,21 @@ def testSetRemoveProperty2Channel(self): self.client.set(property=testProperty) self.assertTrue(checkPropertyOnChannel(self.client, ch0[u'name'], testProperty) , \ 'Error: Property - setTestProp not added to the channel-pyTestChannel1') - + ch1 = self.testChannels[1] ch1['properties'] = [ {'name':'setTestProp', 'owner':self.propOwner, 'value':'testValue2'} ] testProperty['channels'] = [ch1] self.client.set(property=testProperty) '''check if the property has been added to the new channel and removed from the old channel''' - self.assertTrue(checkPropertyOnChannel(self.client, ch1[u'name'], testProperty) and + self.assertTrue(checkPropertyOnChannel(self.client, ch1[u'name'], testProperty) and not checkPropertyOnChannel(self.client, ch0[u'name'], testProperty), \ 'Error: Tag-pySetTag not added to the channel-pyTestChannel2') + finally: # Delete operation causes an error if performed twice, IE: the first delete succeeded '''delete the property and ensure it is removed from the associated channel''' - self.client.delete(propertyName=testProperty['name']) + self.client.delete(propertyName=testProperty[u'name']) self.assertTrue(not checkPropertyOnChannel(self.client, ch0[u'name'], testProperty) and \ - not checkPropertyOnChannel(self.client, ch1[u'name'], testProperty) , \ - 'Error: Failed to delete the tag-pySetTag from channel-pyTestChannel1') - finally: - self.client.delete(tagName=testProperty[u'name']) + not checkPropertyOnChannel(self.client, ch1[u'name'], testProperty), \ + 'Error: Failed to delete the tag-pySetTag from channel-pyTestChannel1') def testGetAllPropperties(self): '''Test setting multiple properties and listing all tags''' @@ -431,10 +430,10 @@ def testGetAllPropperties(self): self.assertEqual(self.client.findProperty(propertyName=prop[u'name']), None, \ 'Error: property ' + prop[u'name'] + ' was not removed') #=============================================================================== -# +# #=============================================================================== class OperationChannelTest(unittest.TestCase): - + def setUp(self): '''Default Owners''' self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') @@ -465,7 +464,7 @@ def testSetDeleteChannel(self): self.assertTrue(len(result) == 1, 'incorrect number of channels returned') self.assertTrue(result[0][u'name'] == u'pyTestChannelName', 'incorrect channel returned') finally: - self.clientCh.delete(channelName=testChannel[u'name']) + self.clientCh.delete(channelName=testChannel[u'name']) result = self.client.find(name=u'pyTestChannelName') self.assertFalse(result, 'incorrect number of channels returned') @@ -509,7 +508,7 @@ def testSetRemoveChannels(self): # delete each individually for ch in testChannels: self.clientCh.delete(channelName=str(ch[u'name'])) - + def testSetChannelsWithProperties(self): ''' This method creates a set of channels and then updates the property values @@ -521,10 +520,10 @@ def testSetChannelsWithProperties(self): ch2 = {u'name':u'orgChannel2', u'owner':self.channelOwner, u'properties':[prop1, prop2]} ch3 = {u'name':u'orgChannel3', u'owner':self.channelOwner, u'properties':[prop1]} channels = [ch1, ch2, ch3] - + self.client.set(property=prop1) self.client.set(property=prop2) - + self.client.set(channels=channels) chs = self.client.find(property=[(u'originalProp1', u'originalVal'), \ (u'originalProp2', u'originalVal')]) @@ -541,20 +540,20 @@ def testSetChannelsWithProperties(self): self.client.delete(propertyName=prop1[u'name']) self.client.delete(propertyName=prop2[u'name']) pass - + def testDestructiveSetRemoveChannels(self): ''' This test will check that a POST in the channels resources is destructive ''' testProp = {u'name':u'testProp', u'owner' : self.propOwner} - try: + try: self.clientProp.set(property=testProp) testProp[u'value'] = 'original' testChannels = [{u'name':u'pyChannel1', u'owner':self.channelOwner, u'properties':[testProp]}, \ {u'name':u'pyChannel2', u'owner':self.channelOwner}, \ - {u'name':u'pyChannel3', u'owner':self.channelOwner}] + {u'name':u'pyChannel3', u'owner':self.channelOwner}] self.clientCh.set(channel=testChannels[0]) - + self.assertEqual(len(self.client.find(name=u'pyChannel*')), 1, \ 'Failed to set a single channel correctly') result = self.client.find(name=u'pyChannel1')[0] @@ -578,7 +577,7 @@ def testSetRemoveSpecialChar(self): spTag = {u'name':u'special{}*', u'owner':self.tagOwner} spChannel[u'properties'] = [spProperty] spChannel[u'tags'] = [spTag] - + try: self.client.set(tag=spTag) self.assertNotEqual(self.client.findTag(spTag[u'name']), None, 'failed to set Tag with special chars') @@ -628,7 +627,7 @@ def testUpdateChannel(self): self.client.set(tag=testTag2) testChannel = {u'name':u'pyTestChannelName1', u'owner': self.channelOwner, u'properties':[testProp2], u'tags':[testTag2]} self.clientCh.update(channel=testChannel) - + result = self.client.find(name=u'pyTestChannelName1') self.assertTrue(len(result) == 1, 'incorrect number of channels returned') self.assertTrue(result[0][u'name'] == u'pyTestChannelName1', 'incorrect channel returned') @@ -646,14 +645,14 @@ def testUpdateChannel(self): #=============================================================================== # Update Opertation Tests #=============================================================================== -''' + class UpdateOperationTest(unittest.TestCase): def setUp(self): - ''''''Default set of Owners'''''' + '''Default set of Owners''' self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') self.propOwner = _testConf.get('DEFAULT', 'propOwner') self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') - ''''''Default set of clients'''''' + '''Default set of clients''' self.client = ChannelFinderClient() self.clientCh = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), \ username=_testConf.get('DEFAULT', 'channelUsername'), \ @@ -664,23 +663,23 @@ def setUp(self): self.clientTag = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), \ username=_testConf.get('DEFAULT', 'tagUsername'), \ password=_testConf.get('DEFAULT', 'tagPassword')) - '''''' Test Properties and Tags '''''' + ''' Test Properties and Tags ''' self.orgTag = {u'name':u'originalTag', u'owner': self.tagOwner} self.orgProp = {u'name':u'originalProp', u'owner':self.propOwner, u'value':u'originalValue'} - + self.clientTag.set(tag=self.orgTag) self.clientProp.set(property=self.orgProp) - + self.clientCh.set(channel={u'name':u'originalChannelName', \ u'owner':self.channelOwner, \ u'properties':[self.orgProp], \ u'tags':[self.orgTag]}) ch = self.client.find(name=u'originalChannelName') - self.assertTrue(len(ch) == 1 and + self.assertTrue(len(ch) == 1 and self.orgProp in ch[0][u'properties'] and \ self.orgTag in ch[0][u'tags']); pass - + def UpdateTagName(self): newTagName = 'updatedTag' self.assertTrue(self.client.findTag(self.orgTag[u'name']) != None) @@ -693,10 +692,11 @@ def UpdateTagName(self): self.assertTrue(self.orgTag not in channelTags and \ {u'name':newTagName, u'owner':self.tagOwner} in channelTags) self.clientTag.update(tag=self.orgTag, originalTagName=newTagName) - + def testUpdateTagOwner(self): + '''Test implemented in testUpdateTag''' pass - + # removed test till bug in the sevice is fixed - channelfinder needs to check for the existance of oldname not name def UpdatePropName(self): newPropName = u'updatedProperty' @@ -710,42 +710,42 @@ def UpdatePropName(self): self.assertTrue(self.orgProp[u'name'] not in channelProperties.keys() and \ newPropName in channelProperties.keys()) self.clientProp.update(property=self.orgProp, originalPropertyName=newPropName) - - + + def testUpdatePropOwner(self): pass - + def testUpdateChannelName(self): ch = self.client.find(name=u'originalChannelName')[0] - newChannel = {u'name':u'updatedChannelName', u'owner':ch.Owner, u'properties': ch[u'properties'], u'tags':ch[u'tags']} + newChannel = {u'name':u'updatedChannelName', u'owner': ch[u'owner'], u'properties': ch[u'properties'], u'tags': ch[u'tags']} self.clientCh.update(originalChannelName=u'originalChannelName', \ channel=newChannel) - self.assertTrue(self.client.find(name=u'originalChannelName') == None) + self.assertTrue(self.client.find(name=u'originalChannelName') == []) self.assertTrue(len(self.client.find(name=u'updatedChannelName')) == 1) # reset the channel back self.clientCh.update(originalChannelName=u'updatedChannelName', \ channel=ch) self.assertTrue(len(self.client.find(name=u'originalChannelName')) == 1) - self.assertTrue(self.client.find(name=u'updatedChannelName') == None) - + self.assertTrue(self.client.find(name=u'updatedChannelName') == []) + def UpdateChannelOwner(self): ch = self.client.find(name='originalChannelName')[0] newChannel = {u'name':ch[u'name'], u'owner':self.tagOwner, u'properties': ch[u'properties'], u'tags':ch[u'tags']} self.clientCh.update(originalChannelName=u'originalChannelName', \ channel=newChannel) - self.assertTrue(self.client.find(name=u'originalChannelName')[0].Owner == self.tagOwner) + self.assertTrue(self.client.find(name=u'originalChannelName')[0][u'owner'] == self.tagOwner) pass - + def testUpdateChannel(self): - '''''' + ''' the test updates the channel name and owner it also updates an existing property and adds a new property and tag leaving an existing tag untouched - + TODO using the lowest lever _tagOwner_ as the newOwner - '''''' + ''' ch = self.client.find(name=u'originalChannelName')[0] updatedProp = {u'name':u'originalProp', u'owner':self.propOwner, u'value':u'updatedValue'} newTag = {u'name':u'updatedTag', u'owner':self.tagOwner} @@ -760,12 +760,12 @@ def testUpdateChannel(self): channel=newChannel) foundChannel = self.client.find(name=u'updatedChannelName')[0] self.assertTrue(foundChannel[u'name'] == u'updatedChannelName' and - foundChannel.Owner == self.channelOwner and \ + foundChannel[u'owner'] == self.channelOwner and \ updatedProp in foundChannel[u'properties'] and\ newProp in foundChannel[u'properties'] and \ newTag in foundChannel[u'tags'] and \ self.orgTag in foundChannel[u'tags']) - + finally: #reset self.clientCh.update(originalChannelName='updatedChannelName', \ @@ -776,26 +776,74 @@ def testUpdateChannel(self): self.clientTag.delete(tagName=newTag[u'name']) if self.clientProp.findProperty(newProp[u'name']): self.clientProp.delete(propertyName=newProp[u'name']) - + def testUpdateChannel2(self): - '''''' + ''' Update a channels using update(channel=updatedChannel) - '''''' - pass - + ''' + ch = self.client.find(name=u'originalChannelName') + self.assertTrue(len(ch) == 1 and + self.orgProp in ch[0][u'properties'] and + self.orgTag in ch[0][u'tags']) + updated_prop = {u'name': u'originalProp', + u'owner': self.propOwner, + u'value': u'newPropValue'} + self.clientCh.update(channel={u'name': u'originalChannelName', + u'owner': u'newOwner', + u'properties': [updated_prop], + u'tags': []}) + ch = self.client.find(name=u'originalChannelName') + self.assertTrue(len(ch) == 1 and + updated_prop in ch[0][u'properties'] and + self.orgTag in ch[0][u'tags'] and + ch[0][u'owner'] == u'newOwner') + + def testUpdateProperty(self): - '''''' + ''' Update a single property using update(property=updatedProperty) - '''''' - pass - + Updates existing channels with new property owner, without altering original value. + ''' + prop = self.client.findProperty(propertyName=u'originalProp') + self.assertDictEqual(prop, {u'owner': u'cf-update', + u'channels': [], + u'name': u'originalProp', + u'value': None}) + + updatedProperty = dict(prop) + updatedProperty[u'owner'] = u'newOwner' + self.clientProp.update(property=updatedProperty) + '''Check property owner''' + prop = self.client.findProperty(propertyName=u'originalProp') + self.assertDictEqual(prop, {u'owner': u'newOwner', + u'channels': [], + u'name': u'originalProp', + u'value': None}) + '''Check existing channel''' + ch = self.client.find(name=u'originalChannelName') + self.assertTrue({u'owner': u'newOwner', + u'name': u'originalProp', + u'value': u'originalValue'} in ch[0][u'properties']) + def testUpdateTag(self): - '''''' + ''' Update a single tag using update(tag=updatedTag) - '''''' - pass - - + Updates owner in all associated channels. + ''' + tag = self.client.findTag(tagName=u'originalTag') + self.assertDictEqual(tag, {u'owner': u'cf-update', u'channels': [], u'name': u'originalTag'}) + + updatedTag = dict(tag) + updatedTag[u'owner'] = u'newOwner' + self.clientTag.update(tag=updatedTag) + '''Check tag owner''' + tag = self.client.findTag(tagName=u'originalTag') + self.assertDictEqual(tag, {u'owner': u'newOwner', u'channels': [], u'name': u'originalTag'}) + '''Checks existing channel''' + ch = self.client.find(name=u'originalChannelName') + self.assertTrue({u'owner': u'newOwner', + u'name': u'originalTag'} in ch[0][u'tags']) + def tearDown(self): self.clientCh.delete(channelName=u'originalChannelName') self.clientTag.delete(tagName=u'originalTag') @@ -807,13 +855,13 @@ def tearDown(self): #=============================================================================== ''' class UpdateAppendTest(unittest.TestCase): - + def setUp(self): - ''''''Default Owners'''''' + '''Default Owners''' self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') self.propOwner = _testConf.get('DEFAULT', 'propOwner') self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') - ''''''Default Client'''''' + '''Default Client''' self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), \ username=_testConf.get('DEFAULT', 'username'), \ password=_testConf.get('DEFAULT', 'password')) @@ -823,7 +871,7 @@ def setUp(self): self.clientTag = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), \ username=_testConf.get('DEFAULT', 'tagUsername'), \ password=_testConf.get('DEFAULT', 'tagPassword')) - + self.Tag1 = {u'name':u'tag1', u'owner':self.tagOwner} self.Tag2 = {u'name':u'tag2', u'owner':self.tagOwner} self.Prop1 = {u'name':u'prop1', u'owner':self.propOwner, u'value':u'initialVal'} @@ -837,9 +885,9 @@ def setUp(self): self.client.set(channels=self.channels) # originally 1 channel has tag Tag1 and 2 channels have tag Tag2 self.assertTrue(len(self.client.find(tagName=self.Tag1[u'name'])) == 1) - self.assertTrue(len(self.client.find(tagName=self.Tag2[u'name'])) == 2) + self.assertTrue(len(self.client.find(tagName=self.Tag2[u'name'])) == 2) pass - + def tearDown(self): self.clientTag.delete(tagName=self.Tag1[u'name']) self.clientTag.delete(tagName=self.Tag2[u'name']) @@ -847,86 +895,87 @@ def tearDown(self): self.clientProp.delete(propertyName=self.Prop2[u'name']) for channel in self.channels: self.client.delete(channelName=channel[u'name']) - self.assertTrue(self.client.find(name=u'orgChannel?') == None) + self.assertTrue(self.client.find(name=u'orgChannel?') == []) pass - + def testUpdateAppendTag2Channel(self): - '''''' + ''' Add tag to channel3 without removing it from the first 2 channels - '''''' + ''' self.clientTag.update(tag=self.Tag2, channelName=self.ch3[u'name']) self.assertTrue(len(self.client.find(tagName=self.Tag2[u'name'])) == 3) - + def testUpdateAppendTag2Channels(self): - '''''' + ''' Add tag to channels 2-3 without removing it from channel 1 - '''''' - channelNames = [ channel[u'name'] for channel in self.channels] + ''' + channelNames = [channel[u'name'] for channel in self.channels] self.clientTag.update(tag=self.Tag1, channelNames=channelNames) self.assertTrue(len(self.client.find(tagName=self.Tag1[u'name'])) == 3) def testUpdateAppendProperty2Channel(self): - '''''' - Test to update a channel with a property - '''''' - self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and \ - self.client.find(name=self.ch3[u'name'])[0][u'properties'] == None, \ + ''' + Test to update a channel with a property + ''' + self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and + self.client.find(name=self.ch3[u'name'])[0][u'properties'] == [], 'the channel already has properties') self.clientProp.update(property=self.Prop1, channelName=self.ch3[u'name']) - self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and \ - self.Prop1 in self.client.find(name=self.ch3[u'name'])[0][u'properties'], \ + self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and + self.Prop1 in self.client.find(name=self.ch3[u'name'])[0][u'properties'], 'failed to update the channel with a new property') - ''''''Check that Value of the property is correctly added'''''' + '''Check that Value of the property is correctly added''' self.Prop2[u'value'] = 'val' self.clientProp.update(property=self.Prop2, channelName=self.ch3[u'name']) chs = self.client.find(name=self.ch3[u'name']) - self.assertTrue(len(chs) == 1 and \ - self.Prop1 in chs[0][u'properties'] and \ - self.Prop2 in chs[0][u'properties'] , \ + self.assertTrue(len(chs) == 1 and + self.Prop1 in chs[0][u'properties'] and + self.Prop2 in chs[0][u'properties'], 'Failed to update the channel with a new property without disturbing the old one') self.client.set(channel=self.ch3) - + def testUpdateAppendProperty2Channels(self): - '''''' + ''' Update a channels with a property - '''''' - self.assertTrue(len(self.client.find(name=self.ch2[u'name'])) == 1 and \ - self.client.find(name=self.ch2[u'name'])[0][u'properties'] == None, \ + ''' + self.assertTrue(len(self.client.find(name=self.ch2[u'name'])) == 1 and + self.client.find(name=self.ch2[u'name'])[0][u'properties'] == [], 'the channel already has properties') - self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and \ - self.client.find(name=self.ch3[u'name'])[0][u'properties'] == None, \ + self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and + self.client.find(name=self.ch3[u'name'])[0][u'properties'] == [], 'the channel already has properties') - self.Prop1[u'value'] = 'testVal' + self.Prop1[u'value'] = 'testVal' self.clientProp.update(property=self.Prop1, channelNames=[self.ch2[u'name'], self.ch3[u'name']]) - self.assertTrue(len(self.client.find(name=self.ch2[u'name'])) == 1 and \ - self.Prop1 in self.client.find(name=self.ch2[u'name'])[0][u'properties'], \ + self.assertTrue(len(self.client.find(name=self.ch2[u'name'])) == 1 and + self.Prop1 in self.client.find(name=self.ch2[u'name'])[0][u'properties'], 'failed to update the channel with a new property') - self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and \ - self.Prop1 in self.client.find(name=self.ch3[u'name'])[0][u'properties'], \ + self.assertTrue(len(self.client.find(name=self.ch3[u'name'])) == 1 and + self.Prop1 in self.client.find(name=self.ch3[u'name'])[0][u'properties'], 'failed to update the channel with a new property') - + + @unittest.skip("Skipping test for unimplemented functionality.") def testUpdateRemoveProperty2Channel(self): - '''''' + ''' Updating a single channel with a property value = empty string is interpreted as a delete property - '''''' + ''' try: self.client.set(channel={u'name':u'testChannel', u'owner':self.ChannelOwner, u'properties':[self.Prop1]}) channel = self.client.find(name=u'testChannel') - self.assertTrue(len(channel) == 1 and self.Prop1[u'name'] in channel[0][u'properties'], \ + self.assertTrue(len(channel) == 1 and self.Prop1 in channel[0][u'properties'], 'Failed to create a test channel with property prop1') self.Prop1[u'value'] = '' channel[0][u'properties'] = [self.Prop1] self.client.update(channel=channel[0]) - self.assertFalse(self.client.find(name=u'testChannel')[0][u'properties'], \ + self.assertFalse(self.client.find(name=u'testChannel')[0][u'properties'], 'Failed to deleted property prop1 form channel testChannel') finally: self.client.delete(channelName=u'testChannel') - + def UserOwnerCheck(self): - '''''' + ''' the _user_ belonging to cf-properties and another group(cf-asd) sets the owner = group but should still be able to update the property - '''''' + ''' try: self.clientProp.set(property={u'name':u'testProperty', u'owner':'cf-asd'}) self.assertTrue({u'name':u'testProperty', u'owner':u'cf-asd'} in self.client.getAllProperties(), \ @@ -939,14 +988,14 @@ def UserOwnerCheck(self): self.clientProp.delete(propertyName=u'testProperty') self.client.delete(channelName=u'testChannel') - ''' + #=========================================================================== # Query Tests #=========================================================================== class QueryTest(unittest.TestCase): - - def setUp(self): + + def setUp(self): '''Default Owners''' self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') self.propOwner = _testConf.get('DEFAULT', 'propOwner') @@ -960,27 +1009,27 @@ def setUp(self): def tearDown(self): pass - + def testQueryChannel(self): pass - + def testEmptyReturn(self): ''' find for non existing entities should return None instead of a 404 ''' self.assertEquals(len(self.client.find(name=u'NonExistingChannelName')), 0,\ 'Failed to return None when searching for a non existing channel') - + def MultiValueQuery(self): ''' add multiple search values for the same parameter Expected behaviour - + Logically OR'ed name=pattern1,pattern2 => return channels with name matching pattern1 OR pattern2 - propName=valPattern1, valPattern2 => return channels with property 'propName' + propName=valPattern1, valPattern2 => return channels with property 'propName' with values matching valPattern1 OR valPattern2 - + Logically AND'ed tagName=pattern1, pattern2 => return channels with tags matching pattern1 AND pattern2 ''' @@ -1029,7 +1078,7 @@ def MultiValueQuery(self): chs = self.client.find(property=[(u'propA', '1'), (u'propA', 'a')]) self.assertEqual(len(chs), 2, \ 'Failed of query propA expected 2 found ' + str(len(chs))) - + ''' Check Find with multiple parameters ''' chs = self.client.find(name=u'pyTestChannel*', \ tagName=tagA[u'name'], \ @@ -1038,24 +1087,24 @@ def MultiValueQuery(self): chs = self.client.find(name=u'pyTestChannel*', \ tagName=tagA[u'name'], \ property=[('propA', 'a')]) - self.assertEqual(len(chs), 1, u'expected 1 found ' + str(len(chs))) - + self.assertEqual(len(chs), 1, u'expected 1 found ' + str(len(chs))) + self.client.delete(channelName=u'pyTestChannelA') self.client.delete(channelName=u'pyTestChannelB') self.client.delete(channelName=u'pyTestChannelAB') - + self.client.delete(tagName=tagA[u'name']) self.client.delete(tagName=tagB[u'name']) self.client.delete(propertyName=propA[u'name']) self.client.delete(propertyName=propB[u'name']) - - - + + + #=============================================================================== # ERROR tests #=============================================================================== class ErrorTest(unittest.TestCase): - + def setUp(self): '''Default Owners''' self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') @@ -1065,49 +1114,49 @@ def setUp(self): self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), \ username=_testConf.get('DEFAULT', 'username'), \ password=_testConf.get('DEFAULT', 'password')) - + self.client.set(property={u'name':'existingProperty',u'owner': self.propOwner}) - + def tearDown(self): self.client.delete(propertyName='existingProperty') - + def testSetChannelWithNonExistingProp(self): self.assertRaises(Exception, \ self.client.set, \ channel={u'name':u'channelName', \ u'owner':self.ChannelOwner, \ u'properties':[{u'name':u'nonExisitngProperty', u'owner':u'owner'}]}) - + def testSetChannelWithNonExistingTag(self): self.assertRaises(Exception, \ self.client.set, \ channel={u'name':'channelName', \ u'owner':self.ChannelOwner, \ u'tags':[{u'name':u'nonExisitngTag', u'owner':u'owner'}]}) - + def testUpdateChannelWithNonExistingProp(self): self.assertRaises(Exception, \ self.client.update, \ channel={u'name':u'channelName', \ u'owner':self.ChannelOwner, \ u'properties':[{u'name':u'nonExisitngProperty', u'owner':u'owner'}]}) - + def testUpdateChannelWithNonExistingTag(self): self.assertRaises(Exception, self.client.update, channel={u'name':u'channelName', \ u'owner':self.ChannelOwner, \ u'tags':[{u'name':'nonExisitngTag', u'owner':u'owner'}]}) - + def testUpdateNonExistingChannel(self): pass - + def testUpdateNonExistingProperty(self): pass - + def testUpdateNoneExistingTag(self): pass - + def testIncorrectFindArguments(self): self.assertRaises(Exception, \ self.client.find, \ @@ -1118,7 +1167,7 @@ def testIncorrectFindArguments(self): self.assertRaises(Exception, \ self.client.find, \ tag='zzz') - + def testCreateChannelWithNullPropertyValue(self): self.assertRaises(Exception, \ self.client.set, \ @@ -1127,7 +1176,7 @@ def testCreateChannelWithNullPropertyValue(self): u'properties':[{u'name':u'existingProperty', u'owner':self.propOwner}]}) self.assertFalse(self.client.find(name=u'channelName'), \ 'Failed: should not be able to create a channel with a property with value null') - + def testUpdateChannelWithNullPropertyValue(self): self.client.set(channel={u'name':u'channelName', \ u'owner':self.ChannelOwner}) @@ -1143,7 +1192,7 @@ def testUpdateChannelWithNullPropertyValue(self): 'Failed: should not be able to update a channel with a property with value null') finally: self.client.delete(channelName=u'channelName') - + def testCreateChannelWithEmptyPropertyValue(self): self.assertRaises(Exception, \ self.client.set, \ @@ -1152,7 +1201,7 @@ def testCreateChannelWithEmptyPropertyValue(self): u'properties':[{u'name':u'existingProperty', u'owner':self.propOwner, u'value':''}]}) self.assertFalse(self.client.find(name=u'channelName'), \ 'Failed: should not be able to create a channel with a property with empty value string') - + def UpdateChannelWithEmptyPropertyValue(self): self.client.set(channel={u'name':u'channelName', \ u'owner':self.ChannelOwner})