def test_get_connection_manager_for_certs_and_timeout(monkeypatch):
    monkeypatch.setattr(RemoteConnection, "get_timeout", lambda _: 10)  # Class state; leaks into subsequent tests.
    remote_connection = RemoteConnection('http://remote', keep_alive=False)
    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']
    def __init__(self, agent_client: AgentClient, remote_server_addr: str):
        RemoteConnection.__init__(self, remote_server_addr=remote_server_addr)
        ReportingCommandExecutor.__init__(self,
                                          agent_client=agent_client,
                                          command_executor=self)

        self.w3c = agent_client.agent_session.dialect == "W3C"
Example #3
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_proxy_url_https_auth(mock_proxy_auth_settings):
    remote_connection = RemoteConnection('https://remote', keep_alive=False)
    proxy_url = remote_connection._get_proxy_url()
    raw_proxy_url, basic_auth_string = remote_connection._seperate_http_proxy_auth()
    assert proxy_url == "https://*****:*****@https_proxy.com:8080"
    assert raw_proxy_url == "https://https_proxy.com:8080"
    assert basic_auth_string == "user:password"
Example #5
0
 def __init__(self,
              remote_server_addr,
              vendor_prefix,
              browser_name,
              keep_alive=True,
              ignore_proxy=False):
     RemoteConnection.__init__(self,
                               remote_server_addr,
                               keep_alive,
                               ignore_proxy=ignore_proxy)
     self.browser_name = browser_name
     self._commands["launchApp"] = (
         'POST', '/session/$sessionId/chromium/launch_app')
     self._commands["setNetworkConditions"] = (
         'POST', '/session/$sessionId/chromium/network_conditions')
     self._commands["getNetworkConditions"] = (
         'GET', '/session/$sessionId/chromium/network_conditions')
     self._commands['executeCdpCommand'] = (
         'POST', '/session/$sessionId/{}/cdp/execute'.format(vendor_prefix))
     self._commands['getSinks'] = (
         'GET',
         '/session/$sessionId/{}/cast/get_sinks'.format(vendor_prefix))
     self._commands['getIssueMessage'] = (
         'GET', '/session/$sessionId/{}/cast/get_issue_message'.format(
             vendor_prefix))
     self._commands['setSinkToUse'] = (
         'POST',
         '/session/$sessionId/{}/cast/set_sink_to_use'.format(vendor_prefix)
     )
     self._commands['startTabMirroring'] = (
         'POST', '/session/$sessionId/{}/cast/start_tab_mirroring'.format(
             vendor_prefix))
     self._commands['stopCasting'] = (
         'POST',
         '/session/$sessionId/{}/cast/stop_casting'.format(vendor_prefix))
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']
Example #7
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
Example #8
0
 def __init__(self, remote_server_addr, keep_alive=True):
     RemoteConnection.__init__(self, remote_server_addr, keep_alive)
     self._commands["launchApp"] = (
         'POST', '/session/$sessionId/chromium/launch_app')
     self._commands["setNetworkConditions"] = (
         'POST', '/session/$sessionId/chromium/network_conditions')
     self._commands["getNetworkConditions"] = (
         'GET', '/session/$sessionId/chromium/network_conditions')
 def __init__(self, agent_client: AgentClient, remote_server_addr: str):
     RemoteConnection.__init__(self, remote_server_addr=remote_server_addr)
     ReportingCommandExecutor.__init__(
         self,
         agent_client=agent_client,
         command_executor=self,
         remote_connection=super(),
     )
Example #10
0
    def __init__(self, remote_server_addr, keep_alive=True):
        RemoteConnection.__init__(self, remote_server_addr, keep_alive)

        self._commands["SET_CONTEXT"] = ("POST", "/session/$sessionId/moz/context")
        self._commands["ELEMENT_GET_ANONYMOUS_CHILDREN"] = \
            ("POST", "/session/$sessionId/moz/xbl/$id/anonymous_children")
        self._commands["ELEMENT_FIND_ANONYMOUS_ELEMENTS_BY_ATTRIBUTE"] = \
            ("POST", "/session/$sessionId/moz/xbl/$id/anonymous_by_attribute")
    def __init__(self, remote_server_addr, keep_alive=True):
        RemoteConnection.__init__(self, remote_server_addr, keep_alive)

        self._commands["GET_PERMISSIONS"] = (
            'GET', '/session/$sessionId/apple/permissions')
        self._commands["SET_PERMISSIONS"] = (
            'POST', '/session/$sessionId/apple/permissions')
        self._commands["ATTACH_DEBUGGER"] = (
            'POST', '/session/$sessionId/apple/attach_debugger')
Example #12
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/")
Example #13
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
Example #14
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)
Example #15
0
    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))
Example #16
0
 def __init__(self, remote_server_addr, keep_alive=True):
     RemoteConnection.__init__(self, remote_server_addr, keep_alive)
     self._commands["launchApp"] = ('POST', '/session/$sessionId/chromium/launch_app')
     self._commands["setNetworkConditions"] = ('POST', '/session/$sessionId/chromium/network_conditions')
     self._commands["getNetworkConditions"] = ('GET', '/session/$sessionId/chromium/network_conditions')
     self._commands['executeCdpCommand'] = ('POST', '/session/$sessionId/goog/cdp/execute')
     self._commands['getSinks'] = ('GET', '/session/$sessionId/goog/cast/get_sinks')
     self._commands['getIssueMessage'] = ('GET', '/session/$sessionId/goog/cast/get_issue_message')
     self._commands['setSinkToUse'] = ('POST', '/session/$sessionId/goog/cast/set_sink_to_use')
     self._commands['startTabMirroring'] = ('POST', '/session/$sessionId/goog/cast/start_tab_mirroring')
     self._commands['stopCasting'] = ('POST', '/session/$sessionId/goog/cast/stop_casting')
Example #17
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
Example #18
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
def patch_init(self, remote_server_addr, keep_alive=False, resolve_ip=True):
    print(
        "\nMonkey patch version: selenium.webdriver.remote.remote_connection")
    RemoteConnection.__org__init__(self,
                                   remote_server_addr,
                                   keep_alive=keep_alive,
                                   resolve_ip=resolve_ip)

    if keep_alive:
        # Define proxy. Default value is squid port.
        PROXY_URL = "http://localhost:3128"
        self._conn = urllib3.ProxyManager(proxy_url=PROXY_URL,
                                          timeout=self._timeout)
Example #20
0
    def __init__(self, remote_server_addr, keep_alive=True):
        RemoteConnection.__init__(self, remote_server_addr, keep_alive)

        self._commands["GET_CONTEXT"] = ('GET', '/session/$sessionId/moz/context')
        self._commands["SET_CONTEXT"] = ("POST", "/session/$sessionId/moz/context")
        self._commands["ELEMENT_GET_ANONYMOUS_CHILDREN"] = \
            ("POST", "/session/$sessionId/moz/xbl/$id/anonymous_children")
        self._commands["ELEMENT_FIND_ANONYMOUS_ELEMENTS_BY_ATTRIBUTE"] = \
            ("POST", "/session/$sessionId/moz/xbl/$id/anonymous_by_attribute")
        self._commands["INSTALL_ADDON"] = \
            ("POST", "/session/$sessionId/moz/addon/install")
        self._commands["UNINSTALL_ADDON"] = \
            ("POST", "/session/$sessionId/moz/addon/uninstall")
        self._commands["FULL_PAGE_SCREENSHOT"] = \
            ("GET", "/session/$sessionId/moz/screenshot/full")
Example #21
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(IMPLICIT_TIMEOUT)

        return driver
Example #22
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
Example #23
0
    def __init__(self, session_id=None, browser_name=''):
        command_executor = 'http://localhost:4444/wd/hub'
        platform = version = ''
        javascript_enabled = True

        self.command_executor = command_executor
        if type(self.command_executor) is str:
            self.command_executor = RemoteConnection(command_executor)

        self.command_executor._commands['GET_SESSION'] = (
            'GET', '/session/$sessionId')

        self.session_id = session_id
        self.capabilities = {}
        self.error_handler = ErrorHandler()

        if session_id:
            self.connect_to_session(browser_name=browser_name,
                                    platform=platform,
                                    version=version,
                                    javascript_enabled=javascript_enabled)
        else:
            self.start_session(browser_name=browser_name,
                               platform=platform,
                               version=version,
                               javascript_enabled=javascript_enabled)
Example #24
0
def driver(request, browser_config):
    # if the assignment below does not make sense to you please read up on object assignments.
    # The point is to make a copy and not mess with the original test spec.
    desired_caps = dict()
    desired_caps.update(browser_config)
    test_name = request.node.name
    username = environ.get('KOBITON_USERNAME', None)
    access_key = environ.get('KOBITON_ACCESS_KEY', None)

    selenium_endpoint = "https://%s:%[email protected]/wd/hub" % (username,
                                                                  access_key)
    desired_caps['name'] = test_name

    executor = RemoteConnection(selenium_endpoint, resolve_ip=False)
    browser = webdriver.Remote(command_executor=executor,
                               desired_capabilities=desired_caps)
    # In case test fails after selenium session creation having this here will help track it down.
    # creates one file per test non ideal but xdist is awful
    if browser is not None:
        with open("%s.testlog" % browser.session_id, 'w') as f:
            f.write("SessionID=%s job-name=%s\n" %
                    (browser.session_id, test_name))
    else:
        raise WebDriverException("Never created!")

    yield browser
    # Teardown starts here
    # report results
    try:
        browser.quit()
    except WebDriverException:
        # we can ignore the exceptions of WebDriverException type -> We're done with tests.
        print(
            'Warning: The driver failed to quit properly. Check test and server side logs.'
        )
Example #25
0
    def __init__(self,
                 executable_path='MicrosoftWebDriver.exe',
                 capabilities=None,
                 port=0,
                 verbose=False,
                 log_path=None):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path,
                                    port=self.port,
                                    verbose=verbose,
                                    log_path=log_path)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(self,
                                 command_executor=RemoteConnection(
                                     'http://localhost:%d' % self.port,
                                     resolve_ip=False),
                                 desired_capabilities=capabilities)
        self._is_remote = False
Example #26
0
    def __get_remote_driver(cls,
                            browser_name,
                            host,
                            port,
                            desired_capabilities=None,
                            **kwargs):
        """
        Return remote WebDriver instance.

        Parameters: see `__new__()`
        Return: <Remote> WebDriver instance
        Throws: KeyError - wrong browser name
        """
        command_executor = RemoteConnection('http://%s:%s/wd/hub' %
                                            (host, port))
        try:
            capabilities = cls.__desired_capabilities_map[browser_name].copy()
        except KeyError as ex:
            ex.args = ("unknown browser: '%s' (valid browsers: %s)"\
              % (browser_name, ', '.join(cls.__desired_capabilities_map.keys())),)
            raise ex
        if desired_capabilities:
            capabilities.update(desired_capabilities)

        return Remote(command_executor=command_executor,
                      desired_capabilities=capabilities,
                      **kwargs)
def driver(request):
    # if the assignment below does not make sense to you please read up on object assignments.
    # The point is to make a copy and not mess with the original test spec.
    desired_caps = {}
    
    browser = {
        "platform": "Windows 10",
        "browserName": "chrome",
        "version": "latest",
        "extendedDebugging": True
    }

    desired_caps.update(browser)
    test_name = request.node.name
    username = environ.get('SAUCE_USERNAME', None)
    access_key = environ.get('SAUCE_ACCESS_KEY', None)

    selenium_endpoint = "http://{}:{}@ondemand.saucelabs.com:80/wd/hub".format(username, access_key)
    desired_caps['name'] = test_name

    executor = RemoteConnection(selenium_endpoint, resolve_ip=False)
    browser = webdriver.Remote(
        command_executor=executor,
        desired_capabilities=desired_caps
    )
    yield browser

    def fin():
        browser.execute_script("sauce:job-result={}".format(str(not request.node.rep_call.failed).lower()))
        browser.quit()
    request.addfinalizer(fin)
def browser(request, browser_config):
    caps = {}
    caps.update(browser_config)

    build_tag = "nerodia-build"
    username = environ.get('SAUCE_USERNAME', None)
    access_key = environ.get('SAUCE_ACCESS_KEY', None)

    selenium_endpoint = "http://ondemand.saucelabs.com/wd/hub"

    caps['username'] = username
    caps['accesskey'] = access_key
    caps['name'] = request.node.name
    caps['build'] = build_tag

    executor = RemoteConnection(selenium_endpoint, resolve_ip=False)
    remote = webdriver.Remote(command_executor=executor,
                              desired_capabilities=caps)

    browser = Browser(browser=remote, desired_capabilities=caps)
    yield browser

    sauce_result = "failed" if request.node.rep_call.failed else "passed"
    browser.execute_script("sauce:job-result={}".format(sauce_result))
    browser.quit()
Example #29
0
    def setup(self, runner):
        """Connect to browser via Selenium's WebDriver implementation."""
        self.runner = runner
        self.logger.debug("Connecting to Selenium on URL: %s" % self.url)

        session_started = False
        try:
            self.webdriver = webdriver.Remote(command_executor=RemoteConnection(self.url.strip("/"),
                                                                                resolve_ip=False),
                                              desired_capabilities=self.capabilities)
        except:
            self.logger.warning(
                "Connecting to Selenium failed:\n%s" % traceback.format_exc())
        else:
            self.logger.debug("Selenium session started")
            session_started = True

        if not session_started:
            self.logger.warning("Failed to connect to Selenium")
            self.executor.runner.send_message("init_failed")
        else:
            try:
                self.after_connect()
            except:
                print >> sys.stderr, traceback.format_exc()
                self.logger.warning(
                    "Failed to connect to navigate initial page")
                self.executor.runner.send_message("init_failed")
            else:
                self.executor.runner.send_message("init_succeeded")
Example #30
0
    def connect(self):
        """Connect to browser via Selenium's WebDriver implementation."""
        self.logger.debug("Connecting to Selenium on URL: %s" % self.url)

        self.webdriver = webdriver.Remote(command_executor=RemoteConnection(self.url.strip("/"),
                                                                            resolve_ip=False),
                                          desired_capabilities=self.capabilities)
Example #31
0
class ResumableRemote(webdriver.Remote):
    def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
                 session_id=None, **kwargs):
        if session_id is not None:
            self.command_executor = command_executor
            try:
                string_type = basestring
            except:
                string_type = str
            if isinstance(self.command_executor, (string_type, bytes)):
                self.command_executor = RemoteConnection(
                        command_executor, keep_alive=kwargs.get('keep_alive', False))
            self.command_executor._commands['get_session'] = ('GET', '/session/$sessionId')
            self._is_remote = True
            self.start_client()
            self.resume_session(session_id)
            self._switch_to = SwitchTo(self)
            self._mobile = Mobile(self)
            self.error_handler = ErrorHandler()
        else:
            super(ResumableRemote, self).__init__(
                  command_executor=command_executor, **kwargs)

    def resume_session(self, session_id):
        self.session_id = session_id
        response = self.command_executor.execute('get_session', {'sessionId': session_id})
        self.capabilities = response['value']
Example #32
0
    def _update_command_executor(self, keep_alive):
        """Update command executor following directConnect feature"""
        direct_protocol = 'directConnectProtocol'
        direct_host = 'directConnectHost'
        direct_port = 'directConnectPort'
        direct_path = 'directConnectPath'

        if (not {direct_protocol, direct_host, direct_port, direct_path}.issubset(set(self.capabilities))):
            message = 'Direct connect capabilities from server were:\n'
            for key in [direct_protocol, direct_host, direct_port, direct_path]:
                message += '{}: \'{}\'\n'.format(key, self.capabilities.get(key, ''))
            logger.warning(message)
            return

        protocol = self.capabilities[direct_protocol]
        hostname = self.capabilities[direct_host]
        port = self.capabilities[direct_port]
        path = self.capabilities[direct_path]
        executor = '{scheme}://{hostname}:{port}{path}'.format(
            scheme=protocol,
            hostname=hostname,
            port=port,
            path=path
        )

        logger.info('Updated request endpoint to %s', executor)
        # Override command executor
        self.command_executor = RemoteConnection(executor, keep_alive=keep_alive)
        self._addCommands()
class Duplicate(WebDriver):
    def __init__(self, sess_id, svr_addr):
        super(WebDriver, self).__init__()
        self.command_executor = RemoteConnection(svr_addr, True)
        self.session_id = sess_id
        self.error_handler = ErrorHandler()
        self.file_detector = LocalFileDetector()

    #override
    def execute(self, driver_command, params=None):
        if self.session_id is not None:
            if not params:
                params = {'sessionId': self.session_id}
            elif 'sessionId' not in params:
                params['sessionId'] = self.session_id

        params = self._wrap_value(params)
        response = self.command_executor.execute(driver_command, params)
        if response:
            self.error_handler.check_response(response)
            response['value'] = self._unwrap_value(response.get('value', None))
            return response
        # If the server doesn't send a response, assume the command was
        # a success
        return {'success': 0, 'value': None, 'sessionId': self.session_id}
def test_get_remote_connection_headers_defaults():
    url = 'http://remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
    assert 'Authorization' not in headers.keys()
    assert 'Connection' not in headers.keys()
    assert headers.get('Accept') == 'application/json'
    assert headers.get('Content-Type') == 'application/json;charset=UTF-8'
    assert headers.get('User-Agent') == 'Python http auth'
def test_get_remote_connection_headers_defaults():
    url = 'http://remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
    assert 'Authorization' not in headers.keys()
    assert 'Connection' not in headers.keys()
    assert headers.get('Accept') == 'application/json'
    assert headers.get('Content-Type') == 'application/json;charset=UTF-8'
    assert headers.get('User-Agent').startswith("selenium/%s (python " % __version__)
    assert headers.get('User-Agent').split(' ')[-1] in {'windows)', 'mac)', 'linux)'}
Example #36
0
    def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
        self.profile = firefox_profile
        self.binary = firefox_binary
        HOST = host
        if self.binary is None:
            self.binary = FirefoxBinary()

        if HOST is None:
            HOST = "127.0.0.1"

        PORT = utils.free_port()
        self.profile.port = PORT 
        self.profile.update_preferences()
        
        self.profile.add_extension()

        self.binary.launch_browser(self.profile)
        _URL = "http://%s:%d/hub" % (HOST, PORT)
        RemoteConnection.__init__(
            self, _URL, keep_alive=True)
# 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",
Example #38
0
    def _browser(self):
        """ Initialize a Chrome webdriver.
        """
        RemoteConnection.set_timeout(CONNECTION_TIMEOUT)

        return webdriver.Firefox()
 def __init__(self, remote_server_addr, keep_alive=True):
     RemoteConnection.__init__(self, remote_server_addr, keep_alive)
     self._commands["launchApp"] = ('POST', '/session/$sessionId/chromium/launch_app')
     self._commands["setNetworkConditions"] = ('POST', '/session/$sessionId/chromium/network_conditions')
     self._commands["getNetworkConditions"] = ('GET', '/session/$sessionId/chromium/network_conditions')
     self._commands['executeCdpCommand'] = ('POST', '/session/$sessionId/goog/cdp/execute')
Example #40
0
    def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
        """Override get_remote_connection_headers in RemoteConnection"""
        headers = RemoteConnection.get_remote_connection_headers(parsed_url, keep_alive=keep_alive)
        headers['User-Agent'] = 'appium/python {} ({})'.format(library_version(), headers['User-Agent'])

        return headers
    def __init__(self, remote_server_addr, keep_alive=True):
        RemoteConnection.__init__(self, remote_server_addr, keep_alive)

        self._commands["GET_PERMISSIONS"] = ('GET', '/session/$sessionId/apple/permissions')
        self._commands["SET_PERMISSIONS"] = ('POST', '/session/$sessionId/apple/permissions')
        self._commands["ATTACH_DEBUGGER"] = ('POST', '/session/$sessionId/apple/attach_debugger')
def test_get_remote_connection_headers_adds_keep_alive_if_requested():
    url = 'http://remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url), keep_alive=True)
    assert headers.get('Connection') == 'keep-alive'
def test_get_remote_connection_headers_adds_auth_header_if_pass():
    url = 'http://*****:*****@remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
    assert headers.get('Authorization') == 'Basic dXNlcjpwYXNz'
Example #44
0
 def __init__(self, remote_server_addr, keep_alive=True):
     RemoteConnection.__init__(self, remote_server_addr, keep_alive)
     self._commands["launchApp"] = ('POST', '/session/$sessionId/chromium/launch_app')
Example #45
0
 def __init__(self, timeout=_DEFAULT_TIMEOUT):
     RemoteConnection.__init__(
         self, "http://localhost:%d/hub" % _DEFAULT_PORT)
     LOGGER.debug("extension connection initiated")
     self.timeout = timeout
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:
Example #47
0
 def __init__(self, remote_server_addr, keep_alive=True):
     RemoteConnection.__init__(self, remote_server_addr, keep_alive)
     self._commands["SET_CONTEXT"] = ('POST',
             '/session/$sessionId/moz/context')