Best Python code snippet using toolium_python
handler.py
Source:handler.py
...68 options.add_argument('--single-process')69 options.add_argument('--disable-dev-shm-usage')70 options.add_argument("--homedir=/tmp")71 return webdriver.Chrome('/opt/chromedriver', chrome_options=options)72def wait_until_element_present(driver, key, location):73 """ Wait until element is presented at location """74 elm = None75 counter = 076 timeup = 1077 while counter < timeup:78 try:79 elm = WebDriverWait(driver, counter).until(80 EC.presence_of_element_located((key, location)))81 except NoSuchElementException as e:82 logger.warn("[WARN] {e}".format(e=e))83 logger.warn("counter: {val}".format(val=counter))84 counter += 1 85 continue86 except TimeoutException as e:87 logger.warn("[WARN] {e}".format(e=e))88 logger.warn("counter: {val}".format(val=counter))89 counter += 190 continue91 else:92 break93 94 return elm95def get_text_by_xpath(driver, location):96 return driver.find_element_by_xpath(location).text97def save_screenshot(driver, filename):98 """ Save screenshot at Amazon S3 """99 logging.info("SSåå¾ãéå§ãã¾ãã")100 driver.save_screenshot("/tmp/" + filename)101 logging.info("SSåå¾ãå®äºãã¾ããã")102 return103def terminate_driver(driver):104 """ Terminate driver """105 driver.close()106 driver.quit()107 return108def get_otp():109 """ get One Time Password """110 logging.info("OTPåå¾ãéå§ãã¾ãã")111 secret_key = MFA_SECRET_NAME112 secret_info = get_secret(secret_key)113 secret = secret_info.get(MFA_SECRET_KEY)114 otp = oathtool.generate_otp(secret)115 logging.info("OTPåå¾ãå®äºãã¾ããã")116 return otp117def create_slack_message(event):118 if not event:119 slack_message = "Emergency Alert (Test)<!channel>"120 else:121 message = json.loads(event['Records'][0]['Sns']['Message'])122 logger.info("Message: " + str(message))123 alarm_name = message['AlarmName']124 new_state = message['NewStateValue']125 reason = message['NewStateReason']126 description = message['AlarmDescription']127 128 slack_message = "Emergency Alert <!channel> \nã¢ã©ã¼ã åï¼ %s\nã¹ãã¼ã¿ã¹ï¼ %s\nã¢ã©ã¼ã çç±ï¼ %s\n説æï¼ %s" % (alarm_name, new_state, reason, description)129 print(slack_message)130 return slack_message131def post_slack(message):132 """ POST to slack """133 logging.info("slackéç¥ãéå§ãã¾ãã")134 # APIãã¼ã¯ã³ãæå®135 secret_key = SLACK_BOT_SECRET_NAME136 secret_info = get_secret(secret_key)137 token = secret_info.get(SLACK_BOT_SECRET_KEY)138 client = WebClient(token=token)139 # ã¢ãããã¼ããããã£ã³ãã«ãæå®140 channel = SLACK_CHANNEL141 try:142 response = client.chat_postMessage(143 channel=channel,144 text=message)145 except SlackApiError as e:146 # You will get a SlackApiError if "ok" is False147 assert e.response["ok"] is False148 assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'149 logger.error("[ERROR] Got an error: " + {e.response['error']})150 thread_ts = response["ts"]151 # 絶対ãã¹ãæå®152 files = glob.glob('/tmp/*.png')153 # è¤æ°ãã¡ã¤ã«ã¢ãããã¼ãã¯slackAPIã¯ãµãã¼ãå¤154 for file in files:155 try:156 response = client.files_upload(157 channels=channel,158 file=file,159 thread_ts=thread_ts)160 assert response["file"] # the uploaded file161 logging.debug(file + "ãslackã¸æ稿ãã¾ããã")162 except SlackApiError as e:163 # You will get a SlackApiError if "ok" is False164 assert e.response["ok"] is False165 assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'166 logger.error("[ERROR] Got an error: " + {e.response['error']})167 logging.info("slackéç¥ãçµäºãã¾ãã")168def get_secret(secret_name):169 logging.info("get aws secret key")170 # Create a Secrets Manager client171 session = boto3.session.Session()172 region = session.region_name173 client = session.client(174 service_name='secretsmanager',175 region_name=region176 )177 try:178 get_secret_value_response = client.get_secret_value(179 SecretId=secret_name180 )181 except ClientError as e:182 if e.response['Error']['Code'] == 'DecryptionFailureException':183 # Secrets Manager can't decrypt the protected secret text using the provided KMS key.184 # Deal with the exception here, and/or rethrow at your discretion.185 raise e186 elif e.response['Error']['Code'] == 'InternalServiceErrorException':187 # An error occurred on the server side.188 # Deal with the exception here, and/or rethrow at your discretion.189 raise e190 elif e.response['Error']['Code'] == 'InvalidParameterException':191 # You provided an invalid value for a parameter.192 # Deal with the exception here, and/or rethrow at your discretion.193 raise e194 elif e.response['Error']['Code'] == 'InvalidRequestException':195 # You provided a parameter value that is not valid for the current state of the resource.196 # Deal with the exception here, and/or rethrow at your discretion.197 raise e198 elif e.response['Error']['Code'] == 'ResourceNotFoundException':199 # We can't find the resource that you asked for.200 # Deal with the exception here, and/or rethrow at your discretion.201 raise e202 else:203 # Decrypts secret using the associated KMS CMK.204 # Depending on whether the secret is a string or binary, one of these fields will be populated.205 if 'SecretString' in get_secret_value_response:206 secret = get_secret_value_response['SecretString']207 else:208 decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])209 210 secret = json.loads(get_secret_value_response.get('SecretString'))211 logging.info(secret_name + "ãåå¾ãã¾ããã")212 213 return secret214def delete_local_screenshot():215 """ delete local screenshot """216 files = glob.glob('/tmp/*.png')217 for file in files:218 os.remove(file)219 logging.debug(file + 'ãåé¤ãã¾ããã') 220 logging.info('ã¹ã¯ãªã¼ã³ã·ã§ãããåé¤ãã¾ããã') 221def main(event, context):222 """ Entrypoint of lambda """223 otp = get_otp()224 slack_message = create_slack_message(event)225 # Debug event to CloudWatch log226 starttime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')227 logging.info("starttime: {}".format(starttime))228 logging.info(json.dumps(event))229 driver = None230 target = None231 url = LOGIN_TARGET_URL232 login_info = get_secret(LOGIN_INFO_SECRET_NAME)233 login_id = login_info.get('username')234 login_pw = login_info.get('password')235 logging.info(login_id)236 try: 237 logging.info( url + "ã¸ã¢ã¯ã»ã¹ãã¾ãã")238 driver = set_selenium_options()239 driver.maximize_window()240 logging.info("ãã°ã¤ã³ãã¼ã¸ã¸ã¢ã¯ã»ã¹ãã¾ãã")241 driver.get(url)242 presented = wait_until_element_present(243 driver, By.ID, LOGIN_LOCATION)244 245 logging.info("ãã°ã¤ã³ãã¼ã¸ã¸ã¢ã¯ã»ã¹ãã¾ããã")246 input_id = driver.find_element_by_name('username')247 input_password = driver.find_element_by_name('password')248 input_id.send_keys(login_id)249 input_password.send_keys(login_pw)250 button_login = driver.find_element_by_class_name('buttoninput')251 logging.info("ãã°ã¤ã³ãã¿ã³ãæ¼ä¸ãã¾ãã")252 253 button_login.click()254 presented = wait_until_element_present(255 driver, By.ID, MFA_PAGE_LOCATION)256 logging.info("ãã°ã¤ã³ã«æåãã¾ãããMFAã³ã¼ããå
¥åãã¾ãã")257 second_pass = get_otp()258 second_input_pass = driver.find_element_by_id('mfacode')259 second_input_pass.send_keys(second_pass)260 logging.info("MFAéä¿¡ãã¿ã³ãæ¼ä¸ãã¾ãã")261 second_button_login = driver.find_element_by_class_name('css3button')262 second_button_login.click()263 presented = wait_until_element_present(264 driver, By.XPATH, CONSOLE_LOCATION)265 logging.info("ã³ã³ã½ã¼ã«ã¸ã®ãã°ã¤ã³ã«æåãã¾ããã")266 # CloudWatchããã·ã¥ãã¼ãã¸ã¢ã¯ã»ã¹267 driver.get(DASHBOARD_URL)268 presented = wait_until_element_present(269 driver, By.ID, DASHBOARD_LOCATION)270 271 filename = 'ss_' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S' + '.png')272 save_screenshot(driver, filename)273 if presented is not None:274 target = driver.find_element_by_xpath(DASHBOARD_LOCATION).text275 # PerformanceInsightã¸ã¢ã¯ã»ã¹276 driver.get(PI_URL)277 presented = wait_until_element_present(278 driver, By.XPATH, PI_LOCATION)279 change_duration_button = driver.find_element_by_xpath(PI_LOCATION)280 change_duration_button.click()281 driver.implicitly_wait(20)282 filename = 'ss_' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S' + '.png')283 save_screenshot(driver, filename)284 if presented is not None:285 target = driver.find_element_by_xpath(PI_LOCATION).text286 post_slack(slack_message)287 delete_local_screenshot()288 endtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')289 logging.info("endtime: {}".format(endtime))290 terminate_driver(driver)291 return {...
order_class.py
Source:order_class.py
1from lib.ui_lib import *2class OrderClass(CommonMethods):3 def get_order_number(self,browser):4 element = self.wait_until_element_present('//div[@class = "alert alert-success"]/p', "XPATH")5 browser_success_msg = element.text6 order_number = browser_success_msg[7:10]7 assert order_number != ''8 return order_number9 def search_order(self,browser,orderID):10 self.wait_until_element_present('keyword-filter', 'ID')11 e = browser.find_element_by_id('keyword-filter')12 e.send_keys(orderID)13 try:14 browser.find_element_by_xpath('//span[@class="responsive-hide"]').click()15 except NoSuchElementException:16 browser.find_element_by_css_selector('.action-divider .filter-button').click()17 except WebDriverException:18 pass19 def get_order_status(self,browser, url, Order_Id):20 browser.get(urlparse.urljoin(url, '/admin/index.php?ToDo=viewOrders'))21 element = self.wait_until_element_present('//input[@id="keyword-filter"]', "XPATH")22 element.clear()23 element.send_keys(Order_Id)24 browser.find_element_by_css_selector('.filter .btn-secondary').click()25 self.wait_until_element_present('status_' + Order_Id, 'ID')26 return browser.find_element_by_id('status_' + Order_Id).get_attribute('value')27 def refund_funds(self,browser, Order_Id):28 # Open order cog29 element = self.wait_until_element_present("//tr[@data-order-id = '" + Order_Id + "']", 'XPATH')30 element = element.find_element_by_class_name('dropdown-trigger')31 element.click()32 # Open Refund modal33 element = self.wait_until_element_present('Refund', 'LINK')34 element.click()35 # Refund transaction36 element = self.wait_until_element_present('//label[@for="refundType_full"]', 'XPATH')37 element.click()38 browser.find_element_by_id('refund-save').click()39 def capture_funds(self,browser, Order_Id):40 # Open order cog41 element = self.wait_until_element_present("//tr[@data-order-id = '" + Order_Id + "']", 'XPATH')42 element = element.find_element_by_class_name('dropdown-trigger')43 element.click()44 # Open capture modal45 element = self.wait_until_element_present('Capture Funds', 'LINK')46 element.click()47 # Process capture48 element = self.wait_until_element_present('#display-modal .dialog-actions .btn-primary', 'CSS_SELECTOR')49 element.click()50 def void_transaction(self,browser, Order_Id):51 # Open order cog52 element = self.wait_until_element_present("//tr[@data-order-id = '" + Order_Id + "']", 'XPATH')53 element = element.find_element_by_class_name('dropdown-trigger')54 element.click()55 # Open capture modal56 element = self.wait_until_element_present('Void Transaction', 'LINK')57 element.click()58 # Process capture59 element = self.wait_until_element_present('#display-modal .dialog-actions .btn-primary', 'CSS_SELECTOR')60 element.click()61 def delete_order(self,browser):62 browser.find_element_by_xpath('//label[@for = "order0"]').click()63 self.select_dropdown_value(browser, 'OrderActionSelect', 'Archive Selected')64 browser.find_element_by_id('action-confirm').click()65 try:66 alert = browser.switch_to_alert()67 alert.accept()68 except WebDriverException:69 browser.execute_script("window.confirm = function(){return true;}");70 browser.find_element_by_id('action-confirm').click()71 #Verify Order delete72 element = self.wait_until_element_present('//div[@class = "alert alert-success"]/p', "XPATH").text73 assert "The selected orders have been deleted successfully." in element74 def goto_view_orders(self,browser):75 self.wait_until_element_present('Orders', 'LINK').click()76 self.wait_until_element_present('View Orders', 'LINK').click()77 def cp_add_order_item(self,browser,name):78 #Add an Item79 element = self.wait_until_element_present('quote-item-search', "ID")80 element.click()81 element.send_keys(name)82 self.wait_until_element_present('//div[@class = "recordContent undefined"]', 'XPATH')83 browser.execute_script("$('#quote-item-search').trigger('keyup')")84 browser.execute_script("$('.recordContent:eq(0)').trigger('click')")85 self.wait_until_element_present('//span[@class = "swatchColour swatchColour_1"]', "XPATH")86 browser.find_element_by_xpath('//span[@class = "swatchColour swatchColour_1"]').click()87 browser.find_element_by_id('dialog-options-submit').click()88 self.wait_until_element_present('//th[@class = "image"]', "XPATH")89 browser.find_element_by_xpath('//button[text() = "Next"]').click()90 self.wait_until_element_present('//label[@for = "shipping-single"]', 'XPATH')91 def cp_select_shipping_payment(self,browser, paymentname):92 browser.find_element_by_xpath('//label[@for = "shipping-single"]').click()93 browser.find_element_by_xpath('//button[text() = "Next"]').click()94 self.wait_until_element_present("//select[@id='paymentMethod']/option[text()='"+paymentname+"']", "XPATH").click()95 self.find_element_by_css_selector('.Field_custom_name input')96 self.execute_script("$('.Field_custom_name input').val('"+paymentname+"');")97 browser.find_element_by_xpath('//button[@class = "btn btn-primary orderMachineSaveButton orderSaveButton"]').click()98 def create_order_controlpanel(self,browser, email, password, firstname, lastname,company,phone,street_add1,street_add2,city,country,state,postcode, invalid_email,invalid_pwd):99 element = self.wait_until_element_present('Orders', "LINK")100 element.click()101 browser.find_element_by_link_text('Add an Order').click()102 element = self.wait_until_element_present('//label[@for = "check-new-customer"]', "XPATH")103 element.click()104 #Validation for Invalid Email105 browser.find_element_by_id('FormField_1').send_keys(invalid_email)106 browser.find_element_by_xpath('//button[text() = "Next"]').click()107 assert "Please enter a valid email address such as joe@example.com" in browser.find_element_by_xpath('//div[@class = "dialog-content"]/p').text108 browser.find_element_by_css_selector('#display-modal .btn-primary').click()109 browser.find_element_by_id('FormField_1').clear()110 browser.find_element_by_id('FormField_1').send_keys(email)111 #Validation for Invalid Password112 browser.find_element_by_id('FormField_2').send_keys(invalid_pwd)113 browser.find_element_by_xpath('//button[text() = "Next"]').click()114 assert "The password and confirmed password do not match." in browser.find_element_by_xpath('//div[@class = "dialog-content"]/p').text115 browser.find_element_by_css_selector('#display-modal .btn-primary').click()116 browser.find_element_by_id('FormField_2').clear()117 browser.find_element_by_id('FormField_2').send_keys(password)118 browser.find_element_by_id('FormField_3').send_keys(password)119 self.select_dropdown_value(browser, 'accountCustomerGroup', '-- Do not assign to any group --')120 browser.find_element_by_id('FormField_4').send_keys(firstname)121 browser.find_element_by_id('FormField_5').send_keys(lastname)122 browser.find_element_by_id('FormField_6').send_keys(company)123 browser.find_element_by_id('FormField_7').send_keys(phone)124 browser.find_element_by_id('FormField_8').send_keys(street_add1)125 browser.find_element_by_id('FormField_9').send_keys(street_add2)126 browser.find_element_by_id('FormField_10').send_keys(city)127 self.select_dropdown_value(browser, 'FormField_11', country)128 self.select_dropdown_value(browser, 'FormField_12', state)129 self.clear_field(browser,'FormField_13')130 browser.find_element_by_id('FormField_13').send_keys(postcode)131 browser.find_element_by_xpath('//button[text() = "Next"]').click()132 #Add an Item133 self.cp_add_order_item(browser,'[Sample] Anna, bright single bangles')134 # Select Shipping address and Payment method135 self.cp_select_shipping_payment(browser, 'Manual Payment')136 # Verify and Assert the success message137 browser_success_msg = self.wait_until_element_present('.alert-success', 'CSS_SELECTOR').text138 order_success_msg="Order #%s has been created successfully." % browser_success_msg[7:10]139 orderID = self.get_order_number(browser)140 assert order_success_msg in browser_success_msg...
Weather_Report.py
Source:Weather_Report.py
...13 def retrieve_temp(self,city_name):14 try:15 temperature_from_UI= Weatherpage.current_weather_from_UI16 locator = 'xpath'17 temperature_from_UI= Utilities.wait_until_element_present(self,locator,timeout=15)18 temperature_from_UI= temperature_from_UI.text19 except Exception as element_not_present_exc:20 raise element_not_present_exc21 finally:22 return temperature_from_UI23 def retrieve_humidity(self):24 humidity= None25 try:26 humidity_from_UI = Weatherpage.current_humidity_from_UI27 locator = 'xpath'28 humidity_from_UI = Utilities.wait_until_element_present(self,locator,timeout=10)29 humidity_from_UI= humidity_from_UI.text30 except Exception as element_not_present_exc:31 raise element_not_present_exc32 finally:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!