Beispiel #1
0
 def _init_firefox(self):
     from selenium import webdriver
     from selenium.webdriver.remote.remote_connection import RemoteConnection
     RemoteConnection.set_timeout(30)
     profile = webdriver.FirefoxProfile()
     profile.set_preference("general.useragent.override", self.user_agent)
     profile.set_preference('intl.accept_languages', 'en-US')
     profile.set_preference("network.proxy.type",
                            1)  # manual proxy configuration
     profile.set_preference('permissions.default.image', 2)
     if self.proxy:
         profile.set_preference("network.http.phishy-userpass-length", 255)
         if 'socks' in self.proxy_type:
             profile.set_preference("network.proxy.socks",
                                    self.proxy.split(':')[0])
             profile.set_preference("network.proxy.socks_port",
                                    int(self.proxy.split(':')[1]))
         else:
             profile.set_preference("network.proxy.http",
                                    self.proxy.split(':')[0])
             profile.set_preference("network.proxy.http_port",
                                    int(self.proxy.split(':')[1]))
     profile.update_preferences()
     driver = webdriver.Firefox(profile)
     driver.set_window_size(1280, 1024)
     driver.set_page_load_timeout(60)
     driver.set_script_timeout(60)
     return driver
Beispiel #2
0
 def get_driver(self, browser, is_incognito=False):
     """here is minimum configuration features to create proper browser session"""
     RemoteConnection.set_timeout(10)
     self.browser = browser
     if not self.driver:
         if browser.lower() == 'chrome':
             capa = DesiredCapabilities.CHROME
             capa["pageLoadStrategy"] = "none"
             options = Options()
             if is_incognito:
                 options.add_argument('--incognito')
             options.add_argument('--no-sandbox')
             self.driver = webdriver.Chrome(options=options,
                                            desired_capabilities=capa)
         elif browser.lower() == 'ff':
             firefox_profile = webdriver.FirefoxProfile()
             if is_incognito:
                 firefox_profile.set_preference(
                     "browser.privatebrowsing.autostart", True)
             else:
                 firefox_profile.set_preference(
                     "browser.privatebrowsing.autostart", False)
             self.driver = webdriver.Firefox(
                 firefox_profile=firefox_profile)
         """easy extend on other different browsers like IE, EDGE ..."""
     self.main_page = MainPage(self.driver)
     self.favicon_generator = FaviconGenerator(self.driver)
     self.install_favicon = InstallFavicon(self.driver)
     return self.driver
def test_get_connection_manager_for_certs_and_timeout():
    remote_connection = RemoteConnection('http://remote', keep_alive=False)
    remote_connection.set_timeout(10)
    conn = remote_connection._get_connection_manager()
    assert conn.connection_pool_kw['timeout'] == 10
    assert conn.connection_pool_kw['cert_reqs'] == 'CERT_REQUIRED'
    assert 'certifi/cacert.pem' in conn.connection_pool_kw['ca_certs']
Beispiel #4
0
 def open_google_at_remote_side_using_chrome(self):
     RemoteConnection.set_timeout(20)
     self.driver = webdriver.Remote(
         command_executor='http://xxx.xxx.xxx.xxx:4444/wd/hub',
         desired_capabilities={
             "browserName": "chrome",
             "platformName": "Windows 8"
         })
     self.driver.get("https://www.google.com.tw/")
Beispiel #5
0
 def _init_webdriver(self):
     from selenium import webdriver
     from selenium.webdriver.remote.remote_connection import RemoteConnection
     RemoteConnection.set_timeout(30)
     driver = webdriver.Firefox()
     driver.set_window_size(1280, 1024)
     driver.set_page_load_timeout(60)
     driver.set_script_timeout(60)
     return driver
Beispiel #6
0
    def get(self, url):
        """
        Buka situs dan handle koneksi error
        """

        # Atur socket timeout
        RemoteConnection.set_timeout(SETTING.SOCKET_TIMEOUT)

        wrapped = errormanager(SETTING.BROWSER.get)
        wrapped(url)
Beispiel #7
0
def get_driver(config, execute_str, retry=3, timeout=20, logger=logging.getLogger('py_test')):
    RemoteConnection.set_timeout(timeout)  # 设置RemoteConnection的初始timeout值
    for i in range(retry):
        try:
            dr = get_driver_(config, execute_str, logger)
            return dr
        except Exception as e:
            if i >= retry - 1:
                raise
            else:
                logger.warning('【{}】\t浏览器初始化出错,尝试进行第{}次初始化。错误信息 => {}'.format(execute_str, i+2, e))
                continue
Beispiel #8
0
class iOSWebTest(unittest.TestCase):

    wrong_username_msg = 'Your username is invalid!'
    wrong_password_msg = 'Your password is invalid!'
    success_msg = 'You logged into a secure area!'

    def setUp(self):
        self._command_executor = RemoteConnection(configs.kobitonServerUrl,
                                                  resolve_ip=False)
        self._command_executor.set_timeout(configs.session_timeout)
        self.driver = webdriver.Remote(configs.kobitonServerUrl,
                                       configs.desired_caps_ios_web)
        self.driver.implicitly_wait(configs.session_timeout)
        self.driver.set_page_load_timeout(configs.session_timeout)

        kobitonSessionId = self.driver.desired_capabilities.get(
            'kobitonSessionId')
        print("https://portal.kobiton.com/sessions/%s" % (kobitonSessionId))

    def tearDown(self):
        self.driver.quit()

    def test_ios_web(self):
        self.verify_invalid_username()
        self.verify_invalid_password()
        self.verify_login_successfully()

    def verify_invalid_username(self):
        print('should return error when we input wrong username')
        self.login('foo', 'SuperSecretPassword!')
        self.assertTrue(self.wrong_username_msg in self.get_message())

    def verify_invalid_password(self):
        print('should return error when we input wrong password')
        self.login('tomsmith', 'SuperSecretPassword')
        self.assertTrue(self.wrong_password_msg in self.get_message())

    def verify_login_successfully(self):
        print(
            'should run test successfully with correct username and password')
        self.login('tomsmith', 'SuperSecretPassword!')
        self.assertTrue(self.success_msg in self.get_message())

    def login(self, username, password):
        self.driver.get('http://the-internet.herokuapp.com/login')
        userE = self.driver.find_element_by_xpath(".//*[@id='username']")
        userE.send_keys(username)
        self.driver.find_element_by_id('password').send_keys(password)
        self.driver.find_element_by_xpath("//form[@name='login']").submit()

    def get_message(self):
        return self.driver.find_element_by_id('flash').text
Beispiel #9
0
    def _browser(self):
        """ Initialize a Firefox webdriver.
        """
        RemoteConnection.set_timeout(CONNECTION_TIMEOUT)

        profile = webdriver.FirefoxProfile()
        preferences = self.config.get('preferences', {})
        for key, value in preferences.items():
            profile.set_preference(key, value)

        driver = webdriver.Firefox(profile)
        # Wait for UI events to complete before failing to find an element.
        driver.implicitly_wait(1)

        return driver
    def _browser(self):
        """ Initialize a Firefox webdriver.
        """
        RemoteConnection.set_timeout(CONNECTION_TIMEOUT)

        profile = webdriver.FirefoxProfile()
        preferences = self.config.get('preferences', {})
        for key, value in preferences.items():
            profile.set_preference(key, value)

        driver = webdriver.Firefox(profile)
        # Wait for UI events to complete before failing to find an element.
        driver.implicitly_wait(IMPLICIT_TIMEOUT)

        return driver
Beispiel #11
0
def _get_driver(capabilities):
    logger.debug('Creating web driver')
    start_time = datetime.now()
    # set resolve_ip to false to make it work in cases when remote driver is running in OpenShift
    command_executor = RemoteConnection(cfg.selenium.web_driver,
                                        resolve_ip=False)
    # increase the timeout because we are waiting for new pod to be created which takes some time
    command_executor.set_timeout(120)
    driver = webdriver.Remote(command_executor,
                              desired_capabilities=capabilities)
    # reset the timeout to default, only driver creation is taking so much time
    command_executor.reset_timeout()
    _delta = datetime.now() - start_time
    logger.debug('Web driver created successfully. Time taken: {} ms'.format(
        int(_delta.total_seconds() * 1000)))
    return driver
Beispiel #12
0
    def getArticles(self, author):
        if author == "https://towardsdatascience.com/@TDSteam":
            pass
        else:
            print("Get Articles...")
            twdsarticles = {}
            # Define Webdriver
            driver = webdriver.Remote(
                command_executor='http://selenium-hub:4444/wd/hub',
                desired_capabilities=getattr(DesiredCapabilities, "FIREFOX"))
            RemoteConnection.set_timeout(36000)
            url = author
            driver.get(url)

            # Scroll page to load whole content
            last_height = driver.execute_script(
                "return document.body.scrollHeight")
            while True:
                # Scroll down to the bottom.
                driver.execute_script(
                    "window.scrollTo(0, document.body.scrollHeight);")
                # Wait to load the page.
                time.sleep(2)
                # Calculate new scroll height and compare with last scroll height.
                new_height = driver.execute_script(
                    "return document.body.scrollHeight")
                if new_height == last_height:
                    break
                last_height = new_height

            # Get source code from page
            htmltext = driver.page_source
            soup = BeautifulSoup(htmltext, "lxml")
            driver.quit()
            # Get TWDS-Articles of each author
            for link in soup.find_all("a", class_=""):
                if "towards" not in link.get('href'):
                    pass
                else:
                    if link.get('href') not in twdsarticles.keys():
                        twdsarticles[link.get('href')] = url
                    else:
                        pass
            print("Received list of articles")
            return twdsarticles
Beispiel #13
0
 def _init_firefox(self, proxy):
     from selenium import webdriver
     from selenium.webdriver.remote.remote_connection import RemoteConnection
     RemoteConnection.set_timeout(30)
     profile = webdriver.FirefoxProfile()
     #profile.set_preference("general.useragent.override", self.user_agent)
     profile.set_preference('intl.accept_languages', 'en-US')
     profile.set_preference("network.proxy.type", 1)  # manual proxy configuration
     if proxy:  # we assume only http proxies are accepted, format: http://host:port
         proxy, port = proxy.replace('http://', '').split(':')
         profile.set_preference("network.proxy.http", proxy)
         profile.set_preference("network.proxy.http_port", int(port))
     profile.update_preferences()
     driver = webdriver.Firefox(profile)
     driver.set_window_size(1280, 1024)
     driver.set_page_load_timeout(60)
     driver.set_script_timeout(60)
     return driver
 def _init_chromium(self):
     from selenium import webdriver
     from selenium.webdriver.remote.remote_connection import RemoteConnection
     RemoteConnection.set_timeout(30)
     chrome_flags = webdriver.DesiredCapabilities.CHROME  # this is for Chrome?
     chrome_options = webdriver.ChromeOptions()  # this is for Chromium
     if self.proxy:
         chrome_options.add_argument('--proxy-server=%s' % self.proxy_type +
                                     '://' + self.proxy)
     chrome_flags["chrome.switches"] = ['--user-agent=%s' % self.user_agent]
     chrome_options.add_argument('--user-agent=%s' % self.user_agent)
     executable_path = '/usr/sbin/chromedriver'
     if not os.path.exists(executable_path):
         executable_path = '/usr/local/bin/chromedriver'
     # initialize webdriver, open the page and make a screenshot
     driver = webdriver.Chrome(desired_capabilities=chrome_flags,
                               chrome_options=chrome_options,
                               executable_path=executable_path)
     return driver
Beispiel #15
0
    def getAuthors(self):
        print("Get Authors...")
        url = "https:/towardsdatascience.com/archive"
        # Define Webdriver
        driver = webdriver.Remote(
            command_executor='http://selenium-hub:4444/wd/hub',
            desired_capabilities=getattr(DesiredCapabilities, "FIREFOX"))
        RemoteConnection.set_timeout(36000)
        driver.get(url)

        # Scroll page to load whole content --> in eigene Methode auslagern!
        last_height = driver.execute_script(
            "return document.body.scrollHeight")
        while True:
            # Scroll down to the bottom.
            driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")
            # Wait to load the page.
            time.sleep(2)
            # Calculate new scroll height and compare with last scroll height.
            new_height = driver.execute_script(
                "return document.body.scrollHeight")
            if new_height == last_height:
                break
            last_height = new_height

        # Get source code from page
        htmltext = driver.page_source
        soup = BeautifulSoup(htmltext, "lxml")
        driver.quit()
        # Extract links to profiles from TWDS Authors
        authors = []
        for link in soup.find_all(
                "a",
                class_=
                "link link--darker link--darken u-accentColor--textDarken u-baseColor--link u-fontSize14 u-flex1"
        ):
            authors.append(link.get('href'))
        # Clear list from duplicates by using a dictionary
        authors = list(dict.fromkeys(authors))
        print("Received list of authors")
        return authors
 def _init_firefox(self):
     from selenium import webdriver
     from selenium.webdriver.remote.remote_connection import RemoteConnection
     RemoteConnection.set_timeout(30)
     profile = webdriver.FirefoxProfile()
     profile.set_preference("general.useragent.override", self.user_agent)
     profile.set_preference("network.proxy.type",
                            1)  # manual proxy configuration
     if self.proxy:
         if 'socks' in self.proxy_type:
             profile.set_preference("network.proxy.socks",
                                    self.proxy.split(':')[0])
             profile.set_preference("network.proxy.socks_port",
                                    int(self.proxy.split(':')[1]))
         else:
             profile.set_preference("network.proxy.http",
                                    self.proxy.split(':')[0])
             profile.set_preference("network.proxy.http_port",
                                    int(self.proxy.split(':')[1]))
     profile.update_preferences()
     driver = webdriver.Firefox(profile)
     return driver
Beispiel #17
0
def _get_driver(capabilities):
    logger.debug('Creating web driver')
    start_time = datetime.now()
    # set resolve_ip to false to make it work in cases when remote driver is running in OpenShift
    # https://github.com/ddavison/selenium-openshift-templates/issues/6
    command_executor = RemoteConnection(cfg.selenium.web_driver,
                                        resolve_ip=False)
    # increase the timeout because we are waiting for new pod to be created which takes some time
    command_executor.set_timeout(120)
    # using keep_alive=True which should save some connections
    # https://github.com/SeleniumHQ/selenium/issues/5758
    # and https://github.com/seleniumhq/selenium/issues/3457
    driver = webdriver.Remote(command_executor,
                              desired_capabilities=capabilities,
                              options=_get_browser_options(),
                              keep_alive=True)
    # reset the timeout to default, only driver creation is taking so much time
    command_executor.reset_timeout()
    _delta = datetime.now() - start_time
    logger.debug('Web driver created successfully. Time taken: {} ms'.format(
        int(_delta.total_seconds() * 1000)))
    return driver
Beispiel #18
0
    def _browser(self):
        """ Initialize a Chrome webdriver.
        """
        RemoteConnection.set_timeout(CONNECTION_TIMEOUT)

        return webdriver.Firefox()
Beispiel #19
0
    Return a Boolean indicating whether a Selenium web driver is
    available.
    """
    try:
        driver = get_web_driver()
        driver.quit()
        return True
    except (ConnectionRefusedError, NameError, RuntimeError,
            WebDriverException) as error:
        print(error)
        _LOGGER.warning('No WebDriver available for functional tests, '
                        'so those tests will be skipped.')
        return False


RemoteConnection.set_timeout(10)
if _TEST_SETTINGS['ENABLED']:
    FUNCTIONAL_TESTS_ENABLED = _web_driver_available()
else:
    FUNCTIONAL_TESTS_ENABLED = False
    _LOGGER.warning('Functional tests are disabled, '
                    'so those tests will be skipped.')


@unittest.skipUnless(FUNCTIONAL_TESTS_ENABLED, 'functional tests disabled')
class FunctionalTest(StaticLiveServerTestCase):
    """
    Base class for a functional test case.
    """
    def __init__(self, *args, **kwargs):
        super(FunctionalTest, self).__init__(*args, **kwargs)
Beispiel #20
0
# See the License for the specific language governing permissions and
# limitations under the License.

from tempfile import mkdtemp

import pom
from pom import ui
from selenium.webdriver import FirefoxProfile
from selenium.webdriver.remote.remote_connection import RemoteConnection

from stepler import config

from .pages import PageBase, pages  # noqa

ui.UI.timeout = config.UI_TIMEOUT
RemoteConnection.set_timeout(config.ACTION_TIMEOUT)
sorted_pages = sorted(pages, key=lambda page: len(page.url))


class Profile(FirefoxProfile):
    """Horizon browser profile."""
    def __init__(self, *args, **kwgs):
        """Constructor."""
        super(Profile, self).__init__(*args, **kwgs)
        self.download_dir = mkdtemp()
        self.set_preference("browser.download.folderList", 2)
        self.set_preference("browser.download.manager.showWhenStarting", False)
        self.set_preference("browser.download.dir", self.download_dir)
        self.set_preference("browser.helperApps.neverAsk.saveToDisk",
                            "application/binary,text/plain,application/zip")
        self.set_preference("browser.download.manager.showAlertOnComplete",
Beispiel #21
0
    def getArticleDetails(self, articles):
        print("Get Article Details...")
        artdic = {}
        # Define Webdriver
        driver = webdriver.Remote(
            command_executor='http://selenium-hub:4444/wd/hub',
            desired_capabilities=getattr(DesiredCapabilities, "FIREFOX"))
        RemoteConnection.set_timeout(36000)
        url = articles
        driver.get(url)

        # Get source code from page
        htmltext = driver.page_source
        soup = BeautifulSoup(htmltext, "lxml")
        driver.quit()
        # Extract field values and parse them to json / dictionary
        tempdic = {}
        try:
            tempdic['Article_ID'] = soup.find(
                "meta", attrs={"name": "parsely-post-id"})["content"]
        except:
            tempdic['Article_ID'] = "0"
        tempdic['URL'] = url
        tempdic['Title'] = soup.title.string
        tempdic['Author'] = soup.find("meta", attrs={"name":
                                                     "author"})["content"]

        # Loop to extract clean date
        tempdic['PublishingDate'] = \
            re.findall(r".+?(?=T)", soup.find("meta", property="article:published_time")["content"])[0]

        # Loop to extract no of responses and reading_time
        tempdic['Reading_time'] = re.findall(
            r"[0-9]",
            soup.find("meta", attrs={"name": "twitter:data1"})["value"])[0]
        try:
            tempdic['No_Responses'] = re.findall(
                r"[0-9]",
                soup.find("span", "az").string)[0]
        except:
            tempdic['No_Responses'] = 0

        # Loop to extract tags
        li = soup.select("ul > li > a")
        tags = []
        for link in li:
            tags.append(link.string)
        tempdic['Tags'] = tags

        # Loop to extract claps
        btns = soup.find_all("button")
        for button in btns:
            if button.string is None:
                pass
            else:
                try:
                    tempdic['Claps'] = (int(button.string))
                except:
                    break

        # Loop to get clean text
        pagetext = ""
        text = soup.findAll("p")
        for t in text:
            pagetext += t.getText()
        # Clean special characters
        pagetext = (" ".join(re.findall(r"[A-Za-z0-9]*",
                                        pagetext))).replace("  ", " ")
        tempdic['Text'] = pagetext
        artdic[url] = tempdic
        return (artdic)
Beispiel #22
0
class AndroidAppTest(unittest.TestCase):

    firstQuestion = 'Acura MDX'
    secondQuestion = 'Cruise Control'

    def setUp(self):
        self._command_executor = RemoteConnection(configs.kobitonServerUrl,
                                                  resolve_ip=False)
        self._command_executor.set_timeout(configs.session_timeout)
        self.driver = webdriver.Remote(self._command_executor,
                                       configs.desired_caps_android_app)
        self.driver.implicitly_wait(configs.session_timeout)

        kobitonSessionId = self.driver.desired_capabilities.get(
            'kobitonSessionId')
        print("https://portal.kobiton.com/sessions/%s" % (kobitonSessionId))

    def tearDown(self):
        self.driver.quit()

    def test_android_app(self):
        self.search_questions_on_Acura_Support_Community()
        self.search_IFixit_on_home_screen()

    def search_questions_on_Acura_Support_Community(self):
        print(
            'should allow to search some questions on Acura Support Community')
        '''
    Steps:
    1. Click on "Car and Truck" Categories on Homepage
    2. Click on "Acura" Categories

    Expected:
    1. General Information is "Acura".
    2.Verify five devices below displays.
    + Acura Integra
    + Acura MDX
    + Acura RL
    + Acura TL
    + Acura TSX
    '''

        self.driver.find_element_by_xpath(
            "//*[@resource-id='android:id/home']").click()
        time.sleep(2)
        self.driver.find_element_by_xpath("//*[@text='Car and Truck']").click()
        time.sleep(2)
        self.driver.find_element_by_xpath("//*[@text='Acura']").click()
        time.sleep(2)

        acuraText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=1]"
        ).text
        acuraIntegraText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=3]"
        ).text
        acuraMDXText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=4]"
        ).text
        acuraRLText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=5]"
        ).text
        acuraTLText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=6]"
        ).text
        acuraTSXText = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=7]"
        ).text

        self.assertEqual('Acura', acuraText)
        self.assertEqual('Acura Integra', acuraIntegraText)
        self.assertEqual('Acura MDX', acuraMDXText)
        self.assertEqual('Acura RL', acuraRLText)
        self.assertEqual('Acura TL', acuraTLText)
        self.assertEqual('Acura TSX', acuraTSXText)
        '''
    Steps:
    1. Click on "Acura" General Information
    2. Swipe from left to right, it will move to Answers tab
    3. Enter keyword 'Acura MDX'
    4. Click Search icon

    Expected: It should show at least 6 results.
    '''

        getAttrName1 = self.search_question(self.firstQuestion)
        '''
    Steps:
    1. Clear text on Search field
    2. Enter keyword 'Cruise Control'
    3. Click on Search icon
    4. Wait a few seconds to get returned result
    5. Close app

    Expected: It should show at least 1 result.
    '''

        self.driver.back()
        getAttrName2 = self.search_question(self.secondQuestion)

        self.driver.close_app()

        getAttrName1 = re.findall('\d+', getAttrName1)[0]
        self.assertTrue(
            int(getAttrName1) >= 6,
            'The expected results are greater or equal to 6 results.')

        getAttrName2 = re.findall('\d+', getAttrName2)[0]
        self.assertTrue(
            int(getAttrName2) >= 1,
            'The expected results are greater or equal to 1 result.')

    def search_IFixit_on_home_screen(self):
        print('should allow to search iFixit on Home screen')
        self.driver.launch_app()
        time.sleep(2)
        self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/action_search']").click()
        self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/abs__search_src_text']"
        ).send_keys('Macbook Pro 2015')
        time.sleep(2)
        self.driver.press_keycode(66)
        time.sleep(5)
        firstResult = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/search_result_count']"
        ).text
        self.driver.find_element_by_xpath(
            "//*[@resource-id='android:id/text1' and @text='Guides']").click()
        self.driver.find_element_by_xpath(
            "//*[@resource-id='android:id/text1' and @text='Devices']").click(
            )
        time.sleep(2)
        secondResult = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/search_result_count']"
        ).text

        firstResult = re.findall('\d+', firstResult)[0]
        self.assertTrue(
            int(firstResult) >= 47,
            'The expected results are greater or equal to 47 results.')

        secondResult = re.findall('\d+', secondResult)[0]
        self.assertTrue(
            int(secondResult) >= 5,
            'The expected results are greater or equal to 5 results.')

    def swipe(self, element, direction='RightLeft'):
        # Get the size of screen.
        size = self.driver.get_window_size()

        startx = size['width'] * 0.90
        # Find endx point which is at left side of screen.
        endx = size['width'] * 0.10
        # Find vertical point where you wants to swipe. It is in middle of screen height.
        starty = size['height'] * 0.50

        if direction == 'RightLeft':
            # Swipe from Right to Left.
            self.driver.swipe(startx, starty, endx, starty, 200)

        if direction == 'LeftRight':
            # Swipe from Left to Right.
            self.driver.swipe(endx, starty, startx, starty, 200)

        time.sleep(5)

    def search_question(self, question):
        self.question = question
        self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_title' and @index=1]"
        ).click()

        WebDriverWait(self.driver, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "//*[@resource-id='com.dozuki.ifixit:id/topic_info_image']")))
        time.sleep(3)
        element = self.driver.find_element_by_xpath(
            "//*[@resource-id='com.dozuki.ifixit:id/topic_info_image']")
        self.swipe(element, 'RightLeft')
        time.sleep(3)
        self.driver.find_element_by_xpath(
            "//*[@resource-id='answersSearch']").send_keys(self.question)

        return self.driver.find_element_by_xpath(
            "//*[contains(@text,'Acura questions') and @index=1]").text
Beispiel #23
0
# See the License for the specific language governing permissions and
# limitations under the License.

from tempfile import mkdtemp

import pom
from pom import ui
from selenium.webdriver import FirefoxProfile
from selenium.webdriver.remote.remote_connection import RemoteConnection

from horizon_autotests import ACTION_TIMEOUT, UI_TIMEOUT

from .pages import PageBase, pages

ui.UI.timeout = UI_TIMEOUT
RemoteConnection.set_timeout(ACTION_TIMEOUT)
sorted_pages = sorted(pages, key=lambda page: len(page.url))


class Profile(FirefoxProfile):
    """Horizon browser profile."""

    def __init__(self, *args, **kwgs):
        """Constructor."""
        super(Profile, self).__init__(*args, **kwgs)
        self.download_dir = mkdtemp()
        self.set_preference("browser.download.folderList", 2)
        self.set_preference("browser.download.manager.showWhenStarting",
                            False)
        self.set_preference("browser.download.dir", self.download_dir)
        self.set_preference("browser.helperApps.neverAsk.saveToDisk",
Beispiel #24
0
class iOSAppTest(unittest.TestCase):
    def setUp(self):
        self._command_executor = RemoteConnection(configs.kobitonServerUrl,
                                                  resolve_ip=False)
        self._command_executor.set_timeout(configs.session_timeout)
        self.driver = webdriver.Remote(configs.kobitonServerUrl,
                                       configs.desired_caps_ios_app)

    def tearDown(self):
        self.driver.quit()

    def test_ios_app(self):
        self.search_questions_on_Acura_Support_Community()
        self.search_IFixit_on_home_screen()

    def search_questions_on_Acura_Support_Community(self):
        print 'should allow to navigate to some devices on Acura Support Community'
        '''
    Steps: 
    1. Click on "Car and Truck" Categories on Homepage
    2. Click on "Acura" Categories

    Expected:
    1. General Information is "Acura".
    2.Verify five devices below displays.
    + Acura Integra
    + Acura MDX
    + Acura RL
    + Acura TL
    + Acura TSX
    '''
        self.driver.find_element_by_xpath(
            "//XCUIElementTypeButton[@name='START A REPAIR']").click()
        time.sleep(5)
        self.driver.find_element_by_xpath("//*[@name='Car and Truck']").click()
        time.sleep(2)
        self.driver.find_element_by_xpath("//*[@name='Acura']").click()
        time.sleep(2)
        WebDriverWait(self.driver, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH, "//XCUIElementTypeNavigationBar")))
        acura_text = self.driver.find_element_by_xpath(
            "//XCUIElementTypeNavigationBar").get_attribute('name')

        has_acura_integra = self.driver.find_element_by_xpath(
            "//XCUIElementTypeStaticText[@name='Acura Integra']").is_displayed(
            )
        has_acura_MDX = self.driver.find_element_by_xpath(
            "//XCUIElementTypeStaticText[@name='Acura MDX']").is_displayed()
        has_acura_RL = self.driver.find_element_by_xpath(
            "//XCUIElementTypeStaticText[@name='Acura RL']").is_displayed()
        has_acura_TL = self.driver.find_element_by_xpath(
            "//XCUIElementTypeStaticText[@name='Acura TL']").is_displayed()
        has_acura_TSX = self.driver.find_element_by_xpath(
            "//XCUIElementTypeStaticText[@name='Acura TSX']").is_displayed()

        self.assertEqual(acura_text, 'Acura')
        self.assertTrue(has_acura_integra)
        self.assertTrue(has_acura_MDX)
        self.assertTrue(has_acura_RL)
        self.assertTrue(has_acura_TL)
        self.assertTrue(has_acura_TSX)

    def search_IFixit_on_home_screen(self):
        print 'should allow to search iFixit on Home screen'
        self.driver.launch_app()
        time.sleep(2)
        self.driver.find_element_by_xpath(
            "//XCUIElementTypeButton[@name='START A REPAIR']").click()
        time.sleep(2)
        self.driver.find_element_by_xpath("//*[@name='Search']").click()
        self.driver.find_element_by_xpath(
            "//XCUIElementTypeSearchField[@name='Search']").send_keys(
                'Macbook Pro 2015')

        time.sleep(2)

        firstListResult = self.driver.find_elements_by_xpath(
            "//XCUIElementTypeStaticText[contains(@label,'MacBook Pro')]")

        self.driver.find_element_by_xpath(
            "//XCUIElementTypeButton[@name='Cancel']").click()
        self.driver.find_element_by_xpath("//*[@name='Search']").click()
        self.driver.find_element_by_xpath(
            "//XCUIElementTypeSearchField[@name='Search']").send_keys('Acura')
        self.driver.find_element_by_xpath(
            "//XCUIElementTypeButton[@name='Categories']").click()
        time.sleep(2)

        secondListResult = self.driver.find_elements_by_xpath(
            "//XCUIElementTypeStaticText[contains(@label,'Acura')]")

        self.assertTrue(
            len(firstListResult) >= 33,
            'The expected results are greater or equal to 33 results.')
        self.assertTrue(
            len(secondListResult) >= 6,
            'The expected results are greater or equal to 6 results.')
Beispiel #25
0
import traceback
from urllib.error import URLError

from bs4 import BeautifulSoup
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import Chrome
from selenium.webdriver.remote.remote_connection import RemoteConnection
from selenium.webdriver.remote.webdriver import Command

from chromoy.exceptions import WebDriverConnectionError, WebDriverPageIsNotReceived
from chromoy.settings import MAX_ATTEMPTS_TO_GET_PAGE
from chromoy.utilities import processes

LOGGER = logging.getLogger('chromoy')

RemoteConnection.set_timeout(60.0)

___all___ = ["ConnectionMixin"]


class ConnectionMixin(Chrome):
    immortal_processes = []
    # все родительские процессы за всю сессию переиспользований класса
    all_session_processes = []
    init_kwargs = {}
    main_process_pid = None

    def _get(self, url):
        self.execute(Command.GET, {'url': url})

        page_source = self.page_source
from selenium.webdriver.remote.remote_connection import RemoteConnection
import testtools

from openstack_dashboard.test.integration_tests import config
from openstack_dashboard.test.integration_tests import fixtures
from openstack_dashboard.test.integration_tests import steps
from openstack_dashboard.test.integration_tests import utils

try:
    from unittest2.case import SkipTest
except ImportError:
    from unittest.case import SkipTest

LOGGER = logging.getLogger(__name__)
ROOT_PATH = os.path.dirname(os.path.abspath(config.__file__))
RemoteConnection.set_timeout(60)


def gen_random_resource_name(resource="", timestamp=True):
    """Generate random resource name using uuid and timestamp.

    Input fields are usually limited to 255 or 80 characters hence their
    provide enough space for quite long resource names, but it might be
    the case that maximum field length is quite restricted, it is then
    necessary to consider using shorter resource argument or avoid using
    timestamp by setting timestamp argument to False.
    """
    fields = ["horizon"]
    if resource:
        fields.append(resource)
    if timestamp: