Best Python code snippet using tox_python
make_interface.py
Source:make_interface.py
1"""2This file includes functionality to generate interfaces3Prompt specification4-------------------5Prompts are specified through dictionaries that include the following6fields:71. header82. description93. inputs:10 [11 a. label12 b. description13 c. help14 d. input type15 e. options16 ]17Input types18-----------19text (min,maximum, default):20 string between minimum and maximum characters21bool (default):22 a True/False value23radio (['a','b',...'z'], default):24 select one multiple-choice option from list25checkbox (['a','b',...,'z'],minimum,maximum, default)26 select between minimum and maximum items from list27integer (minimum,maximum, default):28 enter a number between minimum and maximum29float (minimum,maximum, default):30 enter a float (decimal) between minimum and maximum31date (minimum, maximum, default):32 enter a date between minimum and maximum33time (minimum, maximum, default):34 enter a time between minimum and maximum35Example36-------37```python38prompt_specification = dict(39 description = "this is an example of input.\njust see for yourself.",40 header = "Test input",41 inputs = [42 {"label":'enter text', "description":'nothing happens', "help":'', "input_type":'text', "minimum":None, "maximum":None, "default":None} ,43 {"label": 'pick a letter', "description":'any letter', "input_type":'radio', "options":['a','b','c'], "default":'a'},44 ]45)46TLI.prompt(prompt_specification)47```48Should generate something like:49 |-------------------------------------|50 | TEST INPUT |51 |-------------------------------------|52 |this is an example of input. |53 |just see for yourself. |54 |-------------------------------------|55 | enter text: |56 | nothing happens |57 | > |58 | pick a letter: |59 | any letter |60 | > |61 |-------------------------------------|62"""63import time64from collections import OrderedDict65import logging66logger = logging.getLogger("INCA.%s" % __name__)67class noprompt:68 def prompt(*args, **kwargs):69 logger.warning("Prompt required, but disabled")70class TLI:71 HELP_INDICATORS = ["h", "help", "?"]72 def TLI_text(73 label,74 minimum=None,75 maximum=None,76 default=None,77 description="",78 help=None,79 show_help=False,80 *args,81 **kwargs82 ):83 if description or show_help:84 print(label)85 print("\t" + "\t".join(description.split("\n")))86 if show_help:87 if not help:88 print("HELP: unavailable...")89 else:90 print("HELP: {help}".format(**locals()))91 show_default = default and "(default: '{default}')\n".format(**locals()) or ""92 if not minimum and not maximum:93 criteria = ""94 elif minimum and not maximum:95 criteria = "(at least {minimum} characters)".format(**locals())96 elif not minimum and maximum:97 criteria = "(no longer than {maximum} characters)".format(**locals())98 elif minimum and maximum:99 criteria = "(between {minimum} and {maximum} characters)".format(**locals())100 response = input("{show_default}{criteria}\n> ".format(**locals()))101 if not response and default:102 response = default103 help_requested = [104 help_found for help_found in TLI.HELP_INDICATORS if help_found == response105 ]106 if help_requested:107 show_help = True108 return TLI.TLI_text(**locals())109 # validation110 minimum_reached = not type(minimum) == int and True or len(response) > minimum111 maximum_avoided = not type(maximum) == int and True or len(response) < maximum112 if not minimum_reached or not maximum_avoided:113 print("Please make sure you stick to provided minimum and maximum lengths")114 show_help = True115 return TLI.TLI_text(**locals())116 return response117 def TLI_bool(118 label,119 minimum=None,120 maximum=None,121 default=None,122 description="",123 help=None,124 show_help=False,125 *args,126 **kwargs127 ):128 if description or show_help:129 print(label)130 print("\t" + "\t".join(description.split("\n")))131 if show_help:132 if not help:133 print("HELP: unavailable...")134 else:135 print("HELP: {help}".format(**locals()))136 show_default = default and "(default: {default})".format(**locals()) or ""137 response = input("{show_default}> ".format(**locals()))138 if not response and default:139 response = default140 help_requested = [141 help_found for help_found in TLI.HELP_INDICATORS if help_found == response142 ]143 if help_requested:144 show_help = True145 return TLI.TLI_text(**locals())146 # validation147 is_bool = response.lower() in ["true", "false", "t", "f"]148 if not is_bool:149 print("Please make sure you provide a boolean")150 show_help = True151 return TLI.TLI_bool(**locals())152 return response153 def TLI_radio(154 label,155 minimum=None,156 maximum=None,157 default=None,158 description="",159 help=None,160 show_help=False,161 options=[],162 *args,163 **kwargs164 ):165 if description or show_help:166 print(label)167 print("\t" + "\t".join(description.split("\n")))168 if show_help:169 if not help:170 print("HELP: unavailable...")171 else:172 print("HELP: {help}".format(**locals()))173 print("Choices:\n\n" + "\n".join(options) + "\n")174 show_default = default and "(default: {default})".format(**locals()) or ""175 response = input("{show_default}> ".format(**locals()))176 if not response and default:177 response = default178 help_requested = [179 help_found for help_found in TLI.HELP_INDICATORS if help_found == response180 ]181 if help_requested:182 show_help = True183 return TLI.TLI_text(**locals())184 cleanresponse = response.lower().strip()185 # validation186 valid_choice = response in options187 if not valid_choice:188 print("Please make sure you stick to provided options")189 print("You specified {response}".format(**locals()))190 show_help = True191 return TLI.TLI_radio(**locals())192 choice = [c for c in options if c.lower().strip() == cleanresponse][0]193 return choice194 def TLI_checkbox(195 label,196 minimum=None,197 maximum=None,198 default=None,199 description="",200 help=None,201 show_help=False,202 options=[],203 *args,204 **kwargs205 ):206 if description or show_help:207 print(label)208 print("\t" + "\t".join(description.split("\n")))209 if show_help:210 if not help:211 print("HELP: unavailable...")212 else:213 print("HELP: {help}".format(**locals()))214 print("Choices:\n\n" + "\n".join(options) + "\n")215 show_default = default and "(default: {default})".format(**locals()) or ""216 if not minimum and not maximum:217 criteria = ""218 elif minimum and not maximum:219 criteria = "(at least {minimum} choice)".format(**locals())220 elif not minimum and maximum:221 citeria = "(no longer than {maximum} options)".format(**locals())222 elif minimum and maximum:223 criteria = "(between {minimum} and {maximum} options)".format(**locals())224 response = input(225 "{show_default}{criteria} separated by ", "> ".format(**locals())226 )227 if not response and default:228 response = default229 help_requested = [230 help_found for help_found in TLI.HELP_INDICATORS if help_found == response231 ]232 if help_requested:233 show_help = True234 return TLI.TLI_text(**locals())235 # interpretation236 cleanoptions = [choice.lower().strip() for choice in response.split(",")]237 validoptions = [choice for choice in options if choice.lower() in cleanoptions]238 # validation239 minimum_reached = len(validoptions) > minimum240 maximum_avoided = len(validoptions) < maximum241 if not minimum_reached or not maximum_avoided:242 print("Please make sure you stick to provided minimum and maximum options")243 print("You provided:")244 for n, c in enumerate(validoptions):245 print(n + 1, ". ", c)246 show_help = True247 return TLI.TLI_text(**locals())248 return response249 def TLI_integer(250 label,251 minimum=None,252 maximum=None,253 default=None,254 description="",255 help=None,256 show_help=False,257 *args,258 **kwargs259 ):260 if description or show_help:261 print(label)262 print("\t" + "\t".join(description.split("\n")))263 if show_help:264 if not help:265 print("HELP: unavailable...")266 else:267 print("HELP: {help}".format(**locals()))268 show_default = default and "(default: {default})".format(**locals()) or ""269 if not minimum and not maximum:270 criteria = ""271 elif minimum and not maximum:272 criteria = "(at least {minimum})".format(**locals())273 elif not minimum and maximum:274 citeria = "(no longer than {maximum})".format(**locals())275 elif minimum and maximum:276 criteria = "(between {minimum} and {maximum})".format(**locals())277 response = input("{show_default}{criteria}> ".format(**locals()))278 if not response and default:279 response = default280 help_requested = [281 help_found for help_found in TLI.HELP_INDICATORS if help_found == response282 ]283 if help_requested:284 show_help = True285 return TLI.TLI_text(**locals())286 # validation287 try:288 response = int(response.strip())289 correct_type = True290 except ValueError:291 correct_type = False292 minimum_reached = correct_type and response >= minimum293 maximum_avoided = correct_type and response <= maximum294 if not correct_type or not minimum_reached or not maximum_avoided:295 print(296 "Please provide an integer (1,2,3,4..) between the minimum and maximum"297 )298 show_help = True299 return TLI.TLI_text(**locals())300 return response301 def TLI_float(302 label,303 minimum=None,304 maximum=None,305 default=None,306 description="",307 help=None,308 show_help=False,309 *args,310 **kwargs311 ):312 if description or show_help:313 print(label)314 print("\t" + "\t".join(description.split("\n")))315 if show_help:316 if not help:317 print("HELP: unavailable...")318 else:319 print("HELP: {help}".format(**locals()))320 show_default = default and "(default: {default})".format(**locals()) or ""321 if not minimum and not maximum:322 criteria = ""323 elif minimum and not maximum:324 criteria = "(at least {minimum})".format(**locals())325 elif not minimum and maximum:326 citeria = "(no longer than {maximum})".format(**locals())327 elif minimum and maximum:328 criteria = "(between {minimum} and {maximum})".format(**locals())329 response = input("{show_default}{criteria}> ".format(**locals()))330 if not response and default:331 response = default332 help_requested = [333 help_found for help_found in TLI.HELP_INDICATORS if help_found == response334 ]335 if help_requested:336 show_help = True337 return TLI.TLI_text(**locals())338 # validation339 try:340 response = float(response.strip())341 correct_type = True342 except ValueError:343 correct_type = False344 minimum_reached = correct_type and response >= minimum345 maximum_avoided = correct_type and response <= maximum346 if not correct_type or not minimum_reached or not maximum_avoided:347 print(348 "Please provide an decimal (1.1, 3.4, ...) between the minimum and maximum"349 )350 show_help = True351 return TLI.TLI_text(**locals())352 return response353 def TLI_date(354 label,355 minimum=None,356 maximum=None,357 default=None,358 description="",359 help=None,360 show_help=False,361 *args,362 **kwargs363 ):364 def extract_date(string_input):365 try:366 return time.strptime(string_input, "%d-%m-%Y")367 except ValueError:368 return False369 if description or show_help:370 print(label)371 print("\t" + "\t".join(description.split("\n")))372 if show_help:373 if not help:374 print("HELP: unavailable...")375 else:376 print("HELP: {help}".format(**locals()))377 show_default = default and "(default: {default})".format(**locals()) or ""378 if not minimum and not maximum:379 criteria = ""380 elif minimum and not maximum:381 minimum = extract_date(minimum)382 maximum = extract_date("31-12-6000")383 criteria = "(at least {minimum})".format(**locals())384 elif not minimum and maximum:385 minimum = extract_date("01-01-0001")386 maximum = extract_date(maximum)387 citeria = "(no longer than {maximum})".format(**locals())388 elif minimum and maximum:389 minimum = extract_date(minimum)390 maximum = extract_date(maximum)391 criteria = "(between {minimum} and {maximum})".format(**locals())392 response = input("{show_default}{criteria}> ".format(**locals()))393 if not minimum and maximum:394 raise Exception(395 "minimum and/or maximum are misspecified! Use a day-month-year format (e.g. 24-05-1999)"396 )397 if not response and default:398 response = default399 help_requested = [400 help_found for help_found in TLI.HELP_INDICATORS if help_found == response401 ]402 if help_requested:403 show_help = True404 return TLI.TLI_text(**locals())405 # validation406 try:407 response = extract_date(response.strip())408 correct_type = response409 except ValueError:410 correct_type = False411 minimum_reached = correct_type and response >= minimum412 maximum_avoided = correct_type and response <= maximum413 if not correct_type or not minimum_reached or not maximum_avoided:414 print("Please provide an date between the minimum and maximum")415 show_help = True416 return TLI.TLI_text(**locals())417 return response418 def TLI_time(419 label,420 minimum=None,421 maximum=None,422 default=None,423 description="",424 help=None,425 show_help=False,426 *args,427 **kwargs428 ):429 def extract_time(string_input):430 try:431 return time.strptime(string_input, "%H:%M:%S")432 except ValueError:433 return False434 if description or show_help:435 print(label)436 print("\t" + "\t".join(description.split("\n")))437 if show_help:438 if not help:439 print("HELP: unavailable...")440 else:441 print("HELP: {help}".format(**locals()))442 show_default = default and "(default: {default})".format(**locals()) or ""443 if not minimum and not maximum:444 criteria = ""445 elif minimum and not maximum:446 minimum = extract_time(minimum)447 maximum = extract_time("23:59:60") # should always be true448 criteria = "(at least {minimum})".format(**locals())449 elif not minimum and maximum:450 minimum = extract_time("00:00:00") # should always be true451 maximum = extract_time(maximum)452 citeria = "(no longer than {maximum})".format(**locals())453 elif minimum and maximum:454 minimum = extract_time(minimum)455 maximum = extract_time(maximum)456 criteria = "(between {minimum} and {maximum})".format(**locals())457 response = input("{show_default}{criteria}> ".format(**locals()))458 if not minimum and maximum:459 raise Exception(460 "minimum and/or maximum are misspecified! Use a day-month-year format (e.g. 24-05-1999)"461 )462 if not response and default:463 response = default464 help_requested = [465 help_found for help_found in TLI.HELP_INDICATORS if help_found == response466 ]467 if help_requested:468 show_help = True469 return TLI.TLI_text(**locals())470 # validation471 try:472 response = extract_time(response.strip())473 correct_type = response474 except ValueError:475 correct_type = False476 minimum_reached = correct_type and response >= minimum477 maximum_avoided = correct_type and response <= maximum478 if not correct_type or not minimum_reached or not maximum_avoided:479 print(480 "Please provide a time in the format hour:minute:seconds (e.g. '22:45:55') between the minimum and maximum"481 )482 show_help = True483 return TLI.TLI_text(**locals())484 return response485 def prompt(prompt_specification, verify=False):486 """Starts a text-based user interaction.487 Usefull to prompt users to enter specific information based on488 external resources, such as asking users to enter authentication codes.489 Parameters490 ----------491 prompt_specification : dict492 Dict specifying that to show.493 See prompt_specification for more information.494 verify : Bool [default=False]495 whether users should verify their answers (Y/N) before submission496 """497 print(498 """499=============== {prompt_specification[header]:^20.50} ===============500{prompt_specification[description]}501-----------------------------------------------------------------------------------502""".format(503 **locals()504 )505 )506 responses = OrderedDict()507 for prompt in prompt_specification["inputs"]:508 responses.update(509 {510 prompt["label"]: getattr(511 TLI, "TLI_{prompt[input_type]}".format(prompt=prompt)512 )(**prompt)513 }514 )515 print()516 if verify == True:517 outputs = "\n".join(518 ["{k:30.30} : {v}".format(k=k, v=v) for k, v in responses.items()]519 )520 summary = """521================ you provided ===================522{outputs}523Is this correct? (Y/n)524=================================================525> """.format(526 outputs=outputs527 )528 correct = input(summary)529 if not correct.lower().strip() in ["y", "yes", "yeah", ""]:530 return TLI.prompt(prompt_specification, verify)...
utils.py
Source:utils.py
1class Utils(object):2 def chat_message(message):3 payload = {"sender": "bot",4 "text": message}5 return {"type" : "message", "payload" : payload}6 def choice(caption, list_params, show_search=False, show_details=False, show_help=False, helpIconContent=''):7 elements = []8 if show_search and show_details and show_help:9 raise Exception('Not implemented yet')10 elif show_search and show_details and not show_help:11 raise Exception('Not implemented yet')12 elif show_search and not show_details and show_help:13 for i in list_params:14 elements.append({'name': i, 'value': list_params[i]})15 return {"type": "available_choices",16 "payload": {17 "showSearchBar": show_search,18 "showDetails": show_details,19 "caption": caption,20 "showHelpIcon": show_help,21 "helpIconContent" : helpIconContent,22 "elements": elements}}23 elif show_search and not show_details and not show_help:24 for i in list_params:25 elements.append({'name': i, 'value': list_params[i]})26 elif not show_search and show_details and show_help:27 raise Exception('Not implemented yet')28 elif not show_search and show_details and not show_help:29 raise Exception('Not implemented yet')30 elif not show_search and not show_details and show_help:31 for i in list_params:32 elements.append({'name': i, 'value': list_params[i]})33 return {"type": "available_choices",34 "payload": {35 "showSearchBar": show_search,36 "showDetails": show_details,37 "caption": caption,38 "showHelpIcon": show_help,39 "helpIconContent": helpIconContent,40 "elements": elements}}41 else:42 for i in list_params:43 elements.append({'name': i, 'value': list_params[i]})44 return {"type": "available_choices",45 "payload": {46 "showSearchBar": show_search,47 "showDetails": show_details,48 "caption": caption,49 "showHelpIcon": show_help,50 "elements": elements}}51 def param_list(param_dict):52 elements = []53 for i in param_dict:54 elements.append({'field': i, 'values': param_dict[i]})55 return {"type" : "parameters_list",56 "payload" : elements}57 def pie_chart(pie_dict):58 viz = []59 for (k,v) in pie_dict.items():60 viz.append({61 "vizType": "pie-chart",62 "title": k,63 "data": v64 })65 return {"type" : "data_summary",66 "payload" : {67 "viz":viz68 }}69 def tools_setup(add, remove):70 return {"type" : "tools_setup",71 "payload": {72 "add" : [add],73 "remove" : [remove]}}74 def workflow(state, download=False, link_list=[]):75 if download:76 return {"type": "workflow",77 "payload": {"state": state,78 "url": link_list[0]}}79 else:80 return {"type": "workflow",81 "payload": {"state": state}}82 def pyconsole_debug(payload):...
instructions_v1.py
Source:instructions_v1.py
1yes_no = [2 ["yes", "y"],3 ["no", "n"]4]5#String Check6def string_check(choice, options):7 is_valid = ""8 chosen = ""9 for var_list in options:10 # if the snack is in one of the lists, return the full name of the snack11 if choice in var_list:12 # Get full name of snack and put it in title case so it looks nice when outputted13 chosen = var_list[0].title()14 is_valid = "yes"15 break16 # if the chosen option is not valid, set is_valid to no17 else:18 is_valid = "no"19 # if the snack is not OK - ask question again.20 if is_valid == "yes":21 return chosen22 else:23 print("Please enter a valid option")24 print()25 return "invalid choice"26#Function to show instructions if needed.27def instructions(options):28 #loop29 show_help = "invalid choice"30 while show_help == "invalid choice":31 #ask question32 show_help = input("Would you like to see the instructions? \n").lower()33 string_check(show_help, options)34 35 #bc of having issues w/ the loop, had to do this to make sure the loop would loop.36 if show_help == "yes" or show_help == "y" or show_help == "no" or show_help == "n":37 show_help = show_help38 else:39 show_help = "invalid choice"40 if show_help == "yes" or show_help == "y":41 #instructions42 print()43 print("INSTRUCTIONS:")44 print()45 print("1st step: Input name. \n2nd step: Input your age. \n3rd step: Input which snacks you want. In case of change in snacks, the snacks will always be listed. Note that there's a 4 per person per snack type limit. \n4th step: Input if you want to pay with card or credit. \n5th step: Done.")46 return ""47#Main Part48instructions(yes_no)49print()50print("Program launching...")...
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!!