Best Python code snippet using robotframework
selectelement.py
Source:selectelement.py
...92 | `List Selection Should Be` | gender | Female | |93 | `List Selection Should Be` | interests | Test Automation | Python |94 """95 self.info(96 f"Verifying list '{locator}' has option{plural_or_not(expected)} "97 f"[ {' | '.join(expected)} ] selected."98 )99 self.page_should_contain_list(locator)100 options = self._get_selected_options(locator)101 labels = self._get_labels(options)102 values = self._get_values(options)103 if sorted(expected) not in [sorted(labels), sorted(values)]:104 raise AssertionError(105 f"List '{locator}' should have had selection [ {' | '.join(expected)} ] "106 f"but selection was [ {self._format_selection(labels, values)} ]."107 )108 def _format_selection(self, labels, values):109 return " | ".join(f"{label} ({value})" for label, value in zip(labels, values))110 @keyword111 def list_should_have_no_selections(self, locator: str):112 """Verifies selection list ``locator`` has no options selected.113 See the `Locating elements` section for details about the locator114 syntax.115 """116 self.info(f"Verifying list '{locator}' has no selections.")117 options = self._get_selected_options(locator)118 if options:119 selection = self._format_selection(120 self._get_labels(options), self._get_values(options)121 )122 raise AssertionError(123 f"List '{locator}' should have had no selection "124 f"but selection was [ {selection} ]."125 )126 @keyword127 def page_should_contain_list(128 self, locator: str, message: Optional[str] = None, loglevel: str = "TRACE"129 ):130 """Verifies selection list ``locator`` is found from current page.131 See `Page Should Contain Element` for an explanation about ``message``132 and ``loglevel`` arguments.133 See the `Locating elements` section for details about the locator134 syntax.135 """136 self.assert_page_contains(locator, "list", message, loglevel)137 @keyword138 def page_should_not_contain_list(139 self, locator: str, message: Optional[str] = None, loglevel: str = "TRACE"140 ):141 """Verifies selection list ``locator`` is not found from current page.142 See `Page Should Contain Element` for an explanation about ``message``143 and ``loglevel`` arguments.144 See the `Locating elements` section for details about the locator145 syntax.146 """147 self.assert_page_not_contains(locator, "list", message, loglevel)148 @keyword149 def select_all_from_list(self, locator: str):150 """Selects all options from multi-selection list ``locator``.151 See the `Locating elements` section for details about the locator152 syntax.153 """154 self.info(f"Selecting all options from list '{locator}'.")155 select = self._get_select_list(locator)156 if not select.is_multiple:157 raise RuntimeError(158 "'Select All From List' works only with multi-selection lists."159 )160 for index in range(len(select.options)):161 select.select_by_index(index)162 @keyword163 def select_from_list_by_index(self, locator: str, *indexes: str):164 """Selects options from selection list ``locator`` by ``indexes``.165 Indexes of list options start from 0.166 If more than one option is given for a single-selection list,167 the last value will be selected. With multi-selection lists all168 specified options are selected, but possible old selections are169 not cleared.170 See the `Locating elements` section for details about the locator171 syntax.172 """173 if not indexes:174 raise ValueError("No indexes given.")175 plural = "" if len(indexes) == 1 else "es"176 self.info(177 f"Selecting options from selection list '{locator}' "178 f"by index{plural} {', '.join(indexes)}."179 )180 select = self._get_select_list(locator)181 for index in indexes:182 select.select_by_index(int(index))183 @keyword184 def select_from_list_by_value(self, locator: str, *values: str):185 """Selects options from selection list ``locator`` by ``values``.186 If more than one option is given for a single-selection list,187 the last value will be selected. With multi-selection lists all188 specified options are selected, but possible old selections are189 not cleared.190 See the `Locating elements` section for details about the locator191 syntax.192 """193 if not values:194 raise ValueError("No values given.")195 self.info(196 f"Selecting options from selection list '{locator}' by "197 f"value{plural_or_not(values)} {', '.join(values)}."198 )199 select = self._get_select_list(locator)200 for value in values:201 select.select_by_value(value)202 @keyword203 def select_from_list_by_label(self, locator: str, *labels: str):204 """Selects options from selection list ``locator`` by ``labels``.205 If more than one option is given for a single-selection list,206 the last value will be selected. With multi-selection lists all207 specified options are selected, but possible old selections are208 not cleared.209 See the `Locating elements` section for details about the locator210 syntax.211 """212 if not labels:213 raise ValueError("No labels given.")214 self.info(215 f"Selecting options from selection list '{locator}' "216 f"by label{plural_or_not(labels)} {', '.join(labels)}."217 )218 select = self._get_select_list(locator)219 for label in labels:220 select.select_by_visible_text(label)221 @keyword222 def unselect_all_from_list(self, locator: str):223 """Unselects all options from multi-selection list ``locator``.224 See the `Locating elements` section for details about the locator225 syntax.226 New in SeleniumLibrary 3.0.227 """228 self.info(f"Unselecting all options from list '{locator}'.")229 select = self._get_select_list(locator)230 if not select.is_multiple:231 raise RuntimeError(232 "Un-selecting options works only with multi-selection lists."233 )234 select.deselect_all()235 @keyword236 def unselect_from_list_by_index(self, locator: str, *indexes: str):237 """Unselects options from selection list ``locator`` by ``indexes``.238 Indexes of list options start from 0. This keyword works only with239 multi-selection lists.240 See the `Locating elements` section for details about the locator241 syntax.242 """243 if not indexes:244 raise ValueError("No indexes given.")245 plurar = "" if len(indexes) == 1 else "es"246 self.info(247 f"Un-selecting options from selection list '{locator}' by index{plurar} "248 f"{', '.join(indexes)}."249 )250 select = self._get_select_list(locator)251 if not select.is_multiple:252 raise RuntimeError(253 "Un-selecting options works only with multi-selection lists."254 )255 for index in indexes:256 select.deselect_by_index(int(index))257 @keyword258 def unselect_from_list_by_value(self, locator: str, *values: str):259 """Unselects options from selection list ``locator`` by ``values``.260 This keyword works only with multi-selection lists.261 See the `Locating elements` section for details about the locator262 syntax.263 """264 if not values:265 raise ValueError("No values given.")266 self.info(267 f"Un-selecting options from selection list '{locator}' by "268 f"value{plural_or_not(values)} {', '.join(values)}."269 )270 select = self._get_select_list(locator)271 if not select.is_multiple:272 raise RuntimeError(273 "Un-selecting options works only with multi-selection lists."274 )275 for value in values:276 select.deselect_by_value(value)277 @keyword278 def unselect_from_list_by_label(self, locator: str, *labels: str):279 """Unselects options from selection list ``locator`` by ``labels``.280 This keyword works only with multi-selection lists.281 See the `Locating elements` section for details about the locator282 syntax.283 """284 if not labels:285 raise ValueError("No labels given.")286 self.info(287 f"Un-selecting options from selection list '{locator}' by "288 f"label{plural_or_not(labels)} {', '.join(labels)}."289 )290 select = self._get_select_list(locator)291 if not select.is_multiple:292 raise RuntimeError(293 "Un-selecting options works only with multi-selection lists."294 )295 for label in labels:296 select.deselect_by_visible_text(label)297 def _get_select_list(self, locator):298 el = self.find_element(locator, tag="list")299 return Select(el)300 def _get_options(self, locator):301 return self._get_select_list(locator).options302 def _get_selected_options(self, locator):...
post2social.py
Source:post2social.py
1# -*- coding: utf-8 -*-2from django.core.management.base import BaseCommand3from academicPhylogeny.models import PhD, socialMediaPosts4from academicPhylogeny.secrets import FACEBOOK_PHYSPHYLO_PAGE_ID,FACEBOOK_PHYSPHYLO_PAGE_ACCESS_TOKEN, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_KEY_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET5import requests6import tweepy7import re8from datetime import date9class Command(BaseCommand):10 help = 'posts to facebook'11 def add_arguments(self, parser):12 parser.add_argument(13 '--showupcoming',14 action='store_true',15 dest='showupcoming',16 help='show queue of upcoming social media posts rather than posting any',17 )18 def debug(self, TWmsg, FBmsg):19 self.stdout.write("Tweet:" + TWmsg)20 self.stdout.write("\nFacebook:" + FBmsg)21 def showupcoming(self):22 prior_posts = socialMediaPosts.objects.all().values_list("PhD")23 unpostedCurrentYearPhDs = PhD.objects.filter(year=date.today().year, validated=True).exclude(id__in=prior_posts)24 DONOTPOST = [48, 638, 99, 90]25 legacyPhDs = PhD.objects.filter(validated=True, school__isnull=False, year__isnull=False,26 year__lte=2000).order_by("year").exclude(id__in=prior_posts).exclude(id__in=DONOTPOST)27 for each in legacyPhDs[0:99]:28 self.stdout.write(each.__unicode__())29 def post(self, selectedPhD, TWmsg=None, FBmsg=None, link=None):30 newPostDB = None31 # if FBmsg:32 # token = FACEBOOK_PHYSPHYLO_PAGE_ACCESS_TOKEN33 # pageID = FACEBOOK_PHYSPHYLO_PAGE_ID34 # dataDict = {"message": FBmsg, "link": link, "access_token": token}35 # post_url = "https://graph.facebook.com/v2.10/%d/feed" % (pageID,)36 # r = requests.post(url=post_url, data=dataDict)37 # if r.status_code == 200:38 # self.stdout.write(self.style.SUCCESS('Successfully posted to facebook!'))39 # if not newPostDB:40 # newPostDB = socialMediaPosts(PhD=selectedPhD,facebook=True,twitter=False)41 # newPostDB.save()42 # else:43 # newPostDB.facebook = True44 # newPostDB.save()45 # else:46 # self.stdout.write(self.style.ERROR("Facebook post failure."))47 if TWmsg:48 auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_KEY_SECRET)49 auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)50 api = tweepy.API(auth)51 ## all URLS are 23 characters, total max chars is 28052 if len(TWmsg) < 256:53 # need room for a space, then 23 character link, so max length for a single tweet is 256 (256 + 1 space + 23 char link = 280 chars)54 t = api.update_status(TWmsg + " " + link)55 else:56 # leave 10 characters for ... and the tweet number marker with a space in front e.g. ... (1/20)57 # first tweet is thus 107 chars max (link in first tweet)58 n = 24659 tweets = [''] 60 currentTweet = 061 for word in re.findall(r'\S+', TWmsg):62 proposed = " ".join([tweets[currentTweet], word]).lstrip()63 if len(proposed) <= n:64 tweets[currentTweet] = proposed65 else:66 tweets.append("")67 currentTweet += 168 tweets[currentTweet] = " ".join([tweets[currentTweet], word]).lstrip()69 ## add ellipses70 for i in range(0, len(tweets) - 1):71 tweets[i] = tweets[i] + "..."72 ## add link to first tweet73 tweets[0] = tweets[0] + " " + link74 ## add tweet number75 for i in range(0, len(tweets)):76 tweets[i] = tweets[i] + " (%d/%d)" % (i + 1, len(tweets))77 for i in range(0, len(tweets)):78 if i == 0:79 # first tweet stands alone80 t = api.update_status(tweets[i])81 else:82 # subsequent tweets are in reply to previous tweet83 t = api.update_status(tweets[i], in_reply_to_status_id=t.id)84 if not newPostDB:85 newPostDB = socialMediaPosts(PhD=selectedPhD, facebook=False, twitter=True)86 newPostDB.save()87 else:88 newPostDB.twitter = True89 newPostDB.save()90 def handle(self, *args, **options):91 if options['showupcoming']:92 self.showupcoming()93 else:94 prior_posts = socialMediaPosts.objects.all().values_list("PhD")95 unpostedCurrentYearPhDs = PhD.objects.filter(year__in=[date.today().year,date.today().year - 1], validated=True).exclude(id__in=prior_posts)96 DONOTPOST = [48,638,99,90]97 legacyPhDs = PhD.objects.filter(validated=True, school__isnull=False, year__isnull=False, year__lte=2000).order_by("year").exclude(id__in=prior_posts).exclude(id__in=DONOTPOST)98 if unpostedCurrentYearPhDs.__len__() > 0:99 selectedPhD = unpostedCurrentYearPhDs[0]100 link = "https://www.bioanthtree.org%s" % (selectedPhD.get_absolute_url(),)101 FBmsg = ("Congratulations to Dr. %s, who recently completed a PhD at %s with %s."102 " This information now appears in the academic genealogy network on our website!"103 " Submit your own information if it isn't already in the database!") % (104 selectedPhD.firstName + " " + selectedPhD.lastName,105 selectedPhD.school,106 (" and ").join(107 [advisor.firstName + " " + advisor.lastName for advisor in selectedPhD.advisor.all()])108 )109 TWmsg = "Congrats to Dr. %s for completing a PhD at %s with %s! #bioanthphd" % (110 selectedPhD.firstName + " " + selectedPhD.lastName,111 selectedPhD.school,112 " and ".join([advisor.firstName + " " + advisor.lastName for advisor in selectedPhD.advisor.all()]).replace(" ", " ")113 )114 else:115 selectedPhD = legacyPhDs[0]116 link = "https://www.bioanthtree.org%s" % (selectedPhD.get_absolute_url(),)117 advisorPhrase = ""118 advisorPeriodOrNot = "."119 if(len(selectedPhD.advisor.all()) > 0):120 advisorsAnd = (" and ").join(121 [advisor.firstName + " " + advisor.lastName for advisor in selectedPhD.advisor.all()]122 )123 advisorPhrase = "with " + advisorsAnd + "."124 advisorPeriodOrNot = ""125 studentsPhrase = ""126 students = PhD.objects.filter(validated=True, advisor = selectedPhD)127 if len(students) > 0:128 if len(students) == 1:129 plural_or_not=""130 else:131 plural_or_not="s"132 studentsPhrase = "%s advised/has advised at least %d PhD student%s including: %s." %(133 selectedPhD.lastName,134 len(students),135 plural_or_not,136 ", ".join([student.__unicode__().strip() for student in students])137 )138 total_descendant_count = len(selectedPhD.find_children([]))139 if total_descendant_count > 5 and total_descendant_count > len(students):140 totalDescendantPhrase = "In total, %d PhDs in our database are academic descendants of %s." % (total_descendant_count, selectedPhD.lastName)141 else:142 totalDescendantPhrase = ""143 FBmsg = TWmsg = re.sub(" +"," ", "%s completed a PhD at %s in %s%s %s %s %s\n\nLearn more on our website..." % (144 selectedPhD.__unicode__().strip(),145 selectedPhD.school,146 selectedPhD.year,147 advisorPeriodOrNot,148 advisorPhrase,149 studentsPhrase,150 totalDescendantPhrase151 ))152 #self.debug(TWmsg, FBmsg)...
guessing_game.py
Source:guessing_game.py
1"""2file: guessing_game.py3created: 9/27/2021 9:11 PM4author: ciaran mcdevitt5version: v1.0.06licensing: (c) 2021 Ciaran McDevitt, LYIT7 available under the GNU Public License (GPL)8description:9credits:10"""11import random # >> random to generate a random int12import time # >> time to add waits for the flow of the gameplay13if __name__ == '__main__':14 '''15 main function for a guessing game where a user tries to guess a randomly generated number16 between one of three ranges selected from the menu 17 Parameters:18 argument1 (int): lower_range (lowest number of guessing range)19 argument2 (int): upper_range (highest number of guessing range, dynamically set through the menu)20 argument3 (int): guess_counter (keeps track of the number of guesses, displayed in output)21 argument4 (str): chosen_number (for user to select a difficulty level, then cast to an int once checked - isdigit())22 argument5 (str): option (for user to select a difficulty level in menu, 1, 2 or 3 to proceed, any other key to quit)23 argument6 (int): number_to_guess (initialized to zero and then set by difficulty level in menu)24 argument7 (bool): happy_to_keep_playing (initialized to true, could be used to return to menu instead of quitting) 25 argument8 (str): had_enough (after each guess users are asked if they wish to continue or to exit the game) 26 27 Output:28 Users are informed whether their guess is too low, to high or when the guess correctly are informed29 of how many guesses it took30 Each time a user make a guess, if unsuccessful the user is asked if they wish to continue playing31 '''32 lower_range = 133 upper_range = 034 guess_counter = 035 chosen_number = 036 option = 137 number_to_guess = 038 happy_to_keep_playing = True39 while option:40 print("\n______________________________________________\n"41 "Guessing Game Menu\n"42 "______________________________________________\n\n"43 "Select difficulty level of new game\n\n"44 "(1) -Level 1 [1 - 100]\n"45 "(2) -Level 2 [1 - 1000]\n"46 "(3) -Level 3 [1 - 10000]\n\n"47 "-Press any other key to exit the game\n\n"48 " ~ Please enter a choice: ~\n\n\n\t")49 option = input()50 if option == '1':51 print("New game at Level 1!\n")52 upper_range = 10053 number_to_guess = random.randint(lower_range, upper_range)54 # print(f"number_to_guess: {number_to_guess}") # print out number_to_guess so plural grammar can be tested55 elif option == '2':56 print("New game at Level 2!\n")57 upper_range = 100058 number_to_guess = random.randint(lower_range, upper_range)59 elif option == '3':60 print("New game at Level 3!\n")61 upper_range = 1000062 number_to_guess = random.randint(lower_range, upper_range)63 # ********************************************************************************64 # Test: to confirm that range can be met but not breached (uncomment to activate)65 # ********************************************************************************66 # elif option == "RANGE-TEST":67 # upper_range = 1000068 # number_to_guess = random.randint(lower_range, upper_range)69 # for i in range(1000000):70 # number_to_guess = random.randint(lower_range, upper_range)71 # if number_to_guess > 10000:72 # print("fail")73 # print(f"number_to_guess: {number_to_guess}")74 # time.sleep(5)75 # elif number_to_guess == 10000:76 # print(f"#{i}/1000000 : 10000")77 # time.sleep(5)78 # else:79 # pass80 # ********************************************************************************81 else:82 print("Goodbye")83 time.sleep(2)84 quit()85 while happy_to_keep_playing:86 guess_counter += 187 if guess_counter == 1:88 correct_grammar = "a"89 else:90 correct_grammar = "another"91 chosen_number = input(f"Please enter {correct_grammar} number "92 f"between {lower_range} and {upper_range}\n ")93 if chosen_number.isdigit():94 chosen_number = int(chosen_number)95 else:96 print("That's not an int... ")97 if lower_range <= chosen_number < upper_range:98 if chosen_number == number_to_guess:99 if guess_counter == 1:100 plural_or_not = "guess"101 else:102 plural_or_not = "guesses"103 print(f"Congratulations! {chosen_number} is correct\n"104 f" It took you {guess_counter} {plural_or_not}. Well done!")105 time.sleep(5)106 break107 elif chosen_number > number_to_guess:108 print("You've guessed to high...\n")109 else:110 print("You've guessed to low...\n")111 had_enough = input("Keep playing?\t( n / any other key )\n")112 if had_enough == 'n' or had_enough == 'N':113 # happy_to_keep_playing = False114 confirmation_check = input("Are you sure you want to quit ( y / any other key)\n")115 if confirmation_check == "y" or confirmation_check == "Y":116 print("Goodbye")117 time.sleep(2)118 quit()119 else:...
results_language.py
Source:results_language.py
...11 def __str__(self):12 return '{0} -- {1.data!s} -- {1.number_of_documents!s}'.format(self.__class__.__name__, self)13 def __repr__(self):14 return '{0}({1.data!r}, {1.number_of_documents!r})'.format(self.__class__.__name__, self)15 def plural_or_not(self):16 '''Checks if more than one result.'''17 if self.number_of_documents == 1:18 plural_or_not = "contract"19 else:20 plural_or_not = "contracts"21 return plural_or_not22 def convert_results_to_text(self, value):23 '''Convert interger to string with commas.'''24 if self.number_of_documents == 0:25 # Skip everything else and return no results language.26 return "No" # Ex. No contracts found...27 else:28 return "{:,}".format(value)29 def add_initial_language(self, plural_or_not):30 '''Creates initial sentence language.'''31 final_sentence = str(self.convert_results_to_text(32 self.number_of_documents)) + ' ' + plural_or_not + ' found'33 return final_sentence34 def add_keyword_language(self, final_sentence):35 '''Adds keyword or key phrase language.'''36 if self.data['search_input'] != '':37 if len(self.data['search_input'].split()) > 1:38 final_sentence += ' for key phrase "' + \39 self.data['search_input'] + '"'40 # for 'keyword'41 else:42 final_sentence += ' for keyword "' + \43 self.data['search_input'] + '"'44 # for 'keyword'45 return final_sentence46 def add_vendors_language(self, final_sentence):47 '''Adds vendor language.'''48 if self.data['vendor'] != '':49 final_sentence += " involving vendor " + self.data['vendor']50 return final_sentence51 def add_departments_language(self, final_sentence):52 '''Adds department language.'''53 if self.data['department'] != '':54 if self.data['vendor'] == '':55 final_sentence += " involving the " + \56 self.data['department'] + " department"57 elif self.data['vendor'] != '' and self.data['officer'] == '':58 final_sentence += " and the " + self.data['department'] + \59 " department"60 elif self.data['vendor'] != '' and self.data['officer'] != '':61 final_sentence += ", the " + self.data['department'] + \62 " department"63 return final_sentence64 def add_officers_language(self, final_sentence):65 '''Adds officers language.'''66 if self.data['officer'] != '':67 if self.data['vendor'] == '' and self.data['department'] == '':68 final_sentence += " involving officer " + \69 self.data['officer']70 elif self.data['department'] != '':71 final_sentence += " and officer " + self.data['officer']72 return final_sentence73 @staticmethod74 def add_final_sentence_language(final_sentence):75 '''Endings for the sentences.'''76 # Punctuation comes before quotation marks77 if final_sentence[-1] == "'" or final_sentence[-1] == '"':78 last_character = final_sentence[-1]79 final_sentence_list = list(final_sentence)80 final_sentence_list[-1] = '.'81 final_sentence_list.append(last_character)82 final_sentence = ''.join(final_sentence_list)83 else:84 final_sentence += '.'85 return final_sentence86 def main(self):87 '''Runs through all sentence-building methods.'''88 plural_or_not = self.plural_or_not()89 final_sentence = self.add_initial_language(plural_or_not)90 final_sentence = self.add_keyword_language(final_sentence)91 final_sentence = self.add_vendors_language(final_sentence)92 final_sentence = self.add_departments_language(final_sentence)93 final_sentence = self.add_officers_language(final_sentence)94 final_sentence = self.add_final_sentence_language(final_sentence)95 return final_sentence96if __name__ == '__main__':...
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!!