Пример #1
0
class _BrowserManagementKeywords(KeywordGroup):
    def __init__(self):      
        self._remoteBrowser = os.environ.get("PYBROWSER", "0") == "0"
        self._job_id = 0
        self._sauce_rest = SauceRestWrapper()
        self._seleniumlib = BuiltIn().get_library_instance('Selenium2Library')
       
    def open_pyro_browser(self, determined_browser=os.environ.get("PYBROWSER", 'firefox'), selenium_speed=0.5):
        """Opens a browser in the context determined by the suite; such as, Sauce Miltiple, Sauce Single, Sauce Solo, Local Solo and add it to Selenium2Library the browser cache.
        
        If the Robot Framework test code is executed through TeamCity using Sauce CI, the browser will be remotely instantiated throgh the Sauce service. Visit the documentation in the intro to see how the username and key are obtained
        See https://saucelabs.com/login
        
        Returns the index of this browser instance which can be used later to
        switch back to it. Index starts from 1 and is reset back to it when
        `Close All Browsers` keyword is used. See `Switch Browser` for
        example.

        Optional alias is an alias for the browser instance and it can be used
        for switching between browsers (just as index can be used). See `Switch
        Browser` for more details.

        Possible values for local instance `browser` are as follows:

        | firefox          | FireFox   |
        | ff               | FireFox   |
        | internetexplorer | Internet Explorer |
        | ie               | Internet Explorer |
        | googlechrome     | Google Chrome |
        | gc               | Google Chrome |
        | chrome           | Google Chrome |
        | opera            | Opera         |
        | phantomjs        | PhantomJS     |
        | htmlunit         | HTMLUnit      |
        | htmlunitwithjs   | HTMLUnit with Javascipt support |
        | android          | Android       |
        | iphone           | Iphone        |
        | safari           | Safari        |
        
        Note, that you will encounter strange behavior, if you open
        multiple Internet Explorer browser instances. That is also why
        `Switch Browser` only works with one IE browser at most.
        For more information see:
        http://selenium-grid.seleniumhq.org/faq.html#i_get_some_strange_errors_when_i_run_multiple_internet_explorer_instances_on_the_same_machine

        Optional 'ff_profile_dir' is the path to the firefox profile dir if you
        wish to overwrite the default.
        
        Command Line Supercede:
        IMPLICIT_WAIT (Set Selenium Implicit Wait) [can be set in import]
        COMMAND_DELAY (Set Selenium Speed) 
        KEYWORD_TIMEOUT (Set Selenium Timeout) [can be set in import]
        """
        
        print '(open_pyro_browser)'
        if self._remoteBrowser: #sauce            
            self._seleniumlib.open_browser(os.environ['BASE_URL'], browser=determined_browser, remote_url=os.environ["PYROBOT_REMOTE_URL"], desired_capabilities=os.environ["PYROBOT_CAPS"])       
            self._job_id = self._seleniumlib._current_browser().session_id
        else:                   #local solo            
            self._seleniumlib.open_browser(os.environ['BASE_URL'], browser=determined_browser) 
            
        if os.environ.get('SAUCE_API_KEY') and os.environ.get('SAUCE_USERNAME') and self._remoteBrowser:
            print "execute sauce rest to update"
            self._sauce_rest.establish(self._seleniumlib._current_browser().session_id, os.environ.get('SAUCE_USERNAME'), os.environ.get('SAUCE_API_KEY'), sys.argv[2])
            self._sauce_rest.dump_session_id()
            #ondemand_string = "SauceOnDemandSessionID=%s job-name=%s" % (self._job_id, BuiltIn().get_variable_value("${SUITE_NAME}"))
            #print 'setting ONDEMAND_PYRO to : %s' % ondemand_string
            #OperatingSystem().set_environment_variable("ONDEMAND_PYRO", "1111")    
            #os.environ['ONDEMAND_PYRO'] = ondemand_string
        
        self._seleniumlib.maximize_browser_window()
        # Determine timeouts based on commandline
        # IMPLICIT_WAIT
        # COMMAND_DELAY
        # KEYWORD_TIMEOUT
        if 'IMPLICIT_WAIT' in os.environ:
            self._seleniumlib.set_selenium_implicit_wait(os.environ.get('IMPLICIT_WAIT')) 
        if 'COMMAND_DELAY' in os.environ:
            self._seleniumlib.set_selenium_speed(os.environ.get('COMMAND_DELAY')) 
        else:
            print '(open_pyro_browser) setting selenium speed %s' % selenium_speed
            self._seleniumlib.set_selenium_speed(selenium_speed) 
        if 'KEYWORD_TIMEOUT' in os.environ:
            self._seleniumlib.set_selenium_timeout(os.environ.get('KEYWORD_TIMEOUT')) 

    def sencha_login(self, user_name, password, element_on_next_page, suspend_timeouts=True):
    #def sencha_login(self, user_name, password, element_on_next_page):
        """
        Using the instantiated browser from `Open Browser`, the page traverses through the login page and waits for the targeted element on the following page.
        """
        print '(login_sencha)'
        self._seleniumlib.wait_until_element_is_visible('loginnameid-inputEl', timeout=5)
        self._seleniumlib.wait_until_element_is_visible('loginpasswordid-inputEl', timeout=5)
        self._seleniumlib.input_text('loginnameid-inputEl', user_name)
        self._seleniumlib.input_text('loginpasswordid-inputEl', password)
        self._seleniumlib.wait_until_element_is_visible('loginbuttonid-btnIconEl', timeout=5)
        self._seleniumlib.click_element('id=loginbuttonid-btnIconEl')
        self._seleniumlib.wait_until_element_is_visible('id=%s'% element_on_next_page, timeout=5)
        if suspend_timeouts == True:
            print '(login_sencha) javascript issuing suspendAll!'
            self._seleniumlib.execute_javascript('window.ADTRAN.store.RefreshBaseStore.suspendAll();')
            self._seleniumlib.execute_javascript('window.ADTRAN.util.SysPollTask.suspend();')

    def close_pyro_browser():
        print '(close_pyro_browser)'
        # sauce enabled
        #self._seleniumlib = BuiltIn().get_library_instance('Selenium2Library')
        if self._remoteBrowser:
            assert USERNAME_ACCESS_KEY.match(os.environ["PYROBOT_REMOTE_URL"]), 'Incomplete remote_url.'
            username, access_key = USERNAME_ACCESS_KEY.findall(os.environ["PYROBOT_REMOTE_URL"])[0][1:]
            suite_name = BuiltIn().get_variable_value("${SUITE_NAME}")
            suite_status = BuiltIn().get_variable_value("${SUITE STATUS}")
            tags = BuiltIn().get_variable_value("${TEST_TAGS}")
            
            print "name: %s status: %s tags: %s" % (suite_name, suite_status, tags)
            
            token = (':'.join([username, access_key])).encode('base64').strip()
            payload = { 'name': suite_name,
                        'passed': suite_status == 'PASS',
                        'tags': tags}
            headers = {'Authorization': 'Basic {0}'.format(token)}
            url = 'https://saucelabs.com/rest/v1/{0}/jobs/{1}'.format(username, self._job_id)
            response = requests.put(url, data=json.dumps(payload), headers=headers)
            assert response.status_code == 200, response.text
            # video_url = json.loads(response.text).get('video_url')
            # if video_url:
                # logger.info('<a href="{0}">video.flv</a>'.format(video_url), html=True)
            ondemand_string = "SauceOnDemandSessionID=%s job-name=%s" % (self._job_id, suite_name)
            print 'setting ONDEMAND_PYRO to : %s' % ondemand_string    
            os.environ['ONDEMAND_PYRO'] = ondemand_string
            #wrapper = Wrapper(self._seleniumlib, username, access_key, sys.argv[2])
            #wrapper.update_sauce_rest(BuiltIn().get_variable_value("${SUITE STATUS}"), BuiltIn().get_variable_value("${TEST_TAGS}"))
        
        self._seleniumlib.close_browser
        self._seleniumlib.close_all_browsers
        print 'CLOSE BROWSER TIME!!'

    def selenium_drag_and_drop(self, locator_type, ele_source, ele_dest):
        self._seleniumlib.drag_and_drop('%s=%s' % (locator_type,ele_source), '%s=%s' % (locator_type,ele_dest))

    def selenium_drag_and_drop_actions(self, locator_type, ele_source, ele_dest):
        self._seleniumlib.mouse_down('%s=%s' % (locator_type,ele_source))
        self._seleniumlib.mouse_over('%s=%s' % (locator_type,ele_dest))
        self._seleniumlib.mouse_up('%s=%s' % (locator_type,ele_dest))

    def selenium_check(self, locator_type, element_locator):
        self._seleniumlib.select_checkbox('%s=%s' % (locator_type,element_locator))
  
    def selenium_uncheck(self, locator_type, element_locator):
        self._seleniumlib.unselect_checkbox('%s=%s' % (locator_type,element_locator))
    
    def selenium_wait_until_element_is_visible(self, locator_type, element_locator, _timeout=5):
        self._seleniumlib.wait_until_element_is_visible('%s=%s' % (locator_type,element_locator), timeout=_timeout)
    
    def selenium_wait_for_element_present(self, locator_type, element_locator):
        self._seleniumlib.wait_until_page_contains_element('%s=%s' % (locator_type,element_locator))
    
    def selenium_verify_text_from_element(self, locator_type, element_locator, text):
        self._seleniumlib.element_text_should_be('%s=%s' % (locator_type,element_locator), text)
    
    def selenium_reload(self, suspend_after_element_found='createUser_wiz'):
        """Refreshes the browser, which is effectively like the user pressed F5.
        Optional, supply the suspend_after_element_found with an element to find after reloading and apply the following javascript:
           window.ADTRAN.store.RefreshBaseStore.suspendAll();
           window.ADTRAN.util.SysPollTask.suspend();
        Note: Setting this to equal None will disable the javascript and wait for element functionality entirely
        """        
        print '(selenium_reload) suspend = %s' % suspend_after_element_found
        self._seleniumlib.reload_page()
        if type(suspend_after_element_found) == type(''):
            print '(selenium_reload) javascript suspendAll issued! (suspend_after_element_found == %s' % suspend_after_element_found
            self._seleniumlib.wait_until_element_is_visible(suspend_after_element_found, error='(selenium_reload) failed because the element was not found after reload')
            self._seleniumlib.execute_javascript('window.ADTRAN.store.RefreshBaseStore.suspendAll();')
            self._seleniumlib.execute_javascript('window.ADTRAN.util.SysPollTask.suspend();')
            
    def selenium_type(self, locator_type, element_locator, text):
        self._seleniumlib.input_text('%s=%s' % (locator_type,element_locator), text)
    
    def selenium_clear(self, locator_type, element_locator):
        self._seleniumlib.input_text('%s=%s' % (locator_type,element_locator), '')
        
    def selenium_verify_attribute_from_element(self, locator_type, element_locator, element_class_locator, text):
        attr_value = self._seleniumlib.get_element_attribute('%s=%s@%s' % (locator_type, element_locator, element_class_locator))
        BuiltIn().should_contain(text, attr_value)
    
    def selenium_click(self, locator_type, element_locator, wait_before_click=5):
        BuiltIn().sleep(wait_before_click)
        self._seleniumlib.click_element('%s=%s' % (locator_type,element_locator))

    def selenium_click_text_from_combobox(self, locator_type, element_locator, text):
        self.selenium_wait_for_element_present(locator_type, element_locator)
        self._seleniumlib.click_element('%s=%s' % (locator_type,element_locator))
        self.selenium_wait_for_element_present('xpath', "//div[contains(@class, 'x-boundlist') and not(contains(@style, 'display: none;'))]/div")
        self.selenium_click('xpath', "//div[contains(@class, 'x-boundlist') and not(contains(@style, 'display: none;'))]/div/ul/li[contains(text(), '%s')]" % text) 

    def selenium_click_text_from_combobox_search(self, locator_type, element_locator, text):
        self.selenium_wait_for_element_present(locator_type, element_locator)        
        self.selenium_type(locator_type, element_locator, text)        
        self.selenium_wait_for_element_present('xpath', "//div[contains(@class, 'x-boundlist') and not(contains(@style, 'display: none;'))]/div")
        self.selenium_click('xpath', "//div[contains(@class, 'x-boundlist') and not(contains(@style, 'display: none;'))]/div/ul/li[contains(text(), '%s')]" % text)
        
    def selenium_populate_combo_and_click_text(self, locator_type, element_locator, text, wait_before_click=5):
        self.selenium_wait_for_element_present(locator_type, element_locator)
        self.selenium_click(locator_type, element_locator)
        #self.selenium_click('xpath', "//div[contains(concat(' ', @class, ' '), 'x-trigger-index-0 x-form-trigger x-form-arrow-trigger x-form-trigger-first')]")
        self.selenium_click('xpath', "//input[@%s='%s']/../../td[2]/div" % (locator_type,element_locator))
        BuiltIn().sleep(wait_before_click)
        #self.selenium_click('xpath', "//li[contains(text(), '%s')]" % text)
        self.selenium_click('xpath', "//div[contains(@class, 'x-boundlist') and not(contains(@style, 'display: none;'))]/div/ul/li[contains(text(), '%s')]" % text) 

    def selenium_double_click(self, locator_type, element_locator):
        self._seleniumlib.double_click_element('%s=%s' % (locator_type, element_locator))
    
    def selenium_element_should_not_be_visible(self, locator_type, element_locator):
        self._seleniumlib.element_should_not_be_visible('%s=%s' % (locator_type, element_locator))
        
    def selenium_click_by_script(self, element_locator):
        self._seleniumlib.execute_javascript("window.document.getElementById('%s').click();" % element_locator)
Пример #2
0
class Inbox(object):
    """
    High level action for Inbox page
    """

    def __init__(self):
        self._selenium2Library = BuiltIn().get_library_instance('selenium2Library')
        self.elements = {
                 'txtTemp' : '',
                'mail_rows' : 'css=div[class^="list-view-item-container ml-bg"]',
                'mail_table' : 'msg-list',
                'btn_popup_category' : 'btn-select-dd',
                'btn_compose' : "css=button[data-action='compose']",
                'txt_to_field' : 'to-field',
                'txt_cc_field' : 'cc-field',
                'txt_bcc_field' : 'bcc-field',
                'txt_subject_field' : 'subject-field',
                'txt_body_field' : 'rtetext',
                'btn_send' : "css=span[data-action='send']",
                'lbl_from' : "css=div.thread-item-header span[aria-label*='from ']",
                'txt_mail_content' : 'css=div.email-wrapped',
                'btn_delete' : 'btn-delete'

        }
    '''
    Usage: Select the email based on row index. 1st-based index.
    '''
    def select_email_by_index(self, row_index = 1):
        locator = self.elements['mail_rows']
        rows = self._selenium2Library.element_find(locator, False, False, None)
        chk_select = rows[int(row_index)-1].find_element(By.CSS_SELECTOR, "input[role='checkbox']" )
        if not chk_select.is_selected():
            chk_select.click()

    '''
    Usage: Select mass emails whose sender is matched with the sender_name
    Note: This keyword couldn't select the all the emails if there are too many.
    '''
    def select_email_by_sender(self, sender_name):
        locator = self.elements['mail_rows']
        my_rows = self._selenium2Library.element_find(locator, False, False, None)
        logger.info(str(len(my_rows)))
        length = len(my_rows)
        print my_rows
        for i in range(len(my_rows)):
            # BuiltIn().sleep(1, "New Row----")
            # logger.info("Row: " + str(i))
            # logger.info(str(len(my_rows)))
            row = my_rows[i]
            # logger.info(str(row))
            self._selenium2Library.wait_until_element_is_displayed(row, self._selenium2Library.timeout)
            element_sender = row.find_element(By.XPATH, ".//div[starts-with(@class,'from')]")
            # logger.info("Found element_sender.")
            self._selenium2Library.wait_until_element_is_displayed(element_sender,
                                                                   self._selenium2Library.timeout)
            # logger.info("Is Sender element displayed? " + str(element_sender.is_displayed()))
            current_sender_name = element_sender.text.strip()
            # logger.info("Current Sender Name: " + current_sender_name)
            if current_sender_name == sender_name:
                # logger.info("Found matched")
                chk_select = row.find_element(By.XPATH, ".//input[@role='checkbox']")
                if not chk_select.is_selected():
                    chk_select.click()
            # Refresh the rows list
            my_rows = self._selenium2Library.element_find(locator, False, False, None)

    '''
    Usage: Select the 1st email whose title is matched with the input.
    '''
    def select_email_by_subject(self, subject):
        locator = self.elements['mail_table']

        email_table = self._selenium2Library.element_find(locator, True, False, None)
        # Find the checkbox which subject is match with the given subject
        xpath_locator = ".//span[normalize-space(@title)='" + subject + "']/ancestor::div[3]//input"
        checkboxes = email_table.find_elements(By.XPATH, xpath_locator)
        for chk_select in checkboxes:
            if not chk_select.is_selected():
                    chk_select.click()

    '''
    Usage: Open email by subject
    '''
    def open_email_by_subject(self, subject):
        locator = self.elements['mail_table']

        email_table = self._selenium2Library.element_find(locator, True, False, None)
        # Find the checkbox which subject is match with the given subject
        xpath_locator = ".//span[normalize-space(@title)='" + subject + "']"
        _element = email_table.find_element(By.XPATH, xpath_locator)
        _element.click()
        self._selenium2Library.wait_until_page_load(self._selenium2Library.timeout)

    '''
    Usage: Select the email by pre-define category
    Params:
        category: All, None, Read, Unread, Starred, Unstarred
    '''
    def select_email_by_category(self, category):
        self._selenium2Library.click_element(self.elements['btn_popup_category'])
        xpath_locator = "xpath=//div[@id='menu-ml-cbox']//span[text()='" + category + "']"
        self._selenium2Library.wait_until_element_is_visible(xpath_locator,
                                                             self._selenium2Library.timeout)
        button = self._selenium2Library.element_find(xpath_locator, True, False, None)
        button.click()

        '''
    Usage: Select the email by pre-define category
    Params:
        category: All, None, Read, Unread, Starred, Unstarred
    '''

    '''
    Usage: Click to compose an email
    Params:

    '''
    def compose_email(self):
        self._selenium2Library.click_element(self.elements['btn_compose'])
        self._selenium2Library.wait_until_element_is_visible(self.elements['txt_to_field'])

    '''
    Usage: Add recipient
    Params:
        to: list of to recipients, separated by ;
        cc: list of cc recipients, separeted by ;
        bcc: list of bcc recipients, separated by ;
    '''
    def _input_recipient(self, locator, text):
        for item in text.split(";"):
            input_text = item.split("|")
            if len(input_text)==1:
                self._selenium2Library.input_text(locator, input_text, False)
                self._selenium2Library.input_text(locator, Keys.TAB, False)
            else:
                self._selenium2Library.input_text(locator, input_text[0], False)
                text_holder = "xpath=//div[contains(.,'" + input_text[1] +"')]"
                self._selenium2Library.wait_until_element_is_displayed(text_holder, self._selenium2Library.timeout)
                #self._selenium2Library.delay(1)
                self._selenium2Library.click_element(text_holder)

    def add_recipients(self, to=None, cc=None, bcc=None):
        list_fields = [to, cc, bcc]
        list_locators = [self.elements['txt_to_field'], self.elements['txt_cc_field'], self.elements['txt_bcc_field']]
        for i in range(len(list_fields)):
            if list_fields[i]:
                self._input_recipient(list_locators[i], list_fields[i])

    def add_content(self, subject, body, override=True):
        if subject:
            self._selenium2Library.input_text(self.elements['txt_subject_field'], subject, override)
        if body:
            self._selenium2Library.input_text(self.elements['txt_body_field'], body, override)

    '''
    Usage: Click Send button to send email
    Params:
    '''
    def send_email(self):
        self._selenium2Library.click_element(self.elements['btn_send'])

    def verify_email_content(self, from_recipient=None, content=None):
        if from_recipient:
            self._selenium2Library.element_text_should_be(self.elements['lbl_from'], from_recipient.strip())
        if content:
            self._selenium2Library.element_text_should_be(self.elements['txt_mail_content'], content.strip())

    '''
    Usage: Delete the selected email
    '''
    def delete_selected_email(self):
        self._selenium2Library.click_element(self.elements['btn_delete'])

        '''
    Usage: Open email by subject
    '''
    def refresh_page_until_email_by_subject_exist(self, subject, timeout):
        # locator = self.elements['mail_table']
        # email_table = self._selenium2Library.element_find(locator, True, False, None)
        # Find the checkbox which subject is match with the given subject
        logger.info(subject, True, True)
        xpath_property = "xpath=//span[normalize-space(@title)='" + subject + "']"
        self._selenium2Library.reload_page_until_element_displayed(xpath_property, timeout)