Best Python code snippet using unittest-xml-reporting_python
instadm.py
Source:instadm.py
1from selenium import webdriver2from webdriver_manager.chrome import ChromeDriverManager as CM3from selenium.webdriver.common.by import By4from selenium.webdriver.support.ui import WebDriverWait5from selenium.common.exceptions import NoSuchElementException6from selenium.webdriver.common.keys import Keys7from selenium.webdriver.common.action_chains import ActionChains8from random import randint, uniform9from time import time, sleep10import logging11import sqlite312DEFAULT_IMPLICIT_WAIT = 3013class InstaDM(object):14 def __init__(self, username, password, headless=True, instapy_workspace=None, profileDir=None):15 self.selectors = {16 "accept_cookies": "//button[text()='Accept']",17 "home_to_login_button": "//button[text()='Log In']",18 "username_field": "username",19 "password_field": "password",20 "button_login": "//button/*[text()='Log In']",21 "login_check": "//*[@aria-label='Home'] | //button[text()='Save Info'] | //button[text()='Not Now']",22 "search_user": "queryBox",23 "select_user": "//div[@aria-labelledby]/div/span//img[@data-testid='user-avatar']",24 "name": "((//div[@aria-labelledby]/div/span//img[@data-testid='user-avatar'])[1]//..//..//..//div[2]/div[2]/div)[1]",25 "next_button": "//button/*[text()='Next']",26 "textarea": "//textarea[@placeholder]",27 "send": "//button[text()='Send']"28 }29 # Selenium config30 options = webdriver.ChromeOptions()31 if profileDir:32 options.add_argument("user-data-dir=profiles/" + profileDir)33 if headless:34 options.add_argument("--headless")35 mobile_emulation = {36 "userAgent": 'Mozilla/5.0 (Linux; Android 4.0.3; HTC One X Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19'37 }38 options.add_experimental_option("mobileEmulation", mobile_emulation)39 self.driver = webdriver.Chrome(executable_path=CM().install(), options=options)40 self.driver.set_window_position(0, 0)41 self.driver.set_window_size(414, 736)42 # Instapy init DB43 self.instapy_workspace = instapy_workspace44 self.conn = None45 self.cursor = None46 if self.instapy_workspace is not None:47 self.conn = sqlite3.connect(self.instapy_workspace + "InstaPy/db/instapy.db")48 self.cursor = self.conn.cursor()49 cursor = self.conn.execute("""50 SELECT count(*)51 FROM sqlite_master52 WHERE type='table'53 AND name='message';54 """)55 count = cursor.fetchone()[0]56 if count == 0:57 self.conn.execute("""58 CREATE TABLE "message" (59 "username" TEXT NOT NULL UNIQUE,60 "message" TEXT DEFAULT NULL,61 "sent_message_at" TIMESTAMP62 );63 """)64 try:65 self.login(username, password)66 except Exception as e:67 logging.error(e)68 print(str(e))69 def login(self, username, password):70 # homepage71 self.driver.get('https://instagram.com/?hl=en')72 self.__random_sleep__(3, 5)73 if self.__wait_for_element__(self.selectors['accept_cookies'], 'xpath', 10):74 self.__get_element__(self.selectors['accept_cookies'], 'xpath').click()75 self.__random_sleep__(3, 5)76 if self.__wait_for_element__(self.selectors['home_to_login_button'], 'xpath', 10):77 self.__get_element__(self.selectors['home_to_login_button'], 'xpath').click()78 self.__random_sleep__(5, 7)79 # login80 logging.info(f'Login with {username}')81 self.__scrolldown__()82 if not self.__wait_for_element__(self.selectors['username_field'], 'name', 10):83 print('Login Failed: username field not visible')84 else:85 self.driver.find_element_by_name(self.selectors['username_field']).send_keys(username)86 self.driver.find_element_by_name(self.selectors['password_field']).send_keys(password)87 self.__get_element__(self.selectors['button_login'], 'xpath').click()88 self.__random_sleep__()89 if self.__wait_for_element__(self.selectors['login_check'], 'xpath', 10):90 print('Login Successful')91 else:92 print('Login Failed: Incorrect credentials')93 def createCustomGreeting(self, greeting):94 # Get username and add custom greeting95 if self.__wait_for_element__(self.selectors['name'], "xpath", 10):96 user_name = self.__get_element__(self.selectors['name'], "xpath").text97 if user_name:98 greeting = greeting + " " + user_name + ", \n\n"99 else: 100 greeting = greeting + ", \n\n"101 return greeting102 def typeMessage(self, user, message):103 # Go to page and type message104 if self.__wait_for_element__(self.selectors['next_button'], "xpath"):105 self.__get_element__(self.selectors['next_button'], "xpath").click()106 self.__random_sleep__()107 if self.__wait_for_element__(self.selectors['textarea'], "xpath"):108 self.__type_slow__(self.selectors['textarea'], "xpath", message)109 self.__random_sleep__()110 if self.__wait_for_element__(self.selectors['send'], "xpath"):111 self.__get_element__(self.selectors['send'], "xpath").click()112 self.__random_sleep__(3, 5)113 print('Message sent successfully')114 def sendMessage(self, user, message, greeting=None):115 logging.info(f'Send message to {user}')116 print(f'Send message to {user}')117 self.driver.get('https://www.instagram.com/direct/new/?hl=en')118 self.__random_sleep__(5, 7)119 try:120 self.__wait_for_element__(self.selectors['search_user'], "name")121 self.__type_slow__(self.selectors['search_user'], "name", user)122 self.__random_sleep__(7, 10)123 if greeting != None:124 greeting = self.createCustomGreeting(greeting)125 # Select user from list126 elements = self.driver.find_elements_by_xpath(self.selectors['select_user'])127 if elements and len(elements) > 0:128 elements[0].click()129 self.__random_sleep__()130 if greeting != None:131 self.typeMessage(user, greeting + message)132 else:133 self.typeMessage(user, message)134 135 if self.conn is not None:136 self.cursor.execute('INSERT INTO message (username, message) VALUES(?, ?)', (user, message))137 self.conn.commit()138 self.__random_sleep__(50, 60)139 return True140 # In case user has changed his username or has a private account141 else:142 print(f'User {user} not found! Skipping.')143 return False144 145 except Exception as e:146 logging.error(e)147 return False148 def sendGroupMessage(self, users, message):149 logging.info(f'Send group message to {users}')150 print(f'Send group message to {users}')151 self.driver.get('https://www.instagram.com/direct/new/?hl=en')152 self.__random_sleep__(5, 7)153 try:154 usersAndMessages = []155 for user in users:156 if self.conn is not None:157 usersAndMessages.append((user, message))158 self.__wait_for_element__(self.selectors['search_user'], "name")159 self.__type_slow__(self.selectors['search_user'], "name", user)160 self.__random_sleep__()161 # Select user from list162 elements = self.driver.find_elements_by_xpath(self.selectors['select_user'])163 if elements and len(elements) > 0:164 elements[0].click()165 self.__random_sleep__()166 else:167 print(f'User {user} not found! Skipping.')168 self.typeMessage(user, message)169 if self.conn is not None:170 self.cursor.executemany("""171 INSERT OR IGNORE INTO message (username, message) VALUES(?, ?)172 """, usersAndMessages)173 self.conn.commit()174 self.__random_sleep__(50, 60)175 return True176 177 except Exception as e:178 logging.error(e)179 return False180 181 def sendGroupIDMessage(self, chatID, message):182 logging.info(f'Send group message to {chatID}')183 print(f'Send group message to {chatID}')184 self.driver.get('https://www.instagram.com/direct/inbox/')185 self.__random_sleep__(5, 7)186 187 # Definitely a better way to do this:188 actions = ActionChains(self.driver) 189 actions.send_keys(Keys.TAB*2 + Keys.ENTER).perform()190 actions.send_keys(Keys.TAB*4 + Keys.ENTER).perform()191 192 if self.__wait_for_element__(f"//a[@href='/direct/t/{chatID}']", 'xpath', 10):193 self.__get_element__(f"//a[@href='/direct/t/{chatID}']", 'xpath').click()194 self.__random_sleep__(3, 5)195 try:196 usersAndMessages = [chatID]197 if self.__wait_for_element__(self.selectors['textarea'], "xpath"):198 self.__type_slow__(self.selectors['textarea'], "xpath", message)199 self.__random_sleep__()200 201 if self.__wait_for_element__(self.selectors['send'], "xpath"):202 self.__get_element__(self.selectors['send'], "xpath").click()203 self.__random_sleep__(3, 5)204 print('Message sent successfully')205 206 if self.conn is not None:207 self.cursor.executemany("""208 INSERT OR IGNORE INTO message (username, message) VALUES(?, ?)209 """, usersAndMessages)210 self.conn.commit()211 self.__random_sleep__(50, 60)212 return True213 214 except Exception as e:215 logging.error(e)216 return False217 def __get_element__(self, element_tag, locator):218 """Wait for element and then return when it is available"""219 try:220 locator = locator.upper()221 dr = self.driver222 if locator == 'ID' and self.is_element_present(By.ID, element_tag):223 return WebDriverWait(dr, 15).until(lambda d: dr.find_element_by_id(element_tag))224 elif locator == 'NAME' and self.is_element_present(By.NAME, element_tag):225 return WebDriverWait(dr, 15).until(lambda d: dr.find_element_by_name(element_tag))226 elif locator == 'XPATH' and self.is_element_present(By.XPATH, element_tag):227 return WebDriverWait(dr, 15).until(lambda d: dr.find_element_by_xpath(element_tag))228 elif locator == 'CSS' and self.is_element_present(By.CSS_SELECTOR, element_tag):229 return WebDriverWait(dr, 15).until(lambda d: dr.find_element_by_css_selector(element_tag))230 else:231 logging.info(f"Error: Incorrect locator = {locator}")232 except Exception as e:233 logging.error(e)234 logging.info(f"Element not found with {locator} : {element_tag}")235 return None236 def is_element_present(self, how, what):237 """Check if an element is present"""238 try:239 self.driver.find_element(by=how, value=what)240 except NoSuchElementException:241 return False242 return True243 def __wait_for_element__(self, element_tag, locator, timeout=30):244 """Wait till element present. Max 30 seconds"""245 result = False246 self.driver.implicitly_wait(0)247 locator = locator.upper()248 for i in range(timeout):249 initTime = time()250 try:251 if locator == 'ID' and self.is_element_present(By.ID, element_tag):252 result = True253 break254 elif locator == 'NAME' and self.is_element_present(By.NAME, element_tag):255 result = True256 break257 elif locator == 'XPATH' and self.is_element_present(By.XPATH, element_tag):258 result = True259 break260 elif locator == 'CSS' and self.is_element_present(By.CSS_SELECTORS, element_tag):261 result = True262 break263 else:264 logging.info(f"Error: Incorrect locator = {locator}")265 except Exception as e:266 logging.error(e)267 print(f"Exception when __wait_for_element__ : {e}")268 sleep(1 - (time() - initTime))269 else:270 print(f"Timed out. Element not found with {locator} : {element_tag}")271 self.driver.implicitly_wait(DEFAULT_IMPLICIT_WAIT)272 return result273 def __type_slow__(self, element_tag, locator, input_text=''):274 """Type the given input text"""275 try:276 self.__wait_for_element__(element_tag, locator, 5)277 element = self.__get_element__(element_tag, locator)278 actions = ActionChains(self.driver)279 actions.click(element).perform()280 for s in input_text:281 element.send_keys(s)282 sleep(uniform(0.25, 0.75))283 except Exception as e:284 logging.error(e)285 print(f'Exception when __typeSlow__ : {e}')286 def __random_sleep__(self, minimum=10, maximum=20):287 t = randint(minimum, maximum)288 logging.info(f'Wait {t} seconds')289 sleep(t)290 def __scrolldown__(self):291 self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")292 def teardown(self):293 self.driver.close()...
test_render_li.py
Source:test_render_li.py
1from django.test.testcases import TestCase2from os.path import join3from mgi.tests import VariableTypesGenerator, DataHandler4class AbstractRenderLiTestSuite(TestCase):5 def setUp(self):6 li_data = join('utils', 'XSDParser', 'tests', 'data', 'renderer', 'default', 'li')7 self.li_data_handler = DataHandler(li_data)8 self.types_generator = VariableTypesGenerator()9 self.content = 'lorem ipsum'10 self.tag_id = '0'11 self.element_tag = 'element'12 # def test_default_parameters(self):13 # result_string = render_li(self.content, self.tag_id, self.element_tag)14 # self.assertEqual(result_string, render_li(unicode(self.content), unicode(self.tag_id),15 # unicode(self.element_tag)))16 # # print result_string17 #18 # result_html = etree.fromstring(result_string)19 # expected_html = self.li_data_handler.get_html2('default')20 #21 # self.assertTrue(are_equals(result_html, expected_html))22 #23 # def test_use_str_text_str(self):24 # use = 'use'25 # text = 'text'26 #27 # result_string = render_li(self.content, self.tag_id, self.element_tag, use, text)28 # self.assertEqual(result_string, render_li(unicode(self.content), unicode(self.tag_id),29 # unicode(self.element_tag), use, text))30 # # print result_string31 #32 # result_html = etree.fromstring(result_string)33 # expected_html = self.li_data_handler.get_html2('use_str_text_str')34 #35 # self.assertTrue(are_equals(result_html, expected_html))36 #37 # def test_use_str_text_none(self):38 # use = 'use'39 # text = None40 #41 # result_string = render_li(self.content, self.tag_id, self.element_tag, use, text)42 # self.assertEqual(result_string, render_li(unicode(self.content), unicode(self.tag_id),43 # unicode(self.element_tag), use, text))44 # # print result_string45 #46 # result_html = etree.fromstring(result_string)47 # expected_html = self.li_data_handler.get_html2('use_str_text_none')48 #49 # self.assertTrue(are_equals(result_html, expected_html))50 #51 # def test_use_none_text_str(self):52 # use = None53 # text = 'text'54 #55 # result_string = render_li(self.content, self.tag_id, self.element_tag, use, text)56 # self.assertEqual(result_string, render_li(unicode(self.content), unicode(self.tag_id),57 # unicode(self.element_tag), use, text))58 # # print result_string59 #60 # result_html = etree.fromstring(result_string)61 # expected_html = self.li_data_handler.get_html2('use_none_text_str')62 #63 # self.assertTrue(are_equals(result_html, expected_html))64 #65 # def test_text_not_str_not_none(self):66 # use = 'string'67 # text = 'string'68 #69 # try:70 # for text in self.types_generator.generate_types_excluding(['str', 'unicode', 'none']):71 # with self.assertRaises(Exception):72 # render_li(self.content, self.tag_id, self.element_tag, use, text)73 # except AssertionError as error:74 # text_type = str(type(text))75 # error.message += ' (use type: ' + text_type + ')'76 # raise AssertionError(error.message)77 #78 # def test_use_not_str_not_none(self):79 # use = 'string'80 #81 # try:82 # for use in self.types_generator.generate_types_excluding(['str', 'unicode', 'none']):83 # with self.assertRaises(Exception):84 # render_li(self.content, self.tag_id, self.element_tag, use)85 # except AssertionError as error:86 # use_type = str(type(use))87 # error.message += ' (use type: ' + use_type + ')'88 # raise AssertionError(error.message)89 #90 # def test_content_not_str(self):91 # content = 'string'92 #93 # try:94 # for content in self.types_generator.generate_types_excluding(['str', 'unicode']):95 # with self.assertRaises(Exception):96 # render_li(content, self.tag_id, self.element_tag)97 # except AssertionError as error:98 # content_type = str(type(content))99 # error.message += ' (content type: ' + content_type + ')'100 # raise AssertionError(error.message)101 #102 # def test_element_tag_not_str(self):103 # element_tag = 'string'104 #105 # try:106 # for element_tag in self.types_generator.generate_types_excluding(['str', 'unicode']):107 # with self.assertRaises(Exception):108 # render_li(self.content, self.tag_id, element_tag)109 # except AssertionError as error:110 # element_tag_type = str(type(element_tag))111 # error.message += ' (element_tag type: ' + element_tag_type + ')'112 # raise AssertionError(error.message)113 #114 # def test_tag_id_not_parsable(self):115 # class TestTagID(object):116 # item = None117 #118 # def __str__(self):119 # return 'undefined' + self.item120 #121 # with self.assertRaises(Exception):...
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!!