Esempio n. 1
0
class ElementKeywords(LibraryComponent):

    def __init__(self, ctx):
        LibraryComponent.__init__(self, ctx)
        self.element_management = SeleniumElementKeywords(ctx)

    @keyword
    def clear_textfield_value(self, locator):
        text = self.element_management.get_value(locator)
        i = 0
        while i < len(text):
            i += 1
            self.element_management.press_key(locator, Keys.BACK_SPACE)
            self.element_management.press_key(locator, Keys.DELETE)

    @keyword
    def scroll_to_element(self, locator):
        self.driver.execute_script("arguments[0].scrollIntoView();", self.find_element(locator))

    def _scroll_to_left_of_webElement(self, element):
        self.driver.execute_script("arguments[0].scrollTo(0,0);", element)

    @keyword
    def js_click(self, element):
        self.driver.execute_script("arguments[0].click();", element)

    @keyword
    def get_child_element_by_tag_and_attribute(self, element, tag, attribute_name, attribute_value):
        child_elements = element.find_elements_by_tag_name(tag)
        for child in child_elements:
            if child.get_attribute(attribute_name).strip() == attribute_value:
                return child
        message = "Child element '%s = %s' not found!" % (attribute_name, attribute_value)
        raise AssertionError(message)
Esempio n. 2
0
 def __init__(self):
     ctx = SeleniumLibrary(screenshot_root_directory='Results')
     AlertKeywords.__init__(self, ctx)
     BrowserManagementKeywords.__init__(self, ctx)
     ElementKeywords.__init__(self, ctx)
     FormElementKeywords.__init__(self, ctx)
     ScreenshotKeywords.__init__(self, ctx)
     SelectElementKeywords.__init__(self, ctx)
     WaitingKeywords.__init__(self, ctx)
     self.screenshot_directory = ctx.screenshot_root_directory
     self.builtIn = CRFBuiltIn()
class KeywordArgumentsElementTest(unittest.TestCase):

    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(locator).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')
        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')
class KeywordArgumentsElementTest(unittest.TestCase):
    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(locator).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')
        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')
Esempio n. 5
0
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None,
                 plugins=None,
                 event_firing_webdriver=None):
        """SeleniumLibrary can be imported with several optional arguments.

        - ``timeout``:
          Default value for `timeouts` used with ``Wait ...`` keywords.
        - ``implicit_wait``:
          Default value for `implicit wait` used when locating elements.
        - ``run_on_failure``:
          Default action for the `run-on-failure functionality`.
        - ``screenshot_root_directory``:
          Location where possible screenshots are created. If not given,
          the directory where the log file is written is used.
        - ``plugins``:
          Allows extending the SeleniumLibrary with external Python classes.
        - ``event_firing_webdriver``:
          Class for wrapping Selenium with
          [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.event_firing_webdriver.html#module-selenium.webdriver.support.event_firing_webdriver|EventFiringWebDriver]
        """
        self.timeout = timestr_to_secs(timeout)
        self.implicit_wait = timestr_to_secs(implicit_wait)
        self.speed = 0.0
        self.run_on_failure_keyword \
            = RunOnFailureKeywords.resolve_keyword(run_on_failure)
        self._running_on_failure_keyword = False
        self.screenshot_root_directory = screenshot_root_directory
        self._element_finder = ElementFinder(self)
        self._plugin_keywords = []
        libraries = [
            AlertKeywords(self),
            BrowserManagementKeywords(self),
            CookieKeywords(self),
            ElementKeywords(self),
            FormElementKeywords(self),
            FrameKeywords(self),
            JavaScriptKeywords(self),
            RunOnFailureKeywords(self),
            ScreenshotKeywords(self),
            SelectElementKeywords(self),
            TableElementKeywords(self),
            WaitingKeywords(self),
            WindowKeywords(self)
        ]
        if is_truthy(plugins):
            plugin_libs = self._parse_plugins(plugins)
            libraries = libraries + plugin_libs
        self._drivers = WebDriverCache()
        DynamicCore.__init__(self, libraries)
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()
        if is_truthy(event_firing_webdriver):
            self.event_firing_webdriver = self._parse_listener(
                event_firing_webdriver)
        else:
            self.event_firing_webdriver = None
        self._running_keyword = None
Esempio n. 6
0
 def __init__(self,
              timeout=5.0,
              implicit_wait=0.0,
              run_on_failure='Capture Page Screenshot',
              screenshot_root_directory=None):
     self.timeout = timestr_to_secs(timeout)
     self.implicit_wait = timestr_to_secs(implicit_wait)
     self.speed = 0.0
     self.run_on_failure_keyword \
         = RunOnFailureKeywords.resolve_keyword(run_on_failure)
     self._running_on_failure_keyword = False
     self.screenshot_root_directory = screenshot_root_directory
     libraries = [
         AlertKeywords(self),
         BrowserManagementKeywords(self),
         CookieKeywords(self),
         ElementKeywords(self),
         FormElementKeywords(self),
         FrameKeywords(self),
         JavaScriptKeywords(self),
         RunOnFailureKeywords(self),
         ScreenshotKeywords(self),
         SelectElementKeywords(self),
         TableElementKeywords(self),
         WaitingKeywords(self),
         WindowKeywords(self),
         KeyboardKeywords(self)
     ]
     self._drivers = WebDriverCache()
     DynamicCore.__init__(self, libraries)
     self.ROBOT_LIBRARY_LISTENER = LibraryListener()
     self._element_finder = ElementFinder(self)
Esempio n. 7
0
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None):
        """SeleniumLibrary can be imported with optional arguments.

        `timeout` is the default timeout used to wait for all waiting actions.
        It can be later set with `Set Selenium Timeout`.

        'implicit_wait' is the implicit timeout that Selenium waits when
        looking for elements.
        It can be later set with `Set Selenium Implicit Wait`.
        See `WebDriver: Advanced Usage`__ section of the SeleniumHQ documentation
        for more information about WebDriver's implicit wait functionality.

        __ http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-and-implicit-waits

        `run_on_failure` specifies the name of a keyword (from any available
        libraries) to execute when a SeleniumLibrary keyword fails. By default
        `Capture Page Screenshot` will be used to take a screenshot of the current page.
        Using the value "Nothing" will disable this feature altogether. See
        `Register Keyword To Run On Failure` keyword for more information about this
        functionality.

        `screenshot_root_directory` specifies the default root directory that screenshots should be
        stored in. If not provided the default directory will be where robotframework places its logfile.

        Examples:
        | Library `|` SeleniumLibrary `|` 15                                            | # Sets default timeout to 15 seconds                                       |
        | Library `|` SeleniumLibrary `|` 0 `|` 5                                       | # Sets default timeout to 0 seconds and default implicit_wait to 5 seconds |
        | Library `|` SeleniumLibrary `|` 5 `|` run_on_failure=Log Source               | # Sets default timeout to 5 seconds and runs `Log Source` on failure       |
        | Library `|` SeleniumLibrary `|` implicit_wait=5 `|` run_on_failure=Log Source | # Sets default implicit_wait to 5 seconds and runs `Log Source` on failure |
        | Library `|` SeleniumLibrary `|` timeout=10      `|` run_on_failure=Nothing    | # Sets default timeout to 10 seconds and does nothing on failure           |
        """
        self.timeout = timestr_to_secs(timeout)
        self.implicit_wait = timestr_to_secs(implicit_wait)
        self.speed = 0.0
        self.run_on_failure_keyword \
            = RunOnFailureKeywords.resolve_keyword(run_on_failure)
        self._running_on_failure_keyword = False
        self.screenshot_root_directory = screenshot_root_directory
        libraries = [
            AlertKeywords(self),
            BrowserManagementKeywords(self),
            RunOnFailureKeywords(self),
            ElementKeywords(self),
            TableElementKeywords(self),
            FormElementKeywords(self),
            SelectElementKeywords(self),
            JavaScriptKeywords(self),
            CookieKeywords(self),
            ScreenshotKeywords(self),
            WaitingKeywords(self)
        ]
        self._browsers = BrowserCache()
        DynamicCore.__init__(self, libraries)
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()
        self.element_finder = ElementFinder(self)
        self._table_element_finder = TableElementFinder(self)
Esempio n. 8
0
    def get_web_element_position(self, locator=None, expected=None):
        web_element_manager = ElementKeywords(self)
        elements = web_element_manager.get_webelements(locator)
        text = ""
        count = 1
        for elem in elements:
            if expected in elem.text:
                web_element_manager.info(
                    "Element '%s' at position '%d' contains text '%s'." %
                    (locator, count, expected))
                return count
            count += 1
            text += elem.text + '\n'

        message = "Element '%s' should have contained text '%s' but " \
                  "its text was '%s'." % (locator, expected, text)
        raise AssertionError(message)
Esempio n. 9
0
class ElementKeywords(LibraryComponent):
    def __init__(self, ctx):
        LibraryComponent.__init__(self, ctx)
        self.SEKeywords = SeleniumElementKeywords(ctx)
        self.waiting_management = WaitingKeywords(ctx)

    @keyword
    def clear_textfield_value(self, locator):
        text = self.SEKeywords.get_value(locator)
        i = 0
        while i < len(text):
            i += 1
            self.SEKeywords.press_key(locator, Keys.BACK_SPACE)
            self.SEKeywords.press_key(locator, Keys.DELETE)

    @keyword
    def find_child_element_by_tag_and_attribute(self, element, tag,
                                                attribute_name,
                                                attribute_value):
        child_elements = element.find_elements_by_tag_name(tag)
        for child in child_elements:
            if child.get_attribute(attribute_name).strip() == attribute_value:
                return ExtWebElement(child)
        message = "Child element '%s = %s' not found!" % (attribute_name,
                                                          attribute_value)
        raise AssertionError(message)

    @keyword
    def find_element_by_attribute(self, attribute, value, tag='*'):
        # return self.find_elements_by_attribute(attribute, value, tag)[0]
        e = self.find_elements_by_attribute(attribute, value, tag)[0]
        print(e)
        return e

    @keyword
    def find_elements_by_attribute(self, attribute, value, tag='*'):
        return [
            ExtWebElement(e)
            for e in self.SEKeywords.find_elements("//" + tag + "[@" +
                                                   attribute + "='" + value +
                                                   "']")
        ]

    def is_any_element_contain_class(self, class_name, element=None):
        try:
            self.find_element_by_class(class_name, element)
            return True
        except:
            return False

    def find_element_by_class(self, class_name, element=None):
        return ExtWebElement(
            self.find_element("//*[contains(@class, '" + class_name + "')]",
                              None, None, element))

    def find_element_by_href(self, value):
        return ExtWebElement(
            self.find_element_by_attribute("href", value, tag='a'))
Esempio n. 10
0
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None,
                 demo=False):
        """SeleniumLibrary can be imported with several optional arguments.

        - ``timeout``:
          Default value for `timeouts` used with ``Wait ...`` keywords.
        - ``implicit_wait``:
          Default value for `implicit wait` used when locating elements.
        - ``run_on_failure``:
          Default action for the `run-on-failure functionality`.
        - ``screenshot_root_directory``:
          Location where possible screenshots are created. If not given,
          the directory where the log file is written is used.
        - ``Demo``
          Flash the element before click, input and etc actions. Set value
          True if you want it.
        """
        self.timeout = timestr_to_secs(timeout)
        self.implicit_wait = timestr_to_secs(implicit_wait)
        self.speed = 0.0
        self.run_on_failure_keyword \
            = RunOnFailureKeywords.resolve_keyword(run_on_failure)
        self._running_on_failure_keyword = False
        self.screenshot_root_directory = screenshot_root_directory
        self.demo = demo
        libraries = [
            AlertKeywords(self),
            BrowserManagementKeywords(self),
            CookieKeywords(self),
            ElementKeywords(self),
            FormElementKeywords(self),
            FrameKeywords(self),
            JavaScriptKeywords(self),
            RunOnFailureKeywords(self),
            ScreenshotKeywords(self),
            SelectElementKeywords(self),
            TableElementKeywords(self),
            WaitingKeywords(self),
            WindowKeywords(self)
        ]
        self._drivers = WebDriverCache()
        DynamicCore.__init__(self, libraries)
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()
        self._element_finder = ElementFinder(self)
Esempio n. 11
0
 def setUpClass(cls):
     cls.ctx = mock()
     cls.element = ElementKeywords(cls.ctx)
Esempio n. 12
0
 def click_element(self, locator):
     locator = self.find_element(locator)
     return ElementKeywords(self).click_element(locator=locator)
Esempio n. 13
0
import os
from SeleniumLibrary import SeleniumLibrary
from SeleniumLibrary.keywords import (
    AlertKeywords, BrowserManagementKeywords, CookieKeywords, ElementKeywords,
    FormElementKeywords, FrameKeywords, JavaScriptKeywords,
    RunOnFailureKeywords, ScreenshotKeywords, SelectElementKeywords,
    TableElementKeywords, WaitingKeywords, WebDriverCache, WindowKeywords)
from robot.libraries.OperatingSystem import OperatingSystem

root = os.path.dirname(os.path.abspath(__file__)) + "\\.."
SL = SeleniumLibrary()
OS = OperatingSystem()

browserManagementKeywords = BrowserManagementKeywords(SL)
cookieKeywords = CookieKeywords(SL)
frameKeywords = FrameKeywords(SL)
javaScriptKeywords = JavaScriptKeywords(SL)
screenshotKeywords = ScreenshotKeywords(SL)
elementKeywords = ElementKeywords(SL)
formElementKeywords = FormElementKeywords(SL)
waitingKeywords = WaitingKeywords(SL)
windowKeywords = WindowKeywords(SL)
selectElementKeywords = SelectElementKeywords(SL)
tableElementKeywords = TableElementKeywords(SL)
Esempio n. 14
0
class KeywordArgumentsElementTest(unittest.TestCase):
    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_element_should_contain(self):
        locator = '//div'
        actual = 'bar'
        expected = 'foo'
        when(self.element)._get_text(locator).thenReturn(actual)
        message = ("Element '%s' should have contained text '%s' but "
                   "its text was '%s'." % (locator, expected, actual))
        with self.assertRaises(AssertionError) as error:
            self.element.element_should_contain('//div', expected)
            self.assertEqual(str(error), message)

        with self.assertRaises(AssertionError) as error:
            self.element.element_should_contain('//div', expected, 'foobar')
            self.assertEqual(str(error), 'foobar')

    def test_element_should_not_contain(self):
        locator = '//div'
        actual = 'bar'
        when(self.element)._get_text(locator).thenReturn(actual)
        message = ("Element '%s' should not contain text '%s' but "
                   "it did." % (locator, actual))
        with self.assertRaises(AssertionError) as error:
            self.element.element_should_not_contain('//div', actual)
            self.assertEqual(str(error), message)

        with self.assertRaises(AssertionError) as error:
            self.element.element_should_not_contain('//div', actual, 'foobar')
            self.assertEqual(str(error), 'foobar')

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_element(locator,
                                        required=False,
                                        first_only=False).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_should_be_visible(self):
        locator = '//div'
        when(self.element).is_visible(locator).thenReturn(None)
        with self.assertRaisesRegexp(AssertionError, 'should be visible'):
            self.element.element_should_be_visible(locator)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_should_be_visible(locator, 'foobar')

    def test_element_should_not_be_visible(self):
        locator = '//div'
        when(self.element).is_visible(locator).thenReturn(True)
        with self.assertRaisesRegexp(AssertionError, 'should not be visible'):
            self.element.element_should_not_be_visible(locator)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_should_not_be_visible(locator, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')

    def test_get_element_attribute(self):
        locator = '//div'
        attrib = 'id'
        element = mock()
        when(self.element).find_element(locator,
                                        required=False).thenReturn(element)
        when(element).get_attribute(attrib).thenReturn('value')
        value = self.element.get_element_attribute(locator, attrib)
        self.assertEqual(value, 'value')

        locator = '//div@id'
        value = self.element.get_element_attribute(locator, 'None')
        self.assertEqual(value, 'value')

    def test_get_matching_xpath_count(self):
        locator = '//div'
        when(self.element).find_element('xpath={}'.format(locator),
                                        first_only=False,
                                        required=False).thenReturn([])
        count = self.element.get_matching_xpath_count(locator)
        self.assertEqual(count, '0')
        count = self.element.get_matching_xpath_count(locator, 'True')
        self.assertEqual(count, '0')

        count = self.element.get_matching_xpath_count(locator, 'False')
        self.assertEqual(count, 0)

    def test_xpath_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_element('xpath={}'.format(locator),
                                        first_only=False,
                                        required=False).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.xpath_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.xpath_should_match_x_times(locator, 1, 'foobar')
class KeywordArgumentsElementTest(unittest.TestCase):

    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_element_should_contain(self):
        locator = '//div'
        actual = 'bar'
        expected = 'foo'
        when(self.element)._get_text(locator).thenReturn(actual)
        message = ("Element '%s' should have contained text '%s' but "
                   "its text was '%s'." % (locator, expected, actual))
        with self.assertRaises(AssertionError) as error:
            self.element.element_should_contain('//div', expected)
            self.assertEqual(str(error), message)

        with self.assertRaises(AssertionError) as error:
            self.element.element_should_contain('//div', expected, 'foobar')
            self.assertEqual(str(error), 'foobar')

    def test_element_should_not_contain(self):
        locator = '//div'
        actual = 'bar'
        when(self.element)._get_text(locator).thenReturn(actual)
        message = ("Element '%s' should not contain text '%s' but "
                   "it did." % (locator, actual))
        with self.assertRaises(AssertionError) as error:
            self.element.element_should_not_contain('//div', actual)
            self.assertEqual(str(error), message)

        with self.assertRaises(AssertionError) as error:
            self.element.element_should_not_contain('//div', actual, 'foobar')
            self.assertEqual(str(error), 'foobar')

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_element(locator, required=False,
                                        first_only=False).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_should_be_visible(self):
        locator = '//div'
        when(self.element).is_visible(locator).thenReturn(None)
        with self.assertRaisesRegexp(AssertionError, 'should be visible'):
            self.element.element_should_be_visible(locator)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_should_be_visible(locator, 'foobar')

    def test_element_should_not_be_visible(self):
        locator = '//div'
        when(self.element).is_visible(locator).thenReturn(True)
        with self.assertRaisesRegexp(AssertionError, 'should not be visible'):
            self.element.element_should_not_be_visible(locator)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_should_not_be_visible(locator, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')

    def test_get_element_attribute(self):
        locator = '//div'
        attrib = 'id'
        element = mock()
        when(self.element).find_element(locator,
                                        required=False).thenReturn(element)
        when(element).get_attribute(attrib).thenReturn('value')
        value = self.element.get_element_attribute(locator, attrib)
        self.assertEqual(value, 'value')

        locator = '//div@id'
        value = self.element.get_element_attribute(locator, 'None')
        self.assertEqual(value, 'value')

    def test_get_matching_xpath_count(self):
        locator = '//div'
        when(self.element).find_element(
            'xpath={}'.format(locator), first_only=False,
            required=False).thenReturn([])
        count = self.element.get_matching_xpath_count(locator)
        self.assertEqual(count, '0')
        count = self.element.get_matching_xpath_count(locator, 'True')
        self.assertEqual(count, '0')

        count = self.element.get_matching_xpath_count(locator, 'False')
        self.assertEqual(count, 0)

    def test_xpath_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_element(
            'xpath={}'.format(locator), first_only=False,
            required=False).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.xpath_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.xpath_should_match_x_times(locator, 1, 'foobar')
 def __init__(self, ctx):
     LibraryComponent.__init__(self, ctx)
     self.element_management = SeleniumElementKeywords(ctx)
     self.formelement_management = FormElementKeywords(ctx)
     self.waiting_management = WaitingKeywords(ctx)
Esempio n. 17
0
def element():
    ctx = mock()
    return ElementKeywords(ctx)
 def setUp(self):
     ctx = mock()
     ctx._browser = mock()
     self.element = ElementKeywords(ctx)
class ElementKeywords(LibraryComponent):
    def __init__(self, ctx):
        LibraryComponent.__init__(self, ctx)
        self.element_management = SeleniumElementKeywords(ctx)
        self.formelement_management = FormElementKeywords(ctx)
        self.waiting_management = WaitingKeywords(ctx)

    @keyword
    def clear_textfield_value(self, locator):
        text = self.element_management.get_value(locator)
        i = 0
        while i < len(text):
            i += 1
            self.element_management.press_key(locator, Keys.BACK_SPACE)
            self.element_management.press_key(locator, Keys.DELETE)

    @keyword
    def scroll_to_element(self, locator):
        self.waiting_management.wait_until_element_is_visible(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();",
                                   self.find_element(locator))

    @keyword
    def scroll_to_top(self, webelement):
        js = "arguments[0].scrollTo(0,-2*arguments[0].scrollHeight);"
        self.driver.execute_script(js, webelement)

    @keyword
    def scroll_to_bottom(self, webelement):
        js = "arguments[0].scrollTo(0,2*arguments[0].scrollHeight);"
        self.driver.execute_script(js, webelement)

    @keyword
    def special_click_element(self, locator):
        try:
            element = self.find_element(locator)
            element.remove_hidden_attribute()
            element.js_click()
        except:
            raise AssertionError("Failed to click element")
            return

    @keyword
    def my_click(self, locator):
        self.find_element(locator).click()

    @keyword
    def set_toggle_button_value(self, element_locator, value):
        element = self.find_element(element_locator)
        current_status = element.get_attribute('className')
        if current_status != value:
            element.js_click()
            return
        return "Failed to set toggle button value"

    @keyword
    def get_toggle_button_value(self, element_locator):
        element = self.find_element(element_locator)
        current_status = element.get_attribute('className')
        if current_status == "toggle active":
            return "True"
        return "False"

    @keyword
    def click_hidden_element(self, locator):
        try:
            if not self._is_element(locator):
                if "auto-tag" in locator:
                    element = self.get_element_by_auto_tag(locator)
                else:
                    element = self.find_element(locator)
            element.remove_hidden_attribute()
            element.js_click()
        except:
            message = "Failed to click on hidden element %s" % locator
            raise AssertionError(message)

    @keyword
    def input_text(self, locator, text):
        self.scroll_to_element(locator)
        # self.clear_textfield_value(locator)
        self.formelement_management.input_text(locator, text)

    @keyword
    def input_password(self, locator, password):
        self.scroll_to_element(locator)
        self.formelement_management.input_password(locator, password)

    @keyword
    def get_elements_by_attribute(self, attribute):
        """
        Get element that has attribute with value
        :param attribute: <attribute_name>=<attribute_value>
        :return: list of found elements
        """
        attribute_name = attribute.split('=')[0]
        attribute_value = attribute.split('=')[1].replace('"', '')
        return self.driver.find_elements_by_xpath("//*[@" + attribute_name +
                                                  "='" + attribute_value +
                                                  "']")

    @keyword
    def get_element_by_attribute(self, attribute):
        elements = self.get_elements_by_attribute(attribute)
        return elements[0] if len(elements) > 0 else elements

    @keyword
    def get_element_by_auto_tag(self, auto_tag):
        return self.get_element_by_attribute(auto_tag)

    @keyword
    def get_elements_by_auto_tag(self, auto_tag):
        return self.get_elements_by_attribute(auto_tag)

    @keyword
    def get_elements_by_tag(self, locator, tag):
        try:
            elements = self.find_elements(locator)
            if len(elements) == 1:
                if elements[0].get_property("tagName") == tag.upper():
                    return elements
                else:
                    return elements[0].find_elements_by_tag_name(tag)
            else:
                return [
                    e for e in elements
                    if e.get_property("tagName") == tag.upper()
                ]
        except:
            message = "Cannot get element(s) by tag '%s' with locator '%s'" % (
                tag, locator)
            raise AssertionError(message)

    @keyword
    def find_element_contains_class(self, class_name):
        class_list = class_name.split(' ')
        elements = self.driver.find_elements_by_class_name(class_list[0])
        for element in elements:
            actual_class_list = element.get_attribute("class").split(' ')
            if Utilities().is_sublist(actual_class_list, class_list[1:]):
                return element
        message = "Not found any element has '%s'" % class_name
        raise AssertionError(message)

    @keyword
    def wait_until_element_has_class(self,
                                     element,
                                     class_name,
                                     timeout=5,
                                     error=None):
        """
        Wait until element contain class name
        :param element: element
        :param class_name: class name to expect element will has
        :param timeout: timeout in second
        :param error: error message
        :return: None
        """
        self.waiting_management._wait_until(
            lambda: class_name in element.get_attribute("class"),
            "Element '%s' has no class name '%s' in <TIMEOUT>" %
            (element, class_name), timeout, error)

    @keyword
    def wait_until_element_has_number_child(self,
                                            element,
                                            class_name,
                                            children_num=1,
                                            timeout=5,
                                            error=None):
        """
        Wait until the element has number of children as expected
        :param element: parent element
        :param class_name: class name of child element
        :param children_num: expected number of children need to wait for
        :param timeout: timeout in second
        :param error: error message
        :return: None
        """
        self.waiting_management._wait_until(
            lambda: len(element.find_elements_by_class_name(class_name)
                        ) == children_num,
            "Element '%s' has more than one child '%s' in <TIMEOUT>" %
            (element, class_name), timeout, error)

    def _is_element(self, item):
        return isinstance(item, WebElement)

    @keyword
    def get_element_contains_text_in_list(self, elements, text):
        """
        Get the element from the list which has input text
        :param elements: list of elements
        :param text: text of finding element
        :return: the element which has input text
        """
        for element in elements:
            actual = element.get_textContent()
            if str(text).strip() == actual:
                return element
        message = "Not found %s in list!" % text
        raise AssertionError(message)

    @keyword
    def select_item_in_list(self, elements, value):
        try:
            element = self.get_element_contains_text_in_list(elements, value)
            element.js_click()
        except:
            message = "Failed to select item %s in list!" % value
            raise AssertionError(message)

    @keyword
    def get_element_text(self, locator):
        text = self.find_element(locator)
        result = text.get_attribute("textContent")
        return result

    @keyword
    def set_special_list_value(self, locator, value):
        list_value = self.find_element(locator)
        values = list_value.find_elements_by_tag_name('span')
        for val in values:
            if val.get_textContent() == value:
                val.click()
                return
        mess = "Not Found By %s" % value
        raise AssertionError(mess)

    @keyword
    def compare_special_element_text(self, locator, value):
        element = self.find_element(locator)
        props = element.get_attribute("textContent")
        if value == props:
            return True
        else:
            mess = ("The text of element '%s' should have been '%s' "
                    "but it was '%s'." % (locator, value, props))
            raise AssertionError(mess)

    @keyword
    def is_disabled(self, locator):
        element = self.find_element(locator)
        props = element.get_attribute("disabled")
        if props == 'true':
            return True
        mess = "Element still is enabled"
        raise AssertionError(mess)

    @keyword
    def wait_until_element_is_disabled(self, locator, timeout=30, error=None):
        self.waiting_management._wait_until(
            lambda: self.is_disabled(locator),
            "Element '%s' still in enable over <TIMEOUT>." % locator, timeout,
            error)

    @keyword
    def text_field_is_disabled(self, locator):
        element = self.find_element(locator)
        props = element.get_attribute("readonly")
        if props == "true":
            return True
        mess = "Text field %s is enabled" % locator
        raise AssertionError(mess)

    @keyword
    def wait_until_text_field_is_disabled(self,
                                          locator,
                                          timeout=30,
                                          error=None):
        self.waiting_management._wait_until(
            lambda: self.text_field_is_disabled(locator),
            "Element '%s' still in enable over <TIMEOUT>." % locator, timeout,
            error)

    @keyword
    def get_length_selectbox(self, locator):
        element = self.find_element(locator)
        props = element.find_elements_by_tag_name('option')
        return len(props)
def element():
    ctx = mock()
    ctx._browser = mock()
    return ElementKeywords(ctx)
Esempio n. 21
0
class KeywordArgumentsElementTest(unittest.TestCase):
    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(locator).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')
        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')

    def test_get_matching_xpath_count(self):
        locator = '//div'
        when(self.element).find_elements('xpath:' + locator).thenReturn([])
        count = self.element.get_matching_xpath_count(locator)
        self.assertEqual(count, '0')
        count = self.element.get_matching_xpath_count(locator, 'True')
        self.assertEqual(count, '0')

        count = self.element.get_matching_xpath_count(locator, 'False')
        self.assertEqual(count, 0)

    def test_xpath_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(
            'xpath:{}'.format(locator)).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.xpath_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.xpath_should_match_x_times(locator, 1, 'foobar')
Esempio n. 22
0
 def setUpClass(cls):
     cls.element_keywords = ElementKeywords(None)
Esempio n. 23
0
 def __init__(self, ctx):
     LibraryComponent.__init__(self, ctx)
     self.element_management = SeleniumElementKeywords(ctx)
Esempio n. 24
0
class KeywordArgumentsElementTest(unittest.TestCase):
    def setUp(self):
        ctx = mock()
        ctx._browser = mock()
        self.element = ElementKeywords(ctx)

    def tearDown(self):
        unstub()

    def test_locator_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(locator).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.locator_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.locator_should_match_x_times(locator, 1, 'foobar')

    def test_element_text_should_be(self):
        locator = '//div'
        element = mock()
        element.text = 'text'
        when(self.element).find_element(locator).thenReturn(element)
        with self.assertRaisesRegexp(AssertionError, 'should have been'):
            self.element.element_text_should_be(locator, 'not text')
        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.element_text_should_be(locator, 'not text', 'foobar')

    def test_get_element_attribute(self):
        locator = '//div'
        attrib = 'id'
        element = mock()
        when(self.element).find_element(locator).thenReturn(element)
        when(element).get_attribute(attrib).thenReturn('value')
        value = self.element.get_element_attribute(locator, attrib)
        self.assertEqual(value, 'value')

        when(logger).warn(
            "Using 'Get Element Attribute' without explicit "
            "attribute is deprecated.", False).thenReturn(None)
        value = self.element.get_element_attribute('//div@id', 'None')
        self.assertEqual(value, 'value')

    def test_get_matching_xpath_count(self):
        locator = '//div'
        when(self.element).find_elements('xpath:' + locator).thenReturn([])
        count = self.element.get_matching_xpath_count(locator)
        self.assertEqual(count, '0')
        count = self.element.get_matching_xpath_count(locator, 'True')
        self.assertEqual(count, '0')

        count = self.element.get_matching_xpath_count(locator, 'False')
        self.assertEqual(count, 0)

    def test_xpath_should_match_x_times(self):
        locator = '//div'
        when(self.element).find_elements(
            'xpath:{}'.format(locator)).thenReturn([])
        with self.assertRaisesRegexp(AssertionError, 'should have matched'):
            self.element.xpath_should_match_x_times(locator, 1)

        with self.assertRaisesRegexp(AssertionError, 'foobar'):
            self.element.xpath_should_match_x_times(locator, 1, 'foobar')
Esempio n. 25
0
 def setUp(self):
     ctx = mock()
     ctx._browser = mock()
     self.element = ElementKeywords(ctx)
Esempio n. 26
0
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None,
                 plugins=None):
        """SeleniumLibrary can be imported with several optional arguments.

        - ``timeout``:
          Default value for `timeouts` used with ``Wait ...`` keywords.
        - ``implicit_wait``:
          Default value for `implicit wait` used when locating elements.
        - ``run_on_failure``:
          Default action for the `run-on-failure functionality`.
        - ``screenshot_root_directory``:
          Location where possible screenshots are created. If not given,
          the directory where the log file is written is used.
        - ``plugins``:
          Allows extending the SeleniumLibrary with external Python classes.
        """
        self.timeout = timestr_to_secs(timeout)
        self.implicit_wait = timestr_to_secs(implicit_wait)
        self.speed = 0.0
        self.run_on_failure_keyword \
            = RunOnFailureKeywords.resolve_keyword(run_on_failure)
        self._running_on_failure_keyword = False
        self.screenshot_root_directory = screenshot_root_directory
        self._element_finder = ElementFinder(self)
        self._plugin_keywords = []
        libraries = [
            AlertKeywords(self),
            BrowserManagementKeywords(self),
            CookieKeywords(self),
            ElementKeywords(self),
            FormElementKeywords(self),
            FrameKeywords(self),
            JavaScriptKeywords(self),
            RunOnFailureKeywords(self),
            ScreenshotKeywords(self),
            SelectElementKeywords(self),
            TableElementKeywords(self),
            WaitingKeywords(self),
            WindowKeywords(self)
        ]
        if is_truthy(plugins):
            parsed_plugins = self._string_to_modules(plugins)
            for index, plugin in enumerate(
                    self._import_modules(parsed_plugins)):
                if not isclass(plugin):
                    message = "Importing test library: '%s' failed." % parsed_plugins[
                        index].plugin
                    raise DataError(message)
                plugin = plugin(self, *parsed_plugins[index].args,
                                **parsed_plugins[index].kw_args)
                if not isinstance(plugin, LibraryComponent):
                    message = 'Plugin does not inherit SeleniumLibrary.base.LibraryComponent'
                    raise PluginError(message)
                self._store_plugin_keywords(plugin)
                libraries.append(plugin)
        self._drivers = WebDriverCache()
        DynamicCore.__init__(self, libraries)
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()