Example #1
0
class FirefoxLauncher(object):
    """Launches the firefox browser."""

    def __init__(self):
        self.extension_connection = ExtensionConnection()
        self._start_cmd = utils.get_firefox_start_cmd()
        self.process = None

    def launch_browser(self, profile):
        """Launches the browser for the given profile name.
        It is assumed the profile already exists.
        """
        self.profile = profile
        while self.extension_connection.is_connectable():
            logging.info("Browser already running, kill it")
            self.extension_connection.connect_and_quit()
            time.sleep(1)
        self._start_from_profile_path(profile.path)

        attempts = 0
        while not self.extension_connection.is_connectable():
            attempts += 1
            if attempts > MAX_START_ATTEMPTS:
                raise RuntimeError("Unablet to start firefox")
            self._start_from_profile_path(profile.path)
            time.sleep(1)

    def _lock_file_exists(self):
        return os.path.exists(os.path.join(self.profile.path, ".parentlock"))

    def kill(self):
        """Kill the browser.

        This is useful when the browser is stuck.
        """
        try:
            if self.process:
                os.kill(self.process.pid, 9)
        except AttributeError:
            # kill may not be available under windows environment
            pass

    def _start_from_profile_path(self, path):
        os.environ["XRE_PROFILE_PATH"] = path
        self.process = Popen([self._start_cmd, "-no-remote", "--verbose"])

    def _wait_until_connectable(self):
        """Blocks until the extension is connectable in the firefox."""
        while not self.extension_connection.is_connectable():
            logging.debug("Waiting for browser to launch...")
            if self.process.returncode:
                # Browser has exited
                return False
            time.sleep(1)
        return True
Example #2
0
class WebDriver(object):
    """The main interface to use for testing,
    which represents an idealised web browser."""
    def __init__(self, profile_name="WebDriver", timeout=30):
        self.browser = FirefoxLauncher()
        self.browser.launch_browser(profile_name)
        self._conn = ExtensionConnection(timeout)
        self._conn.connect()

    def execute_script(self, script, *args):
        """Executes arbitrary javascript.
        For WebElement argument, the format is:
        execute_script("argument[0].value='cheese'", elem)
        """
        converted_args = []
        for arg in args:
            if type(arg) == WebElement:
                converted_args.append({"type": "ELEMENT", "value": arg.id})
            else:
                converted_args.append({"type": "STRING", "value": arg})
        resp = self._conn.driver_command("executeScript", script,
                                         converted_args)

        if "NULL" == resp["resultType"]:
            pass
        elif "ELEMENT" == resp["resultType"]:
            return WebElement(self, resp["response"])
        else:
            return resp["response"]

    def get(self, url):
        """Loads a web page in the current browser."""
        self._command("get", url)

    def get_current_url(self):
        """Gets the current url."""
        return self._command("getCurrentUrl")

    def get_title(self):
        """Gets the title of the current page."""
        return self._command("title")

    def find_element_by_xpath(self, xpath):
        """Finds an element by xpath."""
        try:
            elem_id = self._command("selectElementUsingXPath", xpath)
            elem = WebElement(self, elem_id)
        except ErrorInResponseException, ex:
            utils.handle_find_element_exception(ex)
        return elem
Example #3
0
 def __init__(self):
     self.__dict__ = self.__shared_state
     if "_start_cmd" not in self.__dict__:
         self.extension_connection = ExtensionConnection()
         if platform.system() == "Darwin":
             self._start_cmd = ("/Applications/Firefox.app/Contents/"
                                "MacOS/firefox-bin")
         elif platform.system() == "Windows":
             program_files = os.getenv("PROGRAMFILES")
             if program_files is None:
                 program_files = "\\Program Files"
             self._start_cmd = os.path.join(program_files, 
                                            "Mozilla Firefox\\firefox.exe") 
         else:
             # Maybe iceweasel (Debian) is another candidate...
             for ffname in ["firefox2", "firefox", "firefox-3.0"]:
                 logging.debug("Searching for '%s'...", ffname)
                 process = Popen(["which", ffname], stdout=PIPE)
                 cmd = process.communicate()[0].strip()
                 if cmd != "":
                     logging.debug("Using %s", cmd)
                     self._start_cmd = cmd
                     break
         self.profile_ini = ProfileIni()
         self.process = None
Example #4
0
 def __init__(self, profile=None, timeout=30):
     """Creates a webdriver instance.
     
     Args:
       profile: a FirefoxProfile object (it can also be a profile name,
                but the support for that may be removed in future, it is
                recommended to pass in a FirefoxProfile object)
       timeout: the amount of time to wait for extension socket
     """
     self.browser = FirefoxLauncher()
     if type(profile) == str:
         # This is to be Backward compatible because we used to take a
         # profile name
         profile = FirefoxProfile(name=profile)
     if not profile:
         profile = FirefoxProfile()
     self.browser.launch_browser(profile)
     self._conn = ExtensionConnection(timeout)
     self._conn.connect()
Example #5
0
class WebDriver(object):
    """The main interface to use for testing,
    which represents an idealised web browser."""
    def __init__(self, profile=None, timeout=30):
        """Creates a webdriver instance.
        
        Args:
          profile: a FirefoxProfile object (it can also be a profile name,
                   but the support for that may be removed in future, it is
                   recommended to pass in a FirefoxProfile object)
          timeout: the amount of time to wait for extension socket
        """
        self.browser = FirefoxLauncher()
        if type(profile) == str:
            # This is to be Backward compatible because we used to take a
            # profile name
            profile = FirefoxProfile(name=profile)
        if not profile:
            profile = FirefoxProfile()
        self.browser.launch_browser(profile)
        self._conn = ExtensionConnection(timeout)
        self._conn.connect()

    def execute_script(self, script, *args):
        """Executes arbitrary javascript.
        For WebElement argument, the format is:
        execute_script("argument[0].value='cheese'", elem)
        """
        converted_args = []
        for arg in args:
            if type(arg) == WebElement:
                converted_args.append({"type": "ELEMENT", "value": arg.id})
            else:
                converted_args.append({"type": "STRING", "value": arg})
        resp = self._conn.driver_command("executeScript", script,
                                         converted_args)

        if "NULL" == resp["resultType"]:
            pass
        elif "ELEMENT" == resp["resultType"]:
            return WebElement(self, resp["response"])
        else:
            return resp["response"]

    def get(self, url):
        """Loads a web page in the current browser."""
        self._command("get", url)

    def get_current_url(self):
        """Gets the current url."""
        return self._command("getCurrentUrl")

    def get_title(self):
        """Gets the title of the current page."""
        return self._command("title")

    def find_element_by_xpath(self, xpath):
        """Finds an element by xpath."""
        try:
            elem_id = self._command("selectElementUsingXPath", xpath)
            elem = WebElement(self, elem_id)
        except ErrorInResponseException, ex:
            utils.handle_find_element_exception(ex)
        return elem
Example #6
0
 def __init__(self):
     self.extension_connection = ExtensionConnection()
     self._start_cmd = utils.get_firefox_start_cmd()
     self.process = None
Example #7
0
class FirefoxLauncher(object):
    """Launches the firefox browser."""
    __shared_state = {}

    def __init__(self):
        self.__dict__ = self.__shared_state
        if "_start_cmd" not in self.__dict__:
            self.extension_connection = ExtensionConnection()
            if platform.system() == "Darwin":
                self._start_cmd = ("/Applications/Firefox.app/Contents/"
                                   "MacOS/firefox-bin")
            elif platform.system() == "Windows":
                program_files = os.getenv("PROGRAMFILES")
                if program_files is None:
                    program_files = "\\Program Files"
                self._start_cmd = os.path.join(program_files, 
                                               "Mozilla Firefox\\firefox.exe") 
            else:
                # Maybe iceweasel (Debian) is another candidate...
                for ffname in ["firefox2", "firefox", "firefox-3.0"]:
                    logging.debug("Searching for '%s'...", ffname)
                    process = Popen(["which", ffname], stdout=PIPE)
                    cmd = process.communicate()[0].strip()
                    if cmd != "":
                        logging.debug("Using %s", cmd)
                        self._start_cmd = cmd
                        break
            self.profile_ini = ProfileIni()
            self.process = None

    def launch_browser(self, profile_name):
        """Launches the browser."""
        if self.extension_connection.is_connectable():
            logging.info("Browser already running, kill it")
            self.extension_connection.connect_and_quit()
        if profile_name not in self.profile_ini.profiles:
            Popen([self._start_cmd, "-createProfile", profile_name]).wait()
            self.profile_ini.refresh()
        profile = self.profile_ini.profiles[profile_name]
        profile.remove_lock_file()
        profile.add_extension()
        self.process = Popen([self._start_cmd, "-no-remote", "--verbose", "-P",
               profile_name])
        self._wait_until_connectable()

    def kill(self):
        """Kill the browser.

        This is useful when the browser is stuck.
        """
        try:
            if self.process:
                os.kill(self.process.pid, 9)
        except AttributeError:
            # kill may not be available under windows environment
            pass

    def _wait_until_connectable(self):
        """Blocks until the extension is connectable in the firefox."""
        while not self.extension_connection.is_connectable():
            time.sleep(1)
            logging.debug("Waiting for browser to launch...")
Example #8
0
 def __init__(self, profile_name="WebDriver", timeout=30):
     self.browser = FirefoxLauncher()
     self.browser.launch_browser(profile_name)
     self._conn = ExtensionConnection(timeout)
     self._conn.connect()