How to use class_attribute_value method in Selene

Best Python code snippet using selene_python

postgresql_data_driver.py

Source:postgresql_data_driver.py Github

copy

Full Screen

1import random2import psycopg23from factorizer import utils4from factorizer.data_drivers.data_driver import DataDriver5CREATE_TABLE_STATEMENT = 'CREATE TABLE {table_name_} ({columns_definitions_});'6COLUMN_DEFINITIONS_PATTERN = '"{name_}" {type_}'7COPY_FROM_CSV_WITH_HEADER_STATEMENT = 'COPY {table_name_} ' \8 'FROM STDIN ' \9 'WITH CSV HEADER ' \10 'DELIMITER AS \'{delimiter_}\''11COPY_FROM_CSV_WITHOUT_HEADER_STATEMENT = 'COPY {table_name_} ' \12 'FROM STDIN ' \13 'DELIMITER AS \'{delimiter_}\''14COPY_TO_CSV_WITH_HEADER_STATEMENT = 'SELECT SETSEED({random_seed_}); ' \15 'COPY ({statement_}) ' \16 'TO STDOUT ' \17 'WITH CSV HEADER ' \18 'DELIMITER AS \',\''19COPY_TO_CSV_WITHOUT_HEADER_STATEMENT = 'SELECT SETSEED({random_seed_}); ' \20 'COPY ({statement_}) ' \21 'TO STDOUT ' \22 'DELIMITER AS \',\''23DROP_TABLE_STATEMENT = 'DROP TABLE IF EXISTS {table_name_};'24SELECT_DISTINCT_STATEMENT = 'SELECT DISTINCT "{column_name_}" ' \25 'FROM {table_name_};'26COUNT_STATEMENT = 'SELECT COUNT(*) ' \27 'FROM {table_name_} ' \28 'WHERE "{column_name_}" = \'{value_}\';'29GET_COLUMNS_NAMES_STATEMENT = 'SELECT * ' \30 'FROM {table_name_} ' \31 'LIMIT 0;'32SELECT_SAMPLE_STATEMENT = 'SELECT {attributes_} ' \33 'FROM {table_name_} ' \34 'WHERE "{class_attribute_}" = \'{class_attribute_value_}\' ' \35 'ORDER BY RANDOM() ' \36 'LIMIT {limit_} ' \37 'OFFSET {offset_}'38ATTRIBUTE_TYPE_NAMES = {39 'integer': 'int',40 'real': 'numeric',41 'text': 'text',42}43DATA_CHUNK_SIZE = 409644class PostgreSQLDataDriver(DataDriver):45 """46 Implements a data driver communicating with a PostgreSQL database.47 """48 def __init__(self, database, username, password, hostname, port):49 """50 Initializes the data driver.51 :param database: the name of the database52 :type database: str53 :param username: the username54 :type username: str55 :param password: the password56 :type password: str57 :param hostname: the hostname58 :type hostname: str59 :param port: the port60 :type port: str61 """62 super().__init__()63 self.__connection = psycopg2.connect(64 database=database,65 user=username,66 password=password,67 host=hostname,68 port=port69 )70 self.__cursor = self.__connection.cursor()71 def close(self):72 self.__cursor.close()73 self.__connection.close()74 def create_structure(75 self,76 name,77 attributes78 ):79 # Creates the structure.80 columns_definitions = self.__compose_columns_definitions(attributes)81 self.__cursor.execute(CREATE_TABLE_STATEMENT.format(table_name_=name, columns_definitions_=columns_definitions))82 self.__connection.commit()83 def destroy_structure(84 self,85 name,86 ):87 self.__cursor.execute(DROP_TABLE_STATEMENT.format(table_name_=name))88 self.__connection.commit()89 def fill_structure(90 self,91 name,92 delimiter,93 header,94 input_csv,95 ):96 if header:97 statement = COPY_FROM_CSV_WITH_HEADER_STATEMENT.format(table_name_=name, delimiter_=delimiter)98 else:99 statement = COPY_FROM_CSV_WITHOUT_HEADER_STATEMENT.format(table_name_=name, delimiter_=delimiter)100 self.__cursor.copy_expert(101 statement,102 file=input_csv,103 )104 self.__connection.commit()105 def get_training_split(106 self,107 dataset_name,108 training_rate,109 class_attribute,110 include_attributes,111 exclude_attributes,112 attributes_rate,113 random_seed,114 output_csv,115 include_header,116 class_only,117 ):118 return self._get_split(119 split_type=DataDriver.SplitType.training,120 dataset_name=dataset_name,121 training_rate=training_rate,122 fusion_rate=0,123 training_sample_rate=0,124 training_sample_number=0,125 class_attribute=class_attribute,126 include_attributes=include_attributes,127 exclude_attributes=exclude_attributes,128 attributes_rate=attributes_rate,129 random_seed=random_seed,130 output_csv=output_csv,131 include_header=include_header,132 class_only=False,133 )134 def get_fusion_split(135 self,136 dataset_name,137 training_rate,138 fusion_rate,139 class_attribute,140 include_attributes,141 exclude_attributes,142 attributes_rate,143 random_seed,144 output_csv,145 include_header,146 class_only,147 ):148 return self._get_split(149 split_type=DataDriver.SplitType.fusion,150 dataset_name=dataset_name,151 training_rate=training_rate,152 fusion_rate=fusion_rate,153 training_sample_rate=0,154 training_sample_number=0,155 class_attribute=class_attribute,156 include_attributes=include_attributes,157 exclude_attributes=exclude_attributes,158 attributes_rate=attributes_rate,159 random_seed=random_seed,160 output_csv=output_csv,161 include_header=include_header,162 class_only=class_only,163 )164 def get_test_split(165 self,166 dataset_name,167 training_rate,168 fusion_rate,169 class_attribute,170 include_attributes,171 exclude_attributes,172 attributes_rate,173 random_seed,174 output_csv,175 include_header,176 class_only,177 ):178 return self._get_split(179 split_type=DataDriver.SplitType.test,180 dataset_name=dataset_name,181 training_rate=training_rate,182 fusion_rate=fusion_rate,183 training_sample_rate=0,184 training_sample_number=0,185 class_attribute=class_attribute,186 include_attributes=include_attributes,187 exclude_attributes=exclude_attributes,188 attributes_rate=attributes_rate,189 random_seed=random_seed,190 output_csv=output_csv,191 include_header=include_header,192 class_only=class_only,193 )194 def get_training_sample(195 self,196 dataset_name,197 training_rate,198 sample_rate,199 sample_number,200 class_attribute,201 include_attributes,202 exclude_attributes,203 attributes_rate,204 random_seed,205 output_csv,206 include_header,207 class_only,208 ):209 return self._get_split(210 split_type=DataDriver.SplitType.training_sample,211 dataset_name=dataset_name,212 training_rate=training_rate,213 fusion_rate=0,214 training_sample_rate=sample_rate,215 training_sample_number=sample_number,216 class_attribute=class_attribute,217 include_attributes=include_attributes,218 exclude_attributes=exclude_attributes,219 attributes_rate=attributes_rate,220 random_seed=random_seed,221 output_csv=output_csv,222 include_header=include_header,223 class_only=class_only,224 )225 def _get_split(226 self,227 split_type,228 dataset_name,229 training_rate,230 fusion_rate,231 training_sample_rate,232 training_sample_number,233 class_attribute,234 include_attributes,235 exclude_attributes,236 attributes_rate,237 random_seed,238 output_csv,239 include_header,240 class_only,241 ):242 """243 Outputs the required split to a CSV output file.244 :param split_type: the split type245 :type split_type: DataDriver.SplitType246 :param dataset_name: the name of the dataset247 :type dataset_name: str248 :param training_rate: the percentage of the dataset to consider as training split249 :type training_rate: float250 :param fusion_rate: the percentage of the dataset to consider as fusion split251 :type fusion_rate: float252 :param class_attribute: the name of the class attribute253 :type class_attribute: str254 :param include_attributes: the list of the attributes to include, None otherwise255 :type include_attributes: list[str]256 :param exclude_attributes: the list of the attributes to exclude, None otherwise257 :type exclude_attributes: list[str]258 :param attributes_rate: the percentage of attributes to include259 :type attributes_rate: float260 :param random_seed: the random seed261 :type random_seed: int262 :param output_csv: the output file as an opened stream263 :type output_csv: file264 :param include_header: if True, it includes the header in the output CSV265 :type include_header: bool266 :param class_only: specifies if returning the class column only267 :type class_only: bool268 """269 # Prepares the random generator.270 random_generator = random.Random(random_seed)271 # Retrieves the attributes names except for the class attribute.272 attributes_names = self.__get_attributes_names(dataset_name, class_attribute)273 # Filters the attributes.274 attributes_names = self.__filter_attributes(attributes_names, include_attributes, exclude_attributes)275 # Generates the random list of attributes.276 attributes_sample_size = int(len(attributes_names) * attributes_rate)277 attributes_sample = utils.random_ordered_sample(278 random_generator,279 attributes_names,280 attributes_sample_size,281 )282 # Retrieves the possible class attribute values.283 class_attribute_values = self.__get_class_attribute_values(dataset_name, class_attribute)284 # For each class attribute value samples the data.285 is_first_partition = True286 for class_attribute_value in class_attribute_values:287 # Counts the number of instances for the current partition.288 current_partition_size = self.__get_partition_size(dataset_name, class_attribute, class_attribute_value)289 # Computes all the split sizes.290 current_partition_training_split_size = int(current_partition_size * training_rate)291 current_partition_fusion_split_size = int(current_partition_size * fusion_rate)292 current_partition_test_split_size =\293 current_partition_size - current_partition_training_split_size - current_partition_fusion_split_size294 # Discriminates according to the split type.295 current_partition_split_size = None296 current_partition_split_offset = None297 if split_type == DataDriver.SplitType.training:298 current_partition_split_size = current_partition_training_split_size299 current_partition_split_offset = 0300 elif split_type == DataDriver.SplitType.fusion:301 current_partition_split_size = current_partition_fusion_split_size302 current_partition_split_offset = current_partition_training_split_size303 elif split_type == DataDriver.SplitType.test:304 current_partition_split_size = current_partition_test_split_size305 current_partition_split_offset =\306 current_partition_training_split_size + current_partition_fusion_split_size307 elif split_type == DataDriver.SplitType.training_sample:308 current_partition_split_size = int(current_partition_training_split_size * training_sample_rate)309 current_partition_split_offset = current_partition_split_size * training_sample_number310 # Copies the instances to the output CSV.311 self.__copy_instances_to_csv(312 table_name=dataset_name,313 attributes_sample=attributes_sample,314 class_attribute=class_attribute,315 class_attribute_value=class_attribute_value,316 split_size=current_partition_split_size,317 offset=current_partition_split_offset,318 is_first_partition=is_first_partition,319 random_seed=random_seed,320 output_csv=output_csv,321 include_header=include_header,322 class_only=class_only,323 )324 if is_first_partition:325 is_first_partition = False326 def __get_attributes_names(self, table_name, class_attribute):327 """328 Retrieves the list of attributes except for the class attribute.329 :param table_name: the name of the table330 :type table_name: str331 :param class_attribute: the class attribute name332 :type class_attribute: str333 :return: the list of attributes334 :rtype: list[str]335 """336 self.__cursor.execute(GET_COLUMNS_NAMES_STATEMENT.format(table_name_=table_name))337 attributes_names = [338 column.name339 for column in self.__cursor.description340 if column.name != class_attribute341 ]342 return attributes_names343 def __get_class_attribute_values(self, table_name, class_attribute):344 """345 Retrieves the class attribute values.346 :param table_name: the name of the table347 :type table_name: str348 :param class_attribute: the class attribute name349 :type class_attribute: str350 :return: the class attribute value351 :rtype: list[object]352 """353 self.__cursor.execute(354 SELECT_DISTINCT_STATEMENT.format(355 column_name_=class_attribute,356 table_name_=table_name,357 )358 )359 class_attribute_values = [value[0] for value in self.__cursor.fetchall()]360 return class_attribute_values361 def __get_partition_size(self, table_name, class_attribute, class_attribute_value):362 """363 Retrieves the number of instances in the partition.364 :param table_name: the name of the table365 :type table_name: str366 :param class_attribute: the class attribute name367 :type class_attribute: str368 :param class_attribute_value: the value of the class attribute369 :type class_attribute_value: object370 :return: the partition size371 :rtype: int372 """373 self.__cursor.execute(374 COUNT_STATEMENT.format(375 table_name_=table_name,376 column_name_=class_attribute,377 value_=class_attribute_value,378 )379 )380 current_partition_size = self.__cursor.fetchone()[0]381 return current_partition_size382 def __copy_instances_to_csv(383 self,384 table_name,385 attributes_sample,386 class_attribute,387 class_attribute_value,388 split_size,389 offset,390 is_first_partition,391 random_seed,392 output_csv,393 include_header,394 class_only,395 ):396 """397 Copies the instances to the output CSV file.398 :param table_name: the name of the table399 :type table_name: str400 :param attributes_sample: the list of attributes to select401 :type attributes_sample: list[str]402 :param class_attribute: the name of the class attribute403 :type class_attribute: str404 :param class_attribute_value: the value of the class attribute405 :type class_attribute_value: object406 :param split_size: the number of the instances to obtain407 :type split_size: int408 :param offset: the offset from the instance number 0409 :type offset: int410 :param is_first_partition: specifies if is the first partition that is treated411 :type is_first_partition: bool412 :param random_seed: the random seed413 :type random_seed: int414 :param output_csv: the output file as an opened stream415 :type output_csv: file416 :param include_header: if True, it includes the header in the output CSV417 :type include_header: bool418 :param class_only: specifies if returning the class column only419 :type class_only: bool420 """421 if class_only:422 formatted_attributes_sample = ['"' + class_attribute + '"']423 else:424 formatted_attributes_sample = ['"' + x + '"' for x in attributes_sample]425 formatted_class_attribute_name = '"' + class_attribute + '"'426 formatted_attributes_sample.append(formatted_class_attribute_name)427 statement = SELECT_SAMPLE_STATEMENT.format(428 attributes_=', '.join(formatted_attributes_sample),429 table_name_=table_name,430 class_attribute_=class_attribute,431 class_attribute_value_=class_attribute_value,432 limit_=split_size,433 offset_=offset,434 )435 if is_first_partition and include_header:436 self.__cursor.copy_expert(437 COPY_TO_CSV_WITH_HEADER_STATEMENT.format(438 random_seed_=random_seed,439 statement_=statement,440 ),441 file=output_csv,442 )443 else:444 self.__cursor.copy_expert(445 COPY_TO_CSV_WITHOUT_HEADER_STATEMENT.format(446 random_seed_=random_seed,447 statement_=statement,448 ),449 file=output_csv,450 )451 @staticmethod452 def __compose_columns_definitions(attributes):453 """454 Composes a string containing the attibutes and their types.455 :param attributes: the list of the attribute names456 :type attributes: list[str]457 :return: the string of attributes with types458 :rtype: str459 """460 columns_definitions = []461 for attribute in attributes:462 columns_definitions.append(463 COLUMN_DEFINITIONS_PATTERN.format(464 name_=attribute['name'],465 type_=ATTRIBUTE_TYPE_NAMES[attribute['type']]466 )467 )468 return ', '.join(columns_definitions)469 @staticmethod470 def __filter_attributes(attributes, include, exclude):471 """472 Retrieves the list of the attribute names based on the lists of include and exclude attributes.473 :param attributes: the original list of attributes474 :type attributes: list[str]475 :param include: the attributes to include476 :type include: list[str]477 :param exclude: the attributes to exclude478 :type exclude: list[str]479 :return: the list of filtered attributes480 :rtype list[str]481 """482 if include:483 return include484 if not exclude:485 return attributes486 filtered_attributes = []487 for attribute in attributes:488 if attribute not in exclude:489 filtered_attributes.append(attribute)...

Full Screen

Full Screen

VM_Summary_UIMap.py

Source:VM_Summary_UIMap.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2'''3Created on 2014��10��23��45@author: stm6'''7from selenium.webdriver.common.by import By8from Common.Utils import PD_DebugLog, utils_misc9import time1011class VM_Summary_UIMap():12 '''13 Get the page element from Platform Summary page14 '''15 16 # Routine actions bar("常规" 栏)17 ACTION_BOOTUP, ACTION_SMSBOOT, ACTION_SHUTDOWN, ACTION_POWERDOWN, ACTION_REBOOT = range(1,6)18 19 # More actions bar("更多" 栏)20 ACTION_EDIT, ACTION_RENAME, ACTION_REMOVE, ACTION_VOL_MGMT, ACTION_CONFIG_NIC, \21 ACTION_CDROM_MGMT, ACTION_UNMOUNT, ACTION_MIGRATE, ACTION_VM_TEMPLATE_CONVT, \22 ACTION_REGISTER_IP, ACTION_CANCEL_BOOT_WITH_HOST, ACTION_SOFTWARE_MGMT = range(1,13)23 24 VM_NAME_XPATH = '/html/body/div/fieldset/legend'25 VM_CURRENT_STATUS_XPATH = '//*[@id="vm_status_show"]'26 VM_IPADDR_XPATH = '/html/body/div/form/fieldset/table/tbody/tr/td[2]/ul/li[2]/span[2]'27 28 29 def __init__(self, driver):30 ''' initialize the Platform Summary Page class '''31 32 self.driver = driver33 self.accept_next_alert = True34 35 def _common_enter_summary_frame_proc(self):36 # /html/body/div[2]/div[2]/iframe37 # //*[@id="_summary"]38 # self.driver.switch_to.frame('_summary')39 self.contentpanel = self.driver.find_element(By.ID, 'contentpanel')40 #PD_DebugLog.debug_print(self.contentpanel.page_source)41 self.framesummary = self.contentpanel.find_element(By.ID, '_stage')42 #PD_DebugLog.debug_print(self.frame_summary.)43 44 # continuously get the frame and the sub frame method experience 45 # failed: NoSuchFrameException: Message: u'Unable to locate frame: _stage._summary' ; Stacktrace: 46 # at FirefoxDriver.prototype.switchToFrame (file:///c:/users/stm/appdata/local/temp/tmpaqoscv/extensions/fxdriver@googlecode.com/components/driver_component.js:8974)47 # at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/stm/appdata/local/temp/tmpaqoscv/extensions/fxdriver@googlecode.com/components/command_processor.js:10884)48 # at fxdriver.Timer.prototype.setTimeout/<.notify (file:///c:/users/stm/appdata/local/temp/tmpaqoscv/extensions/fxdriver@googlecode.com/components/command_processor.js:396)49 50 #self.driver_sub = self.driver.switch_to.frame('_stage._summary')51 52 # Failed: the method would not return the driver53 #self.driver_sub = self.driver.switch_to.frame('_stage')54 self.driver.switch_to.frame('_stage')55 self.driver.switch_to.frame('_summary')56 57 self.frame_summary_wrapper = self.driver.find_element(By.XPATH, '//html/body')58 59 def _test_if_in_summary_frame(self):60 # Test if frame summary is present61 # 1. 62 isPresent = self.frame_summary_wrapper != None63 msg = 'Frame summary is %s present'64 if isPresent:65 PD_DebugLog.debug_print(msg % '')66 else:67 PD_DebugLog.debug_print(msg % 'not')68 69 if isPresent:70 path_str = '//html/body/div/fieldset/table/tbody/tr/td[2]/ul/li/span'71 path_str_from_Chrome = '//*[@id="wrapper"]/fieldset/table/tbody/tr/td[2]/ul/li/span[1]'72 title_test_elm = self.driver.find_element(By.XPATH, path_str)73 text = title_test_elm.text74 PD_DebugLog.debug_print('The title is %s .' % text)75 76 def _common_exit_summary_frame_proc(self): 77 self.driver.switch_to.default_content() 78 79 80 def get_vm_static_label_text(self, label_xpath):81 '''82 get the static label text83 '''84 self._common_enter_summary_frame_proc()85 86 elem = self.driver.find_element(By.XPATH, label_xpath)87 text = elem.text88 PD_DebugLog.debug_print("Get the element title: " + elem.text)89 self._common_exit_summary_frame_proc()90 return text91 92 93 def get_vm_name(self):94 '''95 get the vm name96 '''97 return self.get_vm_static_label_text(VM_Summary_UIMap.VM_NAME_XPATH) 98 99 100 def get_vm_ip(self):101 '''102 get the vm name103 '''104 return self.get_vm_static_label_text(VM_Summary_UIMap.VM_IPADDR_XPATH) 105 106 107 def get_vm_current_status(self):108 '''109 To get the vm current status txt110 '''111 return self.get_vm_static_label_text(VM_Summary_UIMap.VM_CURRENT_STATUS_XPATH)112113114 def execute_action_without_confirm_dialog(self, action_type, with_dialog_prompt=False):115 '''116 To execute the action in the route bar without dialog prompt117 '''118 self.execute_action_with_confirm_dialog(action_type, False, False)119 120 121 def execute_action_with_confirm_dialog(self, action_type, confirm=True, with_dialog_prompt=True):122 '''123 To execute the action in the route bar124 '''125 self._common_enter_summary_frame_proc()126 # //*[@id="vm_shutdown"]127 xpath = '//html/body/div/form/div/table/tbody/tr/td/div/ul/li[%d]/a' % action_type128 shutdown_system_elemt = self.driver.find_element(By.XPATH, xpath)129 shutdown_system_elemt.click()130 time.sleep(1)131 132 if with_dialog_prompt:133 alert_dialog = self.driver.switch_to_alert()134 assert alert_dialog135 136 time.sleep(1)137 if confirm:138 alert_dialog.accept()139 else:140 alert_dialog.cancel()141 time.sleep(1)142 143 self._common_exit_summary_frame_proc()144 145 def execute_boot_system(self):146 '''147 To shutdown system148 '''149 self.execute_action_without_confirm_dialog(VM_Summary_UIMap.ACTION_BOOTUP)150 151 152 def execute_shutdown_system(self, shutdown_confirmed=True):153 '''154 To shutdown system155 '''156 self.execute_action_with_confirm_dialog(VM_Summary_UIMap.ACTION_SHUTDOWN, shutdown_confirmed)157 158 159 def execute_powerdown_system(self, powerdown_confirmed=True):160 '''161 To shutdown system162 '''163 self.execute_action_with_confirm_dialog(VM_Summary_UIMap.ACTION_POWERDOWN, powerdown_confirmed)164 165 166 def execute_reboot_system(self, reboot_confirmed=True):167 '''168 To shutdown system169 '''170 self.execute_action_with_confirm_dialog(VM_Summary_UIMap.ACTION_REBOOT, reboot_confirmed)171 172 173 def is_vm_starting(self):174 '''175 To compare the current status txt, if it running return True176 '''177 return self.test_expected_status_text(u'启动中')178 179 180 def is_vm_running(self):181 '''182 To compare the current status txt, if it running return True183 '''184 return self.test_expected_status_text(u'运行')185 186 187 def is_vm_in_shutdown_progress(self):188 return self.is_vm_in_powerdown_progress()189 190 191 def is_vm_in_powerdown_progress(self):192 '''193 To compare the current status txt, if it running return True194 '''195 return self.test_expected_status_text(u'关闭中')196 197 198 def is_vm_in_deleting_progress(self):199 '''200 To compare the current status txt, if it deleting return True201 '''202 return self.test_expected_status_text(u'删除中')203 204 205 def test_expected_status_text(self, status_text):206 '''207 To compare the status text expected208 '''209 expect_text = status_text210 got_text = self.get_vm_current_status()211 212 if expect_text == got_text:213 return True214 else: 215 return False216 217218 def get_more_actions_bar(self):219 '''220 Return the more actions bar221 '''222 self._common_enter_summary_frame_proc()223 224 xpath = '/html/body/div/form/div/table/tbody/tr/td[2]/div/h3/a'225 more_actions_bar_elemt = self.driver.find_element(By.XPATH, xpath)226 class_attribute_value = more_actions_bar_elemt.get_attribute("class")227 228 PD_DebugLog.debug_print("more actions bar class attribute is : " + class_attribute_value)229 if class_attribute_value != 'expand':230 more_actions_bar_elemt.click() 231 232 class_attribute_value = more_actions_bar_elemt.get_attribute("class")233 PD_DebugLog.debug_print("more actions bar class attribute is : " + class_attribute_value)234 235 236 self._common_exit_summary_frame_proc()237 238 return more_actions_bar_elemt, class_attribute_value 239 240 241 def expand_more_actions_bar(self):242 '''243 Make the more actions bar is expanded, if not expand it244 '''245 self._common_enter_summary_frame_proc()246 247 xpath = '/html/body/div/form/div/table/tbody/tr/td[2]/div/h3/a'248 more_actions_bar_elemt = self.driver.find_element(By.XPATH, xpath)249 class_attribute_value = more_actions_bar_elemt.get_attribute("class")250 251 PD_DebugLog.debug_print("more actions bar class attribute is : " + class_attribute_value)252 if class_attribute_value != 'expand':253 more_actions_bar_elemt.click() 254 255 class_attribute_value = more_actions_bar_elemt.get_attribute("class")256 PD_DebugLog.debug_print("more actions bar class attribute is : " + class_attribute_value)257 258 self._common_exit_summary_frame_proc()259 260 261 def return_to_parent(self):262 self.driver.switch_to.default_contenct()263264 265 def execute_action_from_more_actions_bar(self, action_type, with_dialog_prompt=False, confirm=True):266 '''267 execute the action in the more actions bar268 '''269 self._common_enter_summary_frame_proc()270 xpath = '//html/body/div/form/div/table/tbody/tr/td[2]/div/ul/li[%d]/a' % action_type271 elemt = self.driver.find_element(By.XPATH, xpath)272 elemt.click()273 time.sleep(1)274 275 if with_dialog_prompt:276 alert_dialog = self.driver.switch_to_alert()277 assert alert_dialog278 279 time.sleep(1)280 if confirm:281 alert_dialog.accept()282 else:283 alert_dialog.cancel()284 time.sleep(1)285 self._common_exit_summary_frame_proc()286 287 288 def click_register_IP_link(self):289 self.execute_action_from_more_actions_bar(VM_Summary_UIMap.ACTION_REGISTER_IP)290 291 292 def click_remove_vm_link(self):293 self.execute_action_from_more_actions_bar(VM_Summary_UIMap.ACTION_REMOVE, with_dialog_prompt=True, confirm=True)294 295 296 def is_loading_getvminfo(self):297 '''298 <div id="loading_overlay_getvminfo" style="position: fixed; z-index: 0; top: 325.8px; left: 304.5px; display: none;">299 <a class="close"></a>300 <img src="/images/loading.gif" alt="">301 <p>正在获取虚拟机信息</p>302 </div>303 '''304 utils_misc.set_implicity_wait_timeout(self.driver)305 elem = None306 try:307 xpath = '//*[@id="loading_overlay_getvminfo"]/a'308 elem = self.driver.find_element(By.XPATH, xpath)309 class_value = elem.get_attribute('class')310 PD_DebugLog.debug_print("The element's class value is " + class_value)311 utils_misc.restore_implicity_wait_timeout(self.driver)312 except:313 return False314 315 if elem and class_value != 'close':316 return True317 else: ...

Full Screen

Full Screen

builder.py

Source:builder.py Github

copy

Full Screen

1"""2This module provides an object builder inspired by Lombok (Java).3Quick start4###########5Here is a quick example on how to use it.6.. code-block:: python7 @dataclass8 class User:9 name: str10 age: int11 ObjectBuilder(User).name("Foo").age(123).build()12.. note:: This is tested with Python's built-in ``dataclass`` and Pylandic's ``BaseModel``.13"""14import inspect15from dataclasses import dataclass16from typing import Type, Any, Dict, Tuple, List17from gallium.obj.utils import is_optional, get_all_types, is_dataclass_class18@dataclass(frozen=True)19class AttributeSpec:20 """ Class Attribute Specification """21 name: str22 types: Tuple[Type]23 optional: bool24 default: Any25@dataclass26class Attribute:27 """ Class Attribute """28 spec: AttributeSpec29 value: Any30 initialized: bool31 def extract(self):32 if not self.spec.optional and not self.initialized:33 raise RequiredAttributeError(self.spec.name)34 return self.spec.default \35 if self.spec.optional and not self.initialized \36 else self.value37class ObjectBuilder:38 """ Object Builder39 Inspired by the ``lombok.builder`` annotation. (Java)40 """41 __HIDDEN_SCHEMA_PROPERTY_NAME = '__oriole_object_schema__'42 def __init__(self, cls: Type):43 self.__class = cls44 self.__class_schema: List[AttributeSpec] = list()45 self.__attribute_map: Dict[str, Attribute] = dict()46 self._analyze()47 def _analyze(self):48 # Reuse the cache.49 if hasattr(self.__class, self.__HIDDEN_SCHEMA_PROPERTY_NAME):50 self.__class_schema = getattr(self.__class, self.__HIDDEN_SCHEMA_PROPERTY_NAME)51 else:52 for attribute_name, annotation in self.__class.__annotations__.items():53 # Get the default value54 default_value = None55 if hasattr(self.__class, attribute_name):56 class_attribute_value = getattr(self.__class, attribute_name)57 if class_attribute_value is not None and not callable(class_attribute_value):58 default_value = class_attribute_value59 # Add to the schema60 self.__class_schema.append(61 AttributeSpec(name=attribute_name,62 types=get_all_types(annotation),63 optional=is_optional(annotation),64 default=default_value)65 )66 setattr(self.__class, self.__HIDDEN_SCHEMA_PROPERTY_NAME, self.__class_schema)67 if not hasattr(self.__class, '__annotations__'):68 raise IncompatibleBuildableClassError()69 for attr_spec in self.__class_schema:70 self.__attribute_map[attr_spec.name] = Attribute(71 spec=attr_spec,72 value=None,73 initialized=False,74 )75 def build(self, define_all_attributes: bool = True):76 """ Build an instance of the given class77 :param bool define_all_attributes: Flag to whether to fill in all attributes, including the ones which are78 not covered by the constructor.79 """80 properties = {81 attr.spec.name: attr.extract()82 for attr in self.__attribute_map.values()83 }84 if is_dataclass_class(self.__class):85 return self.__class(**properties)86 else:87 # Get the constructor parameters.88 constructor_signature = inspect.signature(self.__class)89 constructor_param_names = [param_name for param_name in constructor_signature.parameters]90 constructor_params = {91 param_name: properties[param_name]92 for param_name in constructor_param_names93 }94 # Instantiate the object.95 obj = self.__class(**constructor_params)96 if define_all_attributes:97 for attr_name, attr_value in properties.items():98 setattr(obj, attr_name, attr_value)99 return obj100 def __getattr__(self, item):101 if item not in self.__attribute_map:102 raise AttributeError(f'No setter for {item}')103 def setter(value):104 self.__attribute_map[item].value = value105 self.__attribute_map[item].initialized = True106 return self107 return setter108class RequiredAttributeError(RuntimeError):109 """ Attribute in question is not defined before building the object """110 pass111class IncompatibleBuildableClassError(RuntimeError):112 """ Class annotations does not exist """113 def __init__(self):114 super().__init__('Requires class annotations. '...

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 Selene 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