Best Python code snippet using pyshould_python
element_locator_tests.py
Source:element_locator_tests.py  
...39    def spec(by, value):  # allow passing by args or kwargs40        pass41    yield mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.find_element', spec=spec)42@pytest.fixture43def expect_all(mocker):44    def spec(by, value):  # allow passing by args or kwargs45        pass46    yield mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.find_elements', spec=spec)47class TestElementLocatorFindsSingleElement(object):48    # by delegating to Selenium49    @pytest.mark.parametrize('finder', Locator.W3C_FINDERS.items())50    def test_delegates_to_seleniums_locators(self, browser, finder, expect_one):51        arg, str = finder52        locate_one(browser, {arg: 'bar'})53        expect_one.assert_called_once_with(str, 'bar')54    def test_raises_exception_if_locating_a_non_link_element_by_link_locator(self, browser):55        selector = {'tag_name': 'div', 'link_text': 'foo'}56        with pytest.raises(Exception) as e:57            locate_one(browser, selector)...okcupid.py
Source:okcupid.py  
...51		secrets = yaml.safe_load(f)52	return secrets53def sleepy():54	time.sleep(6)55def expect_all(*args):56	global driver57	xpath = args[0]58	seconds_waited = 059	if len(args) != 1:60		seconds_waited = args[1]61	elems = driver.find_elements_by_xpath(xpath)62	if len(elems) == 0:63		time.sleep(1)64		if seconds_waited == 20:65			print('waited 20 seconds, returning false')66			return False67		else:68			return(expect_all(xpath,seconds_waited+1))69	else:70		return elems71def expect_first(*args):72	elems = expect_all(*args)73	if not elems:74		return False75	return(elems[0])76def login(url, secrets):77	username = secrets.get('username')78	password = secrets.get('password')79	global driver80	driver.get(url)81	a = expect_first('.//a')82	if a.get_attribute('href') == 'https://www.okcupid.com/login':83		#a.click()84		driver.get(a.get_attribute('href'))85		sleepy()86		email = driver.find_element_by_id('username')87		password = driver.find_element_by_id('password')88		email.send_keys(username)89		password.send_keys(password)90		password.send_keys(Keys.RETURN)91		sleepy()92	print('closing react modal')93	j = expect_first(".//button[@class='reactmodal-header-close']",17)94	if j:95		j.click()96	print('closing accept cookies bar')97	take_cookie = expect_first(".//button[@id='onetrust-accept-btn-handler']")98	if take_cookie:99		take_cookie.click()100	sleepy()101def extract_profile_data():102	profile = {}103	profile['id'] =  driver.current_url.split('/')[-1:][0].split('?')[0]104	profile['date grabbed'] = datetime.now().isoformat()105	profile['details'] = []106	profile['essays'] = []107	profile['username'] = expect_first(".//div[@class='profile-basics-username']").get_attribute('innerText')108	profile['age'] = expect_first(".//span[@class='profile-basics-asl-age']").get_attribute('innerText')109	profile['location'] = expect_first(".//span[@class='profile-basics-asl-location']").get_attribute('innerText')110	profile['match'] = expect_first(".//span[@class='profile-basics-asl-match']").get_attribute('innerText')111	details = expect_all(".//div[@class='matchprofile-details-text']",18)112	essays = expect_all(".//div[@class='profile-essay']",18)113	for det in details:114		profile['details'].append(det.get_attribute('innerText'))115		if essays:116			for essay in essays:117				profile['essays'].append(essay.get_attribute('innerText'))118	intro = driver.find_elements_by_xpath(".//div[starts-with(@class,'firstmessage') and contains(@class,'body-text')]")119	if len(intro) != 0:120		profile['intro message'] = intro[0].get_attribute('innerHTML')121	return profile122	#intro = fun.driver.find_elements_by_xpath(".//div[starts-with(@class,'firstmessage') and contains(@class,'body-text')]")123def filter_profile(profile):124	global exclude_list125	try:126		for exclude in exclude_list:127			for detail in profile['details']:128				if exclude.lower() in detail.lower():129					return False130	except:131		print('there was an error filtering for profile '+profile['username']+' id: '+profile['id'])132	return True133def grab_pictures(profile):134	global driver135	thumb = expect_first(".//div[@class='profile-thumb']")136	thumb.click()137	time.sleep(2)138	images = driver.find_elements_by_xpath(".//img[@class='photo-overlay-image-content']")139	i = 0140	for img in images:141		driver.save_screenshot('images/'+profile['id']+'_'+str(i)+'.png')142		i+=1143		try:144			time.sleep(1)145			img.click()146		except:147			time.sleep(3)148			img.click()149	driver.back()150def navigate(locus):151	global driver152	navbar = expect_all(".//div[@class='navbar-link-icon-container']")153	if locus == 'search':154		navbar[2].click()155	elif locus == 'matches':156		navbar[3].click()157		tabs = expect_all(".//section/div/div/span")158		tabs[2].click()159	elif locus == 'intros':160		navbar[3].click()161		tabs = expect_all(".//section/div/div/span")162		tabs[1].click()163	elif locus == 'doubletake':164		navbar[0].click()165	else:166		driver.get('https://www.okcupid.com/home')167def double_press(buttons):168	try:169		buttons[0].click()170	except:171		buttons[1].click()172	sleepy()173def send_message(message):174	global driver175	try:176		mbox = expect_all(".//textarea[@class='messenger-composer']",18)177		mbox[0].send_keys(message)178		time.sleep(2)179		buttons = driver.find_elements_by_xpath(".//button[@class='messenger-toolbar-send']")180		double_press(buttons)181		retvalue = True182	except:183		retvalue = False184	try:185		buttons = expect_all(".//button[@class='messenger-user-row-close']",18)186		if buttons:187			double_press(buttons)188		buttons = expect_all(".//button[@class='connection-view-container-close-button']",18)189		if buttons:190			double_press(buttons)191	except:192		print('couldn\'t close box')193	return retvalue194def interact_profile(action, profile_data, message):195	global driver196	sleepy()197	print(action)198	pass_button = driver.find_elements_by_xpath(".//button[@id='pass-button']")199	like_button = driver.find_elements_by_xpath(".//button[@id='like-button']")200	unmatch_button = driver.find_elements_by_xpath(".//button[@id='unmatch-button']")201	msg_button = []202	for button in pass_button:203		if button.get_attribute('innerText') == 'MESSAGE':204			msg_button.append(button)205	if not filter_profile(profile_data):206		action = 'unlike'207	if action ==  'like':208		if len(like_button) == 0:209			return 'missing like button'210		return 'liked'211	elif action ==  'like and message':212		print('doing action like and message')213		if len(like_button) == 0:214			return 'missing like button'215		double_press(like_button)216		msg_stat = send_message(message)217		if msg_stat == True:218			return 'liked and messaged'219		else:220			return 'liked'221	elif action ==  'message':222		double_press(msg_button)223		msg_stat = send_message(message)224		if msg_stat == True:225			return 'messaged'226		else:227			return 'failed'228	elif action ==  'unlike':229		if len(unmatch_button) == 0:230			double_press(pass_button)231		else:232			double_press(unmatch_button)233		return 'rejected'234	else:235		return 'no action'236def iterate_error_count():237	global message_error_count238	global profile_iterator239	message_error_count+=1240	if message_error_count == 3: # try 3 times for any one person241		message_error_count = 0242		profile_iterator+=1243def action_list(action):244	global message_error_count245	global profile_iterator246	global action_options247	global opener248	current_action = action_options[action]249	try:250		while True:251			navigate(current_action['location'])252			sleepy()253			logfile = open('okcupid.log','a')254			#Go through list of girls that i like255			profiles = expect_all(".//div[@class='usercard-thumb']")256			if len(profiles) <= profile_iterator:257				logfile.close()258				break259			profiles[profile_iterator].click()260			time.sleep(4)261			pdata = extract_profile_data()262			grab_pictures(pdata)263			pdata['status'] = interact_profile(current_action['action'],pdata,opener)264			pdata['opener'] = opener265			write_status = '|'.join([pdata['username'],pdata['age'],pdata['location'],action,pdata['status'],pdata['date grabbed'],pdata['id']])266			print(pdata['status'])267			logfile.write('\n'+write_status)268			if action == 'collect intros':269				pro_file = open('profiles/men/'+pdata['id'],'w')...test_logging.py
Source:test_logging.py  
...19    def x_plus_two(x_plus_one):20        return x_plus_one + 121    flow = builder.build()22    assert flow.get("x_plus_one") == 223    log_checker.expect_all(24        "Accessed   x(x=1) from definition",25        "Computing  x_plus_one(x=1) ...",26        "Computed   x_plus_one(x=1)",27    )28    assert flow.get("x_plus_two") == 329    if parallel_execution_enabled:30        # This is different from serial execution because we don't pass31        # in-memory cache to the subprocesses. The subprocess loads the32        # entities from disk cache instead.33        log_checker.expect_all(34            "Loaded     x_plus_one(x=1) from disk cache",35            "Computing  x_plus_two(x=1) ...",36            "Computed   x_plus_two(x=1)",37        )38    else:39        log_checker.expect_all(40            "Accessed   x_plus_one(x=1) from in-memory cache",41            "Computing  x_plus_two(x=1) ...",42            "Computed   x_plus_two(x=1)",43        )44    flow = builder.build()45    assert flow.get("x_plus_one") == 246    # We don't access the definitions for simple lookup objects in47    # parallel execution unless we use the objects for computation.48    # Since we load x_plus_one from disk cache, we don't access the49    # definition for x.50    # To clarify: we do access it for looking at the cache, but it's51    # taken from the case key where it is loaded by default and is not52    # counted as definition access in the flow.53    log_checker.expect_all("Loaded     x_plus_one(x=1) from disk cache")54    flow = builder.build()55    assert flow.get("x_plus_two") == 356    log_checker.expect_all("Loaded     x_plus_two(x=1) from disk cache")57    flow = flow.setting("x_plus_one", 3)58    assert flow.get("x_plus_two") == 459    log_checker.expect_all(60        "Accessed   x_plus_one(x_plus_one=3) from definition",61        "Computing  x_plus_two(x_plus_one=3) ...",62        "Computed   x_plus_two(x_plus_one=3)",63    )64class CannotPickleMe:65    def __init__(self):66        # Storing a lock makes it unpickleable67        self.lock = threading.Lock()68    def __str__(self):69        return "Cannot pickle me"70def test_log_unpickleable_value(builder, log_checker):71    @builder72    def log_unpickleable_value():73        # Test that we handle unpickleable value in `LogRecord.msg`.74        logging.info(CannotPickleMe())75        # Test that we handle unpickleable value in `LogRecord.args`.76        logging.info("Logging unpickleable class: %s", CannotPickleMe())77        return 578    assert builder.build().get("log_unpickleable_value") == 579    log_checker.expect_all(80        "Computing  log_unpickleable_value() ...",81        "Cannot pickle me",82        "Logging unpickleable class: Cannot pickle me",83        "Computed   log_unpickleable_value()",...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!!
