Best Python code snippet using pyatom_python
course_booking.py
Source:course_booking.py  
1'''2#############################################################################################3@brief Browser functions for course booking4#############################################################################################5'''6import time7import re8import datetime9from .logging import log, log_warning, log_error10from .progEnums import *11from .basic_actions import CBasicActions12from selenium import webdriver13from selenium.webdriver.common.keys import Keys14from selenium.webdriver.common.by import By15class CCourseBooking(CBasicActions):16    def __init__(self):17        pass18    def start_browser_course_booking(self):19        # Load website20        self.Driver.get(self.Settings.Document['weburl_booking'])21        self.login()22        return self.navigate_to_timeslots()23    def login(self):24        log('Website login...')25        # Set username26        self.set_textbox(_type=By.ID, _tag='user', _sendKeys=self.Settings.Document['username'])27        # Set pwd28        self.set_textbox(_type=By.ID, _tag='password', _sendKeys=self.Settings.Document['password'])29        # CLick login button30        self.click_button(_type=By.CLASS_NAME ,_tag='button')31        # Wait until iFrame "dynamic" is fully loaded32        self.wait_until_tag_is_present(_type=By.ID, _tag='dynamic')33    def navigate_to_timeslots(self):34        self.booktimes()35        self.set_date()36        # Set course type37        self.set_course(self.Settings.Document['courseBooking_enum'])38        # Refresh until timeslots are available39        waitTime = 240        i = 041        available = False42        while not available:43            table = self.get_timeslotTable()44            if table is not None and len(table) > 0:45                available = True46            else:47                # Back to default frame48                self.switch_toDefaultFrame()49                # Driver refresh50                self.Driver.refresh()51                time.sleep(waitTime)52                # Select iFrame again53                self.switch_to_frame(_type=By.ID, _tag='dynamic')54            i = i + 155            # Refresh timeout after 2 mins56            if i > 120 / waitTime:57                log_error('Refresh timeout')58                return dict()59        return self.parse_timeslots()60    def booktimes(self):61        # Default frame62        self.switch_toDefaultFrame()63        # Press Startzeiten64        self.click_button(_type=By.ID, _tag='pr_res_calendar')65    def set_date(self):66        log('Set date: {}'.format(self.Settings.Document['date']))67        self.switch_to_frame(_type=By.ID, _tag='dynamic')68        # Set Date69        self.set_textbox(_type=By.ID, _tag='date', _sendKeys=self.Settings.Document['date'], _keyPress=Keys.ENTER, _options='control+a')70    def set_course(self, _course):71        log('Set course: {}'.format(_course))72        # Set course73        self.set_dropdown(_tag='ro_id', _target=_course)74    def parse_timeslots(self):75        timeslots = dict()76        closedTimeslots = self.get_closedTimeslots()77        table = self.get_timeslotTable()78        if len(table) == 0:79            raise Exception('Could not parse timetable')80        tableSplit = table[0].text.split('\n')81        index = 082        for tSlot in tableSplit:83            btn_text = tSlot.strip()84            if re.search("^[0-9]{1,2}:[0-9]{1,2}$", btn_text):85                if index - 1 > -1:86                    btn_text_BEFORE = tableSplit[index - 1].strip()87                    if re.search("^[0-9]{1,2}:[0-9]{1,2}$", btn_text_BEFORE):88                        # Free89                        isFree = True90                    else:91                        # Not free92                        isFree = False93                else:94                    #  First element free and it is free95                    isFree = True96                # Set free timeslot based on conditions97                if isFree and btn_text not in closedTimeslots:98                    timeslots[btn_text] = CTimeslot(_timeVal=[btn_text, self.Settings.Document['date_converted']], _isFree=True)99                else:100                    timeslots[btn_text] = CTimeslot(_timeVal=[btn_text, self.Settings.Document['date_converted']], _isFree=False)101            index += 1102        # Sort available timeslots early -> old103        done = False104        tups = list(timeslots.items())105        while not done:106            indexChanged = False107            for i in range(0, len(tups)):108                if i + 1 < len(tups):109                    hashLowerIndex = tups[i][1].Slot.hour * 100 + tups[i][1].Slot.minute110                    hashUpperIndex = tups[i + 1][1].Slot.hour * 100 + tups[i + 1][1].Slot.minute111                    if hashUpperIndex < hashLowerIndex:112                        tups[i], tups[i + 1] = tups[i + 1], tups[i]113                        indexChanged = True114            # We ran trough all without switching index -> Done115            if not indexChanged:116                done = True;117        return dict(tups)118    def reservation(self, _timeslot):119        # Set timeslot120        self.select_timeslot(_timeslotStr=_timeslot.Str_text)121        # Switch to iFrame122        self.switch_to_frame(_type=By.ID, _tag='calendar_details')123        # Click reservation button124        self.click_button(_type=By.ID, _tag='btnMakeRes')125    def partner_reservation(self, _id):126        log('Partner reservation')127        # Toggle frames??? Without not working?128        self.switch_toDefaultFrame()129        self.switch_to_frame(_type=By.ID, _tag='dynamic')130        # Set partner131        for i in range(0, 4):132            partner = self.Settings.Document['round'][_id]['partner{}'.format(i)][0]133            if partner['firstName'] != 'None' and partner['lastName'] != 'None':134                log('Partner reservation: {} {}'.format(partner['firstName'], partner['lastName']))135                # Set first name136                self.set_textbox(_type=By.NAME, _tag='fname', _sendKeys=partner['firstName'], _options=['control+a'])137                # Set last name138                self.set_textbox(_type=By.NAME, _tag='lname', _sendKeys=partner['lastName'], _options=['control+a'])139                # Click search button140                self.click_button(_type=By.ID, _tag='btnSearch')141                # Get add button and press it. Classification by image142                hits = self.Driver.find_elements(By.CLASS_NAME, 'abutton')143                foundPartners = 0144                addElement = None145                for hit in hits:146                    if 'img/plus.gif' in hit.get_attribute("src"):147                        foundPartners += 1148                        addElement = hit149                        break150                # We expect exact one hit151                if addElement is not None and foundPartners == 1:152                    addElement.click()153                else:154                    return False155        return True156    def send_reservation(self):157        if self.Settings.TemplateDocument['developermode']:158            log_warning('Developer mode active. No reservation send')159        else:160            # Make reservation161            self.click_button(_type=By.ID, _tag='btnNext')162            log('Reservation send')163    def logout(self):164        try:165            self.switch_toDefaultFrame()166            self.click_button(_type=By.ID, _tag='logout')167        except:168            pass169    ################################################################################## ACTIONS ##################################################################################170    def set_textbox(self, _type, _tag, _sendKeys, _keyPress = Keys.NULL, _options = []):171        # Wait until present172        self.wait_until_tag_is_present(_type=_type, _tag=_tag)173        # Get element by ID174        element = self.Driver.find_element(_type, _tag)175        # Mark text in textbox176        if 'control+a' in _options:177            action = webdriver.ActionChains(self.Driver)178            action.key_down(Keys.LEFT_CONTROL).send_keys_to_element(element, 'a').key_up(Keys.LEFT_CONTROL).perform()179        # Send keys with extra key press at the end or not180        if _keyPress == Keys.NULL:181            element.send_keys(_sendKeys)                                    # Send keys182        else:183            element.send_keys('{} {}'.format(_sendKeys, _keyPress))         # Send keys and press key184    def set_dropdown(self, _tag, _target):185        # Wait until present186        self.wait_until_tag_is_present(_type=By.NAME, _tag=_tag)187        # Get element by name and open it188        element = self.Driver.find_element(By.NAME, _tag)189        element.click()190        if _target == BookingMode.Eighteen:191            # Press key down192            element.send_keys("1")193        elif _target == BookingMode.Nine:194            # Press key down195            element.send_keys("9")196        else:197            raise ValueError('{} is an unknown course'.format(_target))198        element.send_keys(Keys.ENTER)199    def select_timeslot(self, _timeslotStr):200        element = self.get_timeslotByXPath(_timeslotStr)201        if element == None:202            raise ValueError('Could not find timeslot: {}'.format(_timeslotStr.strftime('%H:%M')))203        element.click()204    def get_timeslotByXPath(self, _timeslotStr):205        elements = self.get_allLinks()206        # Find timeslot link207        for element in elements:208            if _timeslotStr == element.text:209                return element210        return None211    def get_timeslotTable(self):212        return self.Driver.find_elements_by_xpath("//*[@id='gridarea']/table/tbody")213    def get_closedTimeslots(self):214        # Get by class215        timeslotsClosed = self.Driver.find_elements(By.CLASS_NAME, "c-closed-txt")216        listTimeslotsClosed = list()217        # Run trough all and create dict218        if timeslotsClosed is not None and len(timeslotsClosed) > 0:219            for element in timeslotsClosed:220                btn_text = element.text.strip()221                if btn_text != '' and btn_text not in listTimeslotsClosed:222                    log('Timeslot is closed: {0}'.format(element.text.replace('\n', '')))223                    listTimeslotsClosed.append(btn_text)224        # Return dict with start times which are closed225        return listTimeslotsClosed226'''227#############################################################################################228@brief Timeslot object. Contains timeslot information229#############################################################################################230'''231class CTimeslot:232    Str_text = None233    Course = None234    Slot = None235    IsFree = False236    def __init__(self, _timeVal, _isFree):237        self.Str_text = _timeVal[0]238        self.IsFree = _isFree239        # Convert timeslot240        timeSplit = _timeVal[0].split(':')...add_addr.py
Source:add_addr.py  
1from __future__ import absolute_import2from random import randint3import time4from selenium.webdriver.common.by import By5from selenium.webdriver.support.ui import Select6from .amz_base import AmzBase7class AddAddress(AmzBase):8    url_tmpl = 'https://{market}/gp/css/account/address/view.html' +\9        '?ie=UTF8&ref_=ya_add_address&viewID=newAddress'10    _nav_link_your_account = [(By.ID, 'nav-link-yourAccount'),11                              (By.ID, 'nav-link-accountList')]12    _address = [13        (By.XPATH, '//div[@data-card-identifier="Addresses"]'),14        (By.XPATH, '//div[@data-card-identifier="AddressesAnd1Click"]')]15    _acct_orders = (By.ID, 'your-orders-button-announce')16    _addr_country_code = [17        (By.ID, 'enterAddressCountryCode'),18        (By.ID, 'address-ui-widgets-countryCode-dropdown-nativeId')]19    _addr_user = [(By.ID, 'enterAddressFullName'),20                  (By.ID, 'address-ui-widgets-enterAddressFullName')]21    _addr_addr1 = [(By.ID, 'enterAddressAddressLine1'),22                   (By.ID, 'address-ui-widgets-enterAddressLine1')]23    _addr_addr2 = [(By.ID, 'enterAddressAddressLine2'),24                   (By.ID, 'address-ui-widgets-enterAddressLine2')]25    _addr_city = [(By.ID, 'enterAddressCity'),26                  (By.ID, 'address-ui-widgets-enterAddressCity')]27    _addr_state = [(By.ID, 'enterAddressStateOrRegion'),28                   (By.ID, 'address-ui-widgets-enterAddressStateOrRegion')]29    _addr_province = [(By.ID,30                       'address-ui-widgets-enterAddressStateOrRegion' +31                       '-dropdown-nativeId')]32    _addr_zip = [(By.ID, 'enterAddressPostalCode'),33                 (By.ID, 'address-ui-widgets-enterAddressPostalCode')]34    _addr_phone = [(By.ID, 'enterAddressPhoneNumber'),35                   (By.ID, 'address-ui-widgets-enterAddressPhoneNumber')]36    _addr_addr_type = [(By.ID, 'AddressType')]37    _addr_gate_code = [(By.ID, 'GateCode'),38                       (By.ID, 'address-ui-widgets-addr-details-gate-code')]39    _addr_submit_btn = [(By.NAME, 'shipToThisAddress'),40                        (By.ID, 'myab_newAddressButton'),41                        (By.XPATH,42                         '//*[@id="address-ui-widgets' +43                         '-enterAddressFormContainer"]/span/span'),44                        (By.XPATH,45                         '//span[@data-action="add-address-popover-submit"]')]46    _addr_suggst_btn = [(By.ID, 'icam_addrSuggestionListSubmitButton'),47                        (By.ID, 'useSelectedAddress'),48                        (By.NAME, 'useSelectedAddress'),49                        (By.NAME,50                         'address-ui-widgets' +51                         '-saveOriginalOrSuggestedAddress')]52    _addr_alert = (By.CLASS_NAME, 'myab-alert-bar-content-text')53    _addr_addr_index_1 = (By.ID, 'addressIndex1')54    _addr_addr_err = (By.CLASS_NAME, 'enterAddressFieldError')55    def __init__(self, driver, params, account):56        AmzBase.__init__(self, driver, params)57        self.account = account58        self.url = self.url_tmpl.format(**{'market': self.url})59        self.addr_info = self.params.get('addr_info', {})60        self.user_name = '%s %s' % (self.addr_info.get('given_name'),61                                    self.addr_info.get('surname'))62    def validate(self):63        if not self.addr_info:64            return False65        return True66    def navigate(self):67        if not self.validate():68            raise self.make_step_failed('Invalid params')69        # goto account dashboard70        account_link = self.find_alternative_elem(self._nav_link_your_account)71        self.click_elem(account_link, wait_time=5)72        # goto address73        address = self.find_alternative_elem(self._address)74        self.click_elem(address, wait_time=5)75        # goto add address76        self.click((By.ID, 'ya-myab-address-add-link'), wait_time=5)77        return True78    def do_add_address(self):79        def _sendkeys(loc_list, keys, wait_time=3):80            elem = self.find_alternative_elem(loc_list)81            self.send_keys_to_elem(elem, keys, wait_time)82        country_code_elem = self.find_alternative_elem(83            self._addr_country_code)84        country_code = Select(country_code_elem)85        country_code.select_by_value(self.addr_info.get('country_code'))86        _sendkeys(self._addr_user, self.user_name)87        _sendkeys(self._addr_addr1, self.addr_info.get('address_line1'))88        if self.addr_info.get('address_line2'):89            _sendkeys(self._addr_addr2, self.addr_info.get('address_line2'))90        _sendkeys(self._addr_city, self.addr_info.get('city'))91        if self.addr_info.get('state'):92            province_elem = self.find_alternative_elem(self._addr_province)93            if province_elem:94                province = Select(province_elem)95                province.select_by_value(self.addr_info.get('state'))96            else:97                _sendkeys(self._addr_state, self.addr_info.get('state'))98        _sendkeys(self._addr_zip, self.addr_info.get('zip_code'))99        telephone = self.addr_info.get('telephone')100        if not telephone:101            telephone = self.account.get('telephone')102        _sendkeys(self._addr_phone, telephone)103        addr_type_elem = self.find_alternative_elem(self._addr_addr_type)104        if addr_type_elem:105            addr_type = Select(addr_type_elem)106            addr_type.select_by_value('RES' if randint(0, 2) <= 1107                                      else 'COM')108        gate_code = self.find_alternative_elem(self._addr_gate_code)109        if gate_code:110            self.send_keys_to_elem(gate_code, '#%s' % randint(1, 9999))111        submit_btn = self.find_alternative_elem(self._addr_submit_btn)112        self.click_elem(submit_btn)113        time.sleep(3 + randint(1, 4))114    def post_add_address(self):115        addr_suggst_btn = self.find_alternative_elem(self._addr_suggst_btn)116        if addr_suggst_btn:117            self.click_elem(self._addr_suggst_btn)118            time.sleep(3 + randint(1, 4))119        # check whether the address is added or not120        name_elems = self.find_elements(By.ID, 'address-ui-widgets-FullName')121        if not name_elems:122            raise self.make_step_failed('Failed to add address')123        full_names = [elem.text for elem in name_elems]124        if self.user_name not in full_names:125            raise self.make_step_failed('Failed to add address')126    def process(self):127        self.do_add_address()128        self.post_add_address()129class AddOrderAddress(AddAddress):130    def __init__(self, driver, params, account):131        AddAddress.__init__(self, driver, params, account)132    def navigate(self):133        return True134    def post_add_address(self):135        addr_suggst_btn = self.find_alternative_elem(self._addr_suggst_btn)136        if addr_suggst_btn:137            self.click_elem(addr_suggst_btn)...sendkey_handler.py
Source:sendkey_handler.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3r"""sendkey_handler -- DESCRIPTION4"""5from xahk.sendkeys.sendkeys import SendKeys6from xahk.bind.key import KeyEventHandler7from xahk.bind.mouse import MouseEventHandler8class SendKeysHandler(KeyEventHandler, MouseEventHandler):9    r"""SendKeysHandler10    SendKeysHandler is a object.11    Responsibility:12    """13    def __init__(self, line):14        r"""15        @Arguments:16        - `args`:17        - `kwargs`:18        """19        self._sendkeys = SendKeys(line)20    def on_key_release(self, event):21        r"""SUMMARY22        on_key_press(event)23        @Arguments:24        - `event`:25        @Return:26        @Error:27        """28        self._sendkeys.send(event.window)29    def on_button_release(self, event):30        r"""SUMMARY31        on_button_press(event)32        @Arguments:33        - `event`:34        @Return:35        @Error:36        """37        self._sendkeys.send()38    def __str__(self):39        return '{}("{}")'.format(super(SendKeysHandler, self).__str__(),40                                 self._sendkeys.line)4142# For Emacs43# Local Variables:44# coding: utf-845# End:...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!!
