diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3977ef9..ca90110 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,21 +3,41 @@ name: Python package -on: - push: - branches: [ "master" ] - pull_request: - branches: [ "master" ] +on: [push, pull_request] jobs: - test: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v3 + - uses: pre-commit/action@v3.0.0 + build: - runs-on: ubuntu-20.04 + runs-on: ubuntu-20.04 # 3.6 is not supported by Ubuntu 22.04 strategy: fail-fast: false matrix: - python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] + python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install . + test: + + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] # testcontainers is not supported on <3.9 + needs: build steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} @@ -34,4 +54,4 @@ jobs: run: docker image prune -af - name: Test with pytest run: | - python -m unittest discover -v -s test -p "test*.py" + python -m unittest discover -v -s test -p "test*.py" diff --git a/.gitignore b/.gitignore index f76e985..370a1e1 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,4 @@ *.pyc build/ *.egg-info/ -.vscode \ No newline at end of file +.vscode diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..b8be4df --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,15 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.9.0 + hooks: + # Run the linter. + - id: ruff + args: [ --fix ] + # Run the formatter. + - id: ruff-format diff --git a/README.md b/README.md index 7b76c3e..07e2704 100644 --- a/README.md +++ b/README.md @@ -6,20 +6,20 @@ A python client library for ChannelFinder. The python channelfinder client library can be configured by setting up a `channelfinderapi.conf` file in the following locations -`/etc/channelfinderapi.conf` -`~/.channelfinderapi.conf` -`channelfinderapi.conf` +`/etc/channelfinderapi.conf` +`~/.channelfinderapi.conf` +`channelfinderapi.conf` -The example preferences: +The example preferences: ``` -cat ~/channelfinderapi.conf -[DEFAULT] -BaseURL=http://localhost:8080/ChannelFinder -username=MyUserName -password=MyPassword +cat ~/channelfinderapi.conf +[DEFAULT] +BaseURL=http://localhost:8080/ChannelFinder +username=MyUserName +password=MyPassword ``` - + ## Development To install with dependancies for testing. @@ -38,4 +38,4 @@ To run all tests: ```bash python -m unittest discover -v -s test -p "test*.py" -``` \ No newline at end of file +``` diff --git a/channelfinder/CFDataTypes.py b/channelfinder/CFDataTypes.py index e663559..761ecf8 100644 --- a/channelfinder/CFDataTypes.py +++ b/channelfinder/CFDataTypes.py @@ -10,19 +10,14 @@ """ -from ._conf import PYTHON3 - -if PYTHON3: - # cmp function is gone in Python 3. - # Define for backward compatibility - def cmp(a, b): - return (a > b) - (a < b) +def cmp(a, b): + return (a > b) - (a < b) class Channel(object): # TODO # updated the properties data structure by splitting it into 2 dict - + # All the attributes are private and read only in an attempt to make the channel object immutable Name = property(lambda self: self.__Name) Owner = property(lambda self: self.__Owner) @@ -42,7 +37,7 @@ def __init__(self, name, owner, properties=None, tags=None): self.__Owner = str(owner).strip() self.Properties = properties self.Tags = tags - + ## TODO don't recreate the dictionary with every get def getProperties(self): """ @@ -85,10 +80,10 @@ def __init__(self, name, owner, value=None): self.Value = value if self.Value: str(value).strip() - - def __cmp__(self, *arg, **kwargs): + + def __cmp__(self, *arg, **kwargs): if arg[0] is None: - return 1 + return 1 return cmp((self.Name, self.Value), (arg[0].Name, arg[0].Value)) @@ -99,7 +94,7 @@ def __init__(self, name, owner): """ self.Name = str(name).strip() self.Owner = str(owner).strip() - + def __cmp__(self, *arg, **kwargs): if arg[0] is None: return 1 diff --git a/channelfinder/ChannelFinderClient.py b/channelfinder/ChannelFinderClient.py index a705188..bc971df 100644 --- a/channelfinder/ChannelFinderClient.py +++ b/channelfinder/ChannelFinderClient.py @@ -8,25 +8,25 @@ """ -import ssl import requests from requests import auth from requests.adapters import HTTPAdapter from requests.exceptions import HTTPError -from urllib3.poolmanager import PoolManager from copy import copy + try: - from json import JSONDecoder, JSONEncoder + from json import JSONEncoder except ImportError: - from simplejson import JSONDecoder, JSONEncoder + from simplejson import JSONEncoder + +from ._conf import basecfg -from ._conf import basecfg, PYTHON3 class ChannelFinderClient(object): - __jsonheader = {'content-type': 'application/json', 'accept': 'application/json'} - __channelsResource = '/resources/channels' - __propertiesResource = '/resources/properties' - __tagsResource = '/resources/tags' + __jsonheader = {"content-type": "application/json", "accept": "application/json"} + __channelsResource = "/resources/channels" + __propertiesResource = "/resources/properties" + __tagsResource = "/resources/tags" def __init__(self, BaseURL=None, username=None, password=None): """ @@ -40,18 +40,15 @@ def __init__(self, BaseURL=None, username=None, password=None): :param username: user name authorized by channel finder service :param password: password for the authorized user """ - try: - self.__baseURL = self.__getDefaultConfig('BaseURL', BaseURL) - self.__userName = self.__getDefaultConfig('username', username) - self.__password = self.__getDefaultConfig('password', password) - if self.__userName and self.__password: - self.__auth = auth.HTTPBasicAuth(self.__userName, self.__password) - else: - self.__auth = None - self.__session = requests.Session() - self.__session.mount(self.__baseURL, HTTPAdapter()) - except: - raise RuntimeError('Failed to create client to ' + self.__baseURL) + self.__baseURL = self.__getDefaultConfig("BaseURL", BaseURL) + self.__userName = self.__getDefaultConfig("username", username) + self.__password = self.__getDefaultConfig("password", password) + if self.__userName and self.__password: + self.__auth = auth.HTTPBasicAuth(self.__userName, self.__password) + else: + self.__auth = None + self.__session = requests.Session() + self.__session.mount(self.__baseURL, HTTPAdapter()) def __getDefaultConfig(self, key, ref): """ @@ -63,10 +60,7 @@ def __getDefaultConfig(self, key, ref): """ result = ref if ref is None: - if PYTHON3: - result = basecfg['DEFAULT'].get(key, None) - elif basecfg.has_option('DEFAULT', key): - result = basecfg.get('DEFAULT', key) + result = basecfg["DEFAULT"].get(key, None) return result def set(self, **kwds): @@ -97,46 +91,46 @@ def set(self, **kwds): 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'}) - + set(tags = [Tag]) >>> set(tags=[{'name':'tag1','tagOwner'},{'name':'tag2','owner':'tagOwner'}]) - + set(property = Property ) >>> set(property={'name':'propertyName','owner':'propertyOwner'}) - + set(properties = [Property]) - >>> set(properties=[{'name':'prop1','owner':'propOwner'},'prop2','propOwner']) - + >>> set(properties=[{'name':'prop1','owner':'propOwner'},'prop2','propOwner']) + *** IMP NOTE: Following operation are destructive *** *** 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') # 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']) - # will create/replace the specified Tag + # 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, 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 channels # and delete it from all other channels - + """ if len(kwds) == 1: self.__handleSingleAddParameter(**kwds) elif len(kwds) == 2: self.__handleMultipleAddParameters(**kwds) else: - raise RuntimeError('incorrect usage: ') + raise RuntimeError("incorrect usage: ") def __handleSingleAddParameter(self, **kwds): """ @@ -151,53 +145,71 @@ def __handleSingleAddParameter(self, **kwds): :param 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, - auth=self.__auth) + if "channel" in kwds: + r = self.__session.put( + self.__baseURL + + self.__channelsResource + + "/" + + kwds["channel"]["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, - auth=self.__auth) + elif "channels" in kwds: + 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, - auth=self.__auth) + elif "tag" in kwds: + r = self.__session.put( + self.__baseURL + self.__tagsResource + "/" + kwds["tag"]["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, - auth=self.__auth) + 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, + 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, - auth=self.__auth) + elif "property" in kwds: + r = self.__session.put( + self.__baseURL + + self.__propertiesResource + + "/" + + kwds["property"]["name"], + data=JSONEncoder().encode(kwds["property"]), + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth, + ) r.raise_for_status() - elif 'properties' in kwds: + 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, - auth=self.__auth) + data = JSONEncoder().encode(kwds["properties"]) + 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 RuntimeError('Incorrect Usage: unknown key') + raise RuntimeError("Incorrect Usage: unknown key") def __handleMultipleAddParameters(self, **kwds): """ @@ -210,36 +222,45 @@ 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, - auth=self.__auth).raise_for_status() - elif 'tag' in kwds and 'channelNames' in kwds: + if "tag" in kwds and "channelName" in kwds: + channels = [{"name": kwds["channelName"].strip(), "owner": self.__userName}] + kwds["tag"]["channels"] = channels + data = kwds["tag"] + self.__session.put( + self.__baseURL + self.__tagsResource + "/" + kwds["tag"]["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 = [] - for eachChannel in kwds['channelNames']: - 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, - 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, - auth=self.__auth).raise_for_status() + for eachChannel in kwds["channelNames"]: + channels.append({"name": eachChannel, "owner": self.__userName}) + kwds["tag"]["channels"] = channels + data = kwds["tag"] + self.__session.put( + self.__baseURL + self.__tagsResource + "/" + kwds["tag"]["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"]["name"], + data=JSONEncoder().encode(data), + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth, + ).raise_for_status() else: - raise RuntimeError('Incorrect Usage: unknown keys') + raise RuntimeError("Incorrect Usage: unknown keys") def find(self, **kwds): """ @@ -300,41 +321,45 @@ def find(self, **kwds): To query for the existance of a tag or property use findTag and findProperty. """ if not self.__baseURL: - raise RuntimeError('Connection not created') + raise RuntimeError("Connection not created") if not len(kwds) > 0: - raise RuntimeError('Incorrect usage: at least one parameter must be specified') + raise RuntimeError( + "Incorrect usage: at least one parameter must be specified" + ) args = [] for key in kwds: - if key == 'name': - patterns = kwds[key].split(',') + if key == "name": + patterns = kwds[key].split(",") for eachPattern in patterns: - args.append(('~name', eachPattern.strip())) - elif key == 'tagName': - patterns = kwds[key].split(',') + args.append(("~name", eachPattern.strip())) + elif key == "tagName": + patterns = kwds[key].split(",") for eachPattern in patterns: - args.append(('~tag', eachPattern.strip())) - elif key == 'property': + args.append(("~tag", eachPattern.strip())) + elif key == "property": for prop in kwds[key]: - patterns = prop[1].split(',') + patterns = prop[1].split(",") for eachPattern in patterns: args.append((prop[0], eachPattern.strip())) - elif key == 'size': - args.append(('~size', '{0:d}'.format(int(kwds[key])))) - elif key == 'ifrom': - args.append(('~from', '{0:d}'.format(int(kwds[key])))) - elif key == 'search_after': - args.append(('~search_after', kwds[key])) + elif key == "size": + args.append(("~size", "{0:d}".format(int(kwds[key])))) + elif key == "ifrom": + args.append(("~from", "{0:d}".format(int(kwds[key])))) + elif key == "search_after": + args.append(("~search_after", kwds[key])) else: - raise RuntimeError('unknown find argument ' + key) + raise RuntimeError("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, - auth=self.__auth) + r = self.__session.get( + url, + params=args, + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth, + ) try: r.raise_for_status() return r.json() @@ -351,11 +376,10 @@ def findTag(self, tagname): :param tagname: tag name of searching :return: Tag object if found, otherwise None """ - url = self.__baseURL + self.__tagsResource + '/' + tagname - r = self.__session.get(url, - headers=copy(self.__jsonheader), - verify=False, - auth=self.__auth) + url = self.__baseURL + self.__tagsResource + "/" + tagname + r = self.__session.get( + url, headers=copy(self.__jsonheader), verify=False, auth=self.__auth + ) try: r.raise_for_status() return r.json() @@ -372,7 +396,7 @@ def findProperty(self, propertyname): :param propertyname: property name for searching :return: Property object if found, otherwise None """ - url = self.__baseURL + self.__propertiesResource + '/' + propertyname + url = self.__baseURL + self.__propertiesResource + "/" + propertyname r = self.__session.get(url, headers=copy(self.__jsonheader), verify=False) try: r.raise_for_status() @@ -452,7 +476,7 @@ def delete(self, **kwds): elif len(kwds) == 2: self.__handleMultipleDeleteParameters(**kwds) else: - raise RuntimeError('incorrect usage: Delete a single Channel/tag/property') + raise RuntimeError("incorrect usage: Delete a single Channel/tag/property") def __handleSingleDeleteParameter(self, **kwds): """ @@ -464,26 +488,35 @@ def __handleSingleDeleteParameter(self, **kwds): :param kwds: :return: """ - if 'channelName' in kwds: - url = self.__baseURL + self.__channelsResource + '/' + kwds['channelName'].strip() - self.__session.delete(url, - headers=copy(self.__jsonheader), - verify=False, - auth=self.__auth).raise_for_status() - elif 'tagName' in kwds: - url = self.__baseURL + self.__tagsResource + '/' + kwds['tagName'].strip() - self.__session.delete(url, - verify=False, - headers=copy(self.__jsonheader), - auth=self.__auth).raise_for_status() - elif 'propertyName' in kwds: - url = self.__baseURL + self.__propertiesResource + '/' + kwds['propertyName'].strip() - self.__session.delete(url, - headers=copy(self.__jsonheader), - verify=False, - auth=self.__auth).raise_for_status() + if "channelName" in kwds: + url = ( + self.__baseURL + + self.__channelsResource + + "/" + + kwds["channelName"].strip() + ) + self.__session.delete( + url, headers=copy(self.__jsonheader), verify=False, auth=self.__auth + ).raise_for_status() + elif "tagName" in kwds: + url = self.__baseURL + self.__tagsResource + "/" + kwds["tagName"].strip() + self.__session.delete( + url, verify=False, headers=copy(self.__jsonheader), auth=self.__auth + ).raise_for_status() + elif "propertyName" in kwds: + url = ( + self.__baseURL + + self.__propertiesResource + + "/" + + kwds["propertyName"].strip() + ) + self.__session.delete( + url, headers=copy(self.__jsonheader), verify=False, auth=self.__auth + ).raise_for_status() else: - raise RuntimeError('Unknown key. Have to be channelName, tagName or proprtyName') + raise RuntimeError( + "Unknown key. Have to be channelName, tagName or proprtyName" + ) def __handleMultipleDeleteParameters(self, **kwds): """ @@ -495,35 +528,57 @@ def __handleMultipleDeleteParameters(self, **kwds): :param 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, - auth=self.__auth).raise_for_status() - elif 'tag' in kwds and 'channelNames' in kwds: + if "tag" in kwds and "channelName" in kwds: + self.__session.delete( + self.__baseURL + + self.__tagsResource + + "/" + + kwds["tag"]["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']) + channelsWithTag = self.find(tagName=kwds["tag"]["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, - 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) + channelNames = [ + channel["name"] + for channel in channelsWithTag + if channel["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"]["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"]["name"], "*")]) + channels = [ + channel + for channel in channelsWithProp + if channel["name"] not in kwds["channelNames"] + ] + self.set(property=kwds["property"], channels=channels) else: - raise RuntimeError('Unknown keys. Have to be ' - '(tag, channelName), ' - '(tag, channelNames), ' - '(property, channelName), ' - 'or (property and channelNames)') + raise RuntimeError( + "Unknown keys. Have to be " + "(tag, channelName), " + "(tag, channelNames), " + "(property, channelName), " + "or (property and channelNames)" + ) def update(self, **kwds): """ @@ -585,13 +640,13 @@ def update(self, **kwds): """ if not self.__baseURL: - raise RuntimeError('Olog client not configured correctly') + raise RuntimeError("Olog client not configured correctly") if len(kwds) == 1: self.__handleSingleUpdateParameter(**kwds) elif len(kwds) == 2: self.__handleMultipleUpdateParameters(**kwds) else: - raise RuntimeError('incorrect usage: ') + raise RuntimeError("incorrect usage: ") def __handleSingleUpdateParameter(self, **kwds): """ @@ -605,47 +660,57 @@ def __handleSingleUpdateParameter(self, **kwds): :param 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, - auth=self.__auth) + if "channel" in kwds: + ch = kwds["channel"] + r = self.__session.post( + self.__baseURL + self.__channelsResource + "/" + ch["name"], + data=JSONEncoder().encode(ch), + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth, + ) r.raise_for_status() - elif 'channels' in kwds: - chs = kwds['channels'] - r = self.__session.post(self.__baseURL + self.__channelsResource, - data=JSONEncoder().encode(chs), - headers=copy(self.__jsonheader), - verify=False, - auth=self.__auth) + elif "channels" in kwds: + chs = kwds["channels"] + r = self.__session.post( + self.__baseURL + self.__channelsResource, + data=JSONEncoder().encode(chs), + 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, - auth=self.__auth) + elif "property" in kwds: + property = kwds["property"] + r = self.__session.post( + self.__baseURL + self.__propertiesResource + "/" + property["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, - auth=self.__auth) + elif "tag" in kwds: + tag = kwds["tag"] + r = self.__session.post( + self.__baseURL + self.__tagsResource + "/" + tag["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, - auth=self.__auth) + elif "tags" in kwds: + 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 RuntimeError('Unknown key. ') + raise RuntimeError("Unknown key. ") def __handleMultipleUpdateParameters(self, **kwds): """ @@ -661,77 +726,111 @@ def __handleMultipleUpdateParameters(self, **kwds): :param kwds: """ - if 'tag' in kwds and 'channelName' in kwds: + if "tag" in kwds and "channelName" in kwds: # 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(kwds["tag"]) + channels = [ + { + "name": kwds["channelName"].strip(), + "owner": self.__userName, + "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["channels"] = channels + self.__session.post( + self.__baseURL + self.__tagsResource + "/" + tag["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: # identity operation performed to prevent side-effects - tag = dict(kwds['tag']) + tag = dict(kwds["tag"]) channels = [] - for eachChannel in kwds['channelNames']: - channels.append({u'name': eachChannel, u'owner': self.__userName, u'tags': [tag]}) + for eachChannel in kwds["channelNames"]: + channels.append( + {"name": eachChannel, "owner": self.__userName, "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: + tag["channels"] = channels + self.__session.post( + self.__baseURL + self.__tagsResource + "/" + tag["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: # 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(kwds["property"]) + channels = [ + { + "name": kwds["channelName"].strip(), + "owner": self.__userName, + "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["channels"] = channels + self.__session.post( + self.__baseURL + self.__propertiesResource + "/" + property["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: # identity operation performed to prevent side-effects - property = dict(kwds['property']) + property = dict(kwds["property"]) channels = [] - for eachChannel in kwds['channelNames']: - channels.append({u'name': eachChannel.strip(), u'owner': self.__userName, u'properties': [property]}) + for eachChannel in kwds["channelNames"]: + channels.append( + { + "name": eachChannel.strip(), + "owner": self.__userName, + "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(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(prop), - headers=copy(self.__jsonheader), - verify=False, - auth=self.__auth).raise_for_status() - 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, - auth=self.__auth).raise_for_status() + property["channels"] = channels + self.__session.post( + self.__baseURL + self.__propertiesResource + "/" + property["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(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(prop), + headers=copy(self.__jsonheader), + verify=False, + auth=self.__auth, + ).raise_for_status() + 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, + auth=self.__auth, + ).raise_for_status() else: - raise RuntimeError('unknown keys') + raise RuntimeError("unknown keys") diff --git a/channelfinder/__init__.py b/channelfinder/__init__.py index cbb42a0..4c838f8 100644 --- a/channelfinder/__init__.py +++ b/channelfinder/__init__.py @@ -1,2 +1,4 @@ -from .CFDataTypes import * -from .ChannelFinderClient import * \ No newline at end of file +from .CFDataTypes import Channel, Property, Tag +from .ChannelFinderClient import ChannelFinderClient + +__all__ = ["Channel", "Property", "Tag", "ChannelFinderClient"] diff --git a/channelfinder/_conf.py b/channelfinder/_conf.py index 9a4a9a6..e39801a 100644 --- a/channelfinder/_conf.py +++ b/channelfinder/_conf.py @@ -12,29 +12,23 @@ password=MyPassword """ - -import sys import os.path +from configparser import ConfigParser -if sys.version_info[0] < 3: - PYTHON3 = False - # Python 2 code in this block - from ConfigParser import SafeConfigParser as ConfigParser -else: - PYTHON3 = True - # Python 3 code in this block - from configparser import ConfigParser def __loadConfig(): - dflt={'BaseURL':'http://localhost:8080/ChannelFinder' - } - cf=ConfigParser(defaults=dflt) -# print os.path.normpath(os.path.expanduser('~/channelfinderapi.conf')) - cf.read([ - '/etc/channelfinderapi.conf', - os.path.expanduser('~/.channelfinderapi.conf'), - 'channelfinderapi.conf' - ]) + dflt = {"BaseURL": "http://localhost:8080/ChannelFinder"} + cf = ConfigParser(defaults=dflt) + # print os.path.normpath(os.path.expanduser('~/channelfinderapi.conf')) + cf.read( + [ + "/etc/channelfinderapi.conf", + os.path.expanduser("~/.channelfinderapi.conf"), + "channelfinderapi.conf", + ] + ) return cf -basecfg=__loadConfig() \ No newline at end of file + + +basecfg = __loadConfig() diff --git a/channelfinder/cfMonitorTest.py b/channelfinder/cfMonitorTest.py index 81a5366..0215681 100644 --- a/channelfinder/cfMonitorTest.py +++ b/channelfinder/cfMonitorTest.py @@ -1,5 +1,5 @@ #!/usr/bin/python -''' +""" Created on Mar 19, 2012 A python script to ensure that the cf-update-ioc is working correctly. @@ -17,7 +17,8 @@ python cf-monitor-test /complete/path/to/daemon/dir -i initialFile -f finalFile @author: shroffk -''' +""" + import sys import os import re @@ -26,51 +27,58 @@ from channelfinder import ChannelFinderClient -SEVR = {0:'OK ', - 1:'Minor ', - 2:'Major '} +SEVR = {0: "OK ", 1: "Minor ", 2: "Major "} -def main(): - requiredOpts = ['initial-file', 'final-file'] +def main(): usage = "usage: %prog -i initial-file -f final-file directory " parser = OptionParser(usage=usage) - parser.add_option('-i', '--initial-file', \ - action='store', type='string', dest='initialFile', \ - help='the initial-file') - parser.add_option('-f', '--final-file', \ - action='store', type='string', dest='finalFile', \ - help='the --final-file') + parser.add_option( + "-i", + "--initial-file", + action="store", + type="string", + dest="initialFile", + help="the initial-file", + ) + parser.add_option( + "-f", + "--final-file", + action="store", + type="string", + dest="finalFile", + help="the --final-file", + ) opts, args = parser.parse_args() - if args == None or len(args) == 0 : - parser.error('Please specify a directory') + if not args: + parser.error("Please specify a directory") if not opts.initialFile: - parser.error('Please specify a initial test files') + parser.error("Please specify a initial test files") if not opts.finalFile: - parser.error('Please specify a final test files') + parser.error("Please specify a final test files") mainRun(opts, args) def mainRun(opts, args): for directory in args: - initialFile = os.path.normpath(directory + '/' + opts.initialFile) - iHostName, iIocName = getArgsFromFilename(initialFile) - finalFile = os.path.normpath(directory + '/' + opts.finalFile) + initialFile = os.path.normpath(directory + "/" + opts.initialFile) + iHostName, iIocName = getArgsFromFilename(initialFile) + finalFile = os.path.normpath(directory + "/" + opts.finalFile) fHostName, fIocName = getArgsFromFilename(finalFile) if getPVNames(initialFile) != getPVNames(finalFile): sys.exit(1) pvNames = getPVNames(initialFile) if len(pvNames) == 0: sys.exit(1) - ''' + """ Touch the initial file and check channelfinder - ''' + """ touch(initialFile) - sleep(2) + sleep(2) check(pvNames, iHostName, iIocName) - ''' + """ Touch the final file and check channelfinder - ''' + """ touch(finalFile) sleep(2) check(pvNames, fHostName, fIocName) @@ -78,11 +86,8 @@ def mainRun(opts, args): def check(pvNames, hostName, iocName): - try: - client = ChannelFinderClient() - except: - raise RuntimeError('Unable to create a valid webResourceClient') - channels = client.find(property=[('hostName', hostName), ('iocName', iocName)]) + client = ChannelFinderClient() + channels = client.find(property=[("hostName", hostName), ("iocName", iocName)]) if channels and len(pvNames) == len(channels): for channel in channels: if channel.Name not in pvNames: @@ -92,25 +97,26 @@ def check(pvNames, hostName, iocName): def touch(fname, times=None): - with open(fname, 'a'): + with open(fname, "a"): os.utime(fname, times) def getArgsFromFilename(completeFilePath): fileName = os.path.split(os.path.normpath(completeFilePath))[1] - pattern4Hostname = '(\S+?)\.\S+' + pattern4Hostname = "(\S+?)\.\S+" match = re.search(pattern4Hostname, fileName) if match: hostName = match.group(1) else: hostName = None - pattern4Iocname = '\S+?\.(\S+?)\.\S+' + pattern4Iocname = "\S+?\.(\S+?)\.\S+" match = re.search(pattern4Iocname, fileName) if match: iocName = match.group(1) else: iocName = None - return hostName, iocName + return hostName, iocName + def getPVNames(completeFilePath, pattern=None): try: @@ -119,13 +125,18 @@ def getPVNames(completeFilePath, pattern=None): 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 finally: f.close() - -if __name__ == '__main__': - main() + + +if __name__ == "__main__": + main() pass diff --git a/channelfinder/cfPropertyManager/CFPropertyManager.py b/channelfinder/cfPropertyManager/CFPropertyManager.py index 689c5b4..7fa1143 100755 --- a/channelfinder/cfPropertyManager/CFPropertyManager.py +++ b/channelfinder/cfPropertyManager/CFPropertyManager.py @@ -1,47 +1,40 @@ # -*- coding: utf-8 -*- -''' +""" SEE cf-property-manager.cfg for example configuration file -''' - +""" from __future__ import print_function -import sys +from configparser import NoSectionError import re from optparse import OptionParser from getpass import getpass from channelfinder import ChannelFinderClient -from channelfinder._conf import basecfg, PYTHON3 +from channelfinder._conf import basecfg global username, client, exclusion_expression, password, SERVICE_URL, quiet, verbose -quiet=False -test=False -verbose=False -CFG_PATH='' -DBL_PATH='' +quiet = False +test = False +verbose = False +CFG_PATH = "" +DBL_PATH = "" dbllines = None cfglines = None expression_list = [] -username = "cf-update" #Defaults reinforced inside mainRun() +username = "cf-update" # Defaults reinforced inside mainRun() password = "1234" -channel_list=[] -SERVICE_URL='https://localhost:8181/ChannelFinder' +channel_list = [] +SERVICE_URL = "https://localhost:8181/ChannelFinder" client = None exclusion_expression = "" -def test_mode(): - test=True; - verbose=True; - quiet=False; - - def readDBL(path): - ''' + """ reads and stores .dbl file for processing - ''' + """ global dbllines dbllines = [line.strip() for line in open(path)] return dbllines @@ -49,7 +42,7 @@ def readDBL(path): def readConfiguration(path): global exclusion_expression - ''' + """ Reads configuration file and calls passes expressions to applyExpression to be run across the .dbl file SEE cf-property-manager.cfg for example configuration file: @@ -60,180 +53,209 @@ def readConfiguration(path): devName=[{][^:}][^:}]* devType=[:][^{]*?[:}](?!.*[{]) IGNORE=.*WtrSkid.* - ''' + """ global cfglines, expression_list, exclusion_expression - cfglines = [line.strip().split("=",1) for line in open(path)] + cfglines = [line.strip().split("=", 1) for line in open(path)] for properties in cfglines: - if(verbose): + if verbose: print(properties[0] + " = " + properties[1]) if properties[0] == "IGNORE": - print("IGNORE "+properties[1]) + print("IGNORE " + properties[1]) exclusion_expression = re.compile(properties[1]) else: - if client.findProperty(properties[0]) != None: + if client.findProperty(properties[0]) is not None: try: expression = re.compile(properties[1]) expression_list.append([expression, properties[0]]) except Exception as e: - print('Failed to find the property',properties[0]) - print('CAUSE:',e.message) + print("Failed to find the property", properties[0]) + print("CAUSE:", e.message) return cfglines def clean(str): - ''' + """ Removes all : { and } from line to simplify regular expression syntax. - ''' - return str.replace(":", "").replace("{", "").replace("}","") + """ + return str.replace(":", "").replace("{", "").replace("}", "") def applyExpression(): - ''' + """ Applies the regular expression to each of the lines in the .dbl file, and calls updateProperty on each result. - ''' + """ global exclusion_expression - if(exclusion_expression==""): - exclusion_expression="[^_]+" + if exclusion_expression == "": + exclusion_expression = "[^_]+" for channel_name in dbllines: prop_list = [] - if(exclusion_expression.search(channel_name) != None): + if exclusion_expression.search(channel_name) is not None: if verbose: - print("EXCLUDE: "+channel_name) + print("EXCLUDE: " + channel_name) else: for expression in expression_list: result = expression[0].search(channel_name) - if result != None: + if result is not None: value = clean(result.group()) - if(verbose): - print( "FOUND: "+value +" in "+ channel_name) + if verbose: + print("FOUND: " + value + " in " + channel_name) if value != "": - prop_list.append({u'name' : expression[1], u'owner' : username, u'value' : value}) + prop_list.append( + {"name": expression[1], "owner": username, "value": value} + ) else: - if(verbose): + if verbose: print("MISSING " + expression[1] + "IN " + channel_name) if verbose: - print("UPDATE "+channel_name) + print("UPDATE " + channel_name) try: - client.update(channel = {u'name' : channel_name, u'owner':username,u'properties':prop_list }) + client.update( + channel={ + "name": channel_name, + "owner": username, + "properties": prop_list, + } + ) except Exception as e: - if PYTHON3: - # Python 3 code in this block - print('Failed to update: ' + channel_name + " \n--Cause:" + str(e).strip()) - else: - # Python 2 code in this block - print('Failed to update: ' + channel_name + " \n--Cause:" + e.message) + print( + "Failed to update: " + channel_name + " \n--Cause:" + str(e).strip() + ) - -def updateProperty(result, property_name,channel_name): - ''' +def updateProperty(result, property_name, channel_name): + """ Creates or updates properties defined in configuration file for any channel object passed. - ''' - if(verbose): - print("ADD "+result+" TO "+property_name+ " IN " +channel_name) - client.set(property={u'name':property_name, u'owner' : username, u'value':result},channelName=channel_name) + """ + if verbose: + print("ADD " + result + " TO " + property_name + " IN " + channel_name) + client.set( + property={"name": property_name, "owner": username, "value": result}, + channelName=channel_name, + ) def addChannel(result, property_name, channel_name): - ''' + """ Presently not used method for building a list of channels to be batch-updated. - ''' + """ global channel_list - if (verbose): - print("ADD "+result+" TO "+property_name+ " IN " +channel_name) - #channel_list.append(Channel(name=channel_name, owner=username,properties=[Property(property_name,username,result)])) - #ch = Channel(name=channel_name, owner=username,properties=[Property(property_name,username,result)]) - #client.update(channel = ch) + if verbose: + print("ADD " + result + " TO " + property_name + " IN " + channel_name) + # channel_list.append(Channel(name=channel_name, owner=username,properties=[Property(property_name,username,result)])) + # ch = Channel(name=channel_name, owner=username,properties=[Property(property_name,username,result)]) + # client.update(channel = ch) + def getPassword(option, opt_str, value, parser): - ''' + """ Simple method to prompt user for password - ''' + """ parser.values.password = getpass() def __getDefaultConfig(arg, value): - ''' + """ Clean reception of command line configurations for default assignment. - ''' - if value == None: + """ + if value is None: try: - return basecfg.get('DEFAULT', arg) - except: + return basecfg.get("DEFAULT", arg) + except (KeyError, NoSectionError): return None else: return value def startClient(): - ''' + """ Initiates client using default values if none are changed. - ''' + """ global client - client= ChannelFinderClient(BaseURL=SERVICE_URL, username=username, password=password) + client = ChannelFinderClient( + BaseURL=SERVICE_URL, username=username, password=password + ) def main(): usage = "usage: %prog [options] filename.dbl filename2.cfg" parser = OptionParser(usage=usage) - parser.add_option('-s', '--service', \ - action='store', type='string', dest='serviceURL', \ - help='the service URL') - parser.add_option('-u', '--username', \ - action='store', type='string', dest='username', \ - help='username') - parser.add_option('-v', '--verbose', \ - action='store_true', default=False, dest='verbose', \ - help='displays additional run information') - parser.add_option('-p', '--password', \ - action='callback', callback=getPassword, \ - dest='password', \ - help='prompt user for password') + parser.add_option( + "-s", + "--service", + action="store", + type="string", + dest="serviceURL", + help="the service URL", + ) + parser.add_option( + "-u", + "--username", + action="store", + type="string", + dest="username", + help="username", + ) + parser.add_option( + "-v", + "--verbose", + action="store_true", + default=False, + dest="verbose", + help="displays additional run information", + ) + 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: - parser.error('Please specify a file') + if not args: + parser.error("Please specify a file") mainRun(opts, args) def mainRun(opts, args): - ''' + """ Collects values from command line flags, also sets default values. Preps for run and initiates. - ''' + """ global username, password, SERVICE_URL, quiet, verbose - username = __getDefaultConfig('username', opts.username) - password = __getDefaultConfig('password', opts.password) - SERVICE_URL = __getDefaultConfig('serviceURL', opts.serviceURL) - verbose = __getDefaultConfig('verbose', opts.verbose) - if username==None: - username='cf-update' #CURRENT DEFAULT - if password==None: - password='1234' #CURRENT DEFAULT - if SERVICE_URL==None: - SERVICE_URL='https://localhost:8181/ChannelFinder' #CURRENT DEFAULT + username = __getDefaultConfig("username", opts.username) + password = __getDefaultConfig("password", opts.password) + SERVICE_URL = __getDefaultConfig("serviceURL", opts.serviceURL) + verbose = __getDefaultConfig("verbose", opts.verbose) + if username is None: + username = "cf-update" # CURRENT DEFAULT + if password is None: + password = "1234" # CURRENT DEFAULT + if SERVICE_URL is None: + SERVICE_URL = "https://localhost:8181/ChannelFinder" # CURRENT DEFAULT startClient() run(args[0], args[1]) -def run(dbl_path,cfg_path): - ''' +def run(dbl_path, cfg_path): + """ Core functionality sequence. - ''' + """ global DBL_PATH, CFG_PATH - if (verbose): + if verbose: print(dbl_path, cfg_path) - DBL_PATH=dbl_path - CFG_PATH=cfg_path + DBL_PATH = dbl_path + CFG_PATH = cfg_path readDBL(DBL_PATH) readConfiguration(CFG_PATH) applyExpression() -''' +""" Initiates program main() run when not being imported. Initiates client for testing when imported. -''' +""" if __name__ == "__main__": try: main() @@ -241,7 +263,3 @@ def run(dbl_path,cfg_path): print("IOError: " + e.message) else: startClient() - - - - diff --git a/channelfinder/cfPropertyManager/__init__.py b/channelfinder/cfPropertyManager/__init__.py index 148e4da..e69de29 100644 --- a/channelfinder/cfPropertyManager/__init__.py +++ b/channelfinder/cfPropertyManager/__init__.py @@ -1 +0,0 @@ -from .CFPropertyManager import * \ No newline at end of file diff --git a/channelfinder/cfPropertyManager/cf-property-manager-config.cfg b/channelfinder/cfPropertyManager/cf-property-manager-config.cfg index 0546a5b..874645a 100644 --- a/channelfinder/cfPropertyManager/cf-property-manager-config.cfg +++ b/channelfinder/cfPropertyManager/cf-property-manager-config.cfg @@ -1,3 +1,3 @@ devName=[{][^:}][^:}]* devType=[:][^{]*?[:}](?!.*[{]) -IGNORE=.*WtrSkid.* \ No newline at end of file +IGNORE=.*WtrSkid.* diff --git a/channelfinder/cfUpdate/CFUpdateIOC.py b/channelfinder/cfUpdate/CFUpdateIOC.py index c389f93..5146394 100644 --- a/channelfinder/cfUpdate/CFUpdateIOC.py +++ b/channelfinder/cfUpdate/CFUpdateIOC.py @@ -1,4 +1,4 @@ -''' +""" Copyright (c) 2010 Brookhaven National Laboratory All rights reserved. Use is subject to license terms and conditions. @@ -8,10 +8,11 @@ CFUpdateIOC provides a command like client to update channelfinder with a list of process variables (usually the output of the dbl command). -''' +""" from __future__ import print_function +from configparser import NoSectionError import os import re from optparse import OptionParser @@ -21,15 +22,16 @@ from channelfinder import ChannelFinderClient from channelfinder._conf import basecfg + def getArgsFromFilename(completeFilePath): fileName = os.path.split(os.path.normpath(completeFilePath))[1] - pattern4Hostname = '(\S+?)\.\S+' + pattern4Hostname = "(\S+?)\.\S+" match = re.search(pattern4Hostname, fileName) if match: hostName = match.group(1) else: hostName = None - pattern4Iocname = '\S+?\.(\S+?)\.\S+' + pattern4Iocname = "\S+?\.(\S+?)\.\S+" match = re.search(pattern4Iocname, fileName) if match: iocName = match.group(1) @@ -37,14 +39,19 @@ def getArgsFromFilename(completeFilePath): iocName = None return hostName, iocName + 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 = 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 list(pvNames) except IOError: return None @@ -52,215 +59,303 @@ def getPVNames(completeFilePath, pattern=None): if f: f.close() -def updateChannelFinder(pvNames, hostName, iocName, time, owner, - service=None, username=None, password=None): - ''' - pvNames = list of pvNames + +def updateChannelFinder( + pvNames, hostName, iocName, time, owner, service=None, username=None, password=None +): + """ + pvNames = list of pvNames ([] permitted will effectively remove the hostname, iocname from all channels) hostName = pv hostName (None not permitted) iocName = pv iocName (None not permitted) owner = the owner of the channels and properties being added, this can be different from the user e.g. user = abc might create a channel with owner = group-abc time = the time at which these channels are being created/modified - [optional] if not specified the default values are used by the + [optional] if not specified the default values are used by the channelfinderapi lib service = channelfinder service URL username = channelfinder username password = channelfinder password - ''' - if hostName == None or iocName == None: - raise RuntimeError('missing hostName or iocName') + """ + if hostName is None or iocName is None: + raise RuntimeError("missing hostName or iocName") channels = [] - try: - client = ChannelFinderClient(BaseURL=service, username=username, password=password) - except: - raise RuntimeError('Unable to create a valid webResourceClient') + client = ChannelFinderClient(BaseURL=service, username=username, password=password) checkPropertiesExist(client, owner) - previousChannelsList = client.findByArgs([(u'hostName', hostName), (u'iocName', iocName)]) - if previousChannelsList != None: + previousChannelsList = client.findByArgs( + [("hostName", hostName), ("iocName", iocName)] + ) + if previousChannelsList is not None: 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', - 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''' - oldHostName = [ prop[u'value'] for prop in ch[u'properties'] if prop[u'name'] == u'hostName'][0] - oldIocName = [ prop[u'value'] for prop in ch[u'properties'] if prop[u'name'] == u'iocName'][0] - channels.append(updateChannel(ch, - owner=owner, - hostName=oldHostName, - iocName=oldIocName, - pvStatus=u'Inactive', - time=time)) + if pvNames is not None and ch["name"] in pvNames: + """""" + channels.append( + updateChannel( + ch, + owner=owner, + hostName=hostName, + iocName=iocName, + pvStatus="Active", + time=time, + ) + ) + pvNames.remove(ch["name"]) + elif pvNames is None or ch["name"] not in pvNames: + """Orphan the channel : mark as inactive, keep the old hostName and iocName""" + oldHostName = [ + prop["value"] + for prop in ch["properties"] + if prop["name"] == "hostName" + ][0] + oldIocName = [ + prop["value"] + for prop in ch["properties"] + if prop["name"] == "iocName" + ][0] + channels.append( + updateChannel( + ch, + owner=owner, + hostName=oldHostName, + iocName=oldIocName, + pvStatus="Inactive", + time=time, + ) + ) # now pvNames contains a list of pv's new on this host/ioc for pv in pvNames: - ch = client.findByArgs([('~name',pv)]) + ch = client.findByArgs([("~name", pv)]) if not ch: - '''New channel''' - 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', - time=time)) + """New channel""" + channels.append( + createChannel( + pv, + chOwner=owner, + hostName=hostName, + iocName=iocName, + pvStatus="Active", + time=time, + ) + ) + elif ch[0] is not 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="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'] - if property[u'name'] != u'hostName' and property[u'name'] != u'iocName' and property[u'name'] != u'pvStatus'] + if channel["properties"]: + properties = [ + property + for property in channel["properties"] + if property["name"] != "hostName" + and property["name"] != "iocName" + and property["name"] != "pvStatus" + ] else: properties = [] - if hostName != None: - properties.append({u'name' : u'hostName', u'owner':owner, u'value' : hostName}) - if iocName != None: - properties.append({u'name' : u'iocName', u'owner':owner, u'value' : iocName}) + if hostName is not None: + properties.append({"name": "hostName", "owner": owner, "value": hostName}) + if iocName is not None: + properties.append({"name": "iocName", "owner": owner, "value": iocName}) if pvStatus: - properties.append({u'name' : u'pvStatus', u'owner':owner, u'value' : pvStatus}) + properties.append({"name": "pvStatus", "owner": owner, "value": pvStatus}) if time: - properties.append({u'name' : u'time', u'owner':owner, u'value' : time}) - channel[u'properties'] = properties + properties.append({"name": "time", "owner": owner, "value": time}) + channel["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="Inactive", time=None +): + """ Helper to create a channel object with the required properties - ''' - ch = {u'name' : chName, u'owner' : chOwner, u'properties' : []} - if hostName != None: - ch[u'properties'].append({u'name' : u'hostName', u'owner':chOwner, u'value' : hostName}) - if iocName != None: - ch[u'properties'].append({u'name' : u'iocName', u'owner':chOwner, u'value' : iocName}) + """ + ch = {"name": chName, "owner": chOwner, "properties": []} + if hostName is not None: + ch["properties"].append( + {"name": "hostName", "owner": chOwner, "value": hostName} + ) + if iocName is not None: + ch["properties"].append({"name": "iocName", "owner": chOwner, "value": iocName}) if pvStatus: - ch[u'properties'].append({u'name' : u'pvStatus', u'owner':chOwner, u'value' : pvStatus}) + ch["properties"].append( + {"name": "pvStatus", "owner": chOwner, "value": pvStatus} + ) if time: - ch[u'properties'].append({u'name' : u'time', u'owner':chOwner, u'value' : time}) + ch["properties"].append({"name": "time", "owner": chOwner, "value": time}) return ch + def checkPropertiesExist(client, propOwner): - ''' + """ Checks if the properties used by dbUpdate are present if not it creates them - ''' - requiredProperties = [u'hostName', u'iocName', u'pvStatus', u'time'] + """ + requiredProperties = ["hostName", "iocName", "pvStatus", "time"] for propName in requiredProperties: - if client.findProperty(propName) == None: + if client.findProperty(propName) is None: try: - client.set(property={u'name' : propName, u'owner' : propOwner}) + client.set(property={"name": propName, "owner": propOwner}) except Exception as e: - print('Failed to create the property',propName) - print('CAUSE:',e.message) + print("Failed to create the property", propName) + print("CAUSE:", e.message) + def ifNoneReturnDefault(object, default): - ''' + """ if the object is None or empty string then this function returns the default value - ''' - if object == None and object != '': - return default - else: + """ + if object: return object + return default + def mainRun(opts, args): - ''' + """ the main is broken so that the unit test can use mock opt objects for testing - ''' + """ for filename in args: - if('*' in filename or '?' in filename): + if "*" in filename or "?" in filename: matchingFiles = glob(filename) for eachMatchingFile in matchingFiles: completeFilePath = os.path.abspath(eachMatchingFile) 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), - password=__getDefaultConfig('password',opts.password)) + 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), + 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), - password=__getDefaultConfig('password',opts.password)) - + 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), + password=__getDefaultConfig("password", opts.password), + ) + + def __getDefaultConfig(arg, value): - if value is None: - try: - return basecfg.get('DEFAULT', arg) - except: - return None - else: - return value - + if value is None: + try: + return basecfg.get("DEFAULT", arg) + except (KeyError, NoSectionError): + return None + else: + return value + + def main(): usage = "usage: %prog [options] filename" parser = OptionParser(usage=usage) - 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', - help='the iocname') - 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', - help='owner if not specified username will default as owner') - 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', - help='username') - parser.add_option('-t', '--time', - action='store', type='string', dest='time', - help='time') - parser.add_option('-p', '--password', - action='callback', callback=getPassword, - dest='password', - help='prompt user for password') + 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", + help="the iocname", + ) + 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", + help="owner if not specified username will default as owner", + ) + 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", + help="username", + ) + parser.add_option( + "-t", "--time", action="store", type="string", dest="time", help="time" + ) + 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: - parser.error('Please specify a file') + if not args: + parser.error("Please specify a file") mainRun(opts, args) + def getPassword(option, opt_str, value, parser): - ''' + """ Simple method to prompt user for password TODO do not show the password. - ''' - parser.values.password = getpass() - -if __name__ == '__main__': + """ + parser.values.password = getpass() + + +if __name__ == "__main__": main() pass diff --git a/channelfinder/util/ChannelUtil.py b/channelfinder/util/ChannelUtil.py index 0275e4e..95b5418 100644 --- a/channelfinder/util/ChannelUtil.py +++ b/channelfinder/util/ChannelUtil.py @@ -9,16 +9,17 @@ from .Validators import PropertyValidator, TagValidator + class ChannelUtil(object): """ Utiltity class """ - + def __init__(self): """ Constructor """ - + @classmethod def getAllTags(cls, channels): """ @@ -34,13 +35,13 @@ def getAllTags(cls, channels): return list(uniqueNames) else: return None - + @classmethod def getAllProperties(cls, channels): """ getAllProperties([Channel]) -> [String] returns a list of the propertyNames of all the properties on the set of channels - """ + """ if isinstance(channels, list): allProperties = [] for channel in channels: @@ -51,8 +52,8 @@ def getAllProperties(cls, channels): return list(uniqueNames) else: return None - - @classmethod + + @classmethod def getAllPropValues(cls, channels, propertyName, key=None): """ given the list of channels return a list of all values @@ -60,10 +61,14 @@ def getAllPropValues(cls, channels, propertyName, key=None): ret = [] for ch in channels: if ch.Properties: - match = [property for property in ch.Properties if property.Name == propertyName] + match = [ + property + for property in ch.Properties + if property.Name == propertyName + ] ret.append(match[0].Value) - return sorted(ret, key=key) - + return sorted(ret, key=key) + @classmethod def validateChannelsWithTag(cls, channels, tag): """ @@ -74,20 +79,19 @@ def validateChannelsWithTag(cls, channels, tag): and false if anyone channel does not have that tag """ return cls.channelsValidityCheck(channels, TagValidator(tag)) - + @classmethod def validateChannelWithProperty(cls, channels, prop): """ Utility method to validate a group of channels to ensure they all have the property 'prop' e.g. ChannelUtil.validateChannelWithProperty(client.find(ElemName='The Magnet'), Property('length','propOwner','0.3')) - - This will return True if all channels with property ElemName with value 'The Magnet' also have the + + This will return True if all channels with property ElemName with value 'The Magnet' also have the property length with value 0.3 """ return cls.channelsValidityCheck(channels, PropertyValidator(prop)) - - + @classmethod def channelsValidityCheck(cls, channels, validator): """ @@ -96,5 +100,5 @@ def channelsValidityCheck(cls, channels, validator): """ for ch in channels: if not validator.validate(ch): - return False + return False return True diff --git a/channelfinder/util/Validators.py b/channelfinder/util/Validators.py index 13e67f3..ea91c26 100644 --- a/channelfinder/util/Validators.py +++ b/channelfinder/util/Validators.py @@ -1,36 +1,37 @@ -''' +""" Created on Mar 13, 2012 @author: shroffk -''' +""" + class TagValidator(object): - ''' + """ A simple Validator that ensures that a particular Tag is present on the channel - ''' - + """ def __init__(self, tag): - ''' + """ Constructor - ''' + """ self.tag = tag def validate(self, channel): tags = [t.Name for t in channel.Tags] return self.tag.Name in tags + class PropertyValidator(object): - ''' + """ A simple Validator that ensures that a particular Property is present on the channel - ''' + """ def __init__(self, prop): - ''' + """ Constructor - ''' + """ self.property = prop - + def validate(self, channel): props = [p.Name for p in channel.Properties] # for p in channel.Properties: diff --git a/channelfinder/util/__init__.py b/channelfinder/util/__init__.py index 03e4db3..e3b4264 100644 --- a/channelfinder/util/__init__.py +++ b/channelfinder/util/__init__.py @@ -1 +1,3 @@ -from .ChannelUtil import ChannelUtil \ No newline at end of file +from .ChannelUtil import ChannelUtil + +__all__ = ["ChannelUtil"] diff --git a/example/demo.py b/example/demo.py index b648d64..f972911 100644 --- a/example/demo.py +++ b/example/demo.py @@ -1,7 +1,7 @@ """ This module is a demo which provides a interface to access channel finder service to get channel information. The Channel Finder service uses a web service, and http protocol to provide EPICS channel name, and its related -properties, tags. The properties supported so far are, which is developed against NSLS II storage ring.: +properties, tags. The properties supported so far are, which is developed against NSLS II storage ring.: 'elem_type': element type 'elem_name': element name 'length': element length @@ -12,8 +12,8 @@ 'girder': girder information 'handle': handle, either setpoint or readback 'symmetry': symmetry (A or B for NSLS II storage ring, following the naming convention) - - + + Created on Mar 14, 2011 National Synchrotron Radiation Facility II @@ -26,6 +26,7 @@ from channelfinder import ChannelFinderClient import urllib3 + urllib3.disable_warnings() @@ -38,42 +39,43 @@ def prop_demo(channel): """ # every property has to be added first before using it. properties = [] - propDict = {'elem_type': 'cf-update', - 'elem_name': 'cf-update', - 'dev_name': 'cf-update', - 'length': 'cf-update', - 's_position': 'cf-update', - 'ordinal': 'cf-update', - 'system': 'cf-update', - 'cell': 'cf-update', - 'girder': 'cf-update', - 'handle': 'cf-update', - 'symmetry': 'cf-update', - 'hostName': 'cf-update', - 'iocName': 'cf-update', - 'pvStatus': 'cf-update', - 'time': 'cf-update', - 'ioctest': 'cf-update', - 'iocid': 'cf-update', - 'iocidtest': 'cf-update' - } + propDict = { + "elem_type": "cf-update", + "elem_name": "cf-update", + "dev_name": "cf-update", + "length": "cf-update", + "s_position": "cf-update", + "ordinal": "cf-update", + "system": "cf-update", + "cell": "cf-update", + "girder": "cf-update", + "handle": "cf-update", + "symmetry": "cf-update", + "hostName": "cf-update", + "iocName": "cf-update", + "pvStatus": "cf-update", + "time": "cf-update", + "ioctest": "cf-update", + "iocid": "cf-update", + "iocidtest": "cf-update", + } properties1 = channel.getAllProperties() for prop in properties1: try: - del propDict[prop['name']] + del propDict[prop["name"]] except KeyError: pass if len(propDict) > 0: for k, v in propDict.items(): - properties.append({u'name': k, u'owner': v}) + properties.append({"name": k, "owner": v}) if len(propDict) == 1: channel.set(property=properties[0]) else: channel.set(properties=properties) print(channel.getAllProperties()) else: - print('all properties are in database already.') + print("all properties are in database already.") def channel_demo(channel): @@ -86,30 +88,35 @@ def channel_demo(channel): try: # the file has the following attributes: # index, read back, set point, phys name, len[m], s[m], type - f = open('lat_conf_table.txt', 'r') + f = open("lat_conf_table.txt", "r") lines = f.readlines() channels = [] for line in lines: - if not (line.startswith('#') or line.startswith('!') or not line.strip()): + if not (line.startswith("#") or line.startswith("!") or not line.strip()): results = line.split() if len(results) < 7: # input file format problem raise - props = [{'name': u'elem_type', 'value': results[6]}, - {'name': u'elem_name', 'value': results[3]}, - {'name': u'length', 'value': results[4]}, - {'name': u's_position', 'value': results[5]}, - {'name': u'ordinal', 'value': results[0]}, - {'name': u'system', 'value': u'SR'} - ] - - if results[1] != 'NULL': - props.append({'name': u'handle', 'value': u'readback'}) - channels.append({u'name': results[1], u'owner': u'cf-update', u'properties': props}) - if results[2] != 'NULL': - props.append({'name': u'handle', 'value': u'setpoint'}) - channels.append({u'name': results[2], u'owner': u'cf-update', u'properties': props}) + props = [ + {"name": "elem_type", "value": results[6]}, + {"name": "elem_name", "value": results[3]}, + {"name": "length", "value": results[4]}, + {"name": "s_position", "value": results[5]}, + {"name": "ordinal", "value": results[0]}, + {"name": "system", "value": "SR"}, + ] + + if results[1] != "NULL": + props.append({"name": "handle", "value": "readback"}) + channels.append( + {"name": results[1], "owner": "cf-update", "properties": props} + ) + if results[2] != "NULL": + props.append({"name": "handle", "value": "setpoint"}) + channels.append( + {"name": results[2], "owner": "cf-update", "properties": props} + ) channel.set(channels=channels) finally: f.close() @@ -123,32 +130,36 @@ def tag_demo(channel): :return: """ # set one tag - tag = {'name': 'example1', 'owner': 'cf-update'} + tag = {"name": "example1", "owner": "cf-update"} channel.set(tag=tag) - + # set a set of tags - tags = [{'name': 'example2', 'owner': 'cf-update'}, - {'name': 'example3', 'owner': 'cf-update'}, - {'name': 'example4', 'owner': 'cf-update'}, - {'name': 'example5', 'owner': 'cf-update'}] + tags = [ + {"name": "example2", "owner": "cf-update"}, + {"name": "example3", "owner": "cf-update"}, + {"name": "example4", "owner": "cf-update"}, + {"name": "example5", "owner": "cf-update"}, + ] channel.set(tags=tags) def addtag2channel_demo(channel): - tag = {'name': 'example1', 'owner': 'cf-update'} + tag = {"name": "example1", "owner": "cf-update"} # set a set of tags - tags = [{'name': 'example2', 'owner': 'cf-update'}, - {'name': 'example3', 'owner': 'cf-update'}, - {'name': 'example4', 'owner': 'cf-update'}, - {'name': 'example5', 'owner': 'cf-update'}] - - channels = channel.find(name='SR*') - channelNames = [ch['name'] for ch in channels] - + tags = [ + {"name": "example2", "owner": "cf-update"}, + {"name": "example3", "owner": "cf-update"}, + {"name": "example4", "owner": "cf-update"}, + {"name": "example5", "owner": "cf-update"}, + ] + + channels = channel.find(name="SR*") + channelNames = [ch["name"] for ch in channels] + # set a tag to many channels channel.set(tag=tag, channelNames=channelNames) - + # set tags to many channels for tag in tags: channel.set(tag=tag, channelNames=channelNames) @@ -161,13 +172,13 @@ def searchchannel_demo(channel): :param channel: :return: """ - channels = channel.find(name='SR*') + channels = channel.find(name="SR*") print(len(channels)) for channel in channels: print(channel) -if __name__ == '__main__': +if __name__ == "__main__": # cf = ChannelFinderClient(BaseURL='https://localhost:8181/ChannelFinder', username='channel', password='1234') cf = ChannelFinderClient() # you can use browser to view results diff --git a/pyproject.toml b/pyproject.toml index 6182786..0043993 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ dependencies = [ "urllib3>=1.22" ] [project.optional-dependencies] -test = ["pytest", "testcontainers>=3.7.0,<4"] +test = ["pytest", "testcontainers>=4"] [project.urls] Homepage = "https://github.com/ChannelFinderService/pyCFClient" diff --git a/test/_testConf.py b/test/_testConf.py index ffd3eda..5e8533b 100644 --- a/test/_testConf.py +++ b/test/_testConf.py @@ -11,59 +11,60 @@ username=MyUserName password=MyPassword """ + import os.path import unittest from testcontainers.compose import DockerCompose -import sys -if sys.version_info[0] < 3: - # Python 2 code in this block - from ConfigParser import SafeConfigParser as ConfigParser -else: - # Python 3 code in this block - from configparser import ConfigParser +from configparser import ConfigParser + def channelFinderDocker(): return DockerCompose("test", compose_file_name="docker-compose.yml") + class ChannelFinderClientTestCase(unittest.TestCase): channelFinderCompose = None + @classmethod def setUpClass(cls) -> None: cls.channelFinderCompose = channelFinderDocker() cls.channelFinderCompose.start() - cls.channelFinderCompose.wait_for(_testConf.get('DEFAULT', 'BaseURL') + "/ChannelFinder") + cls.channelFinderCompose.wait_for(_testConf.get("DEFAULT", "BaseURL")) return super().setUpClass() - + @classmethod def tearDownClass(cls) -> None: if cls.channelFinderCompose is not None: cls.channelFinderCompose.stop() return super().tearDownClass() - -def __loadConfig(): - dflt = {'BaseURL':'http://localhost:8080/ChannelFinder', - 'username' : 'admin', - 'password' : 'adminPass', - 'owner' : 'cf-update', - 'channelOwner' : 'cf-channels', - 'channelUsername' : 'admin', - 'channelPassword' : 'adminPass', - 'propOwner' : 'cf-properties', - 'propUsername' : 'admin', - 'propPassword' : 'adminPass', - 'tagOwner' : 'cf-tags', - 'tagUsername' : 'admin', - 'tagPassword' : 'adminPass' +def __loadConfig(): + dflt = { + "BaseURL": "http://localhost:8080/ChannelFinder", + "username": "admin", + "password": "adminPass", + "owner": "cf-update", + "channelOwner": "cf-channels", + "channelUsername": "admin", + "channelPassword": "adminPass", + "propOwner": "cf-properties", + "propUsername": "admin", + "propPassword": "adminPass", + "tagOwner": "cf-tags", + "tagUsername": "admin", + "tagPassword": "adminPass", } - cf=ConfigParser(defaults=dflt) - cf.read([ - '/etc/channelfinderapi.conf', - os.path.expanduser('~/channelfinderapi.conf'), - 'channelfinderapi.conf' - ]) + cf = ConfigParser(defaults=dflt) + cf.read( + [ + "/etc/channelfinderapi.conf", + os.path.expanduser("~/channelfinderapi.conf"), + "channelfinderapi.conf", + ] + ) return cf -_testConf=__loadConfig() + +_testConf = __loadConfig() diff --git a/test/testCFPpropertyManager.py b/test/testCFPpropertyManager.py index 66607d1..3c1d452 100644 --- a/test/testCFPpropertyManager.py +++ b/test/testCFPpropertyManager.py @@ -1,38 +1,39 @@ from __future__ import print_function import unittest -from channelfinder.cfPropertyManager import CFPropertyManager import re import os from _testConf import _testConf, ChannelFinderClientTestCase import urllib3 -urllib3.disable_warnings() +from channelfinder.cfPropertyManager import CFPropertyManager -class CFPropertyManagerTest(ChannelFinderClientTestCase): +urllib3.disable_warnings() - cfglines = [] +class CFPropertyManagerTest(ChannelFinderClientTestCase): def setUp(self): print("\n---------------------------------------------------------------\n") def test_run(self): - ''' + """ Tests main program full sweep. - ''' - CFPropertyManager.run("cf-property-manager-test-dbl","cf-property-manager-test-cfg") + """ + CFPropertyManager.run( + "cf-property-manager-test-dbl", "cf-property-manager-test-cfg" + ) os.remove("cf-property-manager-test-cfg") os.remove("cf-property-manager-test-dbl") def test_dbl_read(self): - ''' + """ Tests accessibility of cfg file, does not check format - ''' - CFPropertyManager.SERVICE_URL=_testConf.get('DEFAULT', 'BaseURL') - CFPropertyManager.username=_testConf.get('DEFAULT', 'username') - CFPropertyManager.password=_testConf.get('DEFAULT', 'password') + """ + CFPropertyManager.SERVICE_URL = _testConf.get("DEFAULT", "BaseURL") + CFPropertyManager.username = _testConf.get("DEFAULT", "username") + CFPropertyManager.password = _testConf.get("DEFAULT", "password") CFPropertyManager.startClient() fo = open("cf-property-manager-test-dbl", "w+") fo.write("UT:RF-Cu:1{LD}Time:ShtDwn-I") @@ -43,56 +44,61 @@ def test_dbl_read(self): return dbllines def test_regex_error(self): - ''' + """ Tests bad regex error raise. - ''' + """ fo = open("cf-property-manager-test-bad-cfg", "w+") - fo.write("property=["); + fo.write("property=[") fo.close() - cfglines=cfglines = CFPropertyManager.readConfiguration("cf-property-manager-test-bad-cfg") + cfglines = cfglines = CFPropertyManager.readConfiguration( + "cf-property-manager-test-bad-cfg" + ) for properties in cfglines: print(properties[0] + " = " + properties[1]) try: self.assertRaises(Exception, re.compile, properties[1]) except Exception as e: - print('Invalid regular expression: ',properties[1]) - print('CAUSE:',e.message) + print("Invalid regular expression: ", properties[1]) + print("CAUSE:", e.message) os.remove("cf-property-manager-test-bad-cfg") return cfglines - def test_regex(self): - ''' + """ Tests validity of regular expression. - ''' + """ fo = open("cf-property-manager-test-cfg", "w+") - fo.write("devName=[{][^:}][^:}]*\ndevType=[:][^{]*?[:}](?!.*[{])\nIGNORE=.*WtrSkid.*") + fo.write( + "devName=[{][^:}][^:}]*\ndevType=[:][^{]*?[:}](?!.*[{])\nIGNORE=.*WtrSkid.*" + ) fo.close() cfglines = CFPropertyManager.readConfiguration("cf-property-manager-test-cfg") for properties in cfglines: - expression=None + expression = None print(properties[0] + " = " + properties[1]) try: expression = re.compile(properties[1]) - self.assertTrue(expression!=None) + self.assertTrue(expression is not None) except Exception as e: - print('Invalid regular expression: ',properties[1]) - print('CAUSE:',e.message) + print("Invalid regular expression: ", properties[1]) + print("CAUSE:", e.message) return cfglines def test_cfg_read(self): - ''' + """ Tests accessibility of cfg file, does not check format - ''' + """ global cfglines - CFPropertyManager.SERVICE_URL=_testConf.get('DEFAULT', 'BaseURL') - CFPropertyManager.username=_testConf.get('DEFAULT', 'username') - CFPropertyManager.password=_testConf.get('DEFAULT', 'password') + CFPropertyManager.SERVICE_URL = _testConf.get("DEFAULT", "BaseURL") + CFPropertyManager.username = _testConf.get("DEFAULT", "username") + CFPropertyManager.password = _testConf.get("DEFAULT", "password") CFPropertyManager.startClient() fo = open("cf-property-manager-test-cfg", "w+") - fo.write("devName=[{][^:}][^:}]*\ndevType=[:][^{]*?[:}](?!.*[{])\nIGNORE=.*WtrSkid.*") + fo.write( + "devName=[{][^:}][^:}]*\ndevType=[:][^{]*?[:}](?!.*[{])\nIGNORE=.*WtrSkid.*" + ) fo.close() cfglines = CFPropertyManager.readConfiguration("cf-property-manager-test-cfg") for line in cfglines: @@ -100,5 +106,5 @@ def test_cfg_read(self): return cfglines -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/test/testCFUpdateIOC.py b/test/testCFUpdateIOC.py index a14fa38..c14bdaa 100644 --- a/test/testCFUpdateIOC.py +++ b/test/testCFUpdateIOC.py @@ -1,15 +1,21 @@ -''' +""" Copyright (c) 2010 Brookhaven National Laboratory All rights reserved. Use is subject to license terms and conditions. Created on Apr 5, 2011 @author: shroffk -''' +""" + import unittest import os from channelfinder import ChannelFinderClient -from channelfinder.cfUpdate.CFUpdateIOC import getPVNames, getArgsFromFilename, updateChannelFinder, ifNoneReturnDefault +from channelfinder.cfUpdate.CFUpdateIOC import ( + getPVNames, + getArgsFromFilename, + updateChannelFinder, + ifNoneReturnDefault, +) from time import time from tempfile import NamedTemporaryFile from copy import copy @@ -17,133 +23,197 @@ from _testConf import _testConf, ChannelFinderClientTestCase import urllib3 + urllib3.disable_warnings() class UpdateIOCTest(ChannelFinderClientTestCase): def setUp(self): - if _testConf.has_option('DEFAULT', 'BaseURL'): - self.baseURL = _testConf.get('DEFAULT', 'BaseURL') - if _testConf.has_option('DEFAULT', 'username'): - self.username = _testConf.get('DEFAULT', 'username') - if _testConf.has_option('DEFAULT', 'password'): - self.password = _testConf.get('DEFAULT', 'password') - if _testConf.has_option('DEFAULT', 'owner'): - self.owner = _testConf.get('DEFAULT', 'owner') - - pass + if _testConf.has_option("DEFAULT", "BaseURL"): + self.baseURL = _testConf.get("DEFAULT", "BaseURL") + if _testConf.has_option("DEFAULT", "username"): + self.username = _testConf.get("DEFAULT", "username") + if _testConf.has_option("DEFAULT", "password"): + self.password = _testConf.get("DEFAULT", "password") + if _testConf.has_option("DEFAULT", "owner"): + self.owner = _testConf.get("DEFAULT", "owner") + pass def tearDown(self): pass def testParameterParsing(self): -# scrap.mainRun(mockOpt('mockhostname', 'mockiocname'), []) + # scrap.mainRun(mockOpt('mockhostname', 'mockiocname'), []) pass - + def testGetArgsFromFilename(self): - #parse just file name - hostname, iocname = getArgsFromFilename('aaa.bbb.ccc') - self.assertTrue(hostname == 'aaa' and iocname == 'bbb', 'failed to parse the file name correctly') + # parse just file name + hostname, iocname = getArgsFromFilename("aaa.bbb.ccc") + self.assertTrue( + hostname == "aaa" and iocname == "bbb", + "failed to parse the file name correctly", + ) # parse file name from complete path - hostname, iocname = getArgsFromFilename('complete/path/to/file/aaa.bbb.ccc') - self.assertTrue(hostname == 'aaa' and iocname == 'bbb', 'failed to parse the file path correctly') + hostname, iocname = getArgsFromFilename("complete/path/to/file/aaa.bbb.ccc") + self.assertTrue( + hostname == "aaa" and iocname == "bbb", + "failed to parse the file path correctly", + ) # parse file which does not fit the format - hostname, iocname = getArgsFromFilename('complete/path/to/file/somefilename') - self.assertTrue(hostname == None and iocname == None, 'failed to parse the file path correctly') + hostname, iocname = getArgsFromFilename("complete/path/to/file/somefilename") + self.assertTrue( + hostname is None and iocname is None, + "failed to parse the file path correctly", + ) # file with only hostName - hostname, iocname = getArgsFromFilename('complete/path/to/file/aaa.somefilename') - self.assertTrue(hostname == 'aaa' and iocname == None, 'failed to parse the file correctly') + hostname, iocname = getArgsFromFilename( + "complete/path/to/file/aaa.somefilename" + ) + self.assertTrue( + hostname == "aaa" and iocname is None, "failed to parse the file correctly" + ) # parse the hostname/iocname from 1st and 2nd positions seperated by . - hostname, iocname = getArgsFromFilename('complete/path/to/file/aaa.bbb.ccc.ddd') - self.assertTrue(hostname == 'aaa' and iocname == 'bbb', 'failed to parse the file correctly') + hostname, iocname = getArgsFromFilename("complete/path/to/file/aaa.bbb.ccc.ddd") + self.assertTrue( + hostname == "aaa" and iocname == "bbb", "failed to parse the file correctly" + ) pass def testAddUpdateChannels(self): # Check the method finds the error conditions and raises exceptions self.assertRaises(Exception, updateChannelFinder, [[], None, None]) - self.assertRaises(Exception, updateChannelFinder, [[], None, 'iocname']) - self.assertRaises(Exception, updateChannelFinder, [[], 'hostName', None]) + self.assertRaises(Exception, updateChannelFinder, [[], None, "iocname"]) + self.assertRaises(Exception, updateChannelFinder, [[], "hostName", None]) # create default client client = ChannelFinderClient() - + # add new pv's t1 = str(time()) - hostName1 = 'update-test-hostname' + t1 - iocName1 = 'update-test-iocName' + t1 - channels = client.find(property=[('hostName', hostName1), ('iocName', iocName1)]) - self.assertTrue(channels == None or len(channels) == 0, 'channels already present') + hostName1 = "update-test-hostname" + t1 + iocName1 = "update-test-iocName" + t1 + channels = client.find( + property=[("hostName", hostName1), ("iocName", iocName1)] + ) + self.assertTrue(not channels, "channels already present") # New Channels added - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName1, \ - iocName1, \ - owner=self.owner, \ - time=t1, \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(property=[('hostName', hostName1), ('iocName', iocName1), ('time', t1)]) - self.assertTrue(len(channels) == 2, 'failed to create the channels with appropriate properties') + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName1, + iocName1, + owner=self.owner, + time=t1, + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find( + property=[("hostName", hostName1), ("iocName", iocName1), ("time", t1)] + ) + self.assertTrue( + len(channels) == 2, + "failed to create the channels with appropriate properties", + ) t2 = str(time()) - hostName2 = 'update-test-hostname' + t2 - iocName2 = 'update-test-iocName' + t2 + hostName2 = "update-test-hostname" + t2 + iocName2 = "update-test-iocName" + t2 # Existing channels are updated - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName2, \ - iocName2, \ - owner=self.owner, \ - time=t2, \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - # no channels should have the old proerty values - self.assertTrue(not client.find(property=[('hostName', hostName1), ('iocName', iocName1), ('time', t1)]), \ - 'failed to update the channels with appropriate properties, old values found') + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName2, + iocName2, + owner=self.owner, + time=t2, + service=self.baseURL, + username=self.username, + password=self.password, + ) + # no channels should have the old proerty values + self.assertTrue( + not client.find( + property=[("hostName", hostName1), ("iocName", iocName1), ("time", t1)] + ), + "failed to update the channels with appropriate properties, old values found", + ) # channels should be updated to the new values - self.assertTrue(len(client.find(property=[('hostName', hostName2), ('iocName', iocName2), ('time', t2)])) == 2, \ - 'failed to update the channels with appropriate properties') + self.assertTrue( + len( + client.find( + property=[ + ("hostName", hostName2), + ("iocName", iocName2), + ("time", t2), + ] + ) + ) + == 2, + "failed to update the channels with appropriate properties", + ) # Cleanup - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) - client.delete(channelName='cf-update-pv1') - client.delete(channelName='cf-update-pv2') + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) + client.delete(channelName="cf-update-pv1") + client.delete(channelName="cf-update-pv2") pass - + def testAddUpdateChannelsWithProperties(self): - ''' + """ This is to check that existing properties of channels are not affected. - ''' - unaffectedProperty = {u'name':u'unaffectedProperty', u'owner':self.owner, u'value':u'unchanged'} + """ + unaffectedProperty = { + "name": "unaffectedProperty", + "owner": self.owner, + "value": "unchanged", + } # create default client - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) client.set(property=unaffectedProperty) - + # add new pv's t1 = str(time()) - hostName1 = 'update-test-hostname' + t1 - iocName1 = 'update-test-iocName' + t1 + hostName1 = "update-test-hostname" + t1 + iocName1 = "update-test-iocName" + t1 # New Channels added - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) - client.set(channel={u'name':u'cf-update-pv1', u'owner':u'cf-update', u'properties':[unaffectedProperty]}) - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName1, \ - iocName1, \ - owner=self.owner, \ - time=t1, \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(property=[('hostName', hostName1), ('iocName', iocName1), ('time', t1)]) - self.assertTrue(len(channels) == 2, 'failed to create the channels with appropriate properties') - channels = client.find(name='cf-update-pv1') + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) + client.set( + channel={ + "name": "cf-update-pv1", + "owner": "cf-update", + "properties": [unaffectedProperty], + } + ) + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName1, + iocName1, + owner=self.owner, + time=t1, + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find( + property=[("hostName", hostName1), ("iocName", iocName1), ("time", t1)] + ) + self.assertTrue( + len(channels) == 2, + "failed to create the channels with appropriate properties", + ) + channels = client.find(name="cf-update-pv1") self.assertTrue(len(channels) == 1) - self.assertTrue(len(channels[0][u'properties']) == 5) + self.assertTrue(len(channels[0]["properties"]) == 5) # Cleanup - client.delete(channelName='cf-update-pv1') - client.delete(channelName='cf-update-pv2') - client.delete(propertyName=unaffectedProperty[u'name']) + client.delete(channelName="cf-update-pv1") + client.delete(channelName="cf-update-pv2") + client.delete(propertyName=unaffectedProperty["name"]) def testPreservingOfAttributes(self): - ''' + """ This test is to ensure that existing properties and tags are left untouched. Case1: first time the cf-update comes across these channels and adds hostName and iocName @@ -155,279 +225,474 @@ def testPreservingOfAttributes(self): both hostName and iocName are changed Case5: the channel is removed - in all cases the existing unaffected* property and tag should remain with the channel - ''' - unaffectedProperty = {u'name':u'unaffectedProperty', u'owner':self.owner, u'value':u'unchanged'} - unaffectedTag = {u'name':u'unaffectedTag', u'owner':self.owner} + in all cases the existing unaffected* property and tag should remain with the channel + """ + unaffectedProperty = { + "name": "unaffectedProperty", + "owner": self.owner, + "value": "unchanged", + } + unaffectedTag = {"name": "unaffectedTag", "owner": self.owner} # create default client - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) client.set(property=unaffectedProperty) client.set(tag=unaffectedTag) - - client.set(channel={u'name':u'cf-update-pv1', u'owner':u'cf-update', u'properties':[unaffectedProperty], u'tags':[unaffectedTag]}) - client.set(channel={u'name':u'cf-update-pv2', u'owner':u'cf-update', u'properties':[unaffectedProperty], u'tags':[unaffectedTag]}) - - unaffectedProperty['channels'] = [] - unaffectedTag['channels'] = [] + + client.set( + channel={ + "name": "cf-update-pv1", + "owner": "cf-update", + "properties": [unaffectedProperty], + "tags": [unaffectedTag], + } + ) + client.set( + channel={ + "name": "cf-update-pv2", + "owner": "cf-update", + "properties": [unaffectedProperty], + "tags": [unaffectedTag], + } + ) + + unaffectedProperty["channels"] = [] + unaffectedTag["channels"] = [] # Case1: - hostName = 'initialHost' - iocName = 'initialIoc' - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName, \ - iocName, \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(name='cf-update-pv*') + hostName = "initialHost" + iocName = "initialIoc" + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName, + iocName, + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find(name="cf-update-pv*") for channel in channels: - self.assertTrue(unaffectedProperty in channel['properties'] and unaffectedTag in channel['tags']) - self.assertTrue(self.__check4properties({u'name':u'hostName', u'value':hostName}, channel['properties']) and - self.__check4properties({u'name':u'iocName', u'value':iocName}, channel['properties']) and - self.__check4properties({u'name':u'pvStatus', u'value':u'Active'}, channel['properties']), - 'Failed to update channels with the correct hostName and/or iocName') + self.assertTrue( + unaffectedProperty in channel["properties"] + and unaffectedTag in channel["tags"] + ) + self.assertTrue( + self.__check4properties( + {"name": "hostName", "value": hostName}, channel["properties"] + ) + and self.__check4properties( + {"name": "iocName", "value": iocName}, channel["properties"] + ) + and self.__check4properties( + {"name": "pvStatus", "value": "Active"}, channel["properties"] + ), + "Failed to update channels with the correct hostName and/or iocName", + ) # Case2: - hostName = 'newHost' - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName, \ - iocName, \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(name='cf-update-pv*') + hostName = "newHost" + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName, + iocName, + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find(name="cf-update-pv*") for channel in channels: - self.assertTrue(unaffectedProperty in channel['properties'] and unaffectedTag in channel['tags']) - self.assertTrue(self.__check4properties({u'name':u'hostName', u'value':hostName}, channel['properties']) and - self.__check4properties({u'name':u'iocName', u'value':iocName}, channel['properties']) and - self.__check4properties({u'name':u'pvStatus', u'value':u'Active'}, channel['properties']), - 'Failed to update channels with the correct hostName and/or iocName') - self.assertTrue(not client.find(property=[('hostName', 'initialHost')]), 'Failed to cleanup old property') + self.assertTrue( + unaffectedProperty in channel["properties"] + and unaffectedTag in channel["tags"] + ) + self.assertTrue( + self.__check4properties( + {"name": "hostName", "value": hostName}, channel["properties"] + ) + and self.__check4properties( + {"name": "iocName", "value": iocName}, channel["properties"] + ) + and self.__check4properties( + {"name": "pvStatus", "value": "Active"}, channel["properties"] + ), + "Failed to update channels with the correct hostName and/or iocName", + ) + self.assertTrue( + not client.find(property=[("hostName", "initialHost")]), + "Failed to cleanup old property", + ) # Case 3: - iocName = 'newIoc' - updateChannelFinder(['cf-update-pv1', 'cf-update-pv2'], \ - hostName, \ - iocName, \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(name='cf-update-pv*') + iocName = "newIoc" + updateChannelFinder( + ["cf-update-pv1", "cf-update-pv2"], + hostName, + iocName, + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find(name="cf-update-pv*") for channel in channels: - self.assertTrue(unaffectedProperty in channel['properties'] and unaffectedTag in channel['tags']) - self.assertTrue(self.__check4properties({u'name':u'hostName', u'value':hostName}, channel['properties']) and - self.__check4properties({u'name':u'iocName', u'value':iocName}, channel['properties']) and - self.__check4properties({u'name':u'pvStatus', u'value':u'Active'}, channel['properties']), - 'Failed to update channels with the correct hostName and/or iocName') - self.assertTrue(not client.find(property=[('hostName', 'initialHost')]), 'Failed to cleanup old property') - self.assertTrue(not client.find(property=[('iocName', 'initialIoc')]), 'Failed to cleanup old property') + self.assertTrue( + unaffectedProperty in channel["properties"] + and unaffectedTag in channel["tags"] + ) + self.assertTrue( + self.__check4properties( + {"name": "hostName", "value": hostName}, channel["properties"] + ) + and self.__check4properties( + {"name": "iocName", "value": iocName}, channel["properties"] + ) + and self.__check4properties( + {"name": "pvStatus", "value": "Active"}, channel["properties"] + ), + "Failed to update channels with the correct hostName and/or iocName", + ) + self.assertTrue( + not client.find(property=[("hostName", "initialHost")]), + "Failed to cleanup old property", + ) + self.assertTrue( + not client.find(property=[("iocName", "initialIoc")]), + "Failed to cleanup old property", + ) # Case 4: - updateChannelFinder([], \ - hostName, \ - iocName, \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL , \ - username=self.username, \ - password=self.password) - channels = client.find(name='cf-update-pv*') + updateChannelFinder( + [], + hostName, + iocName, + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + channels = client.find(name="cf-update-pv*") for channel in channels: - self.assertTrue(unaffectedProperty in channel['properties'] and unaffectedTag in channel['tags']) - self.assertTrue(self.__check4properties({u'name':u'hostName', u'value':hostName}, channel['properties']) and - self.__check4properties({u'name':u'iocName', u'value':iocName}, channel['properties']) and - self.__check4properties({u'name':u'pvStatus', u'value':u'Inactive'}, channel['properties']), - 'Failed to update channels with the correct hostName and/or iocName') - self.assertTrue(not client.find(property=[('hostName', 'initialHost')]), 'Failed to cleanup old property') - self.assertTrue(not client.find(property=[('iocName', 'initialIoc')]), 'Failed to cleanup old property') - + self.assertTrue( + unaffectedProperty in channel["properties"] + and unaffectedTag in channel["tags"] + ) + self.assertTrue( + self.__check4properties( + {"name": "hostName", "value": hostName}, channel["properties"] + ) + and self.__check4properties( + {"name": "iocName", "value": iocName}, channel["properties"] + ) + and self.__check4properties( + {"name": "pvStatus", "value": "Inactive"}, channel["properties"] + ), + "Failed to update channels with the correct hostName and/or iocName", + ) + self.assertTrue( + not client.find(property=[("hostName", "initialHost")]), + "Failed to cleanup old property", + ) + self.assertTrue( + not client.find(property=[("iocName", "initialIoc")]), + "Failed to cleanup old property", + ) + # Cleanup - ''' + """ TODO this cleanup code should not be contingent to the successful completion of all checks... - This could pollute CF - ''' - client.delete(channelName='cf-update-pv1') - client.delete(channelName='cf-update-pv2') - client.delete(propertyName=unaffectedProperty[u'name']) - client.delete(tagName=unaffectedTag[u'name']) + This could pollute CF + """ + client.delete(channelName="cf-update-pv1") + client.delete(channelName="cf-update-pv2") + client.delete(propertyName=unaffectedProperty["name"]) + client.delete(tagName=unaffectedTag["name"]) def __check4properties(self, prop, properties): - ''' + """ check if property existing in a list of properties - The equality test will be based on the name and the value while ignoring the owner - ''' - foundProp = [ p for p in properties if p[u'name'] == prop[u'name'] ] - if len(foundProp) == 1 and foundProp[0][u'value'] == prop[u'value']: + The equality test will be based on the name and the value while ignoring the owner + """ + foundProp = [p for p in properties if p["name"] == prop["name"]] + if len(foundProp) == 1 and foundProp[0]["value"] == prop["value"]: return True else: return False def testNoneCheck(self): - self.assertTrue(ifNoneReturnDefault('Value', 'default') == 'Value') - self.assertTrue(ifNoneReturnDefault(None, 'default') == 'default') - self.assertTrue(ifNoneReturnDefault(None, None) == None) - self.assertTrue(ifNoneReturnDefault('', 'default') == '') - + self.assertTrue(ifNoneReturnDefault("Value", "default") == "Value") + self.assertTrue(ifNoneReturnDefault(None, "default") == "default") + self.assertTrue(ifNoneReturnDefault(None, None) is None) + self.assertTrue(ifNoneReturnDefault("", "default") == "default") + def testPVUpdate(self): - ''' - Test condition + """ + Test condition IOC turned on with ch1, ch2 IOC turned on with ch1 only IOC turned on with ch1, ch2 - ''' - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) + """ + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) try: - updateChannelFinder(['ch1', 'ch2'], \ - 'testHost', \ - 'testIOC', \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL, \ - username=self.username, password=self.password) - chs = client.find(property=[('hostName', 'testHost'), ('iocName', 'testIOC'), ('pvStatus', 'Active')]) - self.assertEqual(len(chs), 2, 'Expected 2 positive matches but found ' + str(len(chs))) - updateChannelFinder(['ch1'], \ - 'testHost', \ - 'testIOC', \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL, \ - username=self.username, password=self.password) - chs = client.find(property=[('hostName', 'testHost'), ('iocName', 'testIOC'), ('pvStatus', 'Active')]) - self.assertEqual(len(chs), 1, 'Expected 1 positive matches but found ' + str(len(chs))) - self.assertTrue(chs[0][u'name'] == 'ch1', 'channel with name ch1 not found') - chs = client.find(property=[('hostName', 'testHost'), ('iocName', 'testIOC'), ('pvStatus', 'Inactive')]) - self.assertEqual(len(chs), 1, 'Expected 1 positive matches but found ' + str(len(chs))) - self.assertTrue(chs[0][u'name'] == 'ch2', 'channel with name ch2 not found') - updateChannelFinder(['ch1', 'ch2'], \ - 'testHost', \ - 'testIOC', \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL, \ - username=self.username, password=self.password) - chs = client.find(property=[('hostName', 'testHost'), ('iocName', 'testIOC'), ('pvStatus', 'Active')]) - self.assertEqual(len(chs), 2, 'Expected 2 positive matches but found ' + str(len(chs))) + updateChannelFinder( + ["ch1", "ch2"], + "testHost", + "testIOC", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + chs = client.find( + property=[ + ("hostName", "testHost"), + ("iocName", "testIOC"), + ("pvStatus", "Active"), + ] + ) + self.assertEqual( + len(chs), 2, "Expected 2 positive matches but found " + str(len(chs)) + ) + updateChannelFinder( + ["ch1"], + "testHost", + "testIOC", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + chs = client.find( + property=[ + ("hostName", "testHost"), + ("iocName", "testIOC"), + ("pvStatus", "Active"), + ] + ) + self.assertEqual( + len(chs), 1, "Expected 1 positive matches but found " + str(len(chs)) + ) + self.assertTrue(chs[0]["name"] == "ch1", "channel with name ch1 not found") + chs = client.find( + property=[ + ("hostName", "testHost"), + ("iocName", "testIOC"), + ("pvStatus", "Inactive"), + ] + ) + self.assertEqual( + len(chs), 1, "Expected 1 positive matches but found " + str(len(chs)) + ) + self.assertTrue(chs[0]["name"] == "ch2", "channel with name ch2 not found") + updateChannelFinder( + ["ch1", "ch2"], + "testHost", + "testIOC", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + chs = client.find( + property=[ + ("hostName", "testHost"), + ("iocName", "testIOC"), + ("pvStatus", "Active"), + ] + ) + self.assertEqual( + len(chs), 2, "Expected 2 positive matches but found " + str(len(chs)) + ) finally: - client.delete(channelName='ch1') - client.delete(channelName='ch2') - + client.delete(channelName="ch1") + client.delete(channelName="ch2") + def testPVMove(self): - ''' + """ ch1, ch2 on host1, ioc1 ch1 on host1, ioc1; ch2 on host1, ioc2 (case1) ch1, ch2 on host1, ioc1 (reset) ch1 on host1, ioc1; ch2 on host2, ioc2 (case2) ch1, ch2 on host1, ioc1 (reset) - ''' - client = ChannelFinderClient(BaseURL=self.baseURL, username=self.username, password=self.password) + """ + client = ChannelFinderClient( + BaseURL=self.baseURL, username=self.username, password=self.password + ) try: - updateChannelFinder(['ch1', 'ch2'], \ - 'host1', \ - 'ioc1', \ - owner=self.owner, \ - time=time(),\ - service=self.baseURL, \ - username=self.username, password=self.password) - chs = client.find(property=[('hostName', 'host1'), ('iocName', 'ioc1')]) - self.assertEqual(len(chs), 2, 'Expected 2 positive matches but found ' + str(len(chs))) - '''CASE1''' - updateChannelFinder(['ch1'], \ - 'host1', \ - 'ioc1', \ - time=time(), \ - owner=self.owner, service=self.baseURL, \ - username=self.username, password=self.password) - updateChannelFinder(['ch2'], \ - 'host1', \ - 'ioc2', \ - time=time(), \ - owner=self.owner, service=self.baseURL, \ - username=self.username, password=self.password) - chs = client.find(property=[('hostName', 'host1')]) - self.assertEqual(len(chs), 2, 'Expected 1 positive matches but found ' + str(len(chs))) - self.assertEqual(client.find(property=[('hostName', 'host1'), ('iocName', 'ioc1')])[0][u'name'], 'ch1', \ - 'Failed to find the expected channel _ch1_ with prop host1, ioc1') - self.assertEqual(client.find(property=[('hostName', 'host1'), ('iocName', 'ioc2')])[0][u'name'], 'ch2', \ - 'Failed to find the expected channel _ch2_ with prop host1, ioc2') - '''RESET''' - updateChannelFinder(['ch1', 'ch2'], \ - 'host1', \ - 'ioc1', \ - time=time(), \ - owner=self.owner, service=self.baseURL, \ - username=self.username, password=self.password) - self.assertEqual(len(client.find(property=[('hostName', 'host1'), ('iocName', 'ioc1')])), 2, \ - 'Failed to reset the channels') - '''CASE2''' - updateChannelFinder(['ch1'], \ - 'host1', \ - 'ioc1', \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL, username=self.username, \ - password=self.password) - updateChannelFinder(['ch2'], \ - 'host2', \ - 'ioc2', \ - owner=self.owner, service=self.baseURL, \ - time=time(), \ - username=self.username, password=self.password) - self.assertEqual(client.find(property=[('hostName', 'host1'), ('iocName', 'ioc1')])[0][u'name'], 'ch1', \ - 'Failed to find the expected channel _ch1_ with prop host1, ioc1') - self.assertEqual(client.find(property=[('hostName', 'host2'), ('iocName', 'ioc2')])[0][u'name'], 'ch2', \ - 'Failed to find the expected channel _ch2_ with prop host1, ioc2') - '''RESET''' - updateChannelFinder(['ch1', 'ch2'], \ - 'host1', \ - 'ioc1', \ - owner=self.owner, \ - time=time(), \ - service=self.baseURL, \ - username=self.username, password=self.password) - self.assertEqual(len(client.find(property=[('hostName', 'host1'), ('iocName', 'ioc1')])), 2, \ - 'Failed to reset the channels') + updateChannelFinder( + ["ch1", "ch2"], + "host1", + "ioc1", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + chs = client.find(property=[("hostName", "host1"), ("iocName", "ioc1")]) + self.assertEqual( + len(chs), 2, "Expected 2 positive matches but found " + str(len(chs)) + ) + """CASE1""" + updateChannelFinder( + ["ch1"], + "host1", + "ioc1", + time=time(), + owner=self.owner, + service=self.baseURL, + username=self.username, + password=self.password, + ) + updateChannelFinder( + ["ch2"], + "host1", + "ioc2", + time=time(), + owner=self.owner, + service=self.baseURL, + username=self.username, + password=self.password, + ) + chs = client.find(property=[("hostName", "host1")]) + self.assertEqual( + len(chs), 2, "Expected 1 positive matches but found " + str(len(chs)) + ) + self.assertEqual( + client.find(property=[("hostName", "host1"), ("iocName", "ioc1")])[0][ + "name" + ], + "ch1", + "Failed to find the expected channel _ch1_ with prop host1, ioc1", + ) + self.assertEqual( + client.find(property=[("hostName", "host1"), ("iocName", "ioc2")])[0][ + "name" + ], + "ch2", + "Failed to find the expected channel _ch2_ with prop host1, ioc2", + ) + """RESET""" + updateChannelFinder( + ["ch1", "ch2"], + "host1", + "ioc1", + time=time(), + owner=self.owner, + service=self.baseURL, + username=self.username, + password=self.password, + ) + self.assertEqual( + len(client.find(property=[("hostName", "host1"), ("iocName", "ioc1")])), + 2, + "Failed to reset the channels", + ) + """CASE2""" + updateChannelFinder( + ["ch1"], + "host1", + "ioc1", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + updateChannelFinder( + ["ch2"], + "host2", + "ioc2", + owner=self.owner, + service=self.baseURL, + time=time(), + username=self.username, + password=self.password, + ) + self.assertEqual( + client.find(property=[("hostName", "host1"), ("iocName", "ioc1")])[0][ + "name" + ], + "ch1", + "Failed to find the expected channel _ch1_ with prop host1, ioc1", + ) + self.assertEqual( + client.find(property=[("hostName", "host2"), ("iocName", "ioc2")])[0][ + "name" + ], + "ch2", + "Failed to find the expected channel _ch2_ with prop host1, ioc2", + ) + """RESET""" + updateChannelFinder( + ["ch1", "ch2"], + "host1", + "ioc1", + owner=self.owner, + time=time(), + service=self.baseURL, + username=self.username, + password=self.password, + ) + self.assertEqual( + len(client.find(property=[("hostName", "host1"), ("iocName", "ioc1")])), + 2, + "Failed to reset the channels", + ) finally: - client.delete(channelName='ch1') - client.delete(channelName='ch2') - + client.delete(channelName="ch1") + client.delete(channelName="ch2") + def testRegularExperssion(self): tempFile = NamedTemporaryFile(delete=False) - publicPVs = ['publicPV1', 'publicPV2', 'publicPV3'] - privatePVS = ['_privatePV1', '_privatePV2'] + publicPVs = ["publicPV1", "publicPV2", "publicPV3"] + privatePVS = ["_privatePV1", "_privatePV2"] allPVs = copy(publicPVs) allPVs.extend(privatePVS) for pv in allPVs: - tempFile.write(str.encode(pv + '\n')) + tempFile.write(str.encode(pv + "\n")) tempFile.close() try: pvNames = getPVNames(tempFile.name) - self.assertEqual(len(pvNames), len(allPVs), \ - 'expected ' + str(len(allPVs)) + ' but got ' + str(len(pvNames))) - pvNames = getPVNames(tempFile.name, pattern='[^_]+') - self.assertEqual(len(pvNames), len(publicPVs), \ - 'expected ' + str(len(allPVs)) + ' but got ' + str(len(publicPVs))) - self.assertTrue(frozenset(pvNames).issuperset(frozenset(publicPVs)), \ - 'resulting pvNames contains invalid non public pvs') - self.assertTrue(frozenset(pvNames).isdisjoint(frozenset(privatePVS)), \ - 'result pvNames contains invalid private pvs') + self.assertEqual( + len(pvNames), + len(allPVs), + "expected " + str(len(allPVs)) + " but got " + str(len(pvNames)), + ) + pvNames = getPVNames(tempFile.name, pattern="[^_]+") + self.assertEqual( + len(pvNames), + len(publicPVs), + "expected " + str(len(allPVs)) + " but got " + str(len(publicPVs)), + ) + self.assertTrue( + frozenset(pvNames).issuperset(frozenset(publicPVs)), + "resulting pvNames contains invalid non public pvs", + ) + self.assertTrue( + frozenset(pvNames).isdisjoint(frozenset(privatePVS)), + "result pvNames contains invalid private pvs", + ) pass finally: os.remove(tempFile.name) pass - + if __name__ == "__main__": - #import sys;sys.argv = ['', 'Test.testName'] unittest.main() - - -class mockOpt(): + + +class mockOpt: def __init__(self, hostname, iocname, service=None): self.hostname = hostname self.iocname = iocname self.service = service - diff --git a/test/testChannelFinderClient.py b/test/testChannelFinderClient.py index eb7a3b0..23fbb42 100644 --- a/test/testChannelFinderClient.py +++ b/test/testChannelFinderClient.py @@ -21,71 +21,20 @@ class ConnectionTest(ChannelFinderClientTestCase): def testConnection(self): testUrl = getDefaultTestConfig("BaseURL") - self.assertNotEqual(ChannelFinderClient(BaseURL=testUrl, - username=getDefaultTestConfig('username'), - password=getDefaultTestConfig('password')), - None, 'failed to create client') - badBaseurl = ['', 'noSuchURL'] + self.assertNotEqual( + ChannelFinderClient( + BaseURL=testUrl, + username=getDefaultTestConfig("username"), + password=getDefaultTestConfig("password"), + ), + None, + "failed to create client", + ) + badBaseurl = ["", "noSuchURL"] for url in badBaseurl: - self.assertRaises(Exception, ChannelFinderClient, BaseURL=url, msg='message') - - -# =============================================================================== -# Test JSON Parsing -# =============================================================================== -""" -class JSONparserTest(ChannelFinderClientTestCase): - - multiChannels = {u'channels': {u'channel': [{u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:0', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'0'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'19'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:1', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'1'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'22'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:2', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'2'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'38'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:3', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'3'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'65'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:4', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'4'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'78'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:5', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'5'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'79'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:6', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'6'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'90'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:7', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'7'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'5'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:8', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'8'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'64'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}, {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:9', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'9'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'85'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}]}} - singleChannels = {u'channels': {u'channel': {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:2', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'2'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'38'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}}}} - channel = {u'@owner': u'shroffk', u'@name': u'Test_first:a<000>:0:0', u'properties': {u'property': [{u'@owner': u'shroffk', u'@name': u'Test_PropA', u'@value': u'0'}, {u'@owner': u'shroffk', u'@name': u'Test_PropB', u'@value': u'19'}, {u'@owner': u'shroffk', u'@name': u'Test_PropC', u'@value': u'ALL'}]}, u'tags': {u'tag': [{u'@owner': u'shroffk', u'@name': u'Test_TagA'}, {u'@owner': u'shroffk', u'@name': u'Test_TagB'}]}} - noChannel = {u'channels': None} - - def setUp(self): - pass - - def tearDown(self): - pass - - def testSingleChannelsParsing(self): - reply = ChannelFinderClient()._ChannelFinderClient__decodeChannels(self.singleChannels) - self.assertTrue(len(reply) == 1, 'Parse Error'); - self.assertTrue(len(reply[0][u'properties']) == len (self.singleChannels[u'channels'][u'channel'][u'properties']['property']), 'single channel peoperties not parsed correctly') - self.assertTrue(len(reply[0][u'tags']) == len(self.singleChannels[u'channels'][u'channel'][u'tags']['tag']), 'tags not correctly parsed') - pass - - def testMultiChannelsParsing(self): - reply = ChannelFinderClient()._ChannelFinderClient__decodeChannels(self.multiChannels) - self.assertTrue(len(reply) == len(self.multiChannels[u'channels'][u'channel']), 'incorrect number of channels in parsed result') - pass - - def testNoChannelParsing(self): - reply = ChannelFinderClient()._ChannelFinderClient__decodeChannels(self.noChannel) - self.assertTrue(not reply, 'failed parsing an emplty channels list') - - def testChannel(self): - reply = ChannelFinderClient()._ChannelFinderClient__decodeChannel(self.channel) - self.assertTrue(reply[u'name'] == self.channel[u'@name']) - self.assertTrue(reply[u'owner'] == self.channel[u'@owner']) - self.assertTrue(len(reply[u'properties']) == len(self.channel[u'properties'][u'property'])) - self.assertTrue(len(reply[u'tags']) == len(self.channel[u'tags'][u'tag'])) - - def testEncodeChannel(self): - encodedChannel = ChannelFinderClient()._ChannelFinderClient__encodeChannels(\ - [{u'name':u'Test_first:a<000>:0:0', u'owner':u'shroffk', - u'properties':[{u'name':u'Test_PropA', u'owner':u'shroffk', u'value':u'0'}, - {u'name':u'Test_PropB', u'owner':u'shroffk', u'value':u'19'}, - {u'name':u'Test_PropC', u'owner':u'shroffk', u'value':u'ALL'}], - u'tags':[{u'name':u'Test_TagA', u'owner':u'shroffk'}, - {u'name':u'Test_TagB', u'owner':u'shroffk'}]}]) -# 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))) -""" + self.assertRaises( + Exception, ChannelFinderClient, BaseURL=url, msg="message" + ) # =============================================================================== @@ -94,96 +43,131 @@ def testEncodeChannels(self): class OperationTagTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.channelOwner = _testConf.get("DEFAULT", "channelOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default Clients""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) - self.clientTag = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'tagUsername'), - password=_testConf.get('DEFAULT', 'tagPassword')) - self.testChannels = [{u'name': u'pyTestChannel1', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel2', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel3', u'owner': self.channelOwner}] + self.client = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "username"), + password=_testConf.get("DEFAULT", "password"), + ) + self.clientTag = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "tagUsername"), + password=_testConf.get("DEFAULT", "tagPassword"), + ) + self.testChannels = [ + {"name": "pyTestChannel1", "owner": self.channelOwner}, + {"name": "pyTestChannel2", "owner": self.channelOwner}, + {"name": "pyTestChannel3", "owner": self.channelOwner}, + ] self.client.set(channels=self.testChannels) - self.assertTrue(len(self.client.find(name=u'pyTestChannel*')) == 3, - 'Error: Failed to set channel') + self.assertTrue( + len(self.client.find(name="pyTestChannel*")) == 3, + "Error: Failed to set channel", + ) def tearDown(self): for ch in self.testChannels: - self.client.delete(channelName=ch[u'name']) + self.client.delete(channelName=ch["name"]) def testCreateAndDeleteTag(self): - testTag = {'name': 'setTestTag', 'owner': self.tagOwner} + testTag = {"name": "setTestTag", "owner": self.tagOwner} try: self.clientTag.set(tag=testTag) - foundtag = self.client.findTag(testTag['name']) - self.assertIsNotNone(foundtag, 'failed to create a test tag') - self.assertTrue(checkTagInList([foundtag], [testTag]), 'tag not created correctly') + foundtag = self.client.findTag(testTag["name"]) + self.assertIsNotNone(foundtag, "failed to create a test tag") + self.assertTrue( + checkTagInList([foundtag], [testTag]), "tag not created correctly" + ) finally: - self.clientTag.delete(tagName=testTag['name']) - foundtag = self.client.findTag(testTag['name']) - self.assertIsNone(foundtag, 'failed to delete the test tag') + self.clientTag.delete(tagName=testTag["name"]) + foundtag = self.client.findTag(testTag["name"]) + self.assertIsNone(foundtag, "failed to delete the test tag") def testCreateAndDeleteTagWithChannel(self): - testTag = {'name': 'setTestTag', 'owner': self.tagOwner, 'channels': [self.testChannels[0]]} + testTag = { + "name": "setTestTag", + "owner": self.tagOwner, + "channels": [self.testChannels[0]], + } try: - result = self.clientTag.set(tag=testTag) - foundtag = self.client.findTag(testTag['name']) - self.assertIsNotNone(foundtag, 'failed to create a test tag') - self.assertTrue(checkTagInList([foundtag], [testTag]), 'tag not created correctly') + _ = self.clientTag.set(tag=testTag) + foundtag = self.client.findTag(testTag["name"]) + self.assertIsNotNone(foundtag, "failed to create a test tag") + self.assertTrue( + checkTagInList([foundtag], [testTag]), "tag not created correctly" + ) """check the created tag was added to the channel""" - self.assertTrue(checkTagOnChannel(self.client, self.testChannels[0]['name'], foundtag), - 'Failed to correctly set the created tag to the appropriate channel') + self.assertTrue( + checkTagOnChannel(self.client, self.testChannels[0]["name"], foundtag), + "Failed to correctly set the created tag to the appropriate channel", + ) finally: - self.clientTag.delete(tagName=testTag['name']) - foundtag = self.client.findTag(testTag['name']) - self.assertIsNone(foundtag, 'failed to delete the test tag') + self.clientTag.delete(tagName=testTag["name"]) + foundtag = self.client.findTag(testTag["name"]) + self.assertIsNone(foundtag, "failed to delete the test tag") def testCreateAndDeleteTags(self): - testTags = [{u'name': u'pyTag1', u'owner': self.tagOwner}, - {u'name': u'pyTag2', u'owner': self.tagOwner}, - {u'name': u'pyTag3', u'owner': self.tagOwner}] + testTags = [ + {"name": "pyTag1", "owner": self.tagOwner}, + {"name": "pyTag2", "owner": self.tagOwner}, + {"name": "pyTag3", "owner": self.tagOwner}, + ] try: self.clientTag.set(tags=testTags) """Check if all the tags were correctly Added """ for tag in testTags: - self.assertTrue(self.client.findTag(tagname=tag[u'name']), - 'Error: tag ' + tag[u'name'] + ' was not added') + self.assertTrue( + self.client.findTag(tagname=tag["name"]), + "Error: tag " + tag["name"] + " was not added", + ) finally: """delete the Tags """ for tag in testTags: - self.clientTag.delete(tagName=tag[u'name']) + self.clientTag.delete(tagName=tag["name"]) """Check all the tags were correctly removed """ for tag in testTags: - self.assertEqual(self.client.findTag(tagname='pyTag1'), None, - 'Error: tag ' + tag[u'name'] + ' was not removed') + self.assertEqual( + self.client.findTag(tagname="pyTag1"), + None, + "Error: tag " + tag["name"] + " was not removed", + ) def testSetRemoveTag2Channel(self): """ Set Tag to channel removing it from all other channels for non destructive operation check TestUpdateAppend """ - testTag = {u'name': u'pySetTag', u'owner': self.tagOwner} + testTag = {"name": "pySetTag", "owner": self.tagOwner} try: self.client.set(tag=testTag) - self.client.set(tag=testTag, channelName=self.testChannels[0][u'name']) + self.client.set(tag=testTag, channelName=self.testChannels[0]["name"]) - self.assertTrue(checkTagOnChannel(self.client, 'pyTestChannel1', testTag), - 'Error: Tag-pySetTag not added to the channel-pyTestChannel1') + 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']) + self.client.set(tag=testTag, channelName=self.testChannels[1]["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 - 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') + self.assertTrue( + checkTagOnChannel(self.client, self.testChannels[1]["name"], testTag) + and not checkTagOnChannel( + self.client, self.testChannels[0]["name"], testTag + ), + "Error: Tag-pySetTag not added to the channel-pyTestChannel2", + ) + + self.client.delete(tag=testTag, channelName=self.testChannels[1]["name"]) + self.assertTrue( + not checkTagOnChannel( + self.client, self.testChannels[1]["name"], testTag + ), + "Error: Failed to delete the tag-pySetTag from channel-pyTestChannel1", + ) finally: - self.client.delete(tagName=testTag[u'name']) + self.client.delete(tagName=testTag["name"]) # TODO set a check for removing the tag from a subset of channels which have that tag @@ -191,241 +175,362 @@ def testSetRemoveTag2Channels(self): """ Set tags to a set of channels and remove it from all other channels """ - testTag = {u'name': u'pySetTag', u'owner': self.tagOwner} + testTag = {"name": "pySetTag", "owner": self.tagOwner} # the list comprehension is used to construct a list of all the channel names - channelNames = [channel[u'name'] for channel in self.testChannels] + channelNames = [channel["name"] for channel in self.testChannels] try: self.client.set(tag=testTag, channelNames=channelNames) - responseChannelNames = [channel[u'name'] for channel in self.client.find(tagName=testTag[u'name'])] + responseChannelNames = [ + channel["name"] for channel in self.client.find(tagName=testTag["name"]) + ] for ch in channelNames: - self.assertTrue(ch in responseChannelNames, 'Error: tag-pySetTag not added to channel ' + ch) + self.assertTrue( + ch in responseChannelNames, + "Error: tag-pySetTag not added to channel " + ch, + ) self.client.delete(tag=testTag, channelNames=channelNames) - response = self.client.find(tagName=testTag[u'name']) + response = self.client.find(tagName=testTag["name"]) if response: - responseChannelNames = [channel[u'name'] for channel in response] + responseChannelNames = [channel["name"] for channel in response] for ch in channelNames: - self.assertFalse(ch in responseChannelNames, 'Error: tag-pySetTag not removed from channel ' + ch) + self.assertFalse( + ch in responseChannelNames, + "Error: tag-pySetTag not removed from channel " + ch, + ) finally: - self.client.delete(tagName=testTag[u'name']) + self.client.delete(tagName=testTag["name"]) def testUpdateTag(self): """ Add a tag to a group of channels without removing it from existing channels """ - tag = {'name': 'initialTestTag', 'owner': self.tagOwner, 'channels': [self.testChannels[0]]} + tag = { + "name": "initialTestTag", + "owner": self.tagOwner, + "channels": [self.testChannels[0]], + } try: """Create initial tag""" self.clientTag.set(tag=tag) - self.assertIsNotNone(self.client.findTag(tag['name']), 'failed to create a test tag') + self.assertIsNotNone( + self.client.findTag(tag["name"]), "failed to create a test tag" + ) """Update tag with new channels""" - tag['channels'] = [self.testChannels[1], self.testChannels[2]] + 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') + self.assertTrue( + checkTagOnChannel(self.client, channel["name"], tag), + "Failed to updated tag", + ) finally: """cleanup""" - self.client.delete(tagName=tag['name']) - self.assertIsNone(self.client.findTag(tag['name']), 'failed to delete the test tag:' + tag['name']) + self.client.delete(tagName=tag["name"]) + self.assertIsNone( + self.client.findTag(tag["name"]), + "failed to delete the test tag:" + tag["name"], + ) def testUpdateTags(self): """ Add tags to a group of channels without removing it from existing channels """ - tag1 = {'name': 'pyTestTag1', 'owner': self.tagOwner, 'channels': [self.testChannels[0]]} - tag2 = {'name': 'pyTestTag2', 'owner': self.tagOwner, 'channels': [self.testChannels[0]]} + tag1 = { + "name": "pyTestTag1", + "owner": self.tagOwner, + "channels": [self.testChannels[0]], + } + tag2 = { + "name": "pyTestTag2", + "owner": self.tagOwner, + "channels": [self.testChannels[0]], + } try: """Create initial tags which are set on the pyTestChannel1""" self.clientTag.set(tags=[tag1, tag2]) - self.assertIsNotNone(self.client.findTag(tag1['name']), 'failed to create a test tag: pyTestTag1') - self.assertIsNotNone(self.client.findTag(tag1['name']), 'failed to create a test tag: pyTestTag2') + self.assertIsNotNone( + self.client.findTag(tag1["name"]), + "failed to create a test tag: pyTestTag1", + ) + self.assertIsNotNone( + self.client.findTag(tag1["name"]), + "failed to create a test tag: pyTestTag2", + ) """Update tags with new channels""" - tag1['channels'] = [self.testChannels[1], self.testChannels[2]] - tag2['channels'] = [self.testChannels[1], self.testChannels[2]] + tag1["channels"] = [self.testChannels[1], self.testChannels[2]] + tag2["channels"] = [self.testChannels[1], self.testChannels[2]] self.clientTag.update(tags=[tag1, tag2]) """Check that the all channels have been updated with the tags""" for channel in self.testChannels: - self.assertTrue(checkTagOnChannel(self.client, channel['name'], tag1) and - checkTagOnChannel(self.client, channel['name'], tag2), - 'Failed to updated tags') + self.assertTrue( + checkTagOnChannel(self.client, channel["name"], tag1) + and checkTagOnChannel(self.client, channel["name"], tag2), + "Failed to updated tags", + ) finally: """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']) - self.assertIsNone(self.client.findTag(tag2['name']), 'failed to delete the test tag:' + tag2['name']) + 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"], + ) + self.assertIsNone( + self.client.findTag(tag2["name"]), + "failed to delete the test tag:" + tag2["name"], + ) def testGetAllTags(self): """Test setting multiple tags and listing all tags""" - testTags = [{'name': 'testTag1', 'owner': self.tagOwner}, - {'name': 'testTag2', 'owner': self.tagOwner}, - {'name': 'testTag3', 'owner': self.tagOwner}] + testTags = [ + {"name": "testTag1", "owner": self.tagOwner}, + {"name": "testTag2", "owner": self.tagOwner}, + {"name": "testTag3", "owner": self.tagOwner}, + ] try: self.client.set(tags=testTags) allTags = self.client.getAllTags() - self.assertTrue(checkTagInList(allTags, testTags), 'Failed to create multiple tags') + self.assertTrue( + checkTagInList(allTags, testTags), "Failed to create multiple tags" + ) finally: # delete the Tags for tag in testTags: - self.client.delete(tagName=tag['name']) + self.client.delete(tagName=tag["name"]) # Check all the tags were correctly removed for tag in testTags: - self.assertEqual(self.client.findTag(tagname=tag[u'name']), None, - 'Error: property ' + tag[u'name'] + ' was not removed') + self.assertEqual( + self.client.findTag(tagname=tag["name"]), + None, + "Error: property " + tag["name"] + " was not removed", + ) # =============================================================================== # Test all the property operations # =============================================================================== + class OperationPropertyTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') + self.channelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") """Default Clients""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) - self.clientProp = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'propUsername'), - password=_testConf.get('DEFAULT', 'propPassword')) - self.testChannels = [{u'name': u'pyTestChannel1', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel2', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel3', u'owner': self.channelOwner}] + self.client = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "username"), + password=_testConf.get("DEFAULT", "password"), + ) + self.clientProp = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "propUsername"), + password=_testConf.get("DEFAULT", "propPassword"), + ) + self.testChannels = [ + {"name": "pyTestChannel1", "owner": self.channelOwner}, + {"name": "pyTestChannel2", "owner": self.channelOwner}, + {"name": "pyTestChannel3", "owner": self.channelOwner}, + ] self.client.set(channels=self.testChannels) - self.assertTrue(len(self.client.find(name=u'pyTestChannel*')) == 3, - 'Error: Failed to set channel') + self.assertTrue( + len(self.client.find(name="pyTestChannel*")) == 3, + "Error: Failed to set channel", + ) pass def tearDown(self): for ch in self.testChannels: - self.client.delete(channelName=ch[u'name']) + self.client.delete(channelName=ch["name"]) pass def testCreateAndDeleteProperty(self): """ Create and delete a single property """ - testProperty = {'name': 'setTestProp', 'owner': self.propOwner} + testProperty = {"name": "setTestProp", "owner": self.propOwner} try: - result = self.clientProp.set(property=testProperty) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNotNone(foundProperty, 'failed to create a test property') - self.assertTrue(checkPropInList([foundProperty], [testProperty]), 'property not created correctly') + _ = self.clientProp.set(property=testProperty) + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNotNone(foundProperty, "failed to create a test property") + self.assertTrue( + checkPropInList([foundProperty], [testProperty]), + "property not created correctly", + ) finally: - self.client.delete(propertyName=testProperty['name']) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNone(foundProperty, 'failed to delete the test property') + self.client.delete(propertyName=testProperty["name"]) + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNone(foundProperty, "failed to delete the test property") def testCreateAndDeletePropertyWithChannel(self): """ Create and delete a single property """ ch = self.testChannels[0] - ch['properties'] = [{'name': 'setTestProp', 'owner': self.propOwner, 'value': 'testValue1'}] - testProperty = {'name': 'setTestProp', 'owner': self.propOwner, 'channels': [ch]} + ch["properties"] = [ + {"name": "setTestProp", "owner": self.propOwner, "value": "testValue1"} + ] + testProperty = { + "name": "setTestProp", + "owner": self.propOwner, + "channels": [ch], + } try: - result = self.clientProp.set(property=testProperty) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNotNone(foundProperty, 'failed to create a test property') - self.assertTrue(checkPropInList([foundProperty], [testProperty]), 'property not created correctly') + _ = self.clientProp.set(property=testProperty) + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNotNone(foundProperty, "failed to create a test property") + self.assertTrue( + checkPropInList([foundProperty], [testProperty]), + "property not created correctly", + ) """check the created property was added to the channel""" - self.assertTrue(checkPropertyOnChannel(self.client, self.testChannels[0]['name'], foundProperty), - 'Failed to correctly set the created property to the appropriate channel') + self.assertTrue( + checkPropertyOnChannel( + self.client, self.testChannels[0]["name"], foundProperty + ), + "Failed to correctly set the created property to the appropriate channel", + ) finally: - self.client.delete(propertyName=testProperty['name']) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNone(foundProperty, 'failed to delete the test property') + self.client.delete(propertyName=testProperty["name"]) + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNone(foundProperty, "failed to delete the test property") def testCreateAndDeletePropertyWithChannels(self): """ Create and delete a single property """ ch1 = self.testChannels[0] - ch1['properties'] = [{'name': 'setTestProp', 'owner': self.propOwner, 'value': 'testValue1'}] + ch1["properties"] = [ + {"name": "setTestProp", "owner": self.propOwner, "value": "testValue1"} + ] ch2 = self.testChannels[1] - ch2['properties'] = [{'name': 'setTestProp', 'owner': self.propOwner, 'value': 'testValue2'}] - testProperty = {'name': 'setTestProp', 'owner': self.propOwner, 'channels': [ch1, ch2]} + ch2["properties"] = [ + {"name": "setTestProp", "owner": self.propOwner, "value": "testValue2"} + ] + testProperty = { + "name": "setTestProp", + "owner": self.propOwner, + "channels": [ch1, ch2], + } try: self.clientProp.set(property=testProperty) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNotNone(foundProperty, 'failed to create a test property') - self.assertTrue(checkPropInList([foundProperty], [testProperty]), 'property not created correctly') + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNotNone(foundProperty, "failed to create a test property") + self.assertTrue( + checkPropInList([foundProperty], [testProperty]), + "property not created correctly", + ) """check the created property was added to the channel""" - self.assertTrue(checkPropertyOnChannel(self.client, self.testChannels[0]['name'], foundProperty), - 'Failed to correctly set the created property to the appropriate channel') - self.assertTrue(checkPropertyOnChannel(self.client, self.testChannels[1]['name'], foundProperty), - 'Failed to correctly set the created property to the appropriate channel') + self.assertTrue( + checkPropertyOnChannel( + self.client, self.testChannels[0]["name"], foundProperty + ), + "Failed to correctly set the created property to the appropriate channel", + ) + self.assertTrue( + checkPropertyOnChannel( + self.client, self.testChannels[1]["name"], foundProperty + ), + "Failed to correctly set the created property to the appropriate channel", + ) finally: - self.client.delete(propertyName=testProperty['name']) - foundProperty = self.client.findProperty(testProperty['name']) - self.assertIsNone(foundProperty, 'failed to delete the test property') + self.client.delete(propertyName=testProperty["name"]) + foundProperty = self.client.findProperty(testProperty["name"]) + self.assertIsNone(foundProperty, "failed to delete the test property") def testCreateAndDeleteProperties(self): """ Create and delete a set of properties """ - testProperty1 = {'name': 'pyTestProp1', 'owner': self.propOwner} - testProperty2 = {'name': 'pyTestProp2', 'owner': self.propOwner} + testProperty1 = {"name": "pyTestProp1", "owner": self.propOwner} + testProperty2 = {"name": "pyTestProp2", "owner": self.propOwner} try: self.clientProp.set(properties=[testProperty1, testProperty2]) - self.assertTrue(checkPropInList(self.clientProp.getAllProperties(), [testProperty1, testProperty2]), - 'property not created correctly') + self.assertTrue( + checkPropInList( + self.clientProp.getAllProperties(), [testProperty1, testProperty2] + ), + "property not created correctly", + ) finally: - self.client.delete(propertyName=testProperty1['name']) - self.client.delete(propertyName=testProperty2['name']) - self.assertIsNone(self.client.findProperty(testProperty1['name']), 'failed to delete the test property1') - self.assertIsNone(self.client.findProperty(testProperty2['name']), 'failed to delete the test property1') + self.client.delete(propertyName=testProperty1["name"]) + self.client.delete(propertyName=testProperty2["name"]) + self.assertIsNone( + self.client.findProperty(testProperty1["name"]), + "failed to delete the test property1", + ) + self.assertIsNone( + self.client.findProperty(testProperty2["name"]), + "failed to delete the test property1", + ) def testSetRemoveProperty2Channel(self): """ Set Property to channel removing it from all other channels for non destructive operation check TestUpdateAppend """ - testProperty = {'name': 'setTestProp', 'owner': self.propOwner} + testProperty = {"name": "setTestProp", "owner": self.propOwner} try: self.clientProp.set(property=testProperty) ch0 = self.testChannels[0] - ch0['properties'] = [{'name': 'setTestProp', 'owner': self.propOwner, 'value': 'testValue1'}] - testProperty['channels'] = [ch0] + ch0["properties"] = [ + {"name": "setTestProp", "owner": self.propOwner, "value": "testValue1"} + ] + testProperty["channels"] = [ch0] self.client.set(property=testProperty) - self.assertTrue(checkPropertyOnChannel(self.client, ch0[u'name'], testProperty), - 'Error: Property - setTestProp not added to the channel-pyTestChannel1') + self.assertTrue( + checkPropertyOnChannel(self.client, ch0["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] + 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 - not checkPropertyOnChannel(self.client, ch0[u'name'], testProperty), - 'Error: Tag-pySetTag not added to the channel-pyTestChannel2') + self.assertTrue( + checkPropertyOnChannel(self.client, ch1["name"], testProperty) + and not checkPropertyOnChannel(self.client, ch0["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[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') + self.client.delete(propertyName=testProperty["name"]) + self.assertTrue( + not checkPropertyOnChannel(self.client, ch0["name"], testProperty) + and not checkPropertyOnChannel(self.client, ch1["name"], testProperty), + "Error: Failed to delete the tag-pySetTag from channel-pyTestChannel1", + ) def testGetAllPropperties(self): """Test setting multiple properties and listing all tags""" - testProps = [{u'name': u'pyTestProp1', u'owner': self.propOwner}, - {u'name': u'pyTestProp2', u'owner': self.propOwner}, - {u'name': u'pyTestProp3', u'owner': self.propOwner}] + testProps = [ + {"name": "pyTestProp1", "owner": self.propOwner}, + {"name": "pyTestProp2", "owner": self.propOwner}, + {"name": "pyTestProp3", "owner": self.propOwner}, + ] try: self.client.set(properties=testProps) allProperties = self.client.getAllProperties() - self.assertTrue(checkPropInList(allProperties, testProps), 'failed at set a list of properties') + self.assertTrue( + checkPropInList(allProperties, testProps), + "failed at set a list of properties", + ) finally: # delete the Tags for prop in testProps: - self.client.delete(propertyName=prop[u'name']) + self.client.delete(propertyName=prop["name"]) # Check all the tags were correctly removed for prop in testProps: - self.assertEqual(self.client.findProperty(propertyname=prop[u'name']), None, - 'Error: property ' + prop[u'name'] + ' was not removed') + self.assertEqual( + self.client.findProperty(propertyname=prop["name"]), + None, + "Error: property " + prop["name"] + " was not removed", + ) # =============================================================================== @@ -434,176 +539,258 @@ def testGetAllPropperties(self): class OperationChannelTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.channelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default Clients""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) - self.clientCh = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'channelUsername'), - password=_testConf.get('DEFAULT', 'channelPassword')) - self.clientProp = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'propUsername'), - password=_testConf.get('DEFAULT', 'propPassword')) - self.clientTag = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'tagUsername'), - password=_testConf.get('DEFAULT', 'tagPassword')) + self.client = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "username"), + password=_testConf.get("DEFAULT", "password"), + ) + self.clientCh = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "channelUsername"), + password=_testConf.get("DEFAULT", "channelPassword"), + ) + self.clientProp = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "propUsername"), + password=_testConf.get("DEFAULT", "propPassword"), + ) + self.clientTag = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "tagUsername"), + password=_testConf.get("DEFAULT", "tagPassword"), + ) def testSetDeleteChannel(self): """ Set and Delete a simple channel with no properties or tags """ try: - testChannel = {u'name': u'pyTestChannelName', u'owner': self.channelOwner} + testChannel = {"name": "pyTestChannelName", "owner": self.channelOwner} self.clientCh.set(channel=testChannel) - result = self.client.find(name=u'pyTestChannelName') - self.assertTrue(len(result) == 1, 'incorrect number of channels returned') - self.assertTrue(result[0][u'name'] == u'pyTestChannelName', 'incorrect channel returned') + result = self.client.find(name="pyTestChannelName") + self.assertTrue(len(result) == 1, "incorrect number of channels returned") + self.assertTrue( + result[0]["name"] == "pyTestChannelName", "incorrect channel returned" + ) finally: - self.clientCh.delete(channelName=testChannel[u'name']) - result = self.client.find(name=u'pyTestChannelName') - self.assertFalse(result, 'incorrect number of channels returned') + self.clientCh.delete(channelName=testChannel["name"]) + result = self.client.find(name="pyTestChannelName") + self.assertFalse(result, "incorrect number of channels returned") def testSetDeleteChannelWithPropertiesAndTags(self): """ Set and Delete a simple channel with properties or tags """ try: - testProp = {u'name': u'pyTestProp', u'owner': self.propOwner, u'value': u'testVal'} + testProp = { + "name": "pyTestProp", + "owner": self.propOwner, + "value": "testVal", + } self.client.set(property=testProp) - testTag = {u'name': u'pyTestTag', u'owner': self.tagOwner} + testTag = {"name": "pyTestTag", "owner": self.tagOwner} self.client.set(tag=testTag) - testChannel = {u'name': u'pyTestChannelName', u'owner': self.channelOwner, u'properties': [testProp], - u'tags': [testTag]} + testChannel = { + "name": "pyTestChannelName", + "owner": self.channelOwner, + "properties": [testProp], + "tags": [testTag], + } self.clientCh.set(channel=testChannel) - result = self.client.find(name=u'pyTestChannelName') - self.assertTrue(len(result) == 1, 'incorrect number of channels returned') - self.assertTrue(result[0][u'name'] == u'pyTestChannelName', 'incorrect channel returned') + result = self.client.find(name="pyTestChannelName") + self.assertTrue(len(result) == 1, "incorrect number of channels returned") + self.assertTrue( + result[0]["name"] == "pyTestChannelName", "incorrect channel returned" + ) finally: """Cleanup""" - self.clientCh.delete(channelName=testChannel[u'name']) - self.client.delete(tagName=testTag[u'name']) - self.client.delete(propertyName=testProp[u'name']) - result = self.client.find(name=u'pyTestChannelName') - self.assertFalse(result, 'incorrect number of channels returned') + self.clientCh.delete(channelName=testChannel["name"]) + self.client.delete(tagName=testTag["name"]) + self.client.delete(propertyName=testProp["name"]) + result = self.client.find(name="pyTestChannelName") + self.assertFalse(result, "incorrect number of channels returned") def testSetRemoveChannels(self): """ Test Set and Delete on a list of channels with no propties or tags """ - testChannels = [{u'name': u'pyTestChannel1', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel2', u'owner': self.channelOwner}, - {u'name': u'pyTestChannel3', u'owner': self.channelOwner}] + testChannels = [ + {"name": "pyTestChannel1", "owner": self.channelOwner}, + {"name": "pyTestChannel2", "owner": self.channelOwner}, + {"name": "pyTestChannel3", "owner": self.channelOwner}, + ] try: self.clientCh.set(channels=testChannels) - r = self.client.find(name='pyTestChannel*') - self.assertTrue(len(r) == 3, - 'ERROR: # of channels returned expected ' + str(len(r)) + ' expected 3') + r = self.client.find(name="pyTestChannel*") + self.assertTrue( + len(r) == 3, + "ERROR: # of channels returned expected " + str(len(r)) + " expected 3", + ) finally: # delete each individually for ch in testChannels: - self.clientCh.delete(channelName=str(ch[u'name'])) + self.clientCh.delete(channelName=str(ch["name"])) def testSetChannelsWithProperties(self): """ This method creates a set of channels and then updates the property values using the set method with the channels parameter. """ - prop1 = {u'name': u'originalProp1', u'owner': self.propOwner, u'value': u'originalVal'} - prop2 = {u'name': u'originalProp2', u'owner': self.propOwner, u'value': u'originalVal'} - ch1 = {u'name': u'orgChannel1', u'owner': self.channelOwner, u'properties': [prop1, prop2]} - 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]} + prop1 = { + "name": "originalProp1", + "owner": self.propOwner, + "value": "originalVal", + } + prop2 = { + "name": "originalProp2", + "owner": self.propOwner, + "value": "originalVal", + } + ch1 = { + "name": "orgChannel1", + "owner": self.channelOwner, + "properties": [prop1, prop2], + } + ch2 = { + "name": "orgChannel2", + "owner": self.channelOwner, + "properties": [prop1, prop2], + } + ch3 = {"name": "orgChannel3", "owner": self.channelOwner, "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')]) + chs = self.client.find( + property=[ + ("originalProp1", "originalVal"), + ("originalProp2", "originalVal"), + ] + ) self.assertTrue(len(chs) == 2) for ch in chs: - if (ch[u'properties'][0])[u'name'] == 'originalProp1': - (ch[u'properties'][0])[u'value'] = 'newVal' + if (ch["properties"][0])["name"] == "originalProp1": + (ch["properties"][0])["value"] = "newVal" self.client.set(channels=chs) - self.assertTrue(len(self.client.find(property=[('originalProp1', 'newVal')])) == 2, - 'failed to update prop value') + self.assertTrue( + len(self.client.find(property=[("originalProp1", "newVal")])) == 2, + "failed to update prop value", + ) """ clean up """ for ch in channels: - self.client.delete(channelName=ch[u'name']) - self.client.delete(propertyName=prop1[u'name']) - self.client.delete(propertyName=prop2[u'name']) + self.client.delete(channelName=ch["name"]) + self.client.delete(propertyName=prop1["name"]) + self.client.delete(propertyName=prop2["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} + testProp = {"name": "testProp", "owner": self.propOwner} 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}] + testProp["value"] = "original" + testChannels = [ + { + "name": "pyChannel1", + "owner": self.channelOwner, + "properties": [testProp], + }, + {"name": "pyChannel2", "owner": self.channelOwner}, + {"name": "pyChannel3", "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] - self.assertTrue(checkPropWithValueInList(result['properties'], [testProp]), - 'Failed to add pychannel1 correctly') - testChannels[0] = {u'name': u'pyChannel1', u'owner': self.channelOwner} + self.assertEqual( + len(self.client.find(name="pyChannel*")), + 1, + "Failed to set a single channel correctly", + ) + result = self.client.find(name="pyChannel1")[0] + self.assertTrue( + checkPropWithValueInList(result["properties"], [testProp]), + "Failed to add pychannel1 correctly", + ) + testChannels[0] = {"name": "pyChannel1", "owner": self.channelOwner} self.clientCh.set(channels=testChannels) - self.assertEqual(len(self.client.find(name=u'pyChannel*')), 3, - 'Failed to set a list of channels correctly') - self.assertTrue(not self.client.find(name=u'pyChannel1')[0][u'properties'] or - testProp not in self.client.find(name=u'pyChannel1')[0][u'properties'], - 'Failed to set pychannel1 correctly') + self.assertEqual( + len(self.client.find(name="pyChannel*")), + 3, + "Failed to set a list of channels correctly", + ) + self.assertTrue( + not self.client.find(name="pyChannel1")[0]["properties"] + or testProp not in self.client.find(name="pyChannel1")[0]["properties"], + "Failed to set pychannel1 correctly", + ) finally: for ch in testChannels: - self.clientCh.delete(channelName=ch[u'name']) - self.clientProp.delete(propertyName=testProp[u'name']) + self.clientCh.delete(channelName=ch["name"]) + self.clientProp.delete(propertyName=testProp["name"]) def testSetRemoveSpecialChar(self): - spChannel = {u'name': u'special{}*', u'owner': self.channelOwner} - spProperty = {u'name': u'special{}*', u'owner': self.propOwner, u'value': 'sp*'} - spTag = {u'name': u'special{}*', u'owner': self.tagOwner} - spChannel[u'properties'] = [spProperty] - spChannel[u'tags'] = [spTag] + spChannel = {"name": "special{}*", "owner": self.channelOwner} + spProperty = { + "name": "special{}*", + "owner": self.propOwner, + "value": "sp*", + } + spTag = {"name": "special{}*", "owner": self.tagOwner} + spChannel["properties"] = [spProperty] + spChannel["tags"] = [spTag] try: self.client.set(tag=spTag) - self.assertNotEqual(self.client.findTag(spTag[u'name']), None, 'failed to set Tag with special chars') + self.assertNotEqual( + self.client.findTag(spTag["name"]), + None, + "failed to set Tag with special chars", + ) self.client.set(property=spProperty) - self.assertNotEqual(self.client.findProperty(spProperty[u'name']), None, - 'failed to set Property with special chars') + self.assertNotEqual( + self.client.findProperty(spProperty["name"]), + None, + "failed to set Property with special chars", + ) self.client.set(channel=spChannel) - foundChannels = self.client.find(name=spChannel[u'name']) - self.assertNotEqual(foundChannels[0], None, 'failed to set channel with special chars') - self.assertTrue(foundChannels[0][u'name'] == spChannel[u'name'] and - checkTagInList(foundChannels[0][u'tags'], [spTag]) and - checkPropWithValueInList(foundChannels[0][u'properties'], [spProperty]), - 'Returned channel missing required properties and/or tags') + foundChannels = self.client.find(name=spChannel["name"]) + self.assertNotEqual( + foundChannels[0], None, "failed to set channel with special chars" + ) + self.assertTrue( + foundChannels[0]["name"] == spChannel["name"] + and checkTagInList(foundChannels[0]["tags"], [spTag]) + and checkPropWithValueInList( + foundChannels[0]["properties"], [spProperty] + ), + "Returned channel missing required properties and/or tags", + ) finally: """Cleanup""" - self.client.delete(channelName=spChannel[u'name']) - self.assertFalse(self.client.find(name=spChannel[u'name']), 'failed to delete channel with special char') - self.client.delete(tagName=spTag[u'name']) - self.assertTrue(self.client.findTag(spTag[u'name']) == None) - self.client.delete(propertyName=spProperty[u'name']) - self.assertTrue(self.client.findProperty(spProperty[u'name']) == None) + self.client.delete(channelName=spChannel["name"]) + self.assertFalse( + self.client.find(name=spChannel["name"]), + "failed to delete channel with special char", + ) + self.client.delete(tagName=spTag["name"]) + self.assertTrue(self.client.findTag(spTag["name"]) is None) + self.client.delete(propertyName=spProperty["name"]) + self.assertTrue(self.client.findProperty(spProperty["name"]) is None) def testQuotes(self): - spChannel = {u'name': u'\'"Name', u'owner': self.channelOwner} + spChannel = {"name": "'\"Name", "owner": self.channelOwner} self.client.set(channel=spChannel) - self.assertTrue(len(self.client.find(name=u'\'"Name')) == 1) - self.client.delete(channelName=u'\'"Name') + self.assertTrue(len(self.client.find(name="'\"Name")) == 1) + self.client.delete(channelName="'\"Name") # =============================================================================== @@ -615,90 +802,148 @@ def testUpdateChannel(self): Test the updating of a channel by adding tags and properties """ try: - testProp1 = {u'name': u'pyTestProp1', u'owner': self.propOwner, u'value': u'testVal1'} + testProp1 = { + "name": "pyTestProp1", + "owner": self.propOwner, + "value": "testVal1", + } self.client.set(property=testProp1) - testTag1 = {u'name': u'pyTestTag1', u'owner': self.tagOwner} + testTag1 = {"name": "pyTestTag1", "owner": self.tagOwner} self.client.set(tag=testTag1) - testChannel = {u'name': u'pyTestChannelName1', u'owner': self.channelOwner, u'properties': [testProp1], - u'tags': [testTag1]} + testChannel = { + "name": "pyTestChannelName1", + "owner": self.channelOwner, + "properties": [testProp1], + "tags": [testTag1], + } self.clientCh.set(channel=testChannel) - testProp2 = {u'name': u'pyTestProp2', u'owner': self.propOwner, u'value': u'testVal2'} + testProp2 = { + "name": "pyTestProp2", + "owner": self.propOwner, + "value": "testVal2", + } self.client.set(property=testProp2) - testTag2 = {u'name': u'pyTestTag2', u'owner': self.tagOwner} + testTag2 = {"name": "pyTestTag2", "owner": self.tagOwner} self.client.set(tag=testTag2) - testChannel = {u'name': u'pyTestChannelName1', u'owner': self.channelOwner, u'properties': [testProp2], - u'tags': [testTag2]} + testChannel = { + "name": "pyTestChannelName1", + "owner": self.channelOwner, + "properties": [testProp2], + "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') - self.assertTrue(checkTagInList(result[0]['tags'], [testTag1, testTag2]), 'Failed to update the tags') - self.assertTrue(checkPropWithValueInList(result[0]['properties'], [testProp1, testProp2]), - 'Failed to update the properties') + result = self.client.find(name="pyTestChannelName1") + self.assertTrue(len(result) == 1, "incorrect number of channels returned") + self.assertTrue( + result[0]["name"] == "pyTestChannelName1", "incorrect channel returned" + ) + self.assertTrue( + checkTagInList(result[0]["tags"], [testTag1, testTag2]), + "Failed to update the tags", + ) + self.assertTrue( + checkPropWithValueInList( + result[0]["properties"], [testProp1, testProp2] + ), + "Failed to update the properties", + ) finally: """Cleanup""" - self.client.delete(tagName=testTag1[u'name']) - self.client.delete(propertyName=testProp1[u'name']) - self.client.delete(tagName=testTag2[u'name']) - self.client.delete(propertyName=testProp2[u'name']) - self.clientCh.delete(channelName=testChannel[u'name']) - result = self.client.find(name=u'pyTestChannelName') - self.assertFalse(result, 'incorrect number of channels returned') + self.client.delete(tagName=testTag1["name"]) + self.client.delete(propertyName=testProp1["name"]) + self.client.delete(tagName=testTag2["name"]) + self.client.delete(propertyName=testProp2["name"]) + self.clientCh.delete(channelName=testChannel["name"]) + result = self.client.find(name="pyTestChannelName") + self.assertFalse(result, "incorrect number of channels returned") # =============================================================================== # Update Opertation Tests # =============================================================================== + class UpdateOperationTest(ChannelFinderClientTestCase): def setUp(self): """Default set of Owners""" - self.channelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.channelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default set of clients""" self.client = ChannelFinderClient() - self.clientCh = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'channelUsername'), - password=_testConf.get('DEFAULT', 'channelPassword')) - self.clientProp = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'propUsername'), - password=_testConf.get('DEFAULT', 'propPassword')) - self.clientTag = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'tagUsername'), - password=_testConf.get('DEFAULT', 'tagPassword')) + self.clientCh = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "channelUsername"), + password=_testConf.get("DEFAULT", "channelPassword"), + ) + self.clientProp = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "propUsername"), + password=_testConf.get("DEFAULT", "propPassword"), + ) + self.clientTag = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "tagUsername"), + password=_testConf.get("DEFAULT", "tagPassword"), + ) """ 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.orgTagResponse = {u'name': u'originalTag', u'owner': self.tagOwner, u'channels': []} - self.orgPropResponse = {u'name': u'originalProp', u'owner': self.propOwner, u'value': u'originalValue', u'channels': []} + self.orgTag = {"name": "originalTag", "owner": self.tagOwner} + self.orgProp = { + "name": "originalProp", + "owner": self.propOwner, + "value": "originalValue", + } + self.orgTagResponse = { + "name": "originalTag", + "owner": self.tagOwner, + "channels": [], + } + self.orgPropResponse = { + "name": "originalProp", + "owner": self.propOwner, + "value": "originalValue", + "channels": [], + } 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.orgPropResponse in ch[0][u'properties'] and - self.orgTagResponse in ch[0][u'tags']) + self.clientCh.set( + channel={ + "name": "originalChannelName", + "owner": self.channelOwner, + "properties": [self.orgProp], + "tags": [self.orgTag], + } + ) + ch = self.client.find(name="originalChannelName") + self.assertTrue( + len(ch) == 1 + and self.orgPropResponse in ch[0]["properties"] + and self.orgTagResponse in ch[0]["tags"] + ) def UpdateTagName(self): - newTagName = 'updatedTag' - self.assertTrue(self.client.findTag(self.orgTag[u'name']) is not None) - self.clientTag.update(tag={u'name': newTagName, u'owner': self.tagOwner}, - originalTagName=self.orgTag[u'name']) - self.assertTrue(self.client.findTag(self.orgTag[u'name']) is None and - self.client.findTag(newTagName) is not None) + newTagName = "updatedTag" + self.assertTrue(self.client.findTag(self.orgTag["name"]) is not None) + self.clientTag.update( + tag={"name": newTagName, "owner": self.tagOwner}, + originalTagName=self.orgTag["name"], + ) + self.assertTrue( + self.client.findTag(self.orgTag["name"]) is None + and self.client.findTag(newTagName) is not None + ) # check that renaming the Tag does not remove it from any channel - channelTags = self.client.find(name=u'originalChannelName')[0][u'tags'] - self.assertTrue(self.orgTagResponse not in channelTags and - {u'name': newTagName, u'owner': self.tagOwner, u'channels': []} in channelTags) + channelTags = self.client.find(name="originalChannelName")[0]["tags"] + self.assertTrue( + self.orgTagResponse not in channelTags + and {"name": newTagName, "owner": self.tagOwner, "channels": []} + in channelTags + ) self.clientTag.update(tag=self.orgTag, originalTagName=newTagName) def testUpdateTagOwner(self): @@ -707,42 +952,61 @@ def testUpdateTagOwner(self): # 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' - self.assertTrue(self.client.findProperty(self.orgProp[u'name']) is not None) - self.clientProp.update(property={u'name': newPropName, u'owner': self.propOwner}, - originalPropertyName=self.orgProp[u'name']) - self.assertTrue(self.client.findProperty(self.orgProp[u'name']) is None and - self.client.findProperty(newPropName) is not None) + newPropName = "updatedProperty" + self.assertTrue(self.client.findProperty(self.orgProp["name"]) is not None) + self.clientProp.update( + property={"name": newPropName, "owner": self.propOwner}, + originalPropertyName=self.orgProp["name"], + ) + self.assertTrue( + self.client.findProperty(self.orgProp["name"]) is None + and self.client.findProperty(newPropName) is not None + ) # check to ensure that the Property is renamed and not removed from any channels - channelProperties = self.client.find(name=u'originalChannelName')[0].getProperties() - self.assertTrue(self.orgProp[u'name'] not in channelProperties.keys() and - newPropName in channelProperties.keys()) + channelProperties = self.client.find(name="originalChannelName")[ + 0 + ].getProperties() + self.assertTrue( + self.orgProp["name"] not in channelProperties.keys() + and newPropName in channelProperties.keys() + ) self.clientProp.update(property=self.orgProp, originalPropertyName=newPropName) def testUpdatePropOwner(self): self.assertTrue(True) def testUpdateChannelName(self): - ch = self.client.find(name=u'originalChannelName')[0] - 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') == []) - self.assertTrue(len(self.client.find(name=u'updatedChannelName')) == 1) + ch = self.client.find(name="originalChannelName")[0] + newChannel = { + "name": "updatedChannelName", + "owner": ch["owner"], + "properties": ch["properties"], + "tags": ch["tags"], + } + self.clientCh.update( + originalChannelName="originalChannelName", channel=newChannel + ) + self.assertTrue(self.client.find(name="originalChannelName") == []) + self.assertTrue(len(self.client.find(name="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') == []) + self.clientCh.update(originalChannelName="updatedChannelName", channel=ch) + self.assertTrue(len(self.client.find(name="originalChannelName")) == 1) + self.assertTrue(self.client.find(name="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][u'owner'] == self.tagOwner) + ch = self.client.find(name="originalChannelName")[0] + newChannel = { + "name": ch["name"], + "owner": self.tagOwner, + "properties": ch["properties"], + "tags": ch["tags"], + } + self.clientCh.update( + originalChannelName="originalChannelName", channel=newChannel + ) + self.assertTrue( + self.client.find(name="originalChannelName")[0]["owner"] == self.tagOwner + ) def testUpdateChannel(self): """ @@ -754,117 +1018,169 @@ def testUpdateChannel(self): 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} - newProp = {u'name': u'newProp', u'owner': self.propOwner, u'value': u'newValue'} - updatedPropResponse = {u'name': u'originalProp', u'owner': self.propOwner, u'value': u'updatedValue', u'channels': []} - newTagResponse = {u'name': u'updatedTag', u'owner': self.tagOwner, u'channels': []} - newPropResponse = {u'name': u'newProp', u'owner': self.propOwner, u'value': u'newValue', u'channels': []} + ch = self.client.find(name="originalChannelName")[0] + updatedProp = { + "name": "originalProp", + "owner": self.propOwner, + "value": "updatedValue", + } + newTag = {"name": "updatedTag", "owner": self.tagOwner} + newProp = {"name": "newProp", "owner": self.propOwner, "value": "newValue"} + updatedPropResponse = { + "name": "originalProp", + "owner": self.propOwner, + "value": "updatedValue", + "channels": [], + } + newTagResponse = {"name": "updatedTag", "owner": self.tagOwner, "channels": []} + newPropResponse = { + "name": "newProp", + "owner": self.propOwner, + "value": "newValue", + "channels": [], + } try: self.clientTag.set(tag=newTag) self.clientProp.set(property=newProp) - newChannel = {u'name': u'updatedChannelName', u'owner': self.channelOwner, - u'properties': [updatedProp, newProp], - u'tags': [newTag]} - self.clientCh.update(originalChannelName=u'originalChannelName', - channel=newChannel) - foundChannel = self.client.find(name=u'updatedChannelName')[0] - self.assertTrue(foundChannel[u'name'] == u'updatedChannelName' ) - self.assertTrue(foundChannel[u'owner'] == self.channelOwner ) - self.assertTrue(updatedPropResponse in foundChannel[u'properties'] ) - self.assertTrue(newPropResponse in foundChannel[u'properties'] ) - self.assertTrue(newTagResponse in foundChannel[u'tags'] ) - self.assertTrue(self.orgTagResponse in foundChannel[u'tags']) + newChannel = { + "name": "updatedChannelName", + "owner": self.channelOwner, + "properties": [updatedProp, newProp], + "tags": [newTag], + } + self.clientCh.update( + originalChannelName="originalChannelName", channel=newChannel + ) + foundChannel = self.client.find(name="updatedChannelName")[0] + self.assertTrue(foundChannel["name"] == "updatedChannelName") + self.assertTrue(foundChannel["owner"] == self.channelOwner) + self.assertTrue(updatedPropResponse in foundChannel["properties"]) + self.assertTrue(newPropResponse in foundChannel["properties"]) + self.assertTrue(newTagResponse in foundChannel["tags"]) + self.assertTrue(self.orgTagResponse in foundChannel["tags"]) finally: # reset - self.clientCh.update(originalChannelName='updatedChannelName', - channel=ch) - self.assertTrue(len(self.client.find(name='originalChannelName')), - 'failed to reset the updated channels') - if self.clientTag.findTag(newTag[u'name']): - self.clientTag.delete(tagName=newTag[u'name']) - if self.clientProp.findProperty(newProp[u'name']): - self.clientProp.delete(propertyName=newProp[u'name']) + self.clientCh.update(originalChannelName="updatedChannelName", channel=ch) + self.assertTrue( + len(self.client.find(name="originalChannelName")), + "failed to reset the updated channels", + ) + if self.clientTag.findTag(newTag["name"]): + self.clientTag.delete(tagName=newTag["name"]) + if self.clientProp.findProperty(newProp["name"]): + self.clientProp.delete(propertyName=newProp["name"]) def testUpdateChannel2(self): """ Update a channels using update(channel=updatedChannel) """ - ch = self.client.find(name=u'originalChannelName') - self.assertTrue(len(ch) == 1 and - self.orgPropResponse in ch[0][u'properties'] and - self.orgTagResponse in ch[0][u'tags']) - updatedProp = {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': [updatedProp], - u'tags': []}) - ch = self.client.find(name=u'originalChannelName') - updatedPropResponse = {u'name': u'originalProp', - u'owner': self.propOwner, - u'value': u'newPropValue', u'channels':[]} + ch = self.client.find(name="originalChannelName") + self.assertTrue( + len(ch) == 1 + and self.orgPropResponse in ch[0]["properties"] + and self.orgTagResponse in ch[0]["tags"] + ) + updatedProp = { + "name": "originalProp", + "owner": self.propOwner, + "value": "newPropValue", + } + self.clientCh.update( + channel={ + "name": "originalChannelName", + "owner": "newOwner", + "properties": [updatedProp], + "tags": [], + } + ) + ch = self.client.find(name="originalChannelName") + updatedPropResponse = { + "name": "originalProp", + "owner": self.propOwner, + "value": "newPropValue", + "channels": [], + } self.assertTrue(len(ch) == 1) - self.assertTrue(updatedPropResponse in ch[0][u'properties']) - self.assertTrue(self.orgTagResponse in ch[0][u'tags']) - self.assertTrue(ch[0][u'owner'] == u'newOwner') + self.assertTrue(updatedPropResponse in ch[0]["properties"]) + self.assertTrue(self.orgTagResponse in ch[0]["tags"]) + self.assertTrue(ch[0]["owner"] == "newOwner") def testUpdateProperty(self): """ Update a single property using update(property=updatedProperty) Updates existing channels with new property owner, without altering original value. """ - prop = self.client.findProperty(propertyname=u'originalProp') - prop[u'channels'] = [] - self.assertDictEqual(prop, {u'owner': self.propOwner, - u'channels': [], - u'name': u'originalProp', - u'value': None}) + prop = self.client.findProperty(propertyname="originalProp") + prop["channels"] = [] + self.assertDictEqual( + prop, + { + "owner": self.propOwner, + "channels": [], + "name": "originalProp", + "value": None, + }, + ) updatedProperty = dict(prop) - updatedProperty[u'owner'] = u'newOwner' + updatedProperty["owner"] = "newOwner" self.clientProp.update(property=updatedProperty) """Check property owner""" - prop = self.client.findProperty(propertyname=u'originalProp') - prop[u'channels'] = [] - self.assertDictEqual(prop, {u'owner': u'newOwner', - u'channels': [], - u'name': u'originalProp', - u'value': None}) + prop = self.client.findProperty(propertyname="originalProp") + prop["channels"] = [] + self.assertDictEqual( + prop, + { + "owner": "newOwner", + "channels": [], + "name": "originalProp", + "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', u'channels': []} in ch[0][u'properties']) + ch = self.client.find(name="originalChannelName") + self.assertTrue( + { + "owner": "newOwner", + "name": "originalProp", + "value": "originalValue", + "channels": [], + } + in ch[0]["properties"] + ) def testUpdateTag(self): """ Update a single tag using update(tag=updatedTag) Updates owner in all associated channels. """ - tag = self.client.findTag(tagname=u'originalTag') - tag[u'channels'] = [] - self.assertDictEqual(tag, {u'owner': self.tagOwner, u'channels': [], u'name': u'originalTag'}) + tag = self.client.findTag(tagname="originalTag") + tag["channels"] = [] + self.assertDictEqual( + tag, {"owner": self.tagOwner, "channels": [], "name": "originalTag"} + ) updatedTag = dict(tag) - updatedTag[u'owner'] = u'newOwner' + updatedTag["owner"] = "newOwner" self.clientTag.update(tag=updatedTag) """Check tag owner""" - tag = self.client.findTag(tagname=u'originalTag') - tag[u'channels'] = [] - self.assertDictEqual(tag, {u'owner': u'newOwner', u'channels': [], u'name': u'originalTag'}) + tag = self.client.findTag(tagname="originalTag") + tag["channels"] = [] + self.assertDictEqual( + tag, {"owner": "newOwner", "channels": [], "name": "originalTag"} + ) """Checks existing channel""" - ch = self.client.find(name=u'originalChannelName') - self.assertTrue({u'owner': u'newOwner', - u'name': u'originalTag', u'channels':[]} in ch[0][u'tags']) + ch = self.client.find(name="originalChannelName") + self.assertTrue( + {"owner": "newOwner", "name": "originalTag", "channels": []} + in ch[0]["tags"] + ) def tearDown(self): - self.clientCh.delete(channelName=u'originalChannelName') - self.clientTag.delete(tagName=u'originalTag') - self.clientProp.delete(propertyName=u'originalProp') + self.clientCh.delete(channelName="originalChannelName") + self.clientTag.delete(tagName="originalTag") + self.clientProp.delete(propertyName="originalProp") """ @@ -877,108 +1193,145 @@ def tearDown(self): class UpdateAppendTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.ChannelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default Client""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) - self.clientProp = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'propUsername'), - password=_testConf.get('DEFAULT', 'propPassword')) - 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'} - self.Prop2 = {u'name': u'prop2', u'owner': self.propOwner, u'value': u'initialVal'} + self.client = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "username"), + password=_testConf.get("DEFAULT", "password"), + ) + self.clientProp = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "propUsername"), + password=_testConf.get("DEFAULT", "propPassword"), + ) + self.clientTag = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "tagUsername"), + password=_testConf.get("DEFAULT", "tagPassword"), + ) + + self.Tag1 = {"name": "tag1", "owner": self.tagOwner} + self.Tag2 = {"name": "tag2", "owner": self.tagOwner} + self.Prop1 = {"name": "prop1", "owner": self.propOwner, "value": "initialVal"} + self.Prop2 = {"name": "prop2", "owner": self.propOwner, "value": "initialVal"} self.Prop1Response = self.Prop1.copy() self.Prop1Response["channels"] = [] - self.Prop2Response = {u'name': u'prop2', u'owner': self.propOwner, u'value': u'initialVal'} + self.Prop2Response = { + "name": "prop2", + "owner": self.propOwner, + "value": "initialVal", + } self.Prop2Response = self.Prop2.copy() self.Prop2Response["channels"] = [] - self.ch1 = {u'name': u'orgChannel1', u'owner': self.ChannelOwner, u'tags': [self.Tag1, self.Tag2]} - self.ch2 = {u'name': u'orgChannel2', u'owner': self.ChannelOwner, u'tags': [self.Tag2]} - self.ch3 = {u'name': u'orgChannel3', u'owner': self.ChannelOwner} + self.ch1 = { + "name": "orgChannel1", + "owner": self.ChannelOwner, + "tags": [self.Tag1, self.Tag2], + } + self.ch2 = { + "name": "orgChannel2", + "owner": self.ChannelOwner, + "tags": [self.Tag2], + } + self.ch3 = {"name": "orgChannel3", "owner": self.ChannelOwner} self.channels = [self.ch1, self.ch2, self.ch3] self.clientTag.set(tags=[self.Tag1, self.Tag2]) self.clientProp.set(properties=[self.Prop1, self.Prop2]) 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.Tag1["name"])) == 1) + self.assertTrue(len(self.client.find(tagName=self.Tag2["name"])) == 2) pass def tearDown(self): - self.clientTag.delete(tagName=self.Tag1[u'name']) - self.clientTag.delete(tagName=self.Tag2[u'name']) - self.clientProp.delete(propertyName=self.Prop1[u'name']) - self.clientProp.delete(propertyName=self.Prop2[u'name']) + self.clientTag.delete(tagName=self.Tag1["name"]) + self.clientTag.delete(tagName=self.Tag2["name"]) + self.clientProp.delete(propertyName=self.Prop1["name"]) + self.clientProp.delete(propertyName=self.Prop2["name"]) for channel in self.channels: - self.client.delete(channelName=channel[u'name']) - self.assertTrue(self.client.find(name=u'orgChannel?') == []) + self.client.delete(channelName=channel["name"]) + self.assertTrue(self.client.find(name="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) + self.clientTag.update(tag=self.Tag2, channelName=self.ch3["name"]) + self.assertTrue(len(self.client.find(tagName=self.Tag2["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["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) + self.assertTrue(len(self.client.find(tagName=self.Tag1["name"])) == 3) def testUpdateAppendProperty2Channel(self): """ Test to update a channel with a property """ - self.assertEqual(len(self.client.find(name=self.ch3[u'name'])), 1) - self.assertEqual(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.assertEqual(len(self.client.find(name=self.ch3[u'name'])), 1) - ch3 = self.client.find(name=self.ch3[u'name']) - self.assertTrue(self.Prop1Response in ch3[0][u'properties'], - 'failed to update the channel with a new property') + self.assertEqual(len(self.client.find(name=self.ch3["name"])), 1) + self.assertEqual( + self.client.find(name=self.ch3["name"])[0]["properties"], + [], + "the channel already has properties", + ) + self.clientProp.update(property=self.Prop1, channelName=self.ch3["name"]) + self.assertEqual(len(self.client.find(name=self.ch3["name"])), 1) + ch3 = self.client.find(name=self.ch3["name"]) + self.assertTrue( + self.Prop1Response in ch3[0]["properties"], + "failed to update the channel with a new property", + ) """Check that Value of the property is correctly added""" - self.Prop2[u'value'] = 'val' - self.Prop2Response[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.Prop1Response in chs[0][u'properties'] and - self.Prop2Response in chs[0][u'properties'], - 'Failed to update the channel with a new property without disturbing the old one') + self.Prop2["value"] = "val" + self.Prop2Response["value"] = "val" + self.clientProp.update(property=self.Prop2, channelName=self.ch3["name"]) + chs = self.client.find(name=self.ch3["name"]) + self.assertTrue( + len(chs) == 1 + and self.Prop1Response in chs[0]["properties"] + and self.Prop2Response in chs[0]["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'] == [], - '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'] == [], - 'the channel already has properties') - self.Prop1[u'value'] = 'testVal' - self.Prop1Response[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.Prop1Response 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.Prop1Response in self.client.find(name=self.ch3[u'name'])[0][u'properties'], - 'failed to update the channel with a new property') + self.assertTrue( + len(self.client.find(name=self.ch2["name"])) == 1 + and self.client.find(name=self.ch2["name"])[0]["properties"] == [], + "the channel already has properties", + ) + self.assertTrue( + len(self.client.find(name=self.ch3["name"])) == 1 + and self.client.find(name=self.ch3["name"])[0]["properties"] == [], + "the channel already has properties", + ) + self.Prop1["value"] = "testVal" + self.Prop1Response["value"] = "testVal" + self.clientProp.update( + property=self.Prop1, channelNames=[self.ch2["name"], self.ch3["name"]] + ) + self.assertTrue( + len(self.client.find(name=self.ch2["name"])) == 1 + and self.Prop1Response + in self.client.find(name=self.ch2["name"])[0]["properties"], + "failed to update the channel with a new property", + ) + self.assertTrue( + len(self.client.find(name=self.ch3["name"])) == 1 + and self.Prop1Response + in self.client.find(name=self.ch3["name"])[0]["properties"], + "failed to update the channel with a new property", + ) @unittest.skip("Skipping test for unimplemented functionality.") def testUpdateRemoveProperty2Channel(self): @@ -986,17 +1339,27 @@ 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.Prop1Response 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.set( + channel={ + "name": "testChannel", + "owner": self.ChannelOwner, + "properties": [self.Prop1], + } + ) + channel = self.client.find(name="testChannel") + self.assertTrue( + len(channel) == 1 and self.Prop1Response in channel[0]["properties"], + "Failed to create a test channel with property prop1", + ) + self.Prop1["value"] = "" + channel[0]["properties"] = [self.Prop1] self.client.update(channel=channel[0]) - self.assertFalse(self.client.find(name=u'testChannel')[0][u'properties'], - 'Failed to deleted property prop1 form channel testChannel') + self.assertFalse( + self.client.find(name="testChannel")[0]["properties"], + "Failed to deleted property prop1 form channel testChannel", + ) finally: - self.client.delete(channelName=u'testChannel') + self.client.delete(channelName="testChannel") def UserOwnerCheck(self): """ @@ -1004,33 +1367,44 @@ def UserOwnerCheck(self): 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(), - 'failed to add testProperty') - self.client.set(channel={u'name': u'testChannel', u'owner': u'cf-channels'}) - self.clientProp.update(property={u'name': u'testProperty', u'owner': u'cf-asd', u'value': u'val'}, - channelName=u'testChannel') - self.assertEqual(len(self.client.find(property=[(u'testProperty', '*')])), 1, - 'Failed to update testChannel with testProperty') + self.clientProp.set(property={"name": "testProperty", "owner": "cf-asd"}) + self.assertTrue( + {"name": "testProperty", "owner": "cf-asd"} + in self.client.getAllProperties(), + "failed to add testProperty", + ) + self.client.set(channel={"name": "testChannel", "owner": "cf-channels"}) + self.clientProp.update( + property={"name": "testProperty", "owner": "cf-asd", "value": "val"}, + channelName="testChannel", + ) + self.assertEqual( + len(self.client.find(property=[("testProperty", "*")])), + 1, + "Failed to update testChannel with testProperty", + ) finally: - self.clientProp.delete(propertyName=u'testProperty') - self.client.delete(channelName=u'testChannel') + self.clientProp.delete(propertyName="testProperty") + self.client.delete(channelName="testChannel") # =========================================================================== # Query Tests # =========================================================================== + class QueryTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.ChannelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default Client""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) + self.client = ChannelFinderClient( + BaseURL=_testConf.get("DEFAULT", "BaseURL"), + username=_testConf.get("DEFAULT", "username"), + password=_testConf.get("DEFAULT", "password"), + ) pass def tearDown(self): @@ -1043,8 +1417,11 @@ def testEmptyReturn(self): """ find for non existing entities should return None instead of a 404 """ - self.assertEqual(len(self.client.find(name=u'NonExistingChannelName')), 0, - 'Failed to return None when searching for a non existing channel') + self.assertEqual( + len(self.client.find(name="NonExistingChannelName")), + 0, + "Failed to return None when searching for a non existing channel", + ) def MultiValueQuery(self): """ @@ -1059,70 +1436,101 @@ def MultiValueQuery(self): Logically AND'ed tagName=pattern1, pattern2 => return channels with tags matching pattern1 AND pattern2 """ - tagA = {u'name': u'tagA', u'owner': self.tagOwner} - tagB = {u'name': u'tagB', u'owner': self.tagOwner} + tagA = {"name": "tagA", "owner": self.tagOwner} + tagB = {"name": "tagB", "owner": self.tagOwner} self.client.set(tag=tagA) self.client.set(tag=tagB) - propA = {u'name': u'propA', u'owner': self.propOwner} - propB = {u'name': u'propB', u'owner': self.propOwner} + propA = {"name": "propA", "owner": self.propOwner} + propB = {"name": "propB", "owner": self.propOwner} self.client.set(property=propA) self.client.set(property=propB) - self.client.set(channel={u'name': u'pyTestChannelA', - u'owner': self.ChannelOwner, - u'tags': [tagA], - u'properties': [{u'name': u'propA', u'owner': self.propOwner, u'value': u'1'}]}) - self.client.set(channel={u'name': u'pyTestChannelB', - u'owner': self.ChannelOwner, - u'tags': [tagB], - u'properties': [{u'name': u'propB', u'owner': self.propOwner, u'value': u'2'}]}) - self.client.set(channel={u'name': u'pyTestChannelAB', - u'owner': self.ChannelOwner, - u'tags': [tagA, tagB], - u'properties': [{u'name': u'propA', u'owner': self.propOwner, u'value': u'a'}, - {u'name': u'propB', u'owner': self.propOwner, u'value': u'b'}]}) + self.client.set( + channel={ + "name": "pyTestChannelA", + "owner": self.ChannelOwner, + "tags": [tagA], + "properties": [ + {"name": "propA", "owner": self.propOwner, "value": "1"} + ], + } + ) + self.client.set( + channel={ + "name": "pyTestChannelB", + "owner": self.ChannelOwner, + "tags": [tagB], + "properties": [ + {"name": "propB", "owner": self.propOwner, "value": "2"} + ], + } + ) + self.client.set( + channel={ + "name": "pyTestChannelAB", + "owner": self.ChannelOwner, + "tags": [tagA, tagB], + "properties": [ + {"name": "propA", "owner": self.propOwner, "value": "a"}, + {"name": "propB", "owner": self.propOwner, "value": "b"}, + ], + } + ) """Tag Queries""" - self.assertEqual(len(self.client.find(tagName=u'tagA')), 2, - 'failed to successfully complete a query for tagA') - self.assertEqual(len(self.client.find(tagName=u'tagB')), 2, - 'failed to successfully complete a query for tagB') - self.assertEqual(len(self.client.find(tagName=u'tagA,tagB')), 1, - 'failed to complete a query with ORed tagNames') + self.assertEqual( + len(self.client.find(tagName="tagA")), + 2, + "failed to successfully complete a query for tagA", + ) + self.assertEqual( + len(self.client.find(tagName="tagB")), + 2, + "failed to successfully complete a query for tagB", + ) + self.assertEqual( + len(self.client.find(tagName="tagA,tagB")), + 1, + "failed to complete a query with ORed tagNames", + ) """Property Queries""" - chs = self.client.find(property=[(u'propA', '*')]) - self.assertEqual(len(chs), 2, - 'Failed of query propA expected 2 found ' + str(len(chs))) - chs = self.client.find(property=[(u'propA', '1')]) - self.assertEqual(len(chs), 1, - 'Failed of query propA expected 1 found ' + str(len(chs))) + chs = self.client.find(property=[("propA", "*")]) + self.assertEqual( + len(chs), 2, "Failed of query propA expected 2 found " + str(len(chs)) + ) + chs = self.client.find(property=[("propA", "1")]) + self.assertEqual( + len(chs), 1, "Failed of query propA expected 1 found " + str(len(chs)) + ) """conditions AND'ed""" """channels which have both propA and propB""" - chs = self.client.find(property=[(u'propA', '*'), (u'propB', '*')]) - self.assertEqual(len(chs), 1, - 'Failed of query propA expected 1 found ' + str(len(chs))) + chs = self.client.find(property=[("propA", "*"), ("propB", "*")]) + self.assertEqual( + len(chs), 1, "Failed of query propA expected 1 found " + str(len(chs)) + ) """conditions OR'ed""" """channels which have propA = pattern1 OR pattern2""" - 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))) + chs = self.client.find(property=[("propA", "1"), ("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'], - property=[(u'propA', '*')]) - self.assertEqual(len(chs), 2, 'expected 2 found ' + str(len(chs))) - 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))) + chs = self.client.find( + name="pyTestChannel*", tagName=tagA["name"], property=[("propA", "*")] + ) + self.assertEqual(len(chs), 2, "expected 2 found " + str(len(chs))) + chs = self.client.find( + name="pyTestChannel*", tagName=tagA["name"], property=[("propA", "a")] + ) + self.assertEqual(len(chs), 1, "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(channelName="pyTestChannelA") + self.client.delete(channelName="pyTestChannelB") + self.client.delete(channelName="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']) + self.client.delete(tagName=tagA["name"]) + self.client.delete(tagName=tagB["name"]) + self.client.delete(propertyName=propA["name"]) + self.client.delete(propertyName=propB["name"]) # =============================================================================== @@ -1131,46 +1539,64 @@ def MultiValueQuery(self): class ErrorTest(ChannelFinderClientTestCase): def setUp(self): """Default Owners""" - self.ChannelOwner = _testConf.get('DEFAULT', 'channelOwner') - self.propOwner = _testConf.get('DEFAULT', 'propOwner') - self.tagOwner = _testConf.get('DEFAULT', 'tagOwner') + self.ChannelOwner = _testConf.get("DEFAULT", "channelOwner") + self.propOwner = _testConf.get("DEFAULT", "propOwner") + self.tagOwner = _testConf.get("DEFAULT", "tagOwner") """Default Client""" - self.client = ChannelFinderClient(BaseURL=_testConf.get('DEFAULT', 'BaseURL'), - username=_testConf.get('DEFAULT', 'username'), - password=_testConf.get('DEFAULT', 'password')) + 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}) + self.client.set(property={"name": "existingProperty", "owner": self.propOwner}) def tearDown(self): - self.client.delete(propertyName='existingProperty') + 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'}]}) + self.assertRaises( + Exception, + self.client.set, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [{"name": "nonExisitngProperty", "owner": "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'}]}) + self.assertRaises( + Exception, + self.client.set, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "tags": [{"name": "nonExisitngTag", "owner": "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'}]}) + self.assertRaises( + Exception, + self.client.update, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [{"name": "nonExisitngProperty", "owner": "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'}]}) + self.assertRaises( + Exception, + self.client.update, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "tags": [{"name": "nonExisitngTag", "owner": "owner"}], + }, + ) def testUpdateNonExistingChannel(self): pass @@ -1182,65 +1608,91 @@ def testUpdateNoneExistingTag(self): pass def testIncorrectFindArguments(self): - self.assertRaises(Exception, - self.client.find, - processVariable='zzz') - self.assertRaises(Exception, - self.client.find, - properties='zzz') - self.assertRaises(Exception, - self.client.find, - tag='zzz') + self.assertRaises(Exception, self.client.find, processVariable="zzz") + self.assertRaises(Exception, self.client.find, properties="zzz") + self.assertRaises(Exception, self.client.find, tag="zzz") def testCreateChannelWithNullPropertyValue(self): - self.assertRaises(Exception, - self.client.set, - channel={u'name': u'channelName', - u'owner': self.ChannelOwner, - 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') + self.assertRaises( + Exception, + self.client.set, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [{"name": "existingProperty", "owner": self.propOwner}], + }, + ) + self.assertFalse( + self.client.find(name="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}) + self.client.set(channel={"name": "channelName", "owner": self.ChannelOwner}) try: - self.assertRaises(Exception, - self.client.update, - channel={u'name': u'channelName', - u'owner': self.ChannelOwner, - u'properties': [{u'name': u'existingProperty', u'owner': self.propOwner}]}) - print("client: " + str(self.client.find(name='channelName')[0])) - # should this/ be if client.find... == None ??? - self.assertFalse('existingProperty' in self.client.find(name=u'channelName')[0][u'properties'], - 'Failed: should not be able to update a channel with a property with value null') + self.assertRaises( + Exception, + self.client.update, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [ + {"name": "existingProperty", "owner": self.propOwner} + ], + }, + ) + print("client: " + str(self.client.find(name="channelName")[0])) + # should this/ be if client.find... is None ??? + self.assertFalse( + "existingProperty" + in self.client.find(name="channelName")[0]["properties"], + "Failed: should not be able to update a channel with a property with value null", + ) finally: - self.client.delete(channelName=u'channelName') + self.client.delete(channelName="channelName") def testCreateChannelWithEmptyPropertyValue(self): - self.assertRaises(Exception, - self.client.set, - channel={u'name': u'channelName', - u'owner': self.ChannelOwner, - 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') + self.assertRaises( + Exception, + self.client.set, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [ + {"name": "existingProperty", "owner": self.propOwner, "value": ""} + ], + }, + ) + self.assertFalse( + self.client.find(name="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}) + self.client.set(channel={"name": "channelName", "owner": self.ChannelOwner}) try: - self.assertRaises(Exception, - self.client.update, - channel={u'name': u'channelName', - u'owner': self.ChannelOwner, - u'properties': [ - {u'name': u'existingProperty', u'owner': self.propOwner, u'value': u''}]}) - self.assertFalse(u'existingProperty' in ChannelUtil.getAllProperties(self.client.find(name=u'channelName')), - 'Failed: should not be able to update a channel with a property with empty value string') + self.assertRaises( + Exception, + self.client.update, + channel={ + "name": "channelName", + "owner": self.ChannelOwner, + "properties": [ + { + "name": "existingProperty", + "owner": self.propOwner, + "value": "", + } + ], + }, + ) + self.assertFalse( + "existingProperty" + in ChannelUtil.getAllProperties(self.client.find(name="channelName")), + "Failed: should not be able to update a channel with a property with empty value string", + ) finally: - self.client.delete(channelName=u'channelName') + self.client.delete(channelName="channelName") def checkTagInList(allTags, tags): @@ -1249,7 +1701,11 @@ def checkTagInList(allTags, tags): """ found = [] for tag in tags: - [found.append(tag) for t in allTags if t['name'] == tag['name'] and t['owner'] == tag['owner']] + [ + found.append(tag) + for t in allTags + if t["name"] == tag["name"] and t["owner"] == tag["owner"] + ] return tags == found @@ -1259,8 +1715,13 @@ def checkPropWithValueInList(allProps, props): """ found = [] for prop in props: - [found.append(prop) for p in allProps if - p['name'] == prop['name'] and p['owner'] == prop['owner'] and p['value'] == prop['value']] + [ + found.append(prop) + for p in allProps + if p["name"] == prop["name"] + and p["owner"] == prop["owner"] + and p["value"] == prop["value"] + ] return props == found @@ -1270,7 +1731,11 @@ def checkPropInList(allProps, props): """ found = [] for prop in props: - [found.append(prop) for p in allProps if p['name'] == prop['name'] and p['owner'] == prop['owner']] + [ + found.append(prop) + for p in allProps + if p["name"] == prop["name"] and p["owner"] == prop["owner"] + ] return props == found @@ -1279,7 +1744,7 @@ def checkTagOnChannel(client, channelName, tag): utility method which return true is channelName contains tag """ ch = client.find(name=channelName)[0] - if ch[u'tags'] != None and checkTagInList(ch[u'tags'], [tag]): + if ch["tags"] is not None and checkTagInList(ch["tags"], [tag]): return True else: return False @@ -1290,24 +1755,18 @@ def checkPropertyOnChannel(client, channelName, property): utility method which return true is channelName contains property """ ch = client.find(name=channelName)[0] - if ch[u'properties'] != None and checkPropInList(ch[u'properties'], [property]): + if ch["properties"] is not None and checkPropInList(ch["properties"], [property]): return True else: return False def getDefaultTestConfig(arg): - if _testConf.has_option('DEFAULT', arg): - return _testConf.get('DEFAULT', arg) + if _testConf.has_option("DEFAULT", arg): + return _testConf.get("DEFAULT", arg) else: return None if __name__ == "__main__": - # import sys;sys.argv = ['', 'Test.testConnection'] - # suite = unittest.TestLoader().loadTestsFromTestCase(ErrorTest) - # unittest.TextTestRunner(verbosity=2).run(suite) - - # print sys.path - unittest.main() diff --git a/test/testChannelUtil.py b/test/testChannelUtil.py index fe63279..c8e1695 100644 --- a/test/testChannelUtil.py +++ b/test/testChannelUtil.py @@ -1,100 +1,166 @@ -''' +""" Copyright (c) 2010 Brookhaven National Laboratory All rights reserved. Use is subject to license terms and conditions. Created on May 10, 2011 @author: shroffk -''' +""" + import unittest from channelfinder import Channel, Property, Tag from channelfinder.util import ChannelUtil import urllib3 + urllib3.disable_warnings() class ChannelUtilTest(unittest.TestCase): - - def setUp(self): pass - def tearDown(self): pass def testChannelUtil(self): - channel1 = Channel('chName1', 'chOwner', - properties=[Property('location', 'propOwner', 'propVal'), - Property('prop1', 'propOwner', 'propVal')], - tags=[Tag('myTag', 'tagOwner')]) - channel2 = Channel('chName2', 'chOwner', - properties=[Property('location', 'propOwner', 'propVal'), - Property('prop2', 'propOwner', 'propVal')], - tags=[Tag('myTag', 'tagOwner'), - Tag('goldenOrbit', 'tagOwner')]) + channel1 = Channel( + "chName1", + "chOwner", + properties=[ + Property("location", "propOwner", "propVal"), + Property("prop1", "propOwner", "propVal"), + ], + tags=[Tag("myTag", "tagOwner")], + ) + channel2 = Channel( + "chName2", + "chOwner", + properties=[ + Property("location", "propOwner", "propVal"), + Property("prop2", "propOwner", "propVal"), + ], + tags=[Tag("myTag", "tagOwner"), Tag("goldenOrbit", "tagOwner")], + ) channels = [channel1, channel2] allTags = ChannelUtil.getAllTags(channels) - self.assertTrue(len(allTags) == 2, \ - 'expected 2 tags found ' + str(len(allTags))) + self.assertTrue(len(allTags) == 2, "expected 2 tags found " + str(len(allTags))) allPropertyNames = ChannelUtil.getAllProperties(channels) - self.assertTrue(len(allPropertyNames) == 3, \ - 'expected 3 unique properties but found ' + str(len(allPropertyNames))) - + self.assertTrue( + len(allPropertyNames) == 3, + "expected 3 unique properties but found " + str(len(allPropertyNames)), + ) + pass - + def testGetAllPropValues(self): - ch1 = Channel('ch1', 'chOwner', - properties=[Property('location', 'propOwner', '234'), - Property('prop1', 'propOwner', 'propVal')]) - ch2 = Channel('ch2', 'chOwner', - properties=[Property('location', 'propOwner', 'SR'), - Property('prop2', 'propOwner', 'propVal')]) - ch3 = Channel('ch3', 'chOwner', - properties=[Property('location', 'propOwner', 'SR:234'), - Property('prop2', 'propOwner', 'propVal')]) + ch1 = Channel( + "ch1", + "chOwner", + properties=[ + Property("location", "propOwner", "234"), + Property("prop1", "propOwner", "propVal"), + ], + ) + ch2 = Channel( + "ch2", + "chOwner", + properties=[ + Property("location", "propOwner", "SR"), + Property("prop2", "propOwner", "propVal"), + ], + ) + ch3 = Channel( + "ch3", + "chOwner", + properties=[ + Property("location", "propOwner", "SR:234"), + Property("prop2", "propOwner", "propVal"), + ], + ) chs = [ch1, ch2, ch3] - values = ChannelUtil.getAllPropValues(chs, propertyName='location') - self.assertTrue('234' in values, \ - 'Failed to find property(location), value 234 for ch1') - self.assertTrue('SR' in values, \ - 'Failed to find property(location), value SR for ch2') - self.assertTrue('SR:234' in values, \ - 'Failed to find property(location), value SR:234 for ch3') + values = ChannelUtil.getAllPropValues(chs, propertyName="location") + self.assertTrue( + "234" in values, "Failed to find property(location), value 234 for ch1" + ) + self.assertTrue( + "SR" in values, "Failed to find property(location), value SR for ch2" + ) + self.assertTrue( + "SR:234" in values, + "Failed to find property(location), value SR:234 for ch3", + ) pass - - def testValidateWithTag(self): - ch1 = Channel('chName1', 'chOwner', - properties=[Property('location', 'propOwner', 'propVal'), - Property('prop1', 'propOwner', 'propVal')], - tags=[Tag('myTag', 'tagOwner')]) - ch2 = Channel('chName2', 'chOwner', - properties=[Property('location', 'propOwner', 'propVal'), - Property('prop2', 'propOwner', 'propVal')], - tags=[Tag('myTag', 'tagOwner'), - Tag('goldenOrbit', 'tagOwner')]) - self.assertTrue(ChannelUtil.validateChannelsWithTag([ch1, ch2], Tag('myTag', 'someOwner')), \ - 'Failed to validate channels based on TagValidator') - self.assertFalse(ChannelUtil.validateChannelsWithTag([ch1, ch2], Tag('goldenOrbit', 'someOwner')), \ - 'Failed to correctly validate channels based on a TagValidator') + + def testValidateWithTag(self): + ch1 = Channel( + "chName1", + "chOwner", + properties=[ + Property("location", "propOwner", "propVal"), + Property("prop1", "propOwner", "propVal"), + ], + tags=[Tag("myTag", "tagOwner")], + ) + ch2 = Channel( + "chName2", + "chOwner", + properties=[ + Property("location", "propOwner", "propVal"), + Property("prop2", "propOwner", "propVal"), + ], + tags=[Tag("myTag", "tagOwner"), Tag("goldenOrbit", "tagOwner")], + ) + self.assertTrue( + ChannelUtil.validateChannelsWithTag([ch1, ch2], Tag("myTag", "someOwner")), + "Failed to validate channels based on TagValidator", + ) + self.assertFalse( + ChannelUtil.validateChannelsWithTag( + [ch1, ch2], Tag("goldenOrbit", "someOwner") + ), + "Failed to correctly validate channels based on a TagValidator", + ) pass - + def testValidateWithProperty(self): - ch1 = Channel('ch1', 'chOwner', - properties=[Property('location', 'propOwner', '234'), - Property('prop1', 'propOwner', 'propVal')]) - ch2 = Channel('ch2', 'chOwner', - properties=[Property('location', 'propOwner', 'SR'), - Property('prop2', 'propOwner', 'propVal')]) - ch3 = Channel('ch3', 'chOwner', - properties=[Property('location', 'propOwner', 'SR:234'), - Property('prop2', 'propOwner', 'propVal')]) - self.assertTrue(ChannelUtil.validateChannelWithProperty([ch2, ch3], Property('prop2', 'anyOwner', 'propVal'))) - self.assertFalse(ChannelUtil.validateChannelWithProperty([ch1, ch2, ch3], Property('prop2', 'anyOwner', 'propVal')), \ - 'Failed to correctly validate channels based on a PropertyValidator') + ch1 = Channel( + "ch1", + "chOwner", + properties=[ + Property("location", "propOwner", "234"), + Property("prop1", "propOwner", "propVal"), + ], + ) + ch2 = Channel( + "ch2", + "chOwner", + properties=[ + Property("location", "propOwner", "SR"), + Property("prop2", "propOwner", "propVal"), + ], + ) + ch3 = Channel( + "ch3", + "chOwner", + properties=[ + Property("location", "propOwner", "SR:234"), + Property("prop2", "propOwner", "propVal"), + ], + ) + self.assertTrue( + ChannelUtil.validateChannelWithProperty( + [ch2, ch3], Property("prop2", "anyOwner", "propVal") + ) + ) + self.assertFalse( + ChannelUtil.validateChannelWithProperty( + [ch1, ch2, ch3], Property("prop2", "anyOwner", "propVal") + ), + "Failed to correctly validate channels based on a PropertyValidator", + ) pass + if __name__ == "__main__": - #import sys;sys.argv = ['', 'Test.testChannelUtil'] unittest.main()