diff --git a/booster_api/features/src/poc2.py b/booster_api/features/src/poc2.py index e7d75eea..5b04e97b 100644 --- a/booster_api/features/src/poc2.py +++ b/booster_api/features/src/poc2.py @@ -19,7 +19,7 @@ def runTest(self, theString): projectName = os.environ.get('PROJECT_NAME') pipeline = os.environ.get('PIPELINE') spaceId = helpers.getSpaceID() - authHeader = 'Bearer ' + theToken + authHeader = 'Bearer {}'.format(theToken) print 'starting test.....' @@ -37,7 +37,7 @@ def runTest(self, theString): print 'making request ...' r = requests.post('https://forge.api.openshift.io/api/osio/import', headers=headers, data=data) - print 'request results = ' + r.text + print 'request results = {}'.format(r.text) result = r.text if re.search('uuid' , result): diff --git a/booster_api/features/src/space.py b/booster_api/features/src/space.py index 287f7eaa..fe5d9012 100644 --- a/booster_api/features/src/space.py +++ b/booster_api/features/src/space.py @@ -16,7 +16,7 @@ def createSpace(self, spaceName): serverAddress = os.getenv("SERVER_ADDRESS") - authHeader = 'Bearer ' + theToken + authHeader = 'Bearer {}'.format(theToken) headers = {'Accept': 'application/json', 'Authorization': authHeader, @@ -24,20 +24,24 @@ def createSpace(self, spaceName): 'X-Git-Provider': 'GitHub', 'Content-Type': 'application/json'} - data = '{\ - "data": {\ - "attributes": {\ + data = '{{\ + "data": {{\ + "attributes": {{\ "description": "This is the osioperf collaboration space",\ - "name": "' + spaceName + '"\ - },\ + "name": "{}"\ + }},\ "type": "spaces"\ - }\ - }' + }}\ + }}'.format(spaceName) print 'making request ...' - r = requests.post(serverAddress + '/api/spaces', headers=headers, data=data) - print 'request results = ' + r.content + r = requests.post( + '{}/api/spaces'.format(serverAddress), + headers=headers, + data=data + ) + print 'request results = {}'.format(r.content) try: respJson = r.json() diff --git a/booster_api/features/src/support/helpers.py b/booster_api/features/src/support/helpers.py index 6f8ce467..42b67e73 100644 --- a/booster_api/features/src/support/helpers.py +++ b/booster_api/features/src/support/helpers.py @@ -21,11 +21,16 @@ def get_user_tokens(index=0): def create_space_name(template="BDD"): var = datetime.datetime.now() var = var.isoformat().rsplit('.')[0] - space = os.getenv("OSIO_USERNAME") + "-" + template + "-space-" + var + space = "{}-{}-space-{}".format( + os.getenv("OSIO_USERNAME"), + template, + var + ) + space = space.replace('@','-') space = space.replace(':','-') space = space.replace('.','-') - print 'The spacename is: ' + space + print "The spacename is: {}".format(space) return space def getSpaceID(): @@ -145,7 +150,7 @@ def generate_entity_names(static_string=None, no_of_names=1, reverse=False, rese total_entities = count + no_of_names for i in xrange(count, total_entities): if static_string is not None: - mylist.append(static_string + "_" + str(i)) + mylist.append("{}_{}".format(static_string,str(i))) else: mylist.append(i) #Updating global counter @@ -161,7 +166,7 @@ def create_workitem_SDD(title=None, spaceid=None, witype=None, iterationid=None) return None ## Create workitems in Iterations context elif iterationid is not None: - api = "api/spaces/" + spaceid + "/workitems" + api = "api/spaces/{}/workitems".format(spaceid) url = constants.launch_detail.create_url(api) f = read_post_data_file('create_wi_in_iter.json', replace={'$wi_nos_generated':title, '$witype': witype, '$iteration_id': iterationid}) r = req.post(url, headers=constants.request_detail.headers_default, json=f) @@ -170,7 +175,7 @@ def create_workitem_SDD(title=None, spaceid=None, witype=None, iterationid=None) return r ## Create workitems in backlog view else: - api = "api/spaces/" + spaceid + "/workitems" + api = "api/spaces/{}/workitems".format(spaceid) url = constants.launch_detail.create_url(api) f = read_post_data_file('create_wi_in_backlog.json', replace={'$wi_nos_generated':title, '$witype': witype}) r = req.post(url, headers=constants.request_detail.headers_default, json=f) @@ -184,7 +189,7 @@ def create_workitem_SCRUM(title=None, spaceid=None, witype=None, iterationid=Non return None ## Create workitems in Iterations context elif iterationid is not None: - api = "api/spaces/" + spaceid + "/workitems" + api = "api/spaces/{}/workitems".format(spaceid) url = constants.launch_detail.create_url(api) if witype == constants.workitem_constants.witypetask1: f = read_post_data_file('create_wi_in_iter_scrum.json', replace={'$wi_nos_generated':title, '$witype': witype, '$state': 'To Do', '$iteration_id': iterationid}) @@ -196,7 +201,7 @@ def create_workitem_SCRUM(title=None, spaceid=None, witype=None, iterationid=Non return r ## Create workitems in backlog view else: - api = "api/spaces/" + spaceid + "/workitems" + api = "api/spaces/{}/workitems".format(spaceid) url = constants.launch_detail.create_url(api) if witype == constants.workitem_constants.witypetask1: f = read_post_data_file('create_wi_in_backlog_scrum.json', replace={'$wi_nos_generated':title, '$witype': witype, '$state': 'To Do'}) @@ -213,7 +218,7 @@ def add_workitem_comment(workitem_link=None, comment_text=None): return None else: ## Add a comment to the workitem - wi_comment_api = workitem_link + "/comments" + wi_comment_api = "{}/comments".format(workitem_link) f = read_post_data_file('add_wi_comment.json', replace={'$comment_text':comment_text}) return req.post(wi_comment_api, headers=constants.request_detail.headers_default, json=f) @@ -223,7 +228,7 @@ def create_new_label(label_text=None): return None else: ## Add a Label to the space - create_label_api = "api/spaces/" + constants.dynamic_vars.spaceid + "/labels" + create_label_api = "api/spaces/{}/labels".format(constants.dynamic_vars.spaceid) url = constants.launch_detail.create_url(create_label_api) f = read_post_data_file('create_label.json', replace={'$label_name':label_text}) return req.post(url, headers=constants.request_detail.headers_default, json=f) @@ -270,7 +275,7 @@ def delete_space(spaceid=None): return None else: ## Delete a space - api = "api/spaces/" + spaceid + api = "api/spaces/{}".format(spaceid) url = constants.launch_detail.create_url(api) r = req.delete(url, headers=constants.request_detail.headers_default) return r diff --git a/booster_api/features/src/support/loginusers_oauth2.py b/booster_api/features/src/support/loginusers_oauth2.py index 8096e645..858c4588 100644 --- a/booster_api/features/src/support/loginusers_oauth2.py +++ b/booster_api/features/src/support/loginusers_oauth2.py @@ -20,6 +20,7 @@ user_tokens = [] + class LoginUsersOauth2: timeout = 60 @@ -55,14 +56,17 @@ def __init__(self, username="", password=""): self.clientId = os.getenv("AUTH_CLIENT_ID") - self.redirectUrl = self.baseUrl + "/api/status" + self.redirectUrl = "{}/api/status".format(self.baseUrl) self.userTokensIncludeUsername = ( - os.getenv("USER_TOKENS_INCLUDE_USERNAME", "False") == "True") + os.getenv("USER_TOKENS_INCLUDE_USERNAME", "False") == "True" + ) if username == "" or password == "": usersPropertiesFile = os.getenv( - "USERS_PROPERTIES_FILE", "users.properties") + "USERS_PROPERTIES_FILE", + "users.properties" + ) usersProperties = open(usersPropertiesFile) @@ -75,7 +79,6 @@ def __init__(self, username="", password=""): self.userNames.append(username) self.userPasswords.append(password) - def reset_timer(self): self.start = time.time() @@ -99,21 +102,33 @@ def wait_for_url(self, url_contains): ) def log(self, msg): - print "[INFO] " + str(msg) + print "[INFO] {}".format( + str(msg) + ) def report_success(self, name, response_time): - self.log("[OK] " + name + ":" + str(response_time) + "ms") + self.log( + "[OK] {}:{}ms".format( + name, + str(response_time) + ) + ) def report_failure(self, name, response_time, msg): traceback.print_exc() - self.log("[ERROR] " + name + ":" + str(response_time) + "ms") + self.log( + "[ERROR] {}:{}ms".format( + name, + str(response_time) + ) + ) self.driver.quit() def save_snapshot(self, name): - self.driver.save_screenshot(name + ".png") + self.driver.save_screenshot("{}.png".format(name)) def save_browser_log(self, name): - f = open(name + ".log", "w") + f = open("{}.log".format(name), "w") f.write(str(self.driver.get_log('browser'))) def login(self, userIndex=0, _failed=False): @@ -129,27 +144,38 @@ def login(self, userIndex=0, _failed=False): if not failed: self.reset_timer() try: - startUrl = self.baseUrl + "/api/authorize?response_type=code&client_id=" + \ - self.clientId + "&redirect_uri=" + self.redirectUrl + "&state=" + state + startUrl = '{}/api/authorize?response_type=code&client_id={}&redirect_uri={}&state={}'.format( + self.baseUrl, + self.clientId, + self.redirectUrl, + state + ) self.driver.get(startUrl) self.wait_for_clickable_element(By.ID, "kc-login") rt = self.tick_timer() self.metrics[metric].append(rt) - self.report_success(userName + "-" + metric, rt) + self.report_success("{}-{}".format(userName, metric), rt) except Exception as ex: - self.report_failure(userName + "-" + metric, - self.tick_timer(), str(ex)) + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + str(ex) + ) failed = True else: - self.report_failure(userName + "-" + metric, - self.tick_timer(), "Timeout") + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + "Timeout" + ) rt_get_code = -1 metric = "get-code" if not failed: try: self.driver.find_element_by_id( - "username").send_keys(self.userNames[userIndex]) + "username" + ).send_keys(self.userNames[userIndex]) passwd = self.driver.find_element_by_id("password") passwd.send_keys(self.userPasswords[userIndex]) @@ -161,57 +187,87 @@ def login(self, userIndex=0, _failed=False): code = urlparse.parse_qs(parsed.query)['code'][0] rt_get_code = self.tick_timer() self.metrics[metric].append(rt_get_code) - self.report_success(userName + "-" + metric, rt_get_code) + self.report_success( + "{}-{}".format(userName, metric), + rt_get_code + ) except Exception as ex: - self.report_failure(userName + "-" + metric, - self.tick_timer(), str(ex)) + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + str(ex) + ) failed = True else: - self.report_failure(userName + "-" + metric, - self.tick_timer(), "Timeout") + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + "Timeout" + ) global user_tokens metric = "get-token" if not failed: self.reset_timer() try: - data = "grant_type=authorization_code&client_id=" + self.clientId + \ - "&code=" + code + "&redirect_uri=" + self.redirectUrl + data = "grant_type=authorization_code&client_id={}&code={}&redirect_uri={}".format( + self.clientId, + code, + self.redirectUrl + ) headers = {"Content-type": "application/x-www-form-urlencoded"} - tokenUrl = self.baseUrl + "/api/token" + tokenUrl = "{}/api/token".format(self.baseUrl) response = requests.post(tokenUrl, data, headers=headers) content = response.content try: resp_json = response.json() if not response.ok: self.report_failure( - userName + "-" + metric, + "{}-{}".format(userName, metric), self.tick_timer(), - "Got wrong response: [" + content + "]" + "Got wrong response: [{}]".format(content) ) else: rt = self.tick_timer() - out = resp_json["access_token"] + \ - ";" + resp_json["refresh_token"] + out = "{};{}".format( + resp_json["access_token"], + resp_json["refresh_token"] + ) if self.userTokensIncludeUsername: - out += ";" + self.userNames[userIndex] + out = "{};{}".format( + out, + self.userNames[userIndex] + ) user_tokens.append(out) self.metrics[metric].append(rt) - self.report_success(userName + "-" + metric, rt) + self.report_success( + "{}-{}".format(userName, metric), + rt + ) self.metrics["login"].append(rt + rt_get_code) self.report_success( - userName + "-" + "login", rt+rt_get_code) + "{}-login".format(userName), + rt+rt_get_code + ) except ValueError: - response.failure("Got wrong response: [" + content + "]") + response.failure( + "Got wrong response: [{}]".format(content) + ) except Exception as ex: - self.report_failure(userName + "-" + metric, - self.tick_timer(), str(ex)) + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + str(ex) + ) failed = True else: - self.report_failure(userName + "-" + metric, - self.tick_timer(), "Timeout") + self.report_failure( + "{}-{}".format(userName, metric), + self.tick_timer(), + "Timeout" + ) return failed @@ -229,7 +285,7 @@ def login_users(self): del user_tokens[:] n = 0 for u in self.userNames: - self.log("Loggin user " + u + " in") + self.log("Loggin user {} in".format(u)) if self.maxUsers > 0 and n >= self.maxUsers: break self.driver = webdriver.Chrome(chrome_options=opts) @@ -238,17 +294,27 @@ def login_users(self): n += 1 if not failed: - self.log("All " + str(n) + " users done.") + self.log("All {} users done.".format(str(n))) for k in self.metrics.keys(): mSorted = self.metrics[k] mSorted.sort() - self.log(k + "-time-stats:count=" + str(n) + ";min=" + str( - mSorted[0]) + ";med=" + str(mSorted[int(n/2)]) + ";max=" + str(mSorted[n-1])) + self.log( + "{}-time-stats:count={};min={};med={};max={}".format( + k, + n, + mSorted[0], + mSorted[int(n/2)], + mSorted[int(n-1)] + ) + ) else: - self.report_failure("global", - (time.time() - overall_start) * 1000, "Something went wrong.") + self.report_failure( + "global", + (time.time() - overall_start) * 1000, + "Something went wrong." + ) except NoSuchWindowException: sys.exit(1) diff --git a/booster_api/features/steps/import.py b/booster_api/features/steps/import.py index e419562f..142959fa 100644 --- a/booster_api/features/steps/import.py +++ b/booster_api/features/steps/import.py @@ -12,7 +12,7 @@ def step_impl(context): def step_impl(context): global result result = poc.runTest('testing 1234567890') - print ('Result = ' + result) + print ('Result = {}'.format(result)) @then(u'I should see "Success"') def step_impl(context):