Best Python code snippet using robotframework-appiumlibrary_python
levi_checkout.py
Source:levi_checkout.py  
...54                    if self.is_requested_color:55                        self.requested_color = color56                    self.log('Parsing color - {}, quantity - {}'.format(color or 'None', qty), level=WARNING)57                    # self._pre_parse_products()58                    no_longer_available = self._find_by_xpath(59                        './/h2[contains(text(), "This product is no longer available")]')60                    if no_longer_available:61                        self.log('No longer available {}'.format(no_longer_available), level=WARNING)62                        item = CheckoutProductItem()63                        item['url'] = url64                        item['color'] = color65                        item['no_longer_available'] = True66                        yield item67                    else:68                        sold_out_item = self._parse_product_page(url, qty, color)69                        if sold_out_item:70                            sold_out_item['url'] = url71                            yield sold_out_item72                        else:73                            items = self._parse_cart_page()74                            for item in items:75                                item['url'] = url76                                yield item77                        # only need to open new window if its not last color78                    if not color == colors[-1]:79                        self._open_new_session(url)80                self.driver.quit()81    def _parse_item(self, product):82        item = CheckoutProductItem()83        name = self._get_item_name(product)84        item['name'] = name.strip() if name else name85        item['id'] = self._get_item_id(product)86        price = self._get_item_price(product)87        item['price_on_page'] = self._get_item_price_on_page(product)88        color = self._get_item_color(product)89        quantity = self._get_item_quantity(product)90        item['no_longer_available'] = False91        item['not_found'] = False92        if quantity and price:93            quantity = int(quantity)94            if quantity < self.current_requested_quantity:95                item['requested_quantity_not_available'] = True96            else:97                item['requested_quantity_not_available'] = False98            item['price'] = round(float(price) / quantity, 2)99            item['quantity'] = quantity100            item['requested_color'] = self.requested_color101        if color:102            item['color'] = color.upper()103        item['requested_color_not_available'] = (104            color and self.requested_color and105            (self.requested_color.lower() != color.lower()))106        return item107    def _get_colors_names(self):108        time.sleep(10)109        xpath = ('//*[contains(@class,"color-swatches")]//'110                 'li[not(contains(@class,"not-available"))]'111                 '/img[@class="color-swatch-img"]')112        swatches = self._find_by_xpath(xpath)113        return [x.get_attribute("title") for x in swatches]114    def select_size(self, element=None):115        time.sleep(5)116        size_attribute_xpath = (117            '*//*[@id="pdp-buystack-size-values"]'118            '/li[contains(@class,"selected") and not(contains(@class, "not-available"))]')119        size_attributes_xpath = (120            '*//*[@id="pdp-buystack-size-values"]'121            '/li[not(contains(@class, "not-available"))]')122        self._click_attribute(size_attribute_xpath,123                              size_attributes_xpath,124                              element)125    def select_color(self, element=None, color=None):126        time.sleep(5)127        # If color was requested and is available128        if color and color.lower() in map(129                (lambda x: x.lower()), self._get_colors_names()):130            color_attribute_xpath = (131                '*//*[contains(@class,"color-swatches")]//'132                'li[contains(@class,"color-swatch") '133                'and img[translate(@title, "ABCDEFGHIJKLMNOPQRSTUVWXYZ",'134                ' "abcdefghijklmnopqrstuvwxyz")="%s"]]' % color.lower())135        # If color is set by default on the page136        else:137            color_attribute_xpath = (138                '*//*[contains(@class,"color-swatches")]//'139                'li[contains(@class,"color-swatch") '140                'and contains(@class, "selected")]')141        # All Availables Colors142        color_attributes_xpath = (143            '*//*[@class="color-swatches"]//'144            'li[contains(@class,"color-swatch") '145            'and not(contains(@class,"not-available"))]')146        self._click_attribute(color_attribute_xpath,147                              color_attributes_xpath,148                              element)149        time.sleep(4)150    def select_waist(self, element=None):151        time.sleep(4)152        size_attribute_xpath = (153            '*//*[@id="pdp-buystack-waist-values"]'154            '/li[contains(@class,"selected") and not(contains(@class, "not-available"))]')155        size_attributes_xpath = (156            '*//*[@id="pdp-buystack-waist-values"]'157            '/li[not(contains(@class, "not-available"))]')158        self._click_attribute(size_attribute_xpath,159                              size_attributes_xpath,160                              element)161    def select_length(self, element=None):162        time.sleep(4)163        size_attribute_xpath = (164            '*//*[@id="pdp-buystack-length-values"]'165            '/li[contains(@class,"selected") and not(contains(@class, "not-available"))]')166        size_attributes_xpath = (167            '*//*[@id="pdp-buystack-length-values"]'168            '/li[not(contains(@class, "not-available"))]')169        self._click_attribute(size_attribute_xpath,170                              size_attributes_xpath,171                              element)172    def _parse_attributes(self, product, color, quantity):173        time.sleep(4)174        self.select_color(product, color)175        self.select_size(product)176        self.select_waist(product)177        self.select_length(product)178        self._set_quantity(product, quantity)179    @retry_func(Exception)180    def _pre_parse_products(self):181        """Close Modal Windows requesting Email"""182        promp_window = self._find_by_xpath(183            '//*[@class="email-lightbox" or @class="email-lightbox"'184            ']//span[@class="close"]')185        if promp_window and promp_window[0].is_displayed():186            promp_window[0].click()187            time.sleep(2)188        promp_window = self._find_by_xpath('//*[@id="oo_close_prompt" and @aria-label="Close dialog"]')189        if promp_window and promp_window[0].is_displayed():190            promp_window[0].click()191            time.sleep(2)192        more_colors_button = self._find_by_xpath(193            '//*[@class="color-swatch more-button"]')194        if more_colors_button and more_colors_button[0].is_displayed():195            more_colors_button[0].click()196            time.sleep(2)197    def _get_products(self):198        return self._find_by_xpath(199            '//*[@itemtype="http://schema.org/Product"]')200    def _parse_product_page(self, product_url, quantity, color=None):201        """ Process product and add it to the cart"""202        products = self._get_products()203        # Make it iterable for convenience204        is_iterable = isinstance(products, (list, tuple))205        products = products if is_iterable else list(products)206        for product in products:207            sold_out_item = self._parse_one_product_page(product, quantity, color)208            if sold_out_item:209                return sold_out_item210    @retry_func(Exception)211    def _parse_one_product_page(self, product, quantity, color=None):212        # this is moved to separate method to avoid situations in future213        # where multiple product are given, and add to cart button not worked in one of them214        # self._open_new_session(url)215        self._pre_parse_products()216        self._parse_attributes(product, color, quantity)217        sold_out_item = self._add_to_cart(color)218        if sold_out_item:219            return sold_out_item220        self._do_others_actions()221    def _add_to_cart(self, color):222        amount_in_cart = self._find_by_xpath('.//*[@id="minicart_bag_icon"]/*[@class="qty"]')223        amount_in_cart = amount_in_cart[0].text if amount_in_cart else None224        self.log("Amount of items in cart: %s" % amount_in_cart, level=WARNING)225        time.sleep(15)226        add_to_bag = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[contains(@class,"add-to-bag")]')))227        if add_to_bag:228            self._find_by_xpath(229                './/*[@class="pdp-sizes pdp-length-sizes"]/span')[0].click()230            time.sleep(4)231            self.log("Add to bag button: %s" % add_to_bag, level=WARNING)232            add_to_bag.click()233        # if add_to_bag:234        # add_to_bag[0].click()235            # time.sleep(10)236        time.sleep(10)237        amount_in_cart = self._find_by_xpath('.//*[@id="minicart_bag_icon"]/*[@class="qty"]')238        amount_in_cart = amount_in_cart[0].text if amount_in_cart else None239        self.log("Amount of items in cart after first try: %s" % amount_in_cart, level=WARNING)240        if not amount_in_cart or int(amount_in_cart) == 0:241            add_to_bag = self._find_by_xpath(242                '//*[contains(@class,"add-to-bag")]')243            self.log("Add to bag button second try: %s" % add_to_bag, level=WARNING)244            # add_to_bag[0].click()245            if add_to_bag:246                # to remove mouseover from size, blocking add to cart button247                self._find_by_xpath(248                    './/*[@class="pdp-sizes pdp-length-sizes"]/span')[0].click()249                time.sleep(4)250                add_to_bag[0].click()251            time.sleep(10)252            amount_in_cart = self._find_by_xpath('.//*[@id="minicart_bag_icon"]/*[@class="qty"]')253            amount_in_cart = amount_in_cart[0].text if amount_in_cart else None254            self.log("Amount of items in cart after second try: %s" % amount_in_cart, level=WARNING)255        # sold_last_one = self._find_by_xpath('.//*[@id="cart-info"]')256        # sold_last_one = sold_last_one.text if sold_last_one else None257        # self.log("Cart info: %s" % sold_last_one, level=WARNING)258        #259        # sold_last_one = self._find_by_xpath('.//*[@id="hasLowStockError"]')260        # sold_last_one = sold_last_one.text if sold_last_one else None261        # self.log("Sold last one message: %s" % sold_last_one, level=WARNING)262        if not amount_in_cart or int(amount_in_cart) == 0:263            # TODO add more reliable detection of sold out items264            # self._open_new_session('http://www.levi.com/US/en_US/')265            # raise Exception266            item = CheckoutProductItem()267            item['requested_color_not_available'] = True268            item['color'] = color269            return item270    # @retry_func(Exception)271    def _set_quantity(self, product, quantity):272        self.current_requested_quantity = int(quantity)273        self._find_by_xpath(274            '//div[@class="quantity-display"]')[0].click()275        time.sleep(4)276        quantity_option = self._find_by_xpath(277            '*//*[@class="quantity"]'278            '//li[@data-qty-dropdown-value="%d"]' % quantity, product)279        if quantity_option:280            quantity_option[0].click()281        time.sleep(4)282    def _get_product_list_cart(self):283        element = self._find_by_xpath(".//*[@id='useritems-container']")284        element = element[0] if element else None285        if not element:286            self.log("No element, waiting with timeout: %s" % element, level=WARNING)287            time.sleep(45)288            element = self._find_by_xpath(".//*[@id='useritems-container']")289            element = element[0] if element else None290        if not element:291            self.log("No element, using visibility_of_element_located: %s" % element, level=WARNING)292            # ui.WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.ID, 'useritems-container')))293            condition = EC.visibility_of_element_located((By.ID, 'useritems-container'))294            element = self.wait.until(condition)295        return element296    def _get_products_in_cart(self, product_list):297        html_text = product_list.get_attribute('outerHTML')298        selector = scrapy.Selector(text=html_text)299        return selector.xpath('//*[@class="product-tile"]')300    def _get_subtotal(self):301        order_subtotal_element = self.wait.until(302            EC.visibility_of_element_located((...tempmailapi.py
Source:tempmailapi.py  
...39                    pass40        links=list(set(links))41        return links42    @staticmethod43    def _find_by_xpath(driver, xpath):44        try:45            elem=driver.find_element_by_xpath(xpath)46            return elem47        except NoSuchElementException:48            raise NoSuchElementException49    def checkMail(self, mail_num=-1):50        try:51            self.__driver.get(self.__temp_mail.getMail(mail_num))52            mail=self.__parseMail()53            self.__driver.back()54            return mail55        except IndexError:56            raise MailNumOutOfRange("Mail Number out of range")57    58    @staticmethod59    def _is_blank(s):60        out=bool(s and s.strip())61        return (not out)62    def __getEmail(self, timeout, sleep_time, starts_with="Loading"):63        logging.info("Getting email")64        logging.info("staring timer process")65        clock=Clock()66        clock_thread=Thread(target=clock.run, args=(timeout,))67        clock_thread.start()68        email=TempMailAPI._find_by_xpath(self.__driver, consts.email_selector) .get_attribute('value')69        while (email.startswith(starts_with) or email.startswith("Loading") or TempMailAPI._is_blank(email)):70            if (clock_thread.is_alive()==False):71                logging.info("Could not finish in given timeout")72                raise TimerException("Couldn't finish task in given timeout")73            logging.info("dont found email")74            sleep(sleep_time)75            logging.info("trying again for email")76            email=TempMailAPI._find_by_xpath(self.__driver, consts.email_selector).get_attribute('value')77        logging.debug(email)78        logging.info("Found email")79        logging.info("closing timer process")80        clock.terminate()81        logging.info("associating email with object")82        self.__temp_mail.setEmailID(email)83        logging.info("associated email with object")84    def __init__(self, driver_obj, session=0, timeout=20, sleep_time=1):85        logging.info("creating api object")86        self.__driver=driver_obj87        self.timeout=timeout88        self.sleep_time=sleep_time89        if (session != 0):90            self.__driver.session_id=session91        self.__temp_mail=TempMail()92        self.__open()93        logging.info("Created api object")94    def refresh(self):95        TempMailAPI._find_by_xpath(self.__driver, consts.refresh_button_selector).click()96        self.getInbox()97    98    def delEmail(self):99        TempMailAPI._find_by_xpath(self.__driver, consts.delete_email).click()100        self.__temp_mail.resetInbox()101        self.__getEmail(self.timeout, self.sleep_time, starts_with=self.__temp_mail.email_id)102        self.__temp_mail.resetEmail()103    @property104    def session_id(self):105        return (self.__driver.session_id)106    @property107    def inbox_size(self):108        return (self.__temp_mail.inbox_size)109    def getInbox(self):110        mail_links=TempMailAPI._find_links(self.__driver, 'https://temp-mail.org/en/view')111        self.__temp_mail.ext(mail_links)112    def __parseMail(self):113        sender_name=TempMailAPI._find_by_xpath(self.__driver, consts.sender_name).get_attribute("textContent")114        date_time=TempMailAPI._find_by_xpath(self.__driver, consts.mail_date_time).get_attribute("textContent")115        sender_email=TempMailAPI._find_by_xpath(self.__driver, consts.sender_email).get_attribute("textContent")116        subject=TempMailAPI._find_by_xpath(self.__driver, consts.mail_subject).get_attribute("textContent")117        text=TempMailAPI._find_by_xpath(self.__driver, consts.mail_text).get_attribute("textContent")118        #attach=TempMailAPI._find_by_xpath(self.__driver, consts.mail_attach).click()119        return Mail(sender_email, sender_name, date_time, subject, text)120    121    def __del__(self):122        del self.__driver...elementfinder.py
Source:elementfinder.py  
...9        }10    def find(self, locator):11        (prefix, criteria) = self._parse_locator(locator)12        if prefix is None:13            return self._find_by_xpath(criteria)14        else:15            strategy = self._strategies.get(prefix)16            if strategy is None:17                raise ValueError("Element locator with prefix '" + prefix + "' is not supported")18            return strategy(criteria)19    # Strategy routines, private20    def _parse_locator(self,locator):21        prefix = None22        criteria = locator23        if not locator.startswith('//'):24            locator_parts = locator.partition('=')25            if len(locator_parts[1]) > 0 and locator_parts[0].lower() in ["class","xpath"]:26                prefix = locator_parts[0].strip().lower()27                criteria = locator_parts[2].strip()28            elif len(locator_parts[1])==0:29                raise ValueError("Element locator(%s) is without '=' in your locator, wrong format"%locator)30        return (prefix, criteria)31    def _find_by_xpath(self,criteria):32        return Util.driver.find_elements_by_xpath(criteria)33    def _find_by_class_name(self,criteria):34        return Util.driver.find_elements_by_class_name(criteria)35class presence_of_element_located(object):36    """ An expectation for checking that an element is present on the DOM37    of a page. This does not necessarily mean that the element is visible.38    locator - used to find the element39    returns the WebElement once it is located40    """ 41    def __init__(self, locator):42        self.locator=locator43    def __call__(self,driver):...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!!
