def test_selenium_implicit_wait_get():
    sl = SeleniumLibrary(implicit_wait='3')
    assert sl.get_selenium_implicit_wait() == '3 seconds'

    org_value = sl.set_selenium_implicit_wait('1 min')
    assert sl.get_selenium_implicit_wait() == '1 minute'
    assert org_value == '3 seconds'
    def test_tags_in_plugin(self):
        sl = SeleniumLibrary(plugins=self.plugin)
        tags = sl.get_keyword_tags("foo")
        self.assertEqual(tags, ["plugin"])

        tags = sl.get_keyword_tags("open_browser")
        self.assertFalse(tags)
Пример #3
0
    def __init__(self, *args, **kwargs) -> None:
        self.logger = logging.getLogger(__name__)

        self.using_testability = False
        if "use_testability" in args:
            self.using_testability = True
            args = filter(lambda x: x != "use_testability", args)
        if "plugins" in kwargs.keys(
        ) and "SeleniumTestability" in kwargs["plugins"]:
            # SeleniumTestability already included as plugin
            self.using_testability = True
        elif self.using_testability and "plugins" in kwargs.keys():
            # Adding SeleniumTestability as SeleniumLibrary plugin
            kwargs["plugins"] += ",SeleniumTestability"
        elif self.using_testability:
            # Setting SeleniumTestability as SeleniumLibrary plugin
            kwargs["plugins"] = "SeleniumTestability"

        locators_path = kwargs.pop("locators_path", locators.DEFAULT_DATABASE)

        SeleniumLibrary.__init__(self, *args, **kwargs)
        self.drivers = []
        self.locators = locators.LocatorsDatabase(locators_path)
        self._element_finder.register("alias",
                                      self._find_by_alias,
                                      persist=True)
Пример #4
0
    def test_tags_in_plugin(self):
        sl = SeleniumLibrary(plugins=self.plugin)
        tags = sl.get_keyword_tags('foo')
        self.assertEqual(tags, ['plugin'])

        tags = sl.get_keyword_tags('open_browser')
        self.assertFalse(tags)
Пример #5
0
def test_selenium_implicit_wait_get():
    sl = SeleniumLibrary(implicit_wait="3")
    assert sl.get_selenium_implicit_wait() == "3 seconds"

    org_value = sl.set_selenium_implicit_wait("1 min")
    assert sl.get_selenium_implicit_wait() == "1 minute"
    assert org_value == "3 seconds"
class TestGetBrowser(unittest.TestCase):

    def setUp(self):
        self.lib = SeleniumLibrary()

    def test_ie_aliases(self):
        for alias in ['ie', 'IE', 'Internet Explorer', 'INTernETexplOrEr']:
            self.assertEquals(self.lib._get_browser(alias), '*iexplore')

    def test_firefox_aliases(self):
        for alias in ['ff', 'FF', 'firefox', 'FireFox']:
            self.assertEquals(self.lib._get_browser(alias), '*firefox')

    def test_non_alias_is_not_modified(self):
        for non_alias in [
                'FIREFUX',
                'i e 8',
                'C:\\Program Files\\mybrowser\\brow.exe',
                '{"username": "******", "access-key": "7A9cea40-84f7-4d3b-8748-0e94fCd4dX4f"}']:
            self.assertEquals(self.lib._get_browser(non_alias), non_alias)

    def test_patched_remote_control(self):
        rc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'src',
                               'SeleniumLibrary', 'selenium.py')
        self.assertTrue('conn.close()' in open(rc_path).read())
Пример #7
0
 def __init__(self):
     SeleniumLibrary.__init__(self, 30)
     self.add_library_components([
         BrowserKeywords(self),
         ElementKeywords(self),
         MyCustomizedLibraryKeywords(self)
     ])
Пример #8
0
    def __init__(self,
                 screenshot_root_directory='logs',
                 remote_url=ST.REMOTE_URL,
                 browser=ST.BROWSER,
                 headless=False,
                 alias=None,
                 device=None,
                 executable_path=None,
                 options=None,
                 service_args=None,
                 desired_capabilities=None):
        """
        启动浏览器类型可选: Firefox, Chrome, Ie, Opera, Safari, PhantomJS, 可模拟移动设备
        """
        if browser not in [
                'Firefox', 'Chrome', 'Ie', 'Opera', 'Safari', 'PhantomJS'
        ]:
            raise Exception(
                '浏览器类型不对, 仅可选: Firefox, Chrome, Ie, Opera, Safari, PhantomJS')
        self.remote_url = remote_url
        self.browser = browser
        self.headless = headless
        self.alias = alias
        self.device = device
        self.executable_path = executable_path
        self.options = options
        self.service_args = service_args
        self.desired_capabilities = desired_capabilities

        self.ctx = SeleniumLibrary(
            screenshot_root_directory=screenshot_root_directory)
        self.screenshot_directory = ST.LOG_DIR = self.ctx.screenshot_root_directory
        super(AirSelenium, self).__init__(self.ctx)
Пример #9
0
    def __init__(self, *args, **kwargs) -> None:
        locators_path = kwargs.pop("locators_path",
                                   locators.default_locators_path())

        # Parse user-given plugins
        plugins = kwargs.get("plugins", "")
        plugins = set(p for p in plugins.split(",") if p)

        # Add testability if requested
        if "use_testability" in args:
            args = [arg for arg in args if arg != "use_testability"]
            plugins.add("SeleniumTestability")

        # Refresh plugins list
        kwargs["plugins"] = ",".join(plugins)

        SeleniumLibrary.__init__(self, *args, **kwargs)
        self.logger = logging.getLogger(__name__)
        self.using_testability = bool("SeleniumTestability" in plugins)

        # Add support for locator aliases
        self.locators = locators.LocatorsDatabase(locators_path)
        self._element_finder.register("alias",
                                      self._find_by_alias,
                                      persist=True)

        self._embedding_screenshots = False
        self._previous_screenshot_directory = None
        # Embed screenshots in logs by default
        if not notebook.IPYTHON_AVAILABLE:
            self._embedding_screenshots = True
            self._previous_screenshot_directory = self.set_screenshot_directory(
                EMBED)
Пример #10
0
    def test_selenium_implicit_wait_get(self):
        sl = SeleniumLibrary(implicit_wait='3')
        self.assertEqual(sl.get_selenium_implicit_wait(), '3 seconds')

        org_value = sl.set_selenium_implicit_wait('1 min')
        self.assertEqual(sl.get_selenium_implicit_wait(), '1 minute')
        self.assertEqual(org_value, '3 seconds')
    def test_tags_in_plugin(self):
        sl = SeleniumLibrary(plugins=self.plugin)
        tags = sl.get_keyword_tags('foo')
        self.assertEqual(tags, ['plugin'])

        tags = sl.get_keyword_tags('open_browser')
        self.assertFalse(tags)
Пример #12
0
 def __init__(self):
     SeleniumLibrary.__init__(self, 30)
     self.add_library_components([
         BrowserKeywords(self),
         ElementKeywords(self),
         GoBearCoreKeywords(self)
     ])
    def test_set_selenium_implicit_wait(self):
        sl = SeleniumLibrary()
        sl.set_selenium_implicit_wait('5.0')
        self.assertEqual(sl.implicit_wait, 5.0)

        sl.set_selenium_implicit_wait('1 min')
        self.assertEqual(sl.implicit_wait, 60.0)
    def test_selenium_implicit_wait_get(self):
        sl = SeleniumLibrary(implicit_wait='3')
        self.assertEqual(sl.get_selenium_implicit_wait(), '3 seconds')

        org_value = sl.set_selenium_implicit_wait('1 min')
        self.assertEqual(sl.get_selenium_implicit_wait(), '1 minute')
        self.assertEqual(org_value, '3 seconds')
Пример #15
0
    def __init__(self, timeout=60, host=DEFAULT_HOST, port=DEFAULT_PORT, plugin_dir=""):
        """Load the wbSelenium library with arguments for Robot's
        SeleniumLibrary and selenium-server.

        Classes defined in python files are searched in the base directory
        and plugin directory. This class inherits from SeleniumLibrary and
        also all other classes specified in the plugin and base
        directories. Dynamic inheritance is implemented using the
        Class.__bases__ += method which means all external classes must be
        new style (inherit from object). """
        SeleniumLibrary.__init__(self, timeout, host, port)
        # use plugin dir if specified, otherwise just load WikiBhasha base
        extension_paths = [wbSelenium.BASE_DIR] + (plugin_dir and [os.path.abspath(plugin_dir)] or [])
        # get list of all of the javascript files and flatten list
        js_files = sum([self._get_ext_js(path) for path in extension_paths], [])
        self._user_ext_file = js_files and TempJSExtensionFile() or None
        def process_curry(file):
            self._process_js_ext(file, self._user_ext_file)
        map(process_curry, js_files)
        # inherit from other extensions (must take a flat tuple)
        ext_classes = tuple(sum([self._get_ext_classes(path) for path in extension_paths], []))
        # plugins override SeleniumLibrary in MRO
        wbSelenium.__bases__ = ext_classes + wbSelenium.__bases__ 
        for klass in ext_classes:
            log("wbSelenium imported class: " + klass.__name__)
            #super(klass, self).__init__()
            klass.__init__(self)
Пример #16
0
    def test_plugin_does_not_exist(self):
        not_here = os.path.join(self.root_dir, 'not_here.py')
        with self.assertRaises(DataError):
            SeleniumLibrary(plugins=not_here)

        with self.assertRaises(DataError):
            SeleniumLibrary(plugins='SeleniumLibrary.NotHere')
Пример #17
0
 def __init__(self, timeout=5.0, implicit_wait=0.0,
              run_on_failure='Capture Page Screenshot',
              screenshot_root_directory=None):
     SeleniumLibrary.__init__(self, timeout=timeout, implicit_wait=implicit_wait,
                              run_on_failure=run_on_failure,
                              screenshot_root_directory=screenshot_root_directory)
     self.add_library_components([BrowserKeywords(self),
                                  DesiredCapabilitiesKeywords(self)])
Пример #18
0
 def shut_down_selenium_server(self):
     """Stop the previously started selenium-server and clean up any
     temporary files that were created."""
     try: SeleniumLibrary.shut_down_selenium_server(self)
     # error only is thrown when log file was not created,
     # this only happens when a previous sele-server was 
     # running that we didn't start
     except AttributeError: warn("stopped selenium server that we didn't start")
     else: self._user_ext_file.close()
Пример #19
0
def test_sl_init_not_embed():
    sl = SeleniumLibrary(screenshot_root_directory=None)
    assert sl.screenshot_root_directory is None

    sl = SeleniumLibrary(screenshot_root_directory='None')
    assert sl.screenshot_root_directory == 'None'

    sl = SeleniumLibrary(screenshot_root_directory='/path/to/folder')
    assert sl.screenshot_root_directory == '/path/to/folder'
Пример #20
0
class GUILibrary(BasicOperations):
   def __init__(self):
      BasicOperations.__init__(self)
      self.seleniumLib = SeleniumLibrary()
      self.seleniumLib.__init__(timeout=20.0)
      print "Selenium library initialized"

   def helloKeyword(self):
      print "This is hello keyword!"
    def test_tags_in_plugin_args(self):
        sl = SeleniumLibrary(plugins='%s;foo;bar' % self.plugin_varargs)
        tags = sl.get_keyword_tags('foo_1')
        self.assertEqual(tags, ['MyTag', 'plugin'])

        tags = sl.get_keyword_tags('open_browser')
        self.assertFalse(tags)

        tags = sl.get_keyword_tags('add_cookie')
        self.assertEqual(tags, ['plugin'])
    def test_tags_in_plugin_args(self):
        sl = SeleniumLibrary(plugins="%s;foo;bar" % self.plugin_varargs)
        tags = sl.get_keyword_tags("foo_1")
        self.assertEqual(tags, ["MyTag", "plugin"])

        tags = sl.get_keyword_tags("open_browser")
        self.assertFalse(tags)

        tags = sl.get_keyword_tags("add_cookie")
        self.assertEqual(tags, ["plugin"])
Пример #23
0
    def test_tags_in_plugin_args(self):
        sl = SeleniumLibrary(plugins='%s;foo;bar' % self.plugin_varargs)
        tags = sl.get_keyword_tags('foo_1')
        self.assertEqual(tags, ['MyTag', 'plugin'])

        tags = sl.get_keyword_tags('open_browser')
        self.assertFalse(tags)

        tags = sl.get_keyword_tags('add_cookie')
        self.assertEqual(tags, ['plugin'])
Пример #24
0
def test_sl_set_screenshot_directory():
    sl = SeleniumLibrary()
    sl.set_screenshot_directory('EmBed')
    assert sl.screenshot_root_directory == EMBED

    sl.set_screenshot_directory(EMBED)
    assert sl.screenshot_root_directory == EMBED

    sl.set_screenshot_directory('EEmBedD')
    assert 'EEmBedD' in sl.screenshot_root_directory
    assert len('EEmBedD') < len(sl.screenshot_root_directory)

    cur_dir = dirname(abspath(__file__))
    sl.set_screenshot_directory(cur_dir)
    assert sl.screenshot_root_directory == cur_dir
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None):

        # self._builtin = BuiltIn()
        SeleniumLibrary.__init__(
            self,
            timeout=timeout,
            implicit_wait=implicit_wait,
            run_on_failure=run_on_failure,
            screenshot_root_directory=screenshot_root_directory)
        # ContextPatch.__init__(self)
        self.add_library_components([ElementKeywordsExtension(self)])
Пример #26
0
    def start_selenium_server(self, *params):
        """Start a selenium-server using extensions specified in the 
        constructor and selenium-server *params.

        Note that server params `port`, `timeout` and `userExtensions` are 
        not appliciable as they are specified in the wbSelenium 
        constructor."""
        if selenium_server_is_running(self._server_host, self._server_port):
            error = 'an instance of selenium-server on host %s, port %s is already running, please shutdown and rerun testcase' % (self._server_host, self._server_port) 
            warn(error)
            raise RuntimeError, error
        params += ('-port', str(self._server_port))
        if self._user_ext_file:
            params += ('-userExtensions', self._user_ext_file.name)
        SeleniumLibrary.start_selenium_server(self, *params) # unfortunatly this fails silently as well
        wait_until_server_has_started(self._server_host, self._server_port)
Пример #27
0
 def test_plugin_as_last_in_init(self):
     plugin_file = os.path.join(self.root_dir, "plugin_tester.py")
     event_firing_wd = os.path.join(self.root_dir, "MyListener.py")
     sl = SeleniumLibrary(
         plugins=plugin_file, event_firing_webdriver=event_firing_wd
     )
     self.assertEqual(sl.event_firing_webdriver, "should be last")
Пример #28
0
 def test_easier_event_firing_webdriver_from_plugin(self):
     plugin_file = os.path.join(
         self.root_dir, "plugin_with_event_firing_webdriver.py"
     )
     sl = SeleniumLibrary(plugins=plugin_file)
     self.assertEqual(sl._plugin_keywords, ["tidii"])
     self.assertEqual(sl.event_firing_webdriver, "event_firing_webdriver")
Пример #29
0
 def setUpClass(cls):
     cls.sl = SeleniumLibrary()
     cls.root_dir = os.path.dirname(os.path.abspath(__file__))
     Plugin = namedtuple('Plugin', 'plugin, args, kw_args')
     lib = Plugin(plugin=os.path.join(cls.root_dir, 'my_lib.py'),
                  args=[],
                  kw_args={})
     cls.plugin = lib
Пример #30
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()
 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.__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)
     self.logger = get_logger("SeleniumProxy")
     self.logger.debug("__init__()")
     if is_truthy(event_firing_webdriver):
         self.event_firing_webdriver = self._parse_listener(
             event_firing_webdriver)
     self.add_library_components(
         [BrowserKeywords(self), HTTPKeywords(self)])
Пример #32
0
 def test_sl_with_kw_args_plugin(self):
     kw_args_lib = os.path.join(
         self.root_dir,
         "..",
         "..",
         "..",
         "atest",
         "acceptance",
         "1-plugin",
         "PluginWithKwArgs.py;kw1=Text1;kw2=Text2",
     )
     SeleniumLibrary(plugins=kw_args_lib)
Пример #33
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.__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)
     self.ROBOT_LIBRARY_LISTENER = RobotFrameworkListener()
     self.event_firing_webdriver = SeleniumProxyListener
     if is_truthy(event_firing_webdriver):
         self.event_firing_webdriver = self._parse_listener(
             event_firing_webdriver)
     self.add_library_components(
         [BrowserKeywords(self), HTTPKeywords(self)])
Пример #34
0
class BasicOperations:
   
   def __init__(self):      
      self.seleniumLibrary = SeleniumLibrary()
      
   def openBrowserWithSpectrePage(self, browser="ff", port="8080"):
      '''
      Opens default spectre page
      '''
      self.seleniumLibrary.open_browser("http://spectre.dyndns-server.com:%s/" % port, browser)
           
   def openUrl(self, url):
      '''
      Opens given url in active browser window.
      '''
      sel = self.seleniumLibrary._selenium
      sel.open('http://spectre.dyndns-server.com:8080/scrumzu/pbis')
         
   def openScrumzuAtLocalhost(self, browser="ff", port="8080"):
      '''
      Opens scrumzu at localhost
      '''
      self.seleniumLibrary.open_browser("http://localhost:%s/scrumzu" % port, browser)
      
   def closeBrowser(self):
      self.seleniumLibrary.close_all_browsers()
Пример #35
0
def test_set_selenium_implicit_wait():
    sl = SeleniumLibrary()
    sl.set_selenium_implicit_wait("5.0")
    assert sl.implicit_wait == 5.0

    sl.set_selenium_implicit_wait("1 min")
    assert sl.implicit_wait == 60.0
Пример #36
0
    def test_set_selenium_implicit_wait(self):
        sl = SeleniumLibrary()
        sl.set_selenium_implicit_wait('5.0')
        self.assertEqual(sl.implicit_wait, 5.0)

        sl.set_selenium_implicit_wait('1 min')
        self.assertEqual(sl.implicit_wait, 60.0)
def test_set_selenium_implicit_wait():
    sl = SeleniumLibrary()
    sl.set_selenium_implicit_wait('5.0')
    assert sl.implicit_wait == 5.0

    sl.set_selenium_implicit_wait('1 min')
    assert sl.implicit_wait == 60.0
Пример #38
0
    def get_keyword_documentation(self, name):
        if name != '__intro__':
            doc = SeleniumLibrary.get_keyword_documentation(self, name)
            return doc.replace('SeleniumLibrary', 'Selenium2Library')
        intro = inspect.getdoc(SeleniumLibrary)
        intro = intro.replace('SeleniumLibrary', 'Selenium2Library')
        return """
---
*NOTE:* Selenium2Library has been renamed to SeleniumLibrary since version 3.0.
Nowadays Selenium2Library is just a thin wrapper to SeleniumLibrary that eases
with transitioning to the new project. See
[https://github.com/robotframework/SeleniumLibrary|SeleniumLibrary] and
[https://github.com/robotframework/Selenium2Library|Selenium2Library]
project pages for more information.
---
""" + intro
 def test_deprecated_run_on_failure(self):
     when(SeleniumLibrary).failure_occurred().thenReturn(True)
     sl = SeleniumLibrary()
     sl._run_on_failure()
     verify(SeleniumLibrary, times=1).failure_occurred()
Пример #40
0
 def __init__(self):
     self.selLib = SeleniumLibrary()
Пример #41
0
class Redirects(RootClass):
    
    def __init__(self):
        self.selLib = SeleniumLibrary()
        
    def shut_Down_All_Browsers(self):
        self.selLib.close_all_browsers()
        self._info("All browsers closed")
        
    def start_selenium_server_XX(self, profile=None):
        self.selLib.start_selenium_server()
        
    def start_browser(self, url,browser=None):
        if browser == None:
            browser = 'ie'
        self.selLib.set_selenium_timeout(TIMEOUT)
        self.selLib.open_browser(url, browser)
        
    def get_ie(self, shell):
        """
        get IE browser as object
        """
        for win in shell.Windows():
            try:
                if win.Name == "Windows Internet Explorer":
                    return win
            except AttributeError:
                #this is to handle some <unknown> COMObject
                pass
        return None
    
    
    def createReport(self):
        
        body = "<html> <body>" \
               "<h1>Redirects Tests Results</h1> <p>%s</p>""</body> </html>" %(LOCAL_TIME)
        REDIRECT_REPORT_FILE.write(body)
        REDIRECT_LOG_FILE.write("Redirects Tests Results: %s \n" %LOCAL_TIME)
        
    def get_url(self, url, address):
        ie = self.get_ie(SHELL)
        if ie:
            if str(ie.LocationURL) == address:
                self._info("PASS: address %s is redirected to %s" % (url, address))
                REDIRECT_LOG_FILE.write("PASS: address %s is redirected to %s\n" % (url, address))
                REDIRECT_REPORT_FILE.write("<ul><li><font size='3'color='green'><b>PASSED</b></font>\tAddress: \
                <b><a href=%s>%s</a></b> \n    \tredirects to: <b><a href=%s>%s</a></b>\n\n</li></ul>" % (url,url, address,address))
            else:
                self._info('FAIL: address %s is not redirected to %s' % (url, address))
                REDIRECT_LOG_FILE.write('FAIL: address %s is not redirected to %s\n' % (url, address))
                REDIRECT_REPORT_FILE.write("<ul><li><font size='3'color='red'><b>FAILED</b></font>\tAddress: \
                <b><a href=%s>%s</a></b> \n    \tis not redirected to: <b><a href=%s>%s</a></b>\n\n</li></ul>" % (url,url, address,address))
                REDIRECT_REPORT_FILE.write("<ul><li><font size='3'color='red'><b>FAILED</b></font>\tAddress: \
                <b><a href=%s>%s</a></b> \n    \tis redirected to: <b><a href=%s>%s</a></b>\n\n</li></ul>" % (url,url, ie.LocationURL,ie.LocationURL))
            #REDIRECT_REPORT_FILE.close()
        else:
            print "no ie window"
      
    def verify_Redirects(self, input_file):
        """
        redirect_input_file:
        
        url_1 url_2
        #url_1 url_2 
        (...)
        url_1 ->origin
        url_2 -> target 
        if #: skip the line
        """
        redirects_input_file = open(input_file, 'r+')
        searchPattern = re.compile(r'(^[^\/#].*?)\s(.*$)')
        # in reg_exp ? is used for non-greedy search pattern - without ?, first match will cover whole line (up to $) due to .*

        for line in redirects_input_file:
            search = re.search(searchPattern, line)
            if search != None:
                #if url_1 has no 'http://' prefix, then add one:
                if search.group(1).find('://') == -1:
                    url_1 = 'http://%s' % (search.group(1),)
                else:
                    url_1 = search.group(1)
                #the same here, with url_2 (target)
                if search.group(2).find('://') == -1:
                    url_2 = 'http://%s' % (search.group(2),)
                else:
                    url_2 = search.group(2)   
                
                #finally, start browser:
                self.start_browser(url_1, browser='ie')
                #verify if addresses are redirected as expected:
                self.get_url(url_1, url_2)
                
                #afterall, close/shutdown browser:
                self.shut_Down_All_Browsers()
                self.selLib.close_browser()
              
            else:
                self._info("Skipping...")
Пример #42
0
 def __init__(self):
    BasicOperations.__init__(self)
    self.seleniumLib = SeleniumLibrary()
    self.seleniumLib.__init__(timeout=20.0)
    print "Selenium library initialized"
 def test_no_plugin(self):
     sl = SeleniumLibrary()
     tags = sl.get_keyword_tags('open_browser')
     self.assertFalse(tags)
 def test_store_plugin_keywords(self):
     sl = SeleniumLibrary()
     sl._store_plugin_keywords(my_lib('0'))
     self.assertEqual(sl._plugin_keywords, ['bar', 'foo'])
 def test_selenium_implicit_wait_error(self):
     with self.assertRaises(ValueError):
         SeleniumLibrary(implicit_wait='False')
     sl = SeleniumLibrary(implicit_wait='3')
     with self.assertRaises(ValueError):
         sl.set_selenium_implicit_wait('1 vuosi')
 def test_store_plugin_keywords_with_args(self):
     sl = SeleniumLibrary()
     sl._store_plugin_keywords(my_lib_args('000', '111', '222'))
     self.assertEqual(sl._plugin_keywords, ['add_cookie', 'bar_2', 'foo_1'])
 def test_no_libraries(self):
     for item in [None, 'None', '']:
         sl = SeleniumLibrary(plugins=item)
         self.assertEqual(len(sl.get_keyword_names()), 170)
Пример #48
0
class BasicOperations:
   
   def __init__(self):      
      self.seleniumLibrary = SeleniumLibrary()
      
   def openScrumzuAtSpectre(self, browser="ff", port=DEFAULT_PORT):
      '''
      Opens default spectre page
      '''
      self.seleniumLibrary.set_selenium_timeout(30)
      self.seleniumLibrary.open_browser("http://spectre.dyndns-server.com:%s/" % port, browser)
         
   def openScrumzuAtLocalhost(self, browser="opera", port=DEFAULT_PORT):
      '''
      Opens scrumzu at localhost
      '''
      self.seleniumLibrary.set_selenium_timeout(30)
      self.seleniumLibrary.open_browser("http://localhost:%s/scrumzu" % port, browser)

   def clickOn(self, btnId):
      sel = self.seleniumLibrary._selenium
      sel.click("css=[id='%s']" % btnId)
      time.sleep(8)
      if('submit' in btnId):
         sel.wait_for_page_to_load(DEFAULT_TIMEOUT_MS)

 
   def selectCheckbox(self, objId, onoff='on'):
      sel = self.seleniumLibrary._selenium
      chk = 'chk%s' % objId
      if sel.get_value(chk) != onoff:
         sel.click(chk)
      info('Checkbox id=' + chk + ' set to ' + sel.get_value(chk))

   def waitFor(self, el):
      sel = self.seleniumLibrary._selenium
      for i in range(20) :
         if sel.is_element_present(el) :
            info("element appeared after %s" % i)
            break 
         else :
            time.sleep(1)
      else :
         fail("element DID NOT appear")

   def closeBrowser(self):
      self.seleniumLibrary.close_all_browsers()      
      
   def goToPage(self, page):
      sel = self.seleniumLibrary._selenium
      if(page == 'pbis'):
         url = "/scrumzu/TEST/pbis/"
      elif(page == 'teams'):
         url = "/scrumzu/TEST/teams/"
      elif(page == 'sprints'):
         url = "/scrumzu/TEST/sprints/"
      elif(page == 'projects'):
         url = "/scrumzu/projects/"
      elif(page == 'releases'):
         url = "/scrumzu/TEST/releases/"
      elif(page == 'TEST'):
         url = "/scrumzu/TEST"
      else:
         fail("Unknown page given")
         
      sel.open(url)
      sel.wait_for_page_to_load(DEFAULT_TIMEOUT_MS)
     
   def clickPbiActionButton(self, button):
      if(button == "new pbi"):
         btn = pbiAddBtn
      elif(button == "submit form"):
         btn = submitForm
      elif(button == "edit pbi"):
         btn = pbiEditBtn
      elif(button == "delete pbi"):
         btn = pbiDel
      elif(button == "mark as done"):
         btn = pbiMarkAsDone
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
     
      
   def clickTeamActionButton(self, button):
      if(button == "new team"):
         btn = teamAddBtn
      elif(button == "edit team"):
         btn = teamEditBtn
      elif(button == "delete"):
         btn = teamDel
      elif(button == "submit form"):
         btn = submitForm
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
      

   def clickSprintActionButton(self, button):
      if(button == "new sprint"):
         btn = sprintAddBtn
      elif(button == "edit sprint"):
         btn = sprintEditBtn
      elif(button == "delete sprint"):
         btn = sprintDel
      elif(button == "submit form"):
         btn = submitForm
      elif(button == "start sprint"):
         btn = sprintStart
      elif(button == "end sprint"):
         btn = sprintStop
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
  
   def clickProjectActionButton(self, button):
      if(button == "new project"):
         btn = projectAddBtn
      elif(button == "edit project"):
         btn = projectEditBtn
      elif(button == "delete project"):
         btn = projectDel
      elif(button == "submit form"):
         btn = submitForm
      elif(button == "add atr"):
         btn = projectAddAtr
      elif(button == "delete atr"):
         btn = projectDeleteAtr
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
   
   def clickReleaseActionButton(self, button):
      if(button == "new release"):
         btn = releaseAddBtn
      elif(button == "edit release"):
         btn = releaseEditBtn
      elif(button == "delete release"):
         btn = releaseDel
      elif(button == "submit form"):
         btn = submitForm
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
   
            
   def pause(self):
      time.sleep(10)  
      
   def getCurrentDate(self):
      now = datetime.datetime.now()
      return now.strftime("%Y-%m-%d")
   
   
   def login(self, role):
      sel = self.seleniumLibrary._selenium
      if( "%s" % role == "owner" ):
         sel.type( loginTB, owner )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      elif( "%s" % role == "master" ):
         sel.type( loginTB, master )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      elif( "%s" % role == "master2" ):
         sel.type( loginTB, 'sm2' )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      elif( "%s" % role == "user" ):
         sel.type( loginTB, user )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      elif( "%s" % role == "root" ):
         sel.type( loginTB, root )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      elif( "%s" % role == "sp" ):
         sel.type( loginTB, 'sp' )
         sel.type( passwordTB, pswd )
         self.clickOn( logIn )
      else:
         fail("Unknown user")
         
   def logout(self):
      sel = self.seleniumLibrary._selenium
      sel.click( logOut )
      sel.wait_for_page_to_load(DEFAULT_TIMEOUT_MS)
      
      
   def clickFilterActionButton(self, button):
      if(button == "select"):
         btn = filterSelectBtn
      elif(button == "clear"):
         btn = filterClearBtn
      elif(button == "run"):
         btn = filterRunBtn
      else:
         fail("Unknown button")
         
      self.clickOn(btn)
      info(btn + "clicked")
      
   def clickDialogWindowElement(self,element):
      sel = self.seleniumLibrary._selenium
      if(element == 'close filter'):
         el = filterClose
      elif(element == 'add filter'):
         el = filterAdd
      else:
         fail("Unknown element to click")
         
      sel.click(el)
      
   def makeDictionary(self, atr1, val1, atr2, val2):
      dic= {}
      dic[atr1] = val1
      dic[atr2] = val2
      return dic

   def selectCheckboxes(self, ids, idPrefix="chk"):
      for i in ids:
         self.selectCheckbox(i)
         
   def makeList(self, it1, it2):
      return [it1, it2]
 def test_failure_occurred(self):
     when(SeleniumLibrary).failure_occurred().thenReturn(True)
     sl = SeleniumLibrary()
     sl.failure_occurred()
     verify(SeleniumLibrary, times=1).failure_occurred()
 def setUp(self):
     self.lib = SeleniumLibrary()