def create_options(self):
        super().debug_begin()

        options = FirefoxOptions()

        options.add_argument("--start-maximized")

        if super()._language is not None:
            options.add_argument("--lang=" + super()._language)

        if super()._headless:
            options.add_argument("-headless")
            options.add_argument("--disable-gpu")

        profile = FirefoxProfile()
        profile.accept_untrusted_certs = True

        for file_name in self.__plugin_files:
            if '\\.' not in file_name:
                file_name += '.xpi'
            profile.add_extension(os.getcwd() + '/' + file_name)

        options.profile = profile

        if super()._use_proxy:
            # options.add_argument('--ignore-certificate-errors')
            pass

        super().debug_end()

        return options
示例#2
0
    def _profile(self, arguments, extensions, proxy, user_agent):
        """ Compile the capabilities of ChromeDriver inside the Container.

        Args:
            arguments (list):
            extensions (list):
            proxy (Proxy): unused.
            user_agent (str):

        Returns:
            FirefoxProfile
        """
        self.logger.debug('building browser profile')
        profile = FirefoxProfile()
        args = list(self.DEFAULT_ARGUMENTS)

        if self.f(Flags.X_IMG):
            args.append(('permissions.default.image', '2'))

        if self.f(Flags.X_FLASH):
            args.append(('dom.ipc.plugins.enabled.libflashplayer.so', 'false'))

        for ext in extensions:
            profile.add_extension(ext)

        args.extend(arguments)
        for arg_k, value in args:
            profile.set_preference(arg_k, value)
        if user_agent:
            profile.set_preference('general.useragent.override', user_agent)
        return profile
    def create_download_dir_profile_for_firefox(path_to_download, mime_types_file=None, *extensions_files):
        """
        Example use
        | ${profile} | Create Download Dir Profile For Firefox | Artifacts | Resources/mimeTypes.rdf | Resources/webdriver_element_locator-2.0-fx.xpi | Resources/selenium_ide-2.9.1-fx.xpi |
        | Open Browser Extension | https://support.spatialkey.com/spatialkey-sample-csv-data/ | ff_profile_dir=${profile} |
        | Click Element | //a[contains(@href,'sample.csv.zip')]  |
        """
        path_to_download_check = validate_create_artifacts_dir(path_to_download)

        fp = FirefoxProfile()
        fp.set_preference("browser.download.folderList", 2)
        fp.set_preference("browser.download.manager.showWhenStarting", False)
        fp.set_preference("browser.download.manager.alertOnEXEOpen", False)
        fp.set_preference("browser.download.dir", path_to_download_check)
        fp.set_preference("xpinstall.signatures.required", False)
        fp.set_preference("browser.helperApps.alwaysAsk.force", False)
        fp.set_preference("browser.helperApps.neverAsk.saveToDisk",
            "application/msword;application/csv;text/csv;image/png;image/jpeg;application/pdf;text/html;text/plain;application/octet-stream")
        fp.set_preference("pdfjs.disabled", True)
        fp.update_preferences()
        for single_extension in extensions_files:
            fp.add_extension(single_extension)
        if mime_types_file is not None:
            from shutil import copy2
            copy2(os.path.normpath(mime_types_file), fp.profile_dir)
        logger.info("Firefox Profile Created in dir '" + fp.profile_dir + "'")
        return fp.profile_dir
    def create_download_dir_profile_for_firefox(path_to_download,
                                                mime_types_file=None,
                                                *extensions_files):
        """
        Example use
        | ${profile} | Create Download Dir Profile For Firefox | Artifacts | Resources/mimeTypes.rdf | Resources/webdriver_element_locator-2.0-fx.xpi | Resources/selenium_ide-2.9.1-fx.xpi |
        | Open Browser Extension | https://support.spatialkey.com/spatialkey-sample-csv-data/ | ff_profile_dir=${profile} |
        | Click Element | //a[contains(@href,'sample.csv.zip')]  |
        """
        path_to_download_check = validate_create_artifacts_dir(
            path_to_download)

        fp = FirefoxProfile()
        fp.set_preference("browser.download.folderList", 2)
        fp.set_preference("browser.download.manager.showWhenStarting", False)
        fp.set_preference("browser.download.manager.alertOnEXEOpen", False)
        fp.set_preference("browser.download.dir", path_to_download_check)
        fp.set_preference("xpinstall.signatures.required", False)
        fp.set_preference("browser.helperApps.alwaysAsk.force", False)
        fp.set_preference(
            "browser.helperApps.neverAsk.saveToDisk",
            "application/msword;application/csv;text/csv;image/png;image/jpeg;application/pdf;text/html;text/plain;application/octet-stream"
        )
        fp.set_preference("pdfjs.disabled", True)
        fp.update_preferences()
        for single_extension in extensions_files:
            fp.add_extension(single_extension)
        if mime_types_file is not None:
            from shutil import copy2
            copy2(os.path.normpath(mime_types_file), fp.profile_dir)
        logger.info("Firefox Profile Created in dir '" + fp.profile_dir + "'")
        return fp.profile_dir
示例#5
0
    def __init__(self, delay=1, browser="firefox"):
        """delay: Number of extra seconds to wait when a page is
           supposedly loaded. Try raising this in case of weird errors.

           browser: `firefox` or `chrome`. The ChromeDriver executable for your
           OS must be inside the bin directory for Chrome to work. Get it from:
           http://chromedriver.storage.googleapis.com/index.html
        """
        self.extra_delay = delay  # extra time to wait after each operation (s)
        self.temp_dir = mkdtemp()

        self.vdisplay = Xvfb()
        self.vdisplay.start()

        def get_bin_path(subdir):
            path = os_path.dirname(os_path.realpath(__file__)) + os_sep
            return path + os_sep.join([pardir, "bin", subdir])

        if browser == "firefox":
            profile = FirefoxProfile()
            # Open links in same window
            profile.set_preference("browser.link.open_newwindow", 1)
            # Download to temp dir, for files we can't open inline
            profile.set_preference("browser.download.dir", self.temp_dir)
            profile.set_preference("browser.download.folderList", 2)
            profile.set_preference("browser.download.manager.showWhenStarting",
                                   "False")
            profile.set_preference(
                "browser.helperApps.neverAsk.saveToDisk",
                "application/msword, application/vnd.ms-word, application/rtf, application/octet-stream"
            )

            # Add extension for overriding Content-Disposition headers, etc
            extensions_dir = get_bin_path('firefox-plugins-enabled')
            for filename in listdir(extensions_dir):
                fullfilename = os_sep.join([extensions_dir, filename])
                profile.add_extension(extension=fullfilename)

            driver = Firefox(profile)
        elif browser == "chrome":
            # Add extension for overriding Content-Disposition headers
            options = ChromeOptions()
            options.add_extension(get_bin_path('bin/undisposition.crx'))
            driver = Chrome(executable_path=get_bin_path('bin/chromedriver'),
                            chrome_options=options)
        else:
            raise Exception("Not a valid browser name")

        self.selenium_driver = EventFiringWebDriver(driver, CustomListener())
        """selenium_driver is a EventFiringWebDriver, so that it can
           trigger javascript event
        """
        self.browser_version = " ".join([
            self.selenium_driver.capabilities['browserName'],
            self.selenium_driver.capabilities['version']
        ])  # 'Firefox 33.0'
  def makeProfile(self, config):
    
    profile = FirefoxProfile()

    # Disable Firefox auto update
    profile.set_preference("app.update.enabled", False)

    try:
      if config["fire_bug"]:
        profile.add_extension(FIREBUG_EXTENSION)
    
        domain = "extensions.firebug."
        # Set default Firebug preferences
       
        # Avoid Firebug start page
        profile.set_preference(domain + "currentVersion", "2.0.6")
        # Activate everything
        profile.set_preference(domain + "allPagesActivation", "on")
        profile.set_preference(domain + "defaultPanelName", "net")
        # Enable Firebug on all sites
        profile.set_preference(domain + "net.enableSites", True)
       
        self.logger.info("Firebug profile settings enabled")

    except KeyError:
      self.logger.warning("Firebug profile settings failed")
      pass 


    try:
      if config["net_export"]:
        profile.add_extension(NETEXPORT_EXTENSION)

        # Set default NetExport preferences
        self.har_output = config["net_export_output"]
        #self.logger.info("Output HAR directory: {0}".format(self.har_output))
        profile.set_preference(domain + "netexport.defaultLogDir", self.har_output)
        profile.set_preference(domain + "netexport.autoExportToFile", True)
        profile.set_preference(domain + "netexport.alwaysEnableAutoExport", True)
        # Do not show preview output
        profile.set_preference(domain + "netexport.showPreview", True)
        profile.set_preference(domain + "netexport.pageLoadedTimeout", 3000)
        # Log dir
        self.logger.info("NetExport profile settings enabled.")

        # Har ID to check file exists
        self.har_id = int((datetime.datetime.now()-datetime.datetime(1970,1,1)).total_seconds()*1000000)
        self.url += "/?{0}".format(self.har_id)
        #print self.url

    except KeyError:
      self.logger.warning("NetExport profile settings failed")
      pass

    profile.update_preferences()
    return profile
示例#7
0
def test_add_extension_web_extension_without_id(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..', '..')
    extension_path = os.path.join(root_directory, 'third_party', 'firebug', 'mooltipass-1.1.87.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(profile_path, 'extensions', '[email protected]')
    assert os.path.exists(extension_path_in_profile)
    driver.quit()
示例#8
0
def test_add_extension_legacy_extension(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..', '..')
    extension_path = os.path.join(root_directory, 'third_party', 'firebug', 'firebug-1.5.0-fx.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(profile_path, 'extensions', '*****@*****.**')
    assert os.path.exists(extension_path_in_profile)
    driver.quit()
示例#9
0
def firefox_profile(request):
    profile = FirefoxProfile(request.config.getoption('firefox_profile'))
    for preference in request.config.getoption('firefox_preferences'):
        name, value = preference
        if value.isdigit():
            # handle integer preferences
            value = int(value)
        elif value.lower() in ['true', 'false']:
            # handle boolean preferences
            value = value.lower() == 'true'
        profile.set_preference(name, value)
    profile.update_preferences()
    for extension in request.config.getoption('firefox_extensions'):
        profile.add_extension(extension)
    return profile
示例#10
0
    def __init__(self, delay=1, browser="firefox"):
        """delay: Number of extra seconds to wait when a page is
           supposedly loaded. Try raising this in case of weird errors.

           browser: `firefox` or `chrome`. The ChromeDriver executable for your
           OS must be inside the bin directory for Chrome to work. Get it from:
           http://chromedriver.storage.googleapis.com/index.html
        """
        self.extra_delay = delay  # extra time to wait after each operation (s)
        self.temp_dir = mkdtemp()

        self.vdisplay = Xvfb()
        self.vdisplay.start()
        if browser == "firefox":
            profile = FirefoxProfile()
            # Open links in same window
            profile.set_preference("browser.link.open_newwindow", 1)
            # Download to temp dir, for files we can't open inline
            profile.set_preference("browser.download.dir", self.temp_dir)
            profile.set_preference("browser.download.folderList", 2)
            profile.set_preference("browser.download.manager.showWhenStarting",
                                   "False")
            profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
                                   "application/msword, application/vnd.ms-word, application/rtf, application/octet-stream")

            # Add extension for overriding Content-Disposition headers, etc
            extensions_dir = os_sep.join(['bin', 'firefox-plugins-enabled'])
            for filename in listdir(extensions_dir):
                fullfilename = os_sep.join([extensions_dir, filename])
                profile.add_extension(extension=fullfilename)

            driver = Firefox(profile)
        elif browser == "chrome":
            # Add extension for overriding Content-Disposition headers
            options = ChromeOptions()
            options.add_extension('bin/undisposition.crx')
            driver = Chrome(executable_path='bin/chromedriver',
                            chrome_options=options)
        else:
            raise Exception("Not a valid browser name")

        self.selenium_driver = EventFiringWebDriver(driver, CustomListener())
        """selenium_driver is a EventFiringWebDriver, so that it can
           trigger javascript event
        """
        self.browser_version = " ".join([
            self.selenium_driver.capabilities['browserName'],
            self.selenium_driver.capabilities['version']])  # 'Firefox 33.0'
示例#11
0
def test_add_extension_legacy_extension(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..',
                                  '..')
    extension_path = os.path.join(root_directory, 'third_party', 'firebug',
                                  'firebug-1.5.0-fx.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(profile_path, 'extensions',
                                             '*****@*****.**')
    assert os.path.exists(extension_path_in_profile)
    driver.quit()
示例#12
0
def test_add_extension_web_extension_without_id(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..',
                                  '..')
    extension_path = os.path.join(root_directory, 'third_party', 'firebug',
                                  'mooltipass-1.1.87.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(profile_path, 'extensions',
                                             '[email protected]')
    assert os.path.exists(extension_path_in_profile)
    driver.quit()
示例#13
0
def test_add_extension_web_extension_with_id(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..', '..')
    # TODO: This file should probably live in a common directory.
    extension_path = os.path.join(root_directory, 'javascript', 'node', 'selenium-webdriver',
                                  'lib', 'test', 'data', 'firefox', 'webextension.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(profile_path, 'extensions', '*****@*****.**')
    assert os.path.exists(extension_path_in_profile)
    driver.get(webserver.where_is('simpleTest.html'))
    driver.find_element_by_id('webextensions-selenium-example')
    driver.quit()
示例#14
0
    def setup_firefox_profile(self):
        """Return a custom firefox profile with given preferences
        and extensions.

        """
        fp = FirefoxProfile()

        if self.extensions:
            # Load extensions.
            for ext in self.extensions:
                fp.add_extension(ext)

        if self.preferences:
            # Load preferences
            for key, value in self.preferences:
                fp.set_preference(key, value)

        return fp
示例#15
0
def firefox_profile(pytestconfig):
    profile = None
    if pytestconfig.getoption("firefox_profile"):
        profile = FirefoxProfile(pytestconfig.getoption("firefox_profile"))
        warnings.warn(
            "--firefox-profile has been deprecated and will be removed in "
            "a future release. Please use the firefox_options fixture to "
            "set a profile path or FirefoxProfile object using "
            "firefox_options.profile.",
            DeprecationWarning,
        )
    if pytestconfig.getoption("firefox_preferences"):
        profile = profile or FirefoxProfile()
        warnings.warn(
            "--firefox-preference has been deprecated and will be removed in "
            "a future release. Please use the firefox_options fixture to set "
            "preferences using firefox_options.set_preference. If you are "
            "using Firefox 47 or earlier then you will need to create a "
            "FirefoxProfile object with preferences and set this using "
            "firefox_options.profile.",
            DeprecationWarning,
        )
        for preference in pytestconfig.getoption("firefox_preferences"):
            name, value = preference
            if value.isdigit():
                # handle integer preferences
                value = int(value)
            elif value.lower() in ["true", "false"]:
                # handle boolean preferences
                value = value.lower() == "true"
            profile.set_preference(name, value)
        profile.update_preferences()
    if pytestconfig.getoption("firefox_extensions"):
        profile = profile or FirefoxProfile()
        warnings.warn(
            "--firefox-extensions has been deprecated and will be removed in "
            "a future release. Please use the firefox_options fixture to "
            "create a FirefoxProfile object with extensions and set this "
            "using firefox_options.profile.",
            DeprecationWarning,
        )
        for extension in pytestconfig.getoption("firefox_extensions"):
            profile.add_extension(extension)
    return profile
示例#16
0
def get_driver():
    profile = FirefoxProfile()
    profile.add_extension('./bin/quickjava.xpi')

    options = [('startupStatus.Images', 2), ('startupStatus.AnimatedImage', 2),
               ('startupStatuss.CSS', 2), ('startupStatus.Cookies', 2),
               ('startupStatus.Flash', 2), ('startupStatus.Java', 2),
               ('startupStatus.Silverlight', 2)]

    for o, v in options:
        profile.set_preference('thatoneguydotnet.QuickJava.' + o, v)

    try:
        driver = WebDriver(profile)
        driver.implicitly_wait(5.0)
    except WebDriverException as e:
        logger.error(e)
        return None
    return driver
示例#17
0
def test_add_extension_web_extension_with_id(capabilities, webserver):
    current_directory = os.path.dirname(os.path.realpath(__file__))
    root_directory = os.path.join(current_directory, '..', '..', '..', '..',
                                  '..')
    # TODO: This file should probably live in a common directory.
    extension_path = os.path.join(root_directory, 'javascript', 'node',
                                  'selenium-webdriver', 'lib', 'test', 'data',
                                  'firefox', 'webextension.xpi')

    profile = FirefoxProfile()
    profile.add_extension(extension_path)

    driver = Firefox(capabilities=capabilities, firefox_profile=profile)
    profile_path = driver.firefox_profile.path
    extension_path_in_profile = os.path.join(
        profile_path, 'extensions',
        '*****@*****.**')
    assert os.path.exists(extension_path_in_profile)
    driver.get(webserver.where_is('simpleTest.html'))
    driver.find_element_by_id('webextensions-selenium-example')
    driver.quit()
示例#18
0
def firefox_profile(pytestconfig):
    profile = None
    if pytestconfig.getoption('firefox_profile'):
        profile = FirefoxProfile(pytestconfig.getoption('firefox_profile'))
        warnings.warn(
            '--firefox-profile has been deprecated and will be removed in '
            'a future release. Please use the firefox_options fixture to '
            'set a profile path or FirefoxProfile object using '
            'firefox_options.profile.', DeprecationWarning)
    if pytestconfig.getoption('firefox_preferences'):
        profile = profile or FirefoxProfile()
        warnings.warn(
            '--firefox-preference has been deprecated and will be removed in '
            'a future release. Please use the firefox_options fixture to set '
            'preferences using firefox_options.set_preference. If you are '
            'using Firefox 47 or earlier then you will need to create a '
            'FirefoxProfile object with preferences and set this using '
            'firefox_options.profile.', DeprecationWarning)
        for preference in pytestconfig.getoption('firefox_preferences'):
            name, value = preference
            if value.isdigit():
                # handle integer preferences
                value = int(value)
            elif value.lower() in ['true', 'false']:
                # handle boolean preferences
                value = value.lower() == 'true'
            profile.set_preference(name, value)
        profile.update_preferences()
    if pytestconfig.getoption('firefox_extensions'):
        profile = profile or FirefoxProfile()
        warnings.warn(
            '--firefox-extensions has been deprecated and will be removed in '
            'a future release. Please use the firefox_options fixture to '
            'create a FirefoxProfile object with extensions and set this '
            'using firefox_options.profile.', DeprecationWarning)
        for extension in pytestconfig.getoption('firefox_extensions'):
            profile.add_extension(extension)
    return profile
示例#19
0
    def makeProfile(self, config):

        profile = FirefoxProfile()

        # Disable Firefox auto update
        profile.set_preference("app.update.enabled", False)

        try:
            if config["fire_bug"]:
                profile.add_extension(FIREBUG_EXTENSION)

                domain = "extensions.firebug."
                # Set default Firebug preferences

                # Avoid Firebug start page
                profile.set_preference(domain + "currentVersion", "2.0.6")
                # Activate everything
                profile.set_preference(domain + "allPagesActivation", "on")
                profile.set_preference(domain + "defaultPanelName", "net")
                # Enable Firebug on all sites
                profile.set_preference(domain + "net.enableSites", True)

                self.logger.info("Firebug profile settings enabled")

        except KeyError:
            self.logger.warning("Firebug profile settings failed")
            pass

        try:
            if config["net_export"]:
                profile.add_extension(NETEXPORT_EXTENSION)

                # Set default NetExport preferences
                self.har_output = config["net_export_output"]
                #self.logger.info("Output HAR directory: {0}".format(self.har_output))
                profile.set_preference(domain + "netexport.defaultLogDir",
                                       self.har_output)
                profile.set_preference(domain + "netexport.autoExportToFile",
                                       True)
                profile.set_preference(
                    domain + "netexport.alwaysEnableAutoExport", True)
                # Do not show preview output
                profile.set_preference(domain + "netexport.showPreview", True)
                profile.set_preference(domain + "netexport.pageLoadedTimeout",
                                       3000)
                # Log dir
                self.logger.info("NetExport profile settings enabled.")

                # Har ID to check file exists
                self.har_id = int(
                    (datetime.datetime.now() -
                     datetime.datetime(1970, 1, 1)).total_seconds() * 1000000)
                self.url += "/?{0}".format(self.har_id)
                #print self.url

        except KeyError:
            self.logger.warning("NetExport profile settings failed")
            pass

        profile.update_preferences()
        return profile