How to use record_keyval method in autotest

Best Python code snippet using autotest_python

base_job.py

Source:base_job.py Github

copy

Full Screen

...604 self.job_statuses.get(log_entry.status_code, False),605 len(self._reports_container[key]) + 1, operation + "\n"606 )607 self._reports_container[key].append(entry)608 def record_keyval(self, path, dictionary, type_tag=None):609 """610 Append a key-value pairs of dictionary to self._keyval_container in611 TAP format. Once finished write out the keyval.tap file to the file612 system.613 If type_tag is None, then the key must be composed of alphanumeric614 characters (or dashes + underscores). However, if type-tag is not615 null then the keys must also have "{type_tag}" as a suffix. At616 the moment the only valid values of type_tag are "attr" and "perf".617 @param path: The full path of the keyval.tap file to be created618 @param dictionary: The keys and values.619 @param type_tag: The type of the values620 """621 self._keyval_container.setdefault(path, [0, []])622 self._keyval_container[path][0] += 1...

Full Screen

Full Screen

BaseMenu.py

Source:BaseMenu.py Github

copy

Full Screen

1import sys, os2try:3 import readline4except ImportError:5 pass6from ui.textCompleter import TextCompleter7from ui.Colors import color8try:9 from rich import box, print10 from rich.console import Console11 from rich.table import Table12 from rich.align import Align13 from rich.style import Style14 from rich.prompt import Prompt15 from rich.text import Text16 from assets.NanAirLogo import NAN_AIR_LOGO17 RICH_AVAILABLE = True18except ModuleNotFoundError:19 from assets.NanAirLogo import NAN_AIR_LOGO_POOR20 RICH_AVAILABLE = False21class BaseMenu :22 '''Master menu to get from'''23 def __init__(self, logged_in_user=None):24 self.menu_options = {}25 self.clear = lambda: os.system('cls' if os.name=='nt' else 'clear') if not RICH_AVAILABLE else Console().clear()26 self.menu_title = str()27 self.isMainMenu = False28 self.failed = False29 self.loggedIn = False30 self.loggedInUser = self.login() if logged_in_user is None else logged_in_user31 32 def login(self, failed_attempt: bool=False):33 ''' Menu to authenticate user, is shown when no logged in user can be found. '''34 from logic.AuthLogic import AuthAPI35 authApi = AuthAPI()36 self.clear()37 print('Welcome to NaN Air!\nDividing by zero every day.\n')38 print('Incorrect login details, please try again') if failed_attempt else ''39 userSsn = ""40 while userSsn == "":41 if RICH_AVAILABLE:42 userSsn = Prompt.ask('Please enter your employee number to login')43 else:44 userSsn = input('Please enter your employee number to login: ')45 self.clear()46 login_res = authApi.userLogin(userSsn)47 if login_res:48 self.loggedIn = True49 return login_res50 else:51 return self.login(failed_attempt=True)52 def print_options(self):53 '''prints out user opttions'''54 # If the user chose to quit in some menu then we return run55 if self.failed:56 return 'run'57 menuState = 'run'58 # Continue to run if we keep getting 'run'59 while menuState == 'run':60 self.clear()61 if not RICH_AVAILABLE: # If rich isn't available then create basic menu62 to_print = NAN_AIR_LOGO_POOR + '\n\n\n'63 to_print += self.menu_title + '\n'64 # Checks if Rich module is installed, install with 'pip install rich'65 to_print = color('Rich package is not installed, program may not work correctly\nYou can install it by running "pip install rich" in your terminal\n', backgroundColor='red') + to_print66 to_print += ("-"*30) + '\n'67 for key in self.menu_options :68 to_print += f"[{key}] {self.menu_options[key]['title']} \n"69 to_print += ("-"*30)70 print(to_print)71 else: # Hurrah rich is available we can create a cool menu72 menuTable = Table(show_header=False, show_lines=True, min_width=35)73 menuTable.title = self.menu_title74 menuTable.add_column()75 menuTable.add_column()76 for key in self.menu_options: # Add rows into the menu77 try:78 # If the option has declared it's only for managers then we only show that79 if self.menu_options[key]['access'].lower() == 'manager' and self.loggedInUser.isManager:80 menuTable.add_row(key, self.menu_options[key]['title'])81 # Else we show everthing82 elif self.menu_options[key]['access'] != 'manager':83 menuTable.add_row(key, self.menu_options[key]['title'])84 except KeyError:85 # If we get a KeyError then we asume there isn't any option as to who can see this so we add it to the list86 menuTable.add_row(key, self.menu_options[key]['title'])87 menuTable.box = box.MINIMAL88 menuTable.caption = f'You are logged in as {self.loggedInUser.name}'89 menuTable_centered = Align.center(menuTable)90 print(Align.center(Text.from_markup(NAN_AIR_LOGO))) # Print the NaN Air logo91 print(menuTable_centered)92 menuState = self.getUserInput()93 if menuState == 'main': # Check if the user wanted to go to the main menu94 if self.isMainMenu == False:95 return menuState # If this menu is not the main menu then return 'main'96 else:97 menuState = 'run' # If this is the main menu then turn menuState into 'run'98 elif menuState == 'quit':99 self.clear()100 print('Goodbye!')101 exit()102 def getUserInput(self):103 '''Gets the user input, then directs that input into computeUserOptions.\n104 Only used in menus'''105 try:106 user_input = self.waitForKeyPress(print_text=False).upper() #User input107 return self.computeUserOptions(user_input)108 except KeyboardInterrupt:109 print('')110 if input('Are you sure you want to quit? (y/N): ').lower() == 'y':111 return 'quit'112 else:113 self.getUserInput()114 def computeUserOptions(self, user_input)-> str:115 ''' Finds what option the user input corresponds to.\n116 If it's a function, it runs the function.\n117 if it's a class it initiates the class\n118 There are also "special" values such as back, menu or quit'''119 opt = self.menu_options120 # Checks if the user input is in the menu_options121 if user_input in opt:122 123 if 'special' in opt[user_input]:124 if opt[user_input]['special'] == 'back':125 return 'back'126 elif opt[user_input]['special'] == 'main':127 return 'main'128 elif opt[user_input]['special'] == 'quit':129 return 'quit'130 elif 'class' in opt[user_input]:131 opt_class = opt[user_input]['class']132 new_menu = opt_class(logged_in_user=self.loggedInUser) # initiate the selected class133 # Calls the print_options in the selected class134 if new_menu.print_options() == 'main': # If the function returned main then we return that135 return 'main'136 return 'run' # else we return run137 elif 'function' in opt[user_input]:138 opt_func = opt[user_input]['function']139 run_func = getattr(self, opt_func, self.funcNotFound)140 self.clear()141 # Error handler for functions 142 try:143 run_func() # RUN THE FUNCTION!!!144 return 'run'145 except Exception as err:146 return self.errorHandler(err)147 else:148 return 'run'149 else:150 #print(f'Invalid input: {user_input}')151 return 'run'152 def createTable(self, 153 header, 154 obj_list, 155 hide_header: bool=False,156 table_title: str=None, 157 line_between_records: bool=False, 158 return_table: bool=False, 159 justify_table: str='left',160 table_style: str='bright_yellow',161 color_newest: bool=False,162 hide_entry_count: bool=False,163 entry_limit: int=0):164 ''' Creates a Rich table, falls back to default if not available\n165 header can be a list, then it's just the keys to be used. or it can be a dict\n166 Ex. header = {167 KEY: {168 'display_name': TITLE_TO_DISPLAY,169 'prefix': STRING_TO_PREFIX_VALUE,170 'suffix': STRING_TO_SUFFIX_VALUE,171 'justify': string. left, right or center,172 'style': STYLE (can be color, text style, ex. 'bold blue'),173 'header_style': same as style but only applies to the header174 }, ...175 }'''176 obj = obj_list.copy()177 if not RICH_AVAILABLE:178 return self.createTableNoDependency(header, obj, line_between_records)179 table = Table(show_lines=line_between_records) # Initiate the table180 if type(header) is list:181 # If input is a list then we add that in182 old_header = header183 header = {}184 for key in old_header:185 table.add_column(key)186 header.update({key: {}})187 else:188 # populate configs189 for i, key in enumerate(header):190 try: # If display name wasn't set then default to key name191 table.add_column(header[key]['display_name'])192 except KeyError:193 table.add_column(key)194 try:195 table.columns[i].justify = header[key]['justify']196 except KeyError:197 pass198 try:199 table.columns[i].style = header[key]['style']200 except KeyError:201 pass202 try:203 table.columns[i].header_style = header[key]['header_style']204 except KeyError:205 pass206 # If entry_limit is higher than amount of found records then we default to amount of found records207 max_entries = len(obj) if entry_limit == 0 and (entry_limit >= len(obj) if entry_limit !=0 else True) else entry_limit208 for record in obj[:max_entries]:209 try:210 record = record.__dict__211 except AttributeError:212 pass213 row_list = []214 for key in header:215 if key in record:216 if type(record[key]) is list:217 record[key] = ''.join([f'{list_val}'+(', ' if i < (len(record[key]) -1) else '') for i, list_val in enumerate(record[key])])218 elif type(record[key]) is bool:219 record[key] = 'True' if record[key] else 'False'220 elif type(record[key]) is int:221 record[key] = str(record[key])222 elif type(record[key]) is float:223 record[key] = str(round(record[key]))224 try:225 record[key] += header[key]['suffix']226 except KeyError:227 pass228 row_list.append(record[key])229 table.add_row(*row_list)230 if table_title:231 table.title = table_title232 if color_newest:233 table.rows[table.row_count-1].style = 'bright_blue'234 235 if not hide_entry_count: # if asked to not show entry count then don't236 # Shows "found x entries" if there is no limit or if the amount of found entries is the same as the limit237 # else it shows "Showing x entries of y" where x is the limit and y is the total found238 # Useful where space is crucial239 table.caption = (f'Found {len(obj)} entries.') if entry_limit == 0 or (entry_limit >= len(obj) if entry_limit !=0 else False) else (f'Showing {entry_limit} entries of {len(obj)}')240 # table.row_styles = ['none', 'dim'] # Old, doesn't look good, better to have lines between records241 table.border_style = Style.parse(table_style) # Parse the table style to the correct format for Rich242 table.box = box.ROUNDED # Use rounded table style243 table.show_header = not hide_header # invert244 #if justify_table == 'center':245 # print('heha')246 # table_aligned = Align.center(table)247 #elif justify_table == 'right':248 # table_aligned = Align.right(table)249 #elif justify_table == 'left':250 # table_aligned = Align.left(table)251 #else:252 table_aligned = Align.center(table) # Center the table in the terminal253 if return_table: # If the caller needs the table as an object as opposed to printing it254 return table_aligned255 else:256 print(table_aligned)257 return ''258 def createTableNoDependency(self, header: list or dict, objList: list, line_between_records=False):259 '''!!! Backup if rich is not installed, do not call directly !!!\n260 Creates and returns a formatted table. \n261 header input is a list of those keys you want to include in the table\n262 \t Ex. header = ['name', 'email', 'ssn', 'isManager'] \n263 objList is a list of model objects'''264 if type(header) is list: 265 show_keys = {}266 for key in header:267 show_keys.update({key: {}})268 else:269 show_keys = header270 # Add length of each key to dictionary271 for key in show_keys:272 show_keys[key].update({'length': len(key)})273 try:274 show_keys[key]['special_color']275 except KeyError:276 show_keys[key].update({'special_color': None})277 try:278 show_keys[key]['display_name']279 except KeyError:280 show_keys[key].update({'display_name': key})281 try:282 show_keys[key]['prefix']283 except KeyError:284 show_keys[key].update({'prefix': ''})285 try:286 show_keys[key]['suffix']287 except KeyError:288 show_keys[key].update({'suffix': ''})289 # Finds max length for each key290 for record in objList:291 try:292 record = record.__dict__293 except AttributeError:294 pass295 for key in show_keys:296 record_keyVal = len(str(record[key]))297 if record_keyVal > show_keys[key]['length']:298 show_keys[key]['length'] = record_keyVal299 300 # Find total character length of longest line301 total_length = sum([(302 show_keys[key]['length'] + (2 if (len(show_keys) - 1) is i else 3)303 ) for i, key in enumerate(show_keys)])304 # Add top line to table printout305 printout = ''#.join([('-'*total_length),'\n'])306 # Add key header to table printout307 printout += (''.join([308 (color(''.join(309 [ # Bit convoluted but, part before the if statement is the normal printout of the header, the part after the if statement is if header list has a 'special_color' key which then colors that column310 '| ',(''.join(['{:<',str(show_keys[key]['length']),'}']) ), # Specify length of field311 (" |" if (len(show_keys) - 1) is i else " " ) # Put a pipe if this is the end field312 ]313 ), 'black',314 'white')) for i, key in enumerate(show_keys) # For each header value315 ])316 .format(*[show_keys[key]['display_name'] for key in show_keys])) + '\n'# Input all header keys317 318 printout += '|'+('-'*total_length)+'|\n' if line_between_records else ''319 for record in objList:320 try:321 record = record.__dict__322 except AttributeError:323 pass324 printout += (325 ''.join([326 ((''.join(327 ['| {:<',str(show_keys[key]['length']),'}', (" |" if (len(show_keys) - 1) is i else " " )] # Creates a string for format to input data328 )) #if type(record[key]) is not list else (''.join(329 # ['| {:<',str(show_keys[key]['length']),'}',(" |" if (len(show_keys) - 1) is i else " " )]330 # ).format(''.join([x+(', ' if i2 < (len(record[key])-1) else '') for i2, x in enumerate(record[key])]))331 ) for i, key in enumerate(show_keys)332 ])333 .format(*[(str(show_keys[key]['prefix'])+str(record[key])+str(show_keys[key]['suffix']) if type(record[key]) is not list else ''.join(334 [x+(', ' if i2 < (len(record[key])-1) else '') for i2, x in enumerate(record[key])]335 )) for key in show_keys]))+'\n'+(('|'+('-'*total_length)+'|\n') if line_between_records else '') # Adds values to string, adds a prefix and suffix of it exists, and a line between records if asked for336 # Adds bottom line337 printout += '|'+color((''.join([' {:<',str(total_length-2), '} '])).format('Nr. of records: '+str(len(objList))), 'black', 'blue', 'underline')+'|\n'338 printout += ' '+('‾'*total_length)+' '339 340 print(printout)341 return ''342 def waitForKeyPress(self, text_to_print: str='Press any key to continue ', print_text: bool=True):343 ''' Wait for a key press on the console and return it. '''344 # Script gotten from https://stackoverflow.com/questions/983354/how-to-make-a-python-script-wait-for-a-pressed-key345 # Which was rewritten code from the Python Docs346 if print_text:347 print(text_to_print, end='')348 if os.name == 'nt': # If user is on windows then use msvcrt349 import msvcrt350 key = msvcrt.getch()351 if ord(key) == 3 or ord(key) == 26: # Check if input key is Ctrl + C og Ctrl + Z352 raise KeyboardInterrupt353 return key.decode('ASCII')354 else: # If user is on a unix based system then use termios355 import termios356 fd = sys.stdin.fileno()357 oldterm = termios.tcgetattr(fd)358 newattr = termios.tcgetattr(fd)359 newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO360 termios.tcsetattr(fd, termios.TCSANOW, newattr)361 try:362 return sys.stdin.read(1)363 except IOError:364 pass365 finally:366 termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)367 # BUG: DOESN'T WORK ON WINDOWS368 # PROBABLY BCUZ OF READLINE369 def autocomplete_input(self, possible: list=None): # Creates an input that takes possible inputs as a list and provides a autocomplete function370 if 'libedit' in readline.__doc__: # If running python provided with mac then readline is non standard371 readline.parse_and_bind("bind ^I rl_complete") # Different keybind rules if running a mac372 else:373 readline.parse_and_bind("tab: complete") # Normal keybind rules374 readline.set_completer(TextCompleter(possible).complete)375 line = ''376 while line != 'exit':377 line = input('Enter name of user(exit to leave): ')378 if line in possible:379 return line380 381 def funcNotFound(self):382 print('Function not found')383 self.waitForKeyPress()384 def errorHandler(self, err):385 if RICH_AVAILABLE:386 print(Text.from_markup("Uh Oh! I encountered an [underline]error[/underline]", style="white on red"), Text.from_markup(" :cry:"))387 print(err)388 else:389 print(color("Uh Oh! I encountered an error", "white", "red", "underline"))390 print(err)391 self.waitForKeyPress("\nPress any key to return to safety!")...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful