示例#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():
            LOGGER.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("Unable 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, signal.SIGTERM)
        except AttributeError:
            # kill may not be available under windows environment
            pass

    def _start_from_profile_path(self, path):
        os.environ["XRE_PROFILE_PATH"] = path
        os.environ["MOZ_CRASHREPORTER_DISABLE"] = "1"
        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():
            LOGGER.debug("Waiting for browser to launch...")
            if self.process.returncode:
                # Browser has exited
                return False
            time.sleep(1)
        return True
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():
            LOGGER.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("Unable 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, signal.SIGTERM)
        except AttributeError:
            # kill may not be available under windows environment
            pass

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

    def _wait_until_connectable(self):
        """Blocks until the extension is connectable in the firefox."""
        while not self.extension_connection.is_connectable():
            LOGGER.debug("Waiting for browser to launch...")
            if self.process.returncode:
                # Browser has exited
                return False
            time.sleep(1)
        return True
示例#3
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()
示例#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)
     RemoteWebDriver.__init__(self,
                              command_executor=ExtensionConnection(timeout),
                              browser_name='firefox',
                              platform='ANY',
                              version='',
                              javascript_enabled=True)
示例#5
0
 def __init__(self):
     self.extension_connection = ExtensionConnection()
     self._start_cmd = utils.get_firefox_start_cmd()
     self.process = None
示例#6
0
 def __init__(self, parent, id):
     self.parent = parent
     self.conn = ExtensionConnection()
     self.id = id
示例#7
0
class WebElement(object):
    """Represents an HTML element. Generally, all interesting operations to do with
    interacting with a page will be performed through this interface."""

    def __init__(self, parent, id):
        self.parent = parent
        self.conn = ExtensionConnection()
        self.id = id

    def get_text(self):
        """Gets the inner text of the element."""
        return self._command("getElementText")

    def click(self):
        """Clicks the element."""
        self._command("click")

    def submit(self):
        """Submits a form."""
        self._command("submitElement")

    def get_value(self):
        """Gets the value of the element's value attribute."""
        return self._command("getElementValue")

    def clear(self):
        """Clears the text if it's a text entry element."""
        self._command("clear")

    def get_attribute(self, name):
        """Gets the attribute value."""
        return self._command("getElementAttribute", name)

    def toggle(self):
        """Toggles the element state."""
        self._command("toggleElement")

    def is_selected(self):
        """Whether the element is selected."""
        return self._command("getElementSelected")

    def set_selected(self):
        """Selects an elmeent."""
        self._command("setElementSelected")

    def is_enabled(self):
        """Whether the element is enabled."""
        if self.get_attribute("disabled"):
            return False
        else:
            # The "disabled" attribute may not exist
            return True

    def find_elements_by_xpath(self, xpath):
        """Finds elements within the elements by xpath."""
        resp = self._command("findElementsByXPath", xpath)
        elems = []
        for elemId in resp.split(","):
            elem = WebElement(self.parent, elemId)
            elems.append(elem)
        return elems

    def send_keys(self, keys_characters):
        """Simulates typing into the element."""
        self._command("sendKeys", keys_characters)

    def _command(self, _cmd, *args):
        return self.conn.element_command(_cmd, self.id, *args)
 def __init__(self):
     self.extension_connection = ExtensionConnection()
     self._start_cmd = utils.get_firefox_start_cmd()
     self.process = None
示例#9
0
class WebDriver(object):
    name = "Firefox"

    """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._command("executeScript", script, converted_args)
        if "ELEMENT" == resp["type"]:
            return WebElement(self, resp["value"])
        else:
            return resp["value"]

    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."""
        return self._find_element_by("xpath", xpath)

    def find_element_by_link_text(self, link):
        """Finds an element by its link text.

        throws NoSuchElementException when no element is found 
        with the link text.
        """
        return self._find_element_by("link text", link)

    def find_elements_by_link_text(self, link):
        """Finds all elements with the same link text.

        throws NoSuchElementException when no element is found 
        with the link text.
        """
        return self._find_elements_by("link text", link)

    def find_element_by_partial_link_text(self, text):
        """Finds an element by a segment of its link text

        throws NoSuchElementException when no element is found 
        with the link text.
        """
        return self._find_element_by("partial link text", text)

    def find_elements_by_partial_link_text(self, text):
        """Finds all elements by a segment of the link text.

        throws NoSuchElementException when no element is found 
        with the link text.
        """
        return self._find_elements_by("partial link text", text)

    def find_element_by_id(self, id_):
        """Finds an element by its id."""
        return self._find_element_by("id", id_)

    def find_element_by_name(self, name):
        """Finds and element by its name."""
        return self._find_element_by("name", name)

    def find_elements_by_xpath(self, xpath):
        """Finds all the elements for the given xpath query."""
        return self._find_elements_by("xpath", xpath)

    def find_element_by_tag_name(self, tag_name):
        """Finds and element by its tag name."""
        return self._find_element_by("tag name", tag_name)
    
    def find_elements_by_tag_name(self, tag_name):
        """Finds all the elements with the given tag"""
        return self._find_elements_by("tag name", tag_name)

    def get_page_source(self):
        """Gets the page source."""
        return self._command("getPageSource")

    def close(self):
        """Closes the current window.
        Quit the browser if it's the last window open.
        """
        if self._conn.is_connectable():
            self._conn.driver_command("close")
        self.browser.kill()

    def quit(self):
        """Quits the driver and close every associated window."""
        self._conn.quit()
        self.browser.kill()
            

    def switch_to_active_element(self):
        """Returns the element with focus, or BODY if nothing has focus"""
        return WebElement(self, self._command("switchToActiveElement"))

    def switch_to_window(self, window_name):
        """Switches focus to a window."""
        resp = self._command("switchToWindow", window_name)
        if not resp or "No window found" in resp:
            raise InvalidSwitchToTargetException(
                "Window %s not found" % window_name)
        self._conn.context = resp
        
    def get_current_window_handle(self):
        handle = self._command("getCurrentWindowHandle")
        assert "," not in handle, "there should be only one current handle"
        return handle

    def get_window_handles(self):
        return self._command("getWindowHandles")

    def switch_to_frame(self, index_or_name):
        """Switches focus to a frame by index or name."""
        self._command("switchToFrame", str(index_or_name))

    def back(self):
        """Goes back in browser history."""
        self._command("goBack")

    def forward(self):
        """Goes forward in browser history."""
        self._command("goForward")

    def get_cookies(self):
        """Gets all the cookies."""
        try:
            cookie_response = self._command("getCookie")
        except ErrorInResponseException:
            return []

        #cookie_response is a list of cookies of type unicode
        cookies = []
        for cookie_unicode in cookie_response:
            cookie = self.get_cookie_in_dict(cookie_unicode)
            if cookie:
                cookies.append(cookie)
        return cookies

    def delete_all_cookies(self):
        """Gets the current url."""
        cookies = self.get_cookies()
        for cookie in cookies:
            self.delete_cookie(cookie['name'])

    def delete_cookie(self, cookie_name):
        """Delete a cookie."""
        cookie_arg = "{\"name\" : \"%s\"}" % cookie_name
        self._command("deleteCookie", cookie_arg)

    def get_cookie_in_dict(self, cookie_str):          
        """Convert a cookie in unicode (returned by self._command('getCookie'))
        to a dictionary representation.
        """
        tokens = cookie_str.split(";")
        if len(tokens) > 1:
            name, value = tuple(tokens[0].split("=", 1))
            cookie_dict = dict([tuple(token.split("=", 1))
                                for token in tokens[1:] if token])
            cookie_dict["name"] = name
            cookie_dict["value"] = value
            return cookie_dict

    def add_cookie(self, cookie_dict):
        self._command("addCookie", cookie_dict)

    def save_screenshot(self, png_file):
        """Saves a screenshot of the current page into the given
        file."""
        self._command("saveScreenshot", png_file)

    def _command(self, cmd, *args):
        """Forward command on to the extension connection."""
        return self._conn.driver_command(cmd, *args)["response"]

    @property
    def conn(self):
        return self._conn

    def _find_element_by(self, selector, key):
        try:
          elem_id = self._command("findElement", selector, key)
          return WebElement(self, elem_id)
        except ErrorInResponseException, ex:
            utils.handle_find_element_exception(ex)