Commit d47ab421 authored by József Gyürüsi's avatar József Gyürüsi
Browse files

[internal #1848537] Upgrade scripts to use Python3



Change-Id: Ic1e6b456257f08a273cfbdf699eedc2c360cb3fe
Signed-off-by: József Gyürüsi's avatarJózsef Gyürüsi <jozsef.gyurusi@ericsson.com>
parent 359e539b
......@@ -13,30 +13,30 @@ import json
import time
from DsRestAPI import *
print "###############################"
print "Initializing the DsRestAPI Python API"
print "-------------------------------"
print("###############################")
print("Initializing the DsRestAPI Python API")
print("-------------------------------")
api = DsRestAPI("http://localhost:9876/")
print "###############################"
print "Getting help for DataSource Sources element."
print "-------------------------------"
print("###############################")
print("Getting help for DataSource Sources element.")
print("-------------------------------")
print api.getHelp("DataSource", "Sources")
print(api.getHelp("DataSource", "Sources"))
print "###############################"
print "Getting the DataSource Sources element."
print "-------------------------------"
print("###############################")
print("Getting the DataSource Sources element.")
print("-------------------------------")
print api.getData("DataSource", "Sources")
print(api.getData("DataSource", "Sources"))
print "###############################"
print "Pressing the exit button."
print "-------------------------------"
print("###############################")
print("Pressing the exit button.")
print("-------------------------------")
request = """
[
......@@ -51,4 +51,4 @@ request = """
]
"""
print api.getList(json.loads(request))
print(api.getList(json.loads(request)))
......@@ -8,11 +8,11 @@
#// https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html //
#///////////////////////////////////////////////////////////////////////////////
import urllib2
import urllib.request, urllib.error, urllib.parse
import json
url = "http://localhost:3164/titansim.ajaxcall"
json_data = json.dumps({"requests":[ {"getData":{ "source":"ExecCtrl", "element":"Start", "ptcname":"", "params":[] }} ]})
request = urllib2.Request(url, json_data, {'Content-Type': 'text'})
response = urllib2.urlopen(request).read()
request = urllib.request.Request(url, json_data, {'Content-Type': 'text'})
response = urllib.request.urlopen(request).read()
print response
print(response)
......@@ -10,7 +10,7 @@
#///////////////////////////////////////////////////////////////////////////////
import sys
import urllib2
import urllib.request, urllib.error, urllib.parse
import json
class DsRestAPI:
......@@ -23,23 +23,23 @@ class DsRestAPI:
p_url += '/'
self.__url = p_url
self.__url += "api.dsapi"
self._urlOpener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.ProxyHandler({} if not p_useProxy else None))
self._urlOpener = urllib.request.build_opener(urllib.request.HTTPHandler(), urllib.request.ProxyHandler({} if not p_useProxy else None))
def __httpcall(self, postdata, method = 'POST'):
'''
Does a HTTP Request against the specified URL, with the optional POSTDATA piggyback, setting the method to the optional HTTP Verb.
Returns the HTTP Response body.
'''
if not isinstance(postdata, basestring):
if not isinstance(postdata, str):
postdata = json.dumps(postdata)
req = urllib2.Request(self.__url, postdata, {'Content-Type': 'application/json'})
req = urllib.request.Request(self.__url, postdata, {'Content-Type': 'application/json'})
req.add_header('Connection', 'close')
req.get_method = lambda: method
try:
return self._urlOpener.open(req).read()
except Exception as e:
msg = 'Error connecting to server: ' + str(e)
proxyList = [name[0:-5] for name in dir(urllib2.ProxyHandler()) if name.endswith('open')];
proxyList = [name[0:-5] for name in dir(urllib.request.ProxyHandler()) if name.endswith('open')];
if 'http' in proxyList and self.__useProxy:
msg += '\\nThe error may be caused by wrong proxy settings. Current possible poxys are: \\n' + ' '.join(proxyList)
msg += '\\nPlease try to use -noproxy option.'
......@@ -85,52 +85,52 @@ class DsRestAPI:
return help
def usage():
print "Usage:"
print sys.argv[0], "-?"
print sys.argv[0], "[-u <URL>] [-noproxy] -h [source [element]]"
print sys.argv[0], "[-u <URL>] [-noproxy] -f file"
print sys.argv[0], "[-u <URL>] [-noproxy] -j jsonString"
print sys.argv[0], "[-u <URL>] [-noproxy] -source <Source> -element <Element> [-ptcname <PTCName>] [-params <ParamName1 ParamValue1 ParamName2 ParamValue2 ...>] [-content <Content> -tp <Tp> [-indxsInList index1 index2]]"
print "All parameters that are sent to the server are case sensitive."
print "Legend:"
print "\t-?\t\tLocal usage"
print "\t-u\t\tThe URL of the remote server, it is http://localhost:4001 by default."
print "\t-noproxy\tSet this option to disable proxy usage."
print "\t-h\t\tHelp from remote server. Accepts 2 optional arguments to filter on Source, or on Source-specific Element."
print "\t-f\t\tLoad request from a file."
print "\t-j\t\tThe json string as the request. WARNING: use single ' to enclose the string."
print ""
print "List of types for the -tp parameter and their meaning:"
print "\t 1: intType"
print "\t 2: floatType"
print "\t 3: boolType"
print "\t 4: charstringType"
print "\t 5: octetstringType"
print "\t 6: hexstringType"
print "\t 7: bitstringType"
print "\t 8: integerlistType"
print "\t 9: floatlistType"
print "\t10: charstringlistType"
print "\t11: statusLEDType"
print ""
print "Examples:"
print "DataSource help:\t", sys.argv[0], ' -h'
print "Source filtered help:\t", sys.argv[0], ' -h ExecCtrl'
print "Help for an element:\t", sys.argv[0], ' -h ExecCtrl ScGrpStart'
print "Simple GetData request:\t", sys.argv[0], ' -source ExecCtrl -element Progressbar'
print "Use different address:\t", sys.argv[0], ' -u http://127.0.0.1:9876 -source ExecCtrl -element Progressbar'
print "Use without proxy:\t", sys.argv[0], ' -u http://127.0.0.1:4001 -noproxy -source ExecCtrl -element Progressbar'
print "GetData with params:\t", sys.argv[0], ' -source ExecCtrl -element ScGrpStart -params ScenarioGroup ScGroup1'
print "SetData example:\t", sys.argv[0], ' -source ExecCtrl -element ScGrpStart -content true -tp 3 -params ScenarioGroup ScGroup1'
print "GetData from JSON:\t", sys.argv[0], ' -j \'[{"getData": {"source": "ExecCtrl", "element": "ScGrpStart", "params": [{"paramName": "ScenarioGroup", "paramValue": "ScGroup1"}]}}]\''
print "SetData from JSON:\t", sys.argv[0], ' -j \'[{"setData": {"source": "ExecCtrl", "element": "ScGrpStart", "params": [{"paramName": "ScenarioGroup", "paramValue": "ScGroup1"}], "tp": 3, "content": "true"}}]\''
print "Request from file:\t", sys.argv[0], ' -f path/to/request/request.json'
print("Usage:")
print(sys.argv[0], "-?")
print(sys.argv[0], "[-u <URL>] [-noproxy] -h [source [element]]")
print(sys.argv[0], "[-u <URL>] [-noproxy] -f file")
print(sys.argv[0], "[-u <URL>] [-noproxy] -j jsonString")
print(sys.argv[0], "[-u <URL>] [-noproxy] -source <Source> -element <Element> [-ptcname <PTCName>] [-params <ParamName1 ParamValue1 ParamName2 ParamValue2 ...>] [-content <Content> -tp <Tp> [-indxsInList index1 index2]]")
print("All parameters that are sent to the server are case sensitive.")
print("Legend:")
print("\t-?\t\tLocal usage")
print("\t-u\t\tThe URL of the remote server, it is http://localhost:4001 by default.")
print("\t-noproxy\tSet this option to disable proxy usage.")
print("\t-h\t\tHelp from remote server. Accepts 2 optional arguments to filter on Source, or on Source-specific Element.")
print("\t-f\t\tLoad request from a file.")
print("\t-j\t\tThe json string as the request. WARNING: use single ' to enclose the string.")
print("")
print("List of types for the -tp parameter and their meaning:")
print("\t 1: intType")
print("\t 2: floatType")
print("\t 3: boolType")
print("\t 4: charstringType")
print("\t 5: octetstringType")
print("\t 6: hexstringType")
print("\t 7: bitstringType")
print("\t 8: integerlistType")
print("\t 9: floatlistType")
print("\t10: charstringlistType")
print("\t11: statusLEDType")
print("")
print("Examples:")
print("DataSource help:\t", sys.argv[0], ' -h')
print("Source filtered help:\t", sys.argv[0], ' -h ExecCtrl')
print("Help for an element:\t", sys.argv[0], ' -h ExecCtrl ScGrpStart')
print("Simple GetData request:\t", sys.argv[0], ' -source ExecCtrl -element Progressbar')
print("Use different address:\t", sys.argv[0], ' -u http://127.0.0.1:9876 -source ExecCtrl -element Progressbar')
print("Use without proxy:\t", sys.argv[0], ' -u http://127.0.0.1:4001 -noproxy -source ExecCtrl -element Progressbar')
print("GetData with params:\t", sys.argv[0], ' -source ExecCtrl -element ScGrpStart -params ScenarioGroup ScGroup1')
print("SetData example:\t", sys.argv[0], ' -source ExecCtrl -element ScGrpStart -content true -tp 3 -params ScenarioGroup ScGroup1')
print("GetData from JSON:\t", sys.argv[0], ' -j \'[{"getData": {"source": "ExecCtrl", "element": "ScGrpStart", "params": [{"paramName": "ScenarioGroup", "paramValue": "ScGroup1"}]}}]\'')
print("SetData from JSON:\t", sys.argv[0], ' -j \'[{"setData": {"source": "ExecCtrl", "element": "ScGrpStart", "params": [{"paramName": "ScenarioGroup", "paramValue": "ScGroup1"}], "tp": 3, "content": "true"}}]\'')
print("Request from file:\t", sys.argv[0], ' -f path/to/request/request.json')
def printHumanReadableResponse(response):
if "list" in response:
print [str(listElement["node"]["val"]) for listElement in response["list"]]
print([str(listElement["node"]["val"]) for listElement in response["list"]])
else:
print response["node"]["val"]
print(response["node"]["val"])
def DsRestAPIPythonAPIMain(argv):
argv = argv[1:]
......@@ -152,25 +152,25 @@ def DsRestAPIPythonAPIMain(argv):
if '-?' in argv or len(argv) == 0:
usage()
elif '-g' in argv or '-s' in argv:
print '-g and -s parameters are not supported anymore due to an interface rationalization. Please update your request according to the new behavior.'
print('-g and -s parameters are not supported anymore due to an interface rationalization. Please update your request according to the new behavior.')
elif '-h' in argv:
i = argv.index('-h')
if i + 2 < len(argv):
print api.getHelp(argv[i+1], argv[i+2])
print(api.getHelp(argv[i+1], argv[i+2]))
elif i + 1 < len(argv):
print api.getHelp(argv[i+1])
print(api.getHelp(argv[i+1]))
else:
print api.getHelp()
print(api.getHelp())
elif '-f' in argv:
fileName = argv[argv.index('-f') + 1]
f = open(fileName, 'r')
request = json.load(f)
f.close()
print api.getContentList(request)
print(api.getContentList(request))
elif '-j' in argv:
jsonString = argv[argv.index('-j') + 1]
request = json.loads(jsonString)
print api.getContentList(request)
print(api.getContentList(request))
else:
requests = []
request = {}
......@@ -181,7 +181,7 @@ def DsRestAPIPythonAPIMain(argv):
i = 0
while i < len(argv):
if i + 1 >= len(argv):
print 'Suspicious parameter detected:', argv[i]
print('Suspicious parameter detected:', argv[i])
i += 1
elif argv[i] == '-source' and not argv[i+1].startswith('-'):
request['source'] = argv[i+1]
......@@ -211,7 +211,7 @@ def DsRestAPIPythonAPIMain(argv):
request['indxsInList'].append(int(argv[i]))
i += 1
else:
print 'Suspicious parameter detected:', argv[i]
print('Suspicious parameter detected:', argv[i])
i += 1
printHumanReadableResponse(api.get(requests))
return 0
......@@ -221,5 +221,5 @@ if __name__ == "__main__":
try:
errCode = DsRestAPIPythonAPIMain(sys.argv)
except Exception as e:
print 'Error while processing your request: ' + str(e)
print('Error while processing your request: ' + str(e))
sys.exit(errCode)
\ No newline at end of file
......@@ -8,7 +8,7 @@
#// https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html //
#///////////////////////////////////////////////////////////////////////////////
import urllib2
import urllib.request, urllib.error, urllib.parse
import json
import sys
from DsRestAPI import *
......@@ -20,4 +20,4 @@ requestToSend = json.loads(request)["requests"];
url = "http://localhost:" + serverPortNum
api = DsRestAPI(url)
print api.getContentList(requestToSend)
print(api.getContentList(requestToSend))
......@@ -35,9 +35,9 @@ class BaseTestCase(unittest.TestCase):
x = 0
while (x < jsErrorsLength):
if (x == 0):
print '\n*** Test id :', self.id()
print('\n*** Test id :', self.id())
javaScript = "return window.jsErrors[" + str(x) + "] "
print self.driver.execute_script(javaScript) + '\n'
print(self.driver.execute_script(javaScript) + '\n')
x += 1
self.driver.quit()
......
......@@ -157,7 +157,7 @@ def __writeGrpFile(tpdFileName):
return set() # tpd was already processed, return empty set
if not path.exists(grpFile):
print 'Writing file ',grpFile,' ...'
print('Writing file ',grpFile,' ...')
with open(grpFile,'w') as f:
f.write(__getGrp(tpdFileName, projectName,referencedProjects,fileResources))
......@@ -176,7 +176,7 @@ def generatePrj(tpdFileName):
#print 'File already generated: ',prjFileName,' ...'
return # prj was already generated, nothing to do
print 'Writing file ',prjFileName+' ...'
print('Writing file ',prjFileName+' ...')
with open(prjFileName,'w') as f:
f.write(__getPrj(tpdFileName))
......@@ -215,5 +215,5 @@ if __name__ == '__main__':
generatePrj(tpdfile)
except Exception as e:
parser.print_help()
print e
print(e)
exit(1)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment