├── .gitignore ├── AUTHORS ├── CHANGES ├── LICENSE ├── MANIFEST.in ├── README.rst ├── noseselenium ├── __init__.py ├── cases.py ├── plugins.py └── thirdparty │ ├── __init__.py │ └── selenium.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | build/ 3 | dist/ 4 | django_nose_selenium.egg-info/ 5 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Ordered by date of first contribution: 2 | Pascal Hartig 3 | Andreas Pelme 4 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | django-nose-selenium Changelog 2 | ============================== 3 | 4 | Here you can see the list of changes between the releases. 5 | 6 | Version 0.7.3 7 | ------------- 8 | 9 | Bugfix release, released on 2011-08-15 10 | 11 | - Fixed regression regarding static files serving with the CherryPy liveserver 12 | plugin. 13 | 14 | Version 0.7.2 15 | ------------- 16 | 17 | Bugfix release, released on 2011-08-03 18 | 19 | - Restored compatibility with Django 1.2 (#7, reported by Issac Kelly) 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010, Pascal Hartig (weluse GmbH) 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | Neither the name of the weluse GmbH nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 9 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS 2 | include README.rst 3 | include LICENSE 4 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ==================== 2 | django-nose-selenium 3 | ==================== 4 | 5 | .. warning:: 6 | This package is no longer under active development. For Django 1.4+ selenium support, 7 | check out `selenose `_. 8 | 9 | Adds selenium testing support to your nose test suite. 10 | 11 | To use, run nosetests with the ``--with-selenium`` flag. 12 | 13 | 14 | -------- 15 | Tutorial 16 | -------- 17 | 18 | For a complete guide on getting started, have a look at Charl P. Botha's 19 | `concise tutorial on django-nose-selenium 20 | `_. 21 | 22 | ----------------- 23 | Why use Selenium? 24 | ----------------- 25 | 26 | Selenium is a portable testing framework for web applications. It allows you to 27 | write tests that run in the browser to test your user interface and javascript 28 | code that is not available through the usual testing channels. See the examples 29 | below to get a clearer impression of what selenium tests can provide. 30 | 31 | django-nose-selenium allows you to write and run selenium tests the same way as 32 | usual django unit tests. 33 | 34 | ------------ 35 | Requirements 36 | ------------ 37 | 38 | The plugin expects that you have configured the django-nose_ app. In a nutshell, 39 | this is done by running ``pip install django-nose``, adding ``django_nose`` to 40 | ``INSTALLED_APPS`` and setting ``TEST_RUNNER`` to 41 | ``django_nose.NoseTestSuiteRunner`` in the settings.py. 42 | 43 | .. _django-nose: https://github.com/jbalogh/django-nose 44 | 45 | ------------ 46 | Installation 47 | ------------ 48 | 49 | From PyPI:: 50 | 51 | pip install django-nose-selenium 52 | 53 | `In-development version 54 | `_ 55 | via Pip:: 56 | 57 | pip install django-nose-selenium==dev 58 | 59 | Directly from Git:: 60 | 61 | pip install -e 62 | git://github.com/weluse/django-nose-selenium.git#egg=django-nose-selenium 63 | 64 | --------------- 65 | Django Settings 66 | --------------- 67 | 68 | .. _base_settings: 69 | 70 | The plugin supports the following settings: 71 | 72 | * SELENIUM_HOST, default: `127.0.0.1` 73 | * SELENIUM_PORT, default: `4444` 74 | * SELENIUM_BROWSER_COMMAND, default: `chrome` 75 | * SELENIUM_URL_ROOT, default: `http://127.0.0.1:8000` 76 | * FORCE_SELENIUM_TESTS, default: `False`. By default, SocketErrors cause the 77 | tests to be skipped. This options causes the tests to fail when the 78 | Selenium server is unavailable. 79 | 80 | ----- 81 | Usage 82 | ----- 83 | 84 | Define the class variable ``selenium_test = True`` in your nose test class. 85 | You can use ``self.selenium`` to access a selenium instance with the given 86 | options:: 87 | 88 | 89 | class TestSelenium(TestCase): 90 | 91 | selenium_test = True 92 | 93 | def test_start(self): 94 | """Tests the start page.""" 95 | 96 | self.selenium.open("/") 97 | 98 | To run this test, you have to pass the option ``--with-selenium`` to the Django 99 | management command test:: 100 | 101 | python manage.py test --with-selenium 102 | 103 | Alternatively, django-nose-selenium provides a mixin that has the benefit of 104 | raising a SkipTest exception if the plugin was not loaded and the selenium 105 | attribute is accessed:: 106 | 107 | 108 | from noseselenium.cases import SeleniumTestCaseMixin 109 | 110 | 111 | class TestSelenium(TestCase, SeleniumTestCaseMixin): 112 | 113 | def test_start(self): 114 | """Tests the start page.""" 115 | 116 | self.selenium.open("/") 117 | 118 | Fixtures 119 | -------- 120 | 121 | The default fixtures of django are run in transactions and not available to a 122 | live testing server, therefore `noseselenium` provides an option to load **and 123 | commit** fixtures to the database automatically. Please note that there's no 124 | automatic rollback, so the data will stay in your test database for the rest of 125 | the run if you don't provide a custom teardown strategy. 126 | 127 | :: 128 | 129 | from noseselenium.cases import SeleniumTestCaseMixin 130 | 131 | 132 | class TestUserLogin(TestCase, SeleniumTestCaseMixin): 133 | 134 | selenium_fixtures = ['user_data.json'] 135 | 136 | def tearDown(self): 137 | # Remove data from user_data.json 138 | 139 | def test_login(self): 140 | """Tests the login page.""" 141 | 142 | sel = self.selenium 143 | sel.open("/login/") 144 | sel.type("id_username", "pascal") 145 | sel.type("id_password", "iwantapony") 146 | sel.click("//form[@id='myform']/p/button") 147 | sel.wait_for_page_to_load(5000) 148 | self.failUnless(self.is_text_present("Hello, Pascal!")) 149 | 150 | To enable selenium fixtures, nosetests must be called with the 151 | additional ``--with-selenium-fixtures`` flag. 152 | 153 | 154 | Liveserver 155 | ---------- 156 | 157 | `noseselenium` provides expiremental support for running a live server that 158 | Selenium can connect to. Currently, there's a threaded server that reuses 159 | django's development webserver and a cherrypy implementation. It's recommended 160 | you use the cherrypy one as the django devserver is certainly not designed to 161 | run in a multi-threaded environment. 162 | 163 | The liveserver plugin introduces two new configuration options: 164 | 165 | * LIVE_SERVER_ADDRESS, defaults to `0.0.0.0` 166 | * LIVE_SERVER_PORT, defaults to `8080` 167 | * LIVE_SERVER_STATIC, boolean that defaults to True. If enabled, the live 168 | server enables serving of static files via the 169 | ``django.contrib.staticfiles`` app. 170 | 171 | These should match your `Selenium Settings`__. 172 | 173 | __ base_settings_ 174 | 175 | To start the liveserver, nosetest is called with either the 176 | ``--with-djangoliveserver`` or preferably the ``--with-cherrypyliveserver`` 177 | flag. 178 | -------------------------------------------------------------------------------- /noseselenium/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.7.3" 2 | -------------------------------------------------------------------------------- /noseselenium/cases.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | noseselenium.cases 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Testcases for selenium. 7 | 8 | :copyright: 2010, Pascal Hartig 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from nose.plugins.skip import SkipTest 13 | 14 | 15 | class SeleniumSkipper(object): 16 | """ 17 | A class that raises a SkipTest exception when an attribute is 18 | accessed. 19 | """ 20 | 21 | def __getattr__(self, name): 22 | raise SkipTest("SeleniumPlugin not enabled.") 23 | 24 | 25 | class SeleniumTestCaseMixin(object): 26 | """ 27 | Provides a selenium attribute that raises :class:`SkipTest` 28 | when not overwritten by :class:`SeleniumPlugin`. 29 | """ 30 | 31 | # To be replaced by the plugin. 32 | selenium = SeleniumSkipper() 33 | # Triggers the plugin if enabled. 34 | selenium_test = True 35 | start_live_server = True 36 | -------------------------------------------------------------------------------- /noseselenium/plugins.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | noseselenium.plugins 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Provides the nose plugins. 7 | Heavily inspired by `django-sane-testing`_. 8 | 9 | _django-sane-testing: http://github.com/Almad/django-sane-testing/ 10 | 11 | :copyright: 2010-2011, Pascal Hartig 12 | :license: BSD, see LICENSE for more details. 13 | """ 14 | 15 | import socket 16 | import nose 17 | import time 18 | import threading 19 | import django 20 | 21 | from nose.plugins import Plugin 22 | from nose.plugins.skip import SkipTest 23 | from noseselenium.thirdparty.selenium import selenium 24 | from unittest import TestCase 25 | # Liveserver imports 26 | from SocketServer import ThreadingMixIn 27 | from BaseHTTPServer import HTTPServer 28 | from django.core.handlers.wsgi import WSGIHandler 29 | from django.core.servers.basehttp import WSGIRequestHandler, \ 30 | AdminMediaHandler, WSGIServerException 31 | from django.db.backends.creation import TEST_DATABASE_PREFIX 32 | 33 | 34 | def _get_test_db_name(connection): 35 | """Tries to build the test database name like django does.""" 36 | 37 | if connection.settings_dict['TEST_NAME']: 38 | return connection.settings_dict['TEST_NAME'] 39 | else: 40 | old_name = connection.settings_dict['NAME'] 41 | if old_name.startswith(TEST_DATABASE_PREFIX): 42 | return old_name 43 | else: 44 | return TEST_DATABASE_PREFIX + \ 45 | old_name 46 | 47 | 48 | def _set_autocommit(connection): 49 | """Make sure a connection is in autocommit mode.""" 50 | if hasattr(connection.connection, "autocommit"): 51 | if callable(connection.connection.autocommit): 52 | connection.connection.autocommit(True) 53 | else: 54 | connection.connection.autocommit = True 55 | elif hasattr(connection.connection, "set_isolation_level"): 56 | connection.connection.set_isolation_level(0) 57 | 58 | 59 | def _setup_test_db(): 60 | """Activates a test dbs without recreating them.""" 61 | 62 | from django.db import connections 63 | 64 | for alias in connections: 65 | connection = connections[alias] 66 | connection.close() 67 | 68 | test_db_name = _get_test_db_name(connection) 69 | connection.settings_dict['NAME'] = test_db_name 70 | 71 | # SUPPORTS_TRANSACTIONS is not needed in newer versions of djangoo 72 | if not hasattr(connection.features, 'supports_transactions'): 73 | can_rollback = connection.creation._rollback_works() 74 | connection.settings_dict['SUPPORTS_TRANSACTIONS'] = can_rollback 75 | 76 | # Trigger side effects. 77 | connection.cursor() 78 | _set_autocommit(connection) 79 | 80 | 81 | def _patch_static_handler(handler): 82 | """Patch in support for static files serving if supported and enabled. 83 | """ 84 | 85 | if django.VERSION[:2] < (1, 3): 86 | return 87 | 88 | from django.contrib.staticfiles.handlers import StaticFilesHandler 89 | return StaticFilesHandler(handler) 90 | 91 | 92 | def get_test_case_class(nose_test): 93 | """ 94 | Extracts the class from the nose tests that depends on whether it's a 95 | method test case or a function test case. 96 | """ 97 | if isinstance(nose_test.test, nose.case.MethodTestCase): 98 | return nose_test.test.test.im_class 99 | else: 100 | return nose_test.test.__class__ 101 | 102 | 103 | class SeleniumPlugin(Plugin): 104 | """ 105 | Adds a selenium attribute to the nose test case and reads the parameters 106 | from the django config. 107 | Only works with class based tests, so far. 108 | """ 109 | 110 | activation_parameter = "--with-selenium" 111 | name = "selenium" 112 | score = 80 113 | 114 | def startTest(self, test): 115 | """ 116 | When preparing the test, inject a selenium instance. 117 | """ 118 | 119 | test_case = get_test_case_class(test) 120 | if getattr(test_case, "selenium_test", False): 121 | self._inject_selenium(test) 122 | 123 | def stopTest(self, test): 124 | """ 125 | Destroys the selenium connection. 126 | """ 127 | 128 | test_case = get_test_case_class(test) 129 | if getattr(test_case, 'selenium_started', False): 130 | if isinstance(test.test, nose.case.MethodTestCase): 131 | self = test.test.test.im_self 132 | elif isinstance(test.test, TestCase): 133 | self = test.test.run.im_self 134 | 135 | self.selenium.stop() 136 | del self.selenium 137 | 138 | def _inject_selenium(self, test): 139 | """ 140 | Injects a selenium instance into the method. 141 | """ 142 | from django.conf import settings 143 | 144 | test_case = get_test_case_class(test) 145 | test_case.selenium_plugin_started = True 146 | 147 | # Provide some reasonable default values 148 | sel = selenium( 149 | getattr(settings, "SELENIUM_HOST", "localhost"), 150 | int(getattr(settings, "SELENIUM_PORT", 4444)), 151 | getattr(settings, "SELENIUM_BROWSER_COMMAND", "*chrome"), 152 | getattr(settings, "SELENIUM_URL_ROOT", "http://127.0.0.1:8000/")) 153 | 154 | try: 155 | sel.start() 156 | except socket.error: 157 | if getattr(settings, "FORCE_SELENIUM_TESTS", False): 158 | raise 159 | else: 160 | raise SkipTest("Selenium server not available.") 161 | else: 162 | test_case.selenium_started = True 163 | # Only works on method test cases, because we obviously need 164 | # self. 165 | if isinstance(test.test, nose.case.MethodTestCase): 166 | test.test.test.im_self.selenium = sel 167 | elif isinstance(test.test, TestCase): 168 | test.test.run.im_self.selenium = sel 169 | else: 170 | raise SkipTest("Test skipped because it's not a method.") 171 | 172 | 173 | class SeleniumFixturesPlugin(Plugin): 174 | """ 175 | Loads fixtures defined in the attribute `selenium_fixtures`. It does, 176 | however, not take care of removing them after the test or even the whole 177 | test case is run. 178 | Django fixtures are usually run in transactions so a test server accessing 179 | the test database won't be able access the data. 180 | """ 181 | 182 | activation_parameter = "--with-selenium-fixtures" 183 | name = "selenium-fixtures" 184 | score = 80 185 | 186 | def startTest(self, test): 187 | """ 188 | When preparing the database, check for the `selenium_fixtures` 189 | attribute and load those. 190 | """ 191 | 192 | from django.test.testcases import call_command 193 | 194 | test_case = get_test_case_class(test) 195 | fixtures = getattr(test_case, "selenium_fixtures", []) 196 | 197 | if fixtures: 198 | call_command('loaddata', *fixtures, **{ 199 | 'verbosity': 1, 200 | # Necessary to let the test server access them. 201 | 'commit': True 202 | }) 203 | 204 | 205 | class StoppableWSGIServer(ThreadingMixIn, HTTPServer): 206 | """WSGIServer with short timeout, so that server thread can stop this 207 | server. 208 | 209 | This implementation is again from django-sane-testing, while the original 210 | code is taken from django ticket #2879 which proposes a live server in the 211 | django core. 212 | """ 213 | 214 | application = None 215 | 216 | def __init__(self, server_address, RequestHandlerClass=None): 217 | HTTPServer.__init__(self, server_address, RequestHandlerClass) 218 | 219 | def server_bind(self): 220 | """Bind server to socket. Overrided to store server name and 221 | set timeout. 222 | """ 223 | 224 | try: 225 | HTTPServer.server_bind(self) 226 | except Exception as e: 227 | raise WSGIServerException(e) 228 | 229 | self.setup_environ() 230 | self.socket.settimeout(1) 231 | 232 | def get_request(self): 233 | """Checks for timeout when getting request.""" 234 | sock, address = self.socket.accept() 235 | return (sock, address) 236 | 237 | def setup_environ(self): 238 | """Set up a basic environment.""" 239 | 240 | self.base_environ = { 241 | 'SERVER_NAME': self.server_name, 242 | 'GATEWAY_INTERFACE': 'CGI/1.1', 243 | 'SERVER_PORT': str(self.server_port), 244 | 'REMOTE_HOST': '', 245 | 'CONTENT_LENGTH': '', 246 | 'SCRIPT_NAME': '', 247 | } 248 | 249 | def get_app(self): 250 | return self.application 251 | 252 | def set_app(self,application): 253 | self.application = application 254 | 255 | 256 | class AbstractLiveServerPlugin(Plugin): 257 | """Base class for live servers.""" 258 | 259 | score = 70 260 | 261 | def __init__(self): 262 | Plugin.__init__(self) 263 | self.server_started = False 264 | self.server_thread = None 265 | 266 | def start_server(self): 267 | raise NotImplementedError() 268 | 269 | def stop_server(self): 270 | raise NotImplementedError() 271 | 272 | def startTest(self, test): 273 | """Starts the live server.""" 274 | 275 | from django.conf import settings 276 | 277 | test_case = get_test_case_class(test) 278 | 279 | if not self.server_started and \ 280 | getattr(test_case, "start_live_server", False): 281 | 282 | _setup_test_db() 283 | 284 | # Raises an exception if not. 285 | settings.TEST_MODE = True 286 | 287 | self.start_server( 288 | address=getattr(settings, 'LIVE_SERVER_ADDRESS', 289 | '0.0.0.0'), 290 | port=getattr(settings, 'LIVE_SERVER_PORT', 291 | 8080), 292 | serve_static=getattr(settings, 'LIVE_SERVER_STATIC', True) 293 | ) 294 | 295 | self.server_started = True 296 | setattr(test_case, 'http_plugin_started', True) 297 | 298 | def stopTest(self, test): 299 | """Stops the live server if necessary.""" 300 | 301 | test_case = get_test_case_class(test) 302 | if self.server_started and \ 303 | getattr(test_case, 'http_plugin_started', False): 304 | 305 | self.stop_server() 306 | self.server_started = False 307 | 308 | 309 | class TestServerThread(threading.Thread): 310 | """Thread for running a http server while tests are running.""" 311 | 312 | def __init__(self, address, port, serve_static=True): 313 | self.address = address 314 | self.port = port 315 | self.serve_static = serve_static 316 | self._stopevent = threading.Event() 317 | self.started = threading.Event() 318 | self.error = None 319 | super(TestServerThread, self).__init__() 320 | 321 | def run(self): 322 | """Sets up test server and loops over handling http requests.""" 323 | try: 324 | handler = AdminMediaHandler(WSGIHandler()) 325 | if self.serve_static: 326 | handler = _patch_static_handler(handler) 327 | 328 | server_address = (self.address, self.port) 329 | httpd = StoppableWSGIServer(server_address, WSGIRequestHandler) 330 | httpd.application = handler 331 | self.started.set() 332 | except WSGIServerException as err: 333 | self.error = err 334 | self.started.set() 335 | return 336 | 337 | # Loop until we get a stop event. 338 | while not self._stopevent.isSet(): 339 | httpd.handle_request() 340 | 341 | def join(self, timeout=None): 342 | """Stop the thread and wait for it to finish.""" 343 | self._stopevent.set() 344 | threading.Thread.join(self, timeout) 345 | 346 | 347 | class DjangoLiveServerPlugin(AbstractLiveServerPlugin): 348 | """ 349 | Patch Django on fly and start live HTTP server, if TestCase is inherited 350 | from HttpTestCase or start_live_server attribute is set to True. 351 | 352 | Taken from Michael Rogers implementation from `getwindmill.com 353 | `_. 355 | """ 356 | name = 'djangoliveserver' 357 | activation_parameter = '--with-djangoliveserver' 358 | 359 | def start_server(self, address='0.0.0.0', port=8000, serve_static=True): 360 | self.server_thread = TestServerThread(address, port, serve_static) 361 | self.server_thread.start() 362 | self.server_thread.started.wait() 363 | if self.server_thread.error: 364 | raise self.server_thread.error 365 | 366 | def stop_server(self): 367 | self.server_thread.join() 368 | 369 | 370 | class CherryPyLiveServerPlugin(AbstractLiveServerPlugin): 371 | """Live server plugin using cherrypy instead of the django server, 372 | that got its issues. Original code by Mikeal Rogers, released under 373 | Apache License. 374 | """ 375 | 376 | name = 'cherrypyliveserver' 377 | activation_parameter = '--with-cherrypyliveserver' 378 | 379 | def start_server(self, address='0.0.0.0', port=8000, serve_static=True): 380 | from cherrypy.wsgiserver import CherryPyWSGIServer 381 | from threading import Thread 382 | 383 | _application = AdminMediaHandler(WSGIHandler()) 384 | if serve_static: 385 | _application = _patch_static_handler(_application) 386 | 387 | def application(environ, start_response): 388 | environ['PATH_INFO'] = environ['SCRIPT_NAME'] + \ 389 | environ['PATH_INFO'] 390 | 391 | return _application(environ, start_response) 392 | 393 | self.httpd = CherryPyWSGIServer((address, port), application, 394 | server_name='django-test-http') 395 | self.httpd_thread = Thread(target=self.httpd.start) 396 | self.httpd_thread.start() 397 | # FIXME: This could be avoided by passing self to thread class starting 398 | # django and waiting for Event lock 399 | time.sleep(.5) 400 | 401 | def stop_server(self): 402 | self.httpd.stop() 403 | -------------------------------------------------------------------------------- /noseselenium/thirdparty/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weluse/django-nose-selenium/19a09b9455545f70271f884649323a38812793e6/noseselenium/thirdparty/__init__.py -------------------------------------------------------------------------------- /noseselenium/thirdparty/selenium.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2006 ThoughtWorks, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | __docformat__ = "restructuredtext en" 17 | 18 | # This file has been automatically generated via XSL 19 | 20 | import httplib 21 | import urllib 22 | import re 23 | 24 | class selenium: 25 | """ 26 | Defines an object that runs Selenium commands. 27 | 28 | Element Locators 29 | ~~~~~~~~~~~~~~~~ 30 | 31 | Element Locators tell Selenium which HTML element a command refers to. 32 | The format of a locator is: 33 | 34 | \ *locatorType*\ **=**\ \ *argument* 35 | 36 | 37 | We support the following strategies for locating elements: 38 | 39 | 40 | * \ **identifier**\ =\ *id*: 41 | Select the element with the specified @id attribute. If no match is 42 | found, select the first element whose @name attribute is \ *id*. 43 | (This is normally the default; see below.) 44 | * \ **id**\ =\ *id*: 45 | Select the element with the specified @id attribute. 46 | * \ **name**\ =\ *name*: 47 | Select the first element with the specified @name attribute. 48 | 49 | * username 50 | * name=username 51 | 52 | 53 | The name may optionally be followed by one or more \ *element-filters*, separated from the name by whitespace. If the \ *filterType* is not specified, \ **value**\ is assumed. 54 | 55 | * name=flavour value=chocolate 56 | 57 | 58 | * \ **dom**\ =\ *javascriptExpression*: 59 | 60 | Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object 61 | Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block. 62 | 63 | * dom=document.forms['myForm'].myDropdown 64 | * dom=document.images[56] 65 | * dom=function foo() { return document.links[1]; }; foo(); 66 | 67 | 68 | * \ **xpath**\ =\ *xpathExpression*: 69 | Locate an element using an XPath expression. 70 | 71 | * xpath=//img[@alt='The image alt text'] 72 | * xpath=//table[@id='table1']//tr[4]/td[2] 73 | * xpath=//a[contains(@href,'#id1')] 74 | * xpath=//a[contains(@href,'#id1')]/@class 75 | * xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td 76 | * xpath=//input[@name='name2' and @value='yes'] 77 | * xpath=//\*[text()="right"] 78 | 79 | 80 | * \ **link**\ =\ *textPattern*: 81 | Select the link (anchor) element which contains text matching the 82 | specified \ *pattern*. 83 | 84 | * link=The link text 85 | 86 | 87 | * \ **css**\ =\ *cssSelectorSyntax*: 88 | Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package. 89 | 90 | * css=a[href="#id3"] 91 | * css=span#firstChild + span 92 | 93 | 94 | Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). 95 | 96 | * \ **ui**\ =\ *uiSpecifierString*: 97 | Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the Selenium UI-Element Reference for more details. 98 | 99 | * ui=loginPages::loginButton() 100 | * ui=settingsPages::toggle(label=Hide Email) 101 | * ui=forumPages::postBody(index=2)//a[2] 102 | 103 | 104 | 105 | 106 | 107 | Without an explicit locator prefix, Selenium uses the following default 108 | strategies: 109 | 110 | 111 | * \ **dom**\ , for locators starting with "document." 112 | * \ **xpath**\ , for locators starting with "//" 113 | * \ **identifier**\ , otherwise 114 | 115 | Element Filters 116 | ~~~~~~~~~~~~~~~ 117 | 118 | Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator. 119 | 120 | Filters look much like locators, ie. 121 | 122 | \ *filterType*\ **=**\ \ *argument* 123 | 124 | Supported element-filters are: 125 | 126 | \ **value=**\ \ *valuePattern* 127 | 128 | 129 | Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons. 130 | 131 | \ **index=**\ \ *index* 132 | 133 | 134 | Selects a single element based on its position in the list (offset from zero). 135 | 136 | String-match Patterns 137 | ~~~~~~~~~~~~~~~~~~~~~ 138 | 139 | Various Pattern syntaxes are available for matching string values: 140 | 141 | 142 | * \ **glob:**\ \ *pattern*: 143 | Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a 144 | kind of limited regular-expression syntax typically used in command-line 145 | shells. In a glob pattern, "\*" represents any sequence of characters, and "?" 146 | represents any single character. Glob patterns match against the entire 147 | string. 148 | * \ **regexp:**\ \ *regexp*: 149 | Match a string using a regular-expression. The full power of JavaScript 150 | regular-expressions is available. 151 | * \ **regexpi:**\ \ *regexpi*: 152 | Match a string using a case-insensitive regular-expression. 153 | * \ **exact:**\ \ *string*: 154 | 155 | Match a string exactly, verbatim, without any of that fancy wildcard 156 | stuff. 157 | 158 | 159 | 160 | If no pattern prefix is specified, Selenium assumes that it's a "glob" 161 | pattern. 162 | 163 | 164 | 165 | For commands that return multiple values (such as verifySelectOptions), 166 | the string being matched is a comma-separated list of the return values, 167 | where both commas and backslashes in the values are backslash-escaped. 168 | When providing a pattern, the optional matching syntax (i.e. glob, 169 | regexp, etc.) is specified once, as usual, at the beginning of the 170 | pattern. 171 | 172 | 173 | """ 174 | 175 | ### This part is hard-coded in the XSL 176 | def __init__(self, host, port, browserStartCommand, browserURL): 177 | self.host = host 178 | self.port = port 179 | self.browserStartCommand = browserStartCommand 180 | self.browserURL = browserURL 181 | self.sessionId = None 182 | self.extensionJs = "" 183 | 184 | def setExtensionJs(self, extensionJs): 185 | self.extensionJs = extensionJs 186 | 187 | def start(self): 188 | result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL, self.extensionJs]) 189 | try: 190 | self.sessionId = result 191 | except ValueError: 192 | raise Exception, result 193 | 194 | def stop(self): 195 | self.do_command("testComplete", []) 196 | self.sessionId = None 197 | 198 | def do_command(self, verb, args): 199 | conn = httplib.HTTPConnection(self.host, self.port) 200 | body = u'cmd=' + urllib.quote_plus(unicode(verb).encode('utf-8')) 201 | for i in range(len(args)): 202 | body += '&' + unicode(i+1) + '=' + urllib.quote_plus(unicode(args[i]).encode('utf-8')) 203 | if (None != self.sessionId): 204 | body += "&sessionId=" + unicode(self.sessionId) 205 | headers = {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"} 206 | conn.request("POST", "/selenium-server/driver/", body, headers) 207 | 208 | response = conn.getresponse() 209 | #print response.status, response.reason 210 | data = unicode(response.read(), "UTF-8") 211 | result = response.reason 212 | #print "Selenium Result: " + repr(data) + "\n\n" 213 | if (not data.startswith('OK')): 214 | raise Exception, data 215 | return data 216 | 217 | def get_string(self, verb, args): 218 | result = self.do_command(verb, args) 219 | return result[3:] 220 | 221 | def get_string_array(self, verb, args): 222 | csv = self.get_string(verb, args) 223 | token = "" 224 | tokens = [] 225 | escape = False 226 | for i in range(len(csv)): 227 | letter = csv[i] 228 | if (escape): 229 | token = token + letter 230 | escape = False 231 | continue 232 | if (letter == '\\'): 233 | escape = True 234 | elif (letter == ','): 235 | tokens.append(token) 236 | token = "" 237 | else: 238 | token = token + letter 239 | tokens.append(token) 240 | return tokens 241 | 242 | def get_number(self, verb, args): 243 | # Is there something I need to do here? 244 | return self.get_string(verb, args) 245 | 246 | def get_number_array(self, verb, args): 247 | # Is there something I need to do here? 248 | return self.get_string_array(verb, args) 249 | 250 | def get_boolean(self, verb, args): 251 | boolstr = self.get_string(verb, args) 252 | if ("true" == boolstr): 253 | return True 254 | if ("false" == boolstr): 255 | return False 256 | raise ValueError, "result is neither 'true' nor 'false': " + boolstr 257 | 258 | def get_boolean_array(self, verb, args): 259 | boolarr = self.get_string_array(verb, args) 260 | for i in range(len(boolarr)): 261 | if ("true" == boolstr): 262 | boolarr[i] = True 263 | continue 264 | if ("false" == boolstr): 265 | boolarr[i] = False 266 | continue 267 | raise ValueError, "result is neither 'true' nor 'false': " + boolarr[i] 268 | return boolarr 269 | 270 | 271 | 272 | ### From here on, everything's auto-generated from XML 273 | 274 | 275 | def click(self,locator): 276 | """ 277 | Clicks on a link, button, checkbox or radio button. If the click action 278 | causes a new page to load (like a link usually does), call 279 | waitForPageToLoad. 280 | 281 | 'locator' is an element locator 282 | """ 283 | self.do_command("click", [locator,]) 284 | 285 | 286 | def double_click(self,locator): 287 | """ 288 | Double clicks on a link, button, checkbox or radio button. If the double click action 289 | causes a new page to load (like a link usually does), call 290 | waitForPageToLoad. 291 | 292 | 'locator' is an element locator 293 | """ 294 | self.do_command("doubleClick", [locator,]) 295 | 296 | 297 | def context_menu(self,locator): 298 | """ 299 | Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). 300 | 301 | 'locator' is an element locator 302 | """ 303 | self.do_command("contextMenu", [locator,]) 304 | 305 | 306 | def click_at(self,locator,coordString): 307 | """ 308 | Clicks on a link, button, checkbox or radio button. If the click action 309 | causes a new page to load (like a link usually does), call 310 | waitForPageToLoad. 311 | 312 | 'locator' is an element locator 313 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 314 | """ 315 | self.do_command("clickAt", [locator,coordString,]) 316 | 317 | 318 | def double_click_at(self,locator,coordString): 319 | """ 320 | Doubleclicks on a link, button, checkbox or radio button. If the action 321 | causes a new page to load (like a link usually does), call 322 | waitForPageToLoad. 323 | 324 | 'locator' is an element locator 325 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 326 | """ 327 | self.do_command("doubleClickAt", [locator,coordString,]) 328 | 329 | 330 | def context_menu_at(self,locator,coordString): 331 | """ 332 | Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). 333 | 334 | 'locator' is an element locator 335 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 336 | """ 337 | self.do_command("contextMenuAt", [locator,coordString,]) 338 | 339 | 340 | def fire_event(self,locator,eventName): 341 | """ 342 | Explicitly simulate an event, to trigger the corresponding "on\ *event*" 343 | handler. 344 | 345 | 'locator' is an element locator 346 | 'eventName' is the event name, e.g. "focus" or "blur" 347 | """ 348 | self.do_command("fireEvent", [locator,eventName,]) 349 | 350 | 351 | def focus(self,locator): 352 | """ 353 | Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field. 354 | 355 | 'locator' is an element locator 356 | """ 357 | self.do_command("focus", [locator,]) 358 | 359 | 360 | def key_press(self,locator,keySequence): 361 | """ 362 | Simulates a user pressing and releasing a key. 363 | 364 | 'locator' is an element locator 365 | 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". 366 | """ 367 | self.do_command("keyPress", [locator,keySequence,]) 368 | 369 | 370 | def shift_key_down(self): 371 | """ 372 | Press the shift key and hold it down until doShiftUp() is called or a new page is loaded. 373 | 374 | """ 375 | self.do_command("shiftKeyDown", []) 376 | 377 | 378 | def shift_key_up(self): 379 | """ 380 | Release the shift key. 381 | 382 | """ 383 | self.do_command("shiftKeyUp", []) 384 | 385 | 386 | def meta_key_down(self): 387 | """ 388 | Press the meta key and hold it down until doMetaUp() is called or a new page is loaded. 389 | 390 | """ 391 | self.do_command("metaKeyDown", []) 392 | 393 | 394 | def meta_key_up(self): 395 | """ 396 | Release the meta key. 397 | 398 | """ 399 | self.do_command("metaKeyUp", []) 400 | 401 | 402 | def alt_key_down(self): 403 | """ 404 | Press the alt key and hold it down until doAltUp() is called or a new page is loaded. 405 | 406 | """ 407 | self.do_command("altKeyDown", []) 408 | 409 | 410 | def alt_key_up(self): 411 | """ 412 | Release the alt key. 413 | 414 | """ 415 | self.do_command("altKeyUp", []) 416 | 417 | 418 | def control_key_down(self): 419 | """ 420 | Press the control key and hold it down until doControlUp() is called or a new page is loaded. 421 | 422 | """ 423 | self.do_command("controlKeyDown", []) 424 | 425 | 426 | def control_key_up(self): 427 | """ 428 | Release the control key. 429 | 430 | """ 431 | self.do_command("controlKeyUp", []) 432 | 433 | 434 | def key_down(self,locator,keySequence): 435 | """ 436 | Simulates a user pressing a key (without releasing it yet). 437 | 438 | 'locator' is an element locator 439 | 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". 440 | """ 441 | self.do_command("keyDown", [locator,keySequence,]) 442 | 443 | 444 | def key_up(self,locator,keySequence): 445 | """ 446 | Simulates a user releasing a key. 447 | 448 | 'locator' is an element locator 449 | 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". 450 | """ 451 | self.do_command("keyUp", [locator,keySequence,]) 452 | 453 | 454 | def mouse_over(self,locator): 455 | """ 456 | Simulates a user hovering a mouse over the specified element. 457 | 458 | 'locator' is an element locator 459 | """ 460 | self.do_command("mouseOver", [locator,]) 461 | 462 | 463 | def mouse_out(self,locator): 464 | """ 465 | Simulates a user moving the mouse pointer away from the specified element. 466 | 467 | 'locator' is an element locator 468 | """ 469 | self.do_command("mouseOut", [locator,]) 470 | 471 | 472 | def mouse_down(self,locator): 473 | """ 474 | Simulates a user pressing the left mouse button (without releasing it yet) on 475 | the specified element. 476 | 477 | 'locator' is an element locator 478 | """ 479 | self.do_command("mouseDown", [locator,]) 480 | 481 | 482 | def mouse_down_right(self,locator): 483 | """ 484 | Simulates a user pressing the right mouse button (without releasing it yet) on 485 | the specified element. 486 | 487 | 'locator' is an element locator 488 | """ 489 | self.do_command("mouseDownRight", [locator,]) 490 | 491 | 492 | def mouse_down_at(self,locator,coordString): 493 | """ 494 | Simulates a user pressing the left mouse button (without releasing it yet) at 495 | the specified location. 496 | 497 | 'locator' is an element locator 498 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 499 | """ 500 | self.do_command("mouseDownAt", [locator,coordString,]) 501 | 502 | 503 | def mouse_down_right_at(self,locator,coordString): 504 | """ 505 | Simulates a user pressing the right mouse button (without releasing it yet) at 506 | the specified location. 507 | 508 | 'locator' is an element locator 509 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 510 | """ 511 | self.do_command("mouseDownRightAt", [locator,coordString,]) 512 | 513 | 514 | def mouse_up(self,locator): 515 | """ 516 | Simulates the event that occurs when the user releases the mouse button (i.e., stops 517 | holding the button down) on the specified element. 518 | 519 | 'locator' is an element locator 520 | """ 521 | self.do_command("mouseUp", [locator,]) 522 | 523 | 524 | def mouse_up_right(self,locator): 525 | """ 526 | Simulates the event that occurs when the user releases the right mouse button (i.e., stops 527 | holding the button down) on the specified element. 528 | 529 | 'locator' is an element locator 530 | """ 531 | self.do_command("mouseUpRight", [locator,]) 532 | 533 | 534 | def mouse_up_at(self,locator,coordString): 535 | """ 536 | Simulates the event that occurs when the user releases the mouse button (i.e., stops 537 | holding the button down) at the specified location. 538 | 539 | 'locator' is an element locator 540 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 541 | """ 542 | self.do_command("mouseUpAt", [locator,coordString,]) 543 | 544 | 545 | def mouse_up_right_at(self,locator,coordString): 546 | """ 547 | Simulates the event that occurs when the user releases the right mouse button (i.e., stops 548 | holding the button down) at the specified location. 549 | 550 | 'locator' is an element locator 551 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 552 | """ 553 | self.do_command("mouseUpRightAt", [locator,coordString,]) 554 | 555 | 556 | def mouse_move(self,locator): 557 | """ 558 | Simulates a user pressing the mouse button (without releasing it yet) on 559 | the specified element. 560 | 561 | 'locator' is an element locator 562 | """ 563 | self.do_command("mouseMove", [locator,]) 564 | 565 | 566 | def mouse_move_at(self,locator,coordString): 567 | """ 568 | Simulates a user pressing the mouse button (without releasing it yet) on 569 | the specified element. 570 | 571 | 'locator' is an element locator 572 | 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. 573 | """ 574 | self.do_command("mouseMoveAt", [locator,coordString,]) 575 | 576 | 577 | def type(self,locator,value): 578 | """ 579 | Sets the value of an input field, as though you typed it in. 580 | 581 | 582 | Can also be used to set the value of combo boxes, check boxes, etc. In these cases, 583 | value should be the value of the option selected, not the visible text. 584 | 585 | 586 | 'locator' is an element locator 587 | 'value' is the value to type 588 | """ 589 | self.do_command("type", [locator,value,]) 590 | 591 | 592 | def type_keys(self,locator,value): 593 | """ 594 | Simulates keystroke events on the specified element, as though you typed the value key-by-key. 595 | 596 | 597 | This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string; 598 | this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events. 599 | 600 | Unlike the simple "type" command, which forces the specified value into the page directly, this command 601 | may or may not have any visible effect, even in cases where typing keys would normally have a visible effect. 602 | For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in 603 | the field. 604 | 605 | In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to 606 | send the keystroke events corresponding to what you just typed. 607 | 608 | 609 | 'locator' is an element locator 610 | 'value' is the value to type 611 | """ 612 | self.do_command("typeKeys", [locator,value,]) 613 | 614 | 615 | def set_speed(self,value): 616 | """ 617 | Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e., 618 | the delay is 0 milliseconds. 619 | 620 | 'value' is the number of milliseconds to pause after operation 621 | """ 622 | self.do_command("setSpeed", [value,]) 623 | 624 | 625 | def get_speed(self): 626 | """ 627 | Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e., 628 | the delay is 0 milliseconds. 629 | 630 | See also setSpeed. 631 | 632 | """ 633 | return self.get_string("getSpeed", []) 634 | 635 | 636 | def check(self,locator): 637 | """ 638 | Check a toggle-button (checkbox/radio) 639 | 640 | 'locator' is an element locator 641 | """ 642 | self.do_command("check", [locator,]) 643 | 644 | 645 | def uncheck(self,locator): 646 | """ 647 | Uncheck a toggle-button (checkbox/radio) 648 | 649 | 'locator' is an element locator 650 | """ 651 | self.do_command("uncheck", [locator,]) 652 | 653 | 654 | def select(self,selectLocator,optionLocator): 655 | """ 656 | Select an option from a drop-down using an option locator. 657 | 658 | 659 | 660 | Option locators provide different ways of specifying options of an HTML 661 | Select element (e.g. for selecting a specific option, or for asserting 662 | that the selected option satisfies a specification). There are several 663 | forms of Select Option Locator. 664 | 665 | 666 | * \ **label**\ =\ *labelPattern*: 667 | matches options based on their labels, i.e. the visible text. (This 668 | is the default.) 669 | 670 | * label=regexp:^[Oo]ther 671 | 672 | 673 | * \ **value**\ =\ *valuePattern*: 674 | matches options based on their values. 675 | 676 | * value=other 677 | 678 | 679 | * \ **id**\ =\ *id*: 680 | 681 | matches options based on their ids. 682 | 683 | * id=option1 684 | 685 | 686 | * \ **index**\ =\ *index*: 687 | matches an option based on its index (offset from zero). 688 | 689 | * index=2 690 | 691 | 692 | 693 | 694 | 695 | If no option locator prefix is provided, the default behaviour is to match on \ **label**\ . 696 | 697 | 698 | 699 | 'selectLocator' is an element locator identifying a drop-down menu 700 | 'optionLocator' is an option locator (a label by default) 701 | """ 702 | self.do_command("select", [selectLocator,optionLocator,]) 703 | 704 | 705 | def add_selection(self,locator,optionLocator): 706 | """ 707 | Add a selection to the set of selected options in a multi-select element using an option locator. 708 | 709 | @see #doSelect for details of option locators 710 | 711 | 'locator' is an element locator identifying a multi-select box 712 | 'optionLocator' is an option locator (a label by default) 713 | """ 714 | self.do_command("addSelection", [locator,optionLocator,]) 715 | 716 | 717 | def remove_selection(self,locator,optionLocator): 718 | """ 719 | Remove a selection from the set of selected options in a multi-select element using an option locator. 720 | 721 | @see #doSelect for details of option locators 722 | 723 | 'locator' is an element locator identifying a multi-select box 724 | 'optionLocator' is an option locator (a label by default) 725 | """ 726 | self.do_command("removeSelection", [locator,optionLocator,]) 727 | 728 | 729 | def remove_all_selections(self,locator): 730 | """ 731 | Unselects all of the selected options in a multi-select element. 732 | 733 | 'locator' is an element locator identifying a multi-select box 734 | """ 735 | self.do_command("removeAllSelections", [locator,]) 736 | 737 | 738 | def submit(self,formLocator): 739 | """ 740 | Submit the specified form. This is particularly useful for forms without 741 | submit buttons, e.g. single-input "Search" forms. 742 | 743 | 'formLocator' is an element locator for the form you want to submit 744 | """ 745 | self.do_command("submit", [formLocator,]) 746 | 747 | 748 | def open(self,url): 749 | """ 750 | Opens an URL in the test frame. This accepts both relative and absolute 751 | URLs. 752 | 753 | The "open" command waits for the page to load before proceeding, 754 | ie. the "AndWait" suffix is implicit. 755 | 756 | \ *Note*: The URL must be on the same domain as the runner HTML 757 | due to security restrictions in the browser (Same Origin Policy). If you 758 | need to open an URL on another domain, use the Selenium Server to start a 759 | new browser session on that domain. 760 | 761 | 'url' is the URL to open; may be relative or absolute 762 | """ 763 | self.do_command("open", [url,]) 764 | 765 | 766 | def open_window(self,url,windowID): 767 | """ 768 | Opens a popup window (if a window with that ID isn't already open). 769 | After opening the window, you'll need to select it using the selectWindow 770 | command. 771 | 772 | 773 | This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). 774 | In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using 775 | an empty (blank) url, like this: openWindow("", "myFunnyWindow"). 776 | 777 | 778 | 'url' is the URL to open, which can be blank 779 | 'windowID' is the JavaScript window ID of the window to select 780 | """ 781 | self.do_command("openWindow", [url,windowID,]) 782 | 783 | 784 | def select_window(self,windowID): 785 | """ 786 | Selects a popup window using a window locator; once a popup window has been selected, all 787 | commands go to that window. To select the main window again, use null 788 | as the target. 789 | 790 | 791 | 792 | 793 | Window locators provide different ways of specifying the window object: 794 | by title, by internal JavaScript "name," or by JavaScript variable. 795 | 796 | 797 | * \ **title**\ =\ *My Special Window*: 798 | Finds the window using the text that appears in the title bar. Be careful; 799 | two windows can share the same title. If that happens, this locator will 800 | just pick one. 801 | 802 | * \ **name**\ =\ *myWindow*: 803 | Finds the window using its internal JavaScript "name" property. This is the second 804 | parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag) 805 | (which Selenium intercepts). 806 | 807 | * \ **var**\ =\ *variableName*: 808 | Some pop-up windows are unnamed (anonymous), but are associated with a JavaScript variable name in the current 809 | application window, e.g. "window.foo = window.open(url);". In those cases, you can open the window using 810 | "var=foo". 811 | 812 | 813 | 814 | 815 | If no window locator prefix is provided, we'll try to guess what you mean like this: 816 | 817 | 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser). 818 | 819 | 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed 820 | that this variable contains the return value from a call to the JavaScript window.open() method. 821 | 822 | 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names". 823 | 824 | 4.) If \ *that* fails, we'll try looping over all of the known windows to try to find the appropriate "title". 825 | Since "title" is not necessarily unique, this may have unexpected behavior. 826 | 827 | If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log messages 828 | which identify the names of windows created via window.open (and therefore intercepted by Selenium). You will see messages 829 | like the following for each window as it is opened: 830 | 831 | ``debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"`` 832 | 833 | In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). 834 | (This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using 835 | an empty (blank) url, like this: openWindow("", "myFunnyWindow"). 836 | 837 | 838 | 'windowID' is the JavaScript window ID of the window to select 839 | """ 840 | self.do_command("selectWindow", [windowID,]) 841 | 842 | 843 | def select_pop_up(self,windowID): 844 | """ 845 | Simplifies the process of selecting a popup window (and does not offer 846 | functionality beyond what ``selectWindow()`` already provides). 847 | 848 | * If ``windowID`` is either not specified, or specified as 849 | "null", the first non-top window is selected. The top window is the one 850 | that would be selected by ``selectWindow()`` without providing a 851 | ``windowID`` . This should not be used when more than one popup 852 | window is in play. 853 | * Otherwise, the window will be looked up considering 854 | ``windowID`` as the following in order: 1) the "name" of the 855 | window, as specified to ``window.open()``; 2) a javascript 856 | variable which is a reference to a window; and 3) the title of the 857 | window. This is the same ordered lookup performed by 858 | ``selectWindow`` . 859 | 860 | 861 | 862 | 'windowID' is an identifier for the popup window, which can take on a number of different meanings 863 | """ 864 | self.do_command("selectPopUp", [windowID,]) 865 | 866 | 867 | def deselect_pop_up(self): 868 | """ 869 | Selects the main window. Functionally equivalent to using 870 | ``selectWindow()`` and specifying no value for 871 | ``windowID``. 872 | 873 | """ 874 | self.do_command("deselectPopUp", []) 875 | 876 | 877 | def select_frame(self,locator): 878 | """ 879 | Selects a frame within the current window. (You may invoke this command 880 | multiple times to select nested frames.) To select the parent frame, use 881 | "relative=parent" as a locator; to select the top frame, use "relative=top". 882 | You can also select a frame by its 0-based index number; select the first frame with 883 | "index=0", or the third frame with "index=2". 884 | 885 | 886 | You may also use a DOM expression to identify the frame you want directly, 887 | like this: ``dom=frames["main"].frames["subframe"]`` 888 | 889 | 890 | 'locator' is an element locator identifying a frame or iframe 891 | """ 892 | self.do_command("selectFrame", [locator,]) 893 | 894 | 895 | def get_whether_this_frame_match_frame_expression(self,currentFrameString,target): 896 | """ 897 | Determine whether current/locator identify the frame containing this running code. 898 | 899 | 900 | This is useful in proxy injection mode, where this code runs in every 901 | browser frame and window, and sometimes the selenium server needs to identify 902 | the "current" frame. In this case, when the test calls selectFrame, this 903 | routine is called for each frame to figure out which one has been selected. 904 | The selected frame will return true, while all others will return false. 905 | 906 | 907 | 'currentFrameString' is starting frame 908 | 'target' is new frame (which might be relative to the current one) 909 | """ 910 | return self.get_boolean("getWhetherThisFrameMatchFrameExpression", [currentFrameString,target,]) 911 | 912 | 913 | def get_whether_this_window_match_window_expression(self,currentWindowString,target): 914 | """ 915 | Determine whether currentWindowString plus target identify the window containing this running code. 916 | 917 | 918 | This is useful in proxy injection mode, where this code runs in every 919 | browser frame and window, and sometimes the selenium server needs to identify 920 | the "current" window. In this case, when the test calls selectWindow, this 921 | routine is called for each window to figure out which one has been selected. 922 | The selected window will return true, while all others will return false. 923 | 924 | 925 | 'currentWindowString' is starting window 926 | 'target' is new window (which might be relative to the current one, e.g., "_parent") 927 | """ 928 | return self.get_boolean("getWhetherThisWindowMatchWindowExpression", [currentWindowString,target,]) 929 | 930 | 931 | def wait_for_pop_up(self,windowID,timeout): 932 | """ 933 | Waits for a popup window to appear and load up. 934 | 935 | 'windowID' is the JavaScript window "name" of the window that will appear (not the text of the title bar) If unspecified, or specified as "null", this command will wait for the first non-top window to appear (don't rely on this if you are working with multiple popups simultaneously). 936 | 'timeout' is a timeout in milliseconds, after which the action will return with an error. If this value is not specified, the default Selenium timeout will be used. See the setTimeout() command. 937 | """ 938 | self.do_command("waitForPopUp", [windowID,timeout,]) 939 | 940 | 941 | def choose_cancel_on_next_confirmation(self): 942 | """ 943 | 944 | 945 | By default, Selenium's overridden window.confirm() function will 946 | return true, as if the user had manually clicked OK; after running 947 | this command, the next call to confirm() will return false, as if 948 | the user had clicked Cancel. Selenium will then resume using the 949 | default behavior for future confirmations, automatically returning 950 | true (OK) unless/until you explicitly call this command for each 951 | confirmation. 952 | 953 | 954 | 955 | Take note - every time a confirmation comes up, you must 956 | consume it with a corresponding getConfirmation, or else 957 | the next selenium operation will fail. 958 | 959 | 960 | 961 | """ 962 | self.do_command("chooseCancelOnNextConfirmation", []) 963 | 964 | 965 | def choose_ok_on_next_confirmation(self): 966 | """ 967 | 968 | 969 | Undo the effect of calling chooseCancelOnNextConfirmation. Note 970 | that Selenium's overridden window.confirm() function will normally automatically 971 | return true, as if the user had manually clicked OK, so you shouldn't 972 | need to use this command unless for some reason you need to change 973 | your mind prior to the next confirmation. After any confirmation, Selenium will resume using the 974 | default behavior for future confirmations, automatically returning 975 | true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each 976 | confirmation. 977 | 978 | 979 | 980 | Take note - every time a confirmation comes up, you must 981 | consume it with a corresponding getConfirmation, or else 982 | the next selenium operation will fail. 983 | 984 | 985 | 986 | """ 987 | self.do_command("chooseOkOnNextConfirmation", []) 988 | 989 | 990 | def answer_on_next_prompt(self,answer): 991 | """ 992 | Instructs Selenium to return the specified answer string in response to 993 | the next JavaScript prompt [window.prompt()]. 994 | 995 | 'answer' is the answer to give in response to the prompt pop-up 996 | """ 997 | self.do_command("answerOnNextPrompt", [answer,]) 998 | 999 | 1000 | def go_back(self): 1001 | """ 1002 | Simulates the user clicking the "back" button on their browser. 1003 | 1004 | """ 1005 | self.do_command("goBack", []) 1006 | 1007 | 1008 | def refresh(self): 1009 | """ 1010 | Simulates the user clicking the "Refresh" button on their browser. 1011 | 1012 | """ 1013 | self.do_command("refresh", []) 1014 | 1015 | 1016 | def close(self): 1017 | """ 1018 | Simulates the user clicking the "close" button in the titlebar of a popup 1019 | window or tab. 1020 | 1021 | """ 1022 | self.do_command("close", []) 1023 | 1024 | 1025 | def is_alert_present(self): 1026 | """ 1027 | Has an alert occurred? 1028 | 1029 | 1030 | 1031 | This function never throws an exception 1032 | 1033 | 1034 | 1035 | """ 1036 | return self.get_boolean("isAlertPresent", []) 1037 | 1038 | 1039 | def is_prompt_present(self): 1040 | """ 1041 | Has a prompt occurred? 1042 | 1043 | 1044 | 1045 | This function never throws an exception 1046 | 1047 | 1048 | 1049 | """ 1050 | return self.get_boolean("isPromptPresent", []) 1051 | 1052 | 1053 | def is_confirmation_present(self): 1054 | """ 1055 | Has confirm() been called? 1056 | 1057 | 1058 | 1059 | This function never throws an exception 1060 | 1061 | 1062 | 1063 | """ 1064 | return self.get_boolean("isConfirmationPresent", []) 1065 | 1066 | 1067 | def get_alert(self): 1068 | """ 1069 | Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts. 1070 | 1071 | 1072 | Getting an alert has the same effect as manually clicking OK. If an 1073 | alert is generated but you do not consume it with getAlert, the next Selenium action 1074 | will fail. 1075 | 1076 | Under Selenium, JavaScript alerts will NOT pop up a visible alert 1077 | dialog. 1078 | 1079 | Selenium does NOT support JavaScript alerts that are generated in a 1080 | page's onload() event handler. In this case a visible dialog WILL be 1081 | generated and Selenium will hang until someone manually clicks OK. 1082 | 1083 | 1084 | """ 1085 | return self.get_string("getAlert", []) 1086 | 1087 | 1088 | def get_confirmation(self): 1089 | """ 1090 | Retrieves the message of a JavaScript confirmation dialog generated during 1091 | the previous action. 1092 | 1093 | 1094 | 1095 | By default, the confirm function will return true, having the same effect 1096 | as manually clicking OK. This can be changed by prior execution of the 1097 | chooseCancelOnNextConfirmation command. 1098 | 1099 | 1100 | 1101 | If an confirmation is generated but you do not consume it with getConfirmation, 1102 | the next Selenium action will fail. 1103 | 1104 | 1105 | 1106 | NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible 1107 | dialog. 1108 | 1109 | 1110 | 1111 | NOTE: Selenium does NOT support JavaScript confirmations that are 1112 | generated in a page's onload() event handler. In this case a visible 1113 | dialog WILL be generated and Selenium will hang until you manually click 1114 | OK. 1115 | 1116 | 1117 | 1118 | """ 1119 | return self.get_string("getConfirmation", []) 1120 | 1121 | 1122 | def get_prompt(self): 1123 | """ 1124 | Retrieves the message of a JavaScript question prompt dialog generated during 1125 | the previous action. 1126 | 1127 | 1128 | Successful handling of the prompt requires prior execution of the 1129 | answerOnNextPrompt command. If a prompt is generated but you 1130 | do not get/verify it, the next Selenium action will fail. 1131 | 1132 | NOTE: under Selenium, JavaScript prompts will NOT pop up a visible 1133 | dialog. 1134 | 1135 | NOTE: Selenium does NOT support JavaScript prompts that are generated in a 1136 | page's onload() event handler. In this case a visible dialog WILL be 1137 | generated and Selenium will hang until someone manually clicks OK. 1138 | 1139 | 1140 | """ 1141 | return self.get_string("getPrompt", []) 1142 | 1143 | 1144 | def get_location(self): 1145 | """ 1146 | Gets the absolute URL of the current page. 1147 | 1148 | """ 1149 | return self.get_string("getLocation", []) 1150 | 1151 | 1152 | def get_title(self): 1153 | """ 1154 | Gets the title of the current page. 1155 | 1156 | """ 1157 | return self.get_string("getTitle", []) 1158 | 1159 | 1160 | def get_body_text(self): 1161 | """ 1162 | Gets the entire text of the page. 1163 | 1164 | """ 1165 | return self.get_string("getBodyText", []) 1166 | 1167 | 1168 | def get_value(self,locator): 1169 | """ 1170 | Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter). 1171 | For checkbox/radio elements, the value will be "on" or "off" depending on 1172 | whether the element is checked or not. 1173 | 1174 | 'locator' is an element locator 1175 | """ 1176 | return self.get_string("getValue", [locator,]) 1177 | 1178 | 1179 | def get_text(self,locator): 1180 | """ 1181 | Gets the text of an element. This works for any element that contains 1182 | text. This command uses either the textContent (Mozilla-like browsers) or 1183 | the innerText (IE-like browsers) of the element, which is the rendered 1184 | text shown to the user. 1185 | 1186 | 'locator' is an element locator 1187 | """ 1188 | return self.get_string("getText", [locator,]) 1189 | 1190 | 1191 | def highlight(self,locator): 1192 | """ 1193 | Briefly changes the backgroundColor of the specified element yellow. Useful for debugging. 1194 | 1195 | 'locator' is an element locator 1196 | """ 1197 | self.do_command("highlight", [locator,]) 1198 | 1199 | 1200 | def get_eval(self,script): 1201 | """ 1202 | Gets the result of evaluating the specified JavaScript snippet. The snippet may 1203 | have multiple lines, but only the result of the last line will be returned. 1204 | 1205 | 1206 | Note that, by default, the snippet will run in the context of the "selenium" 1207 | object itself, so ``this`` will refer to the Selenium object. Use ``window`` to 1208 | refer to the window of your application, e.g. ``window.document.getElementById('foo')`` 1209 | 1210 | If you need to use 1211 | a locator to refer to a single element in your application page, you can 1212 | use ``this.browserbot.findElement("id=foo")`` where "id=foo" is your locator. 1213 | 1214 | 1215 | 'script' is the JavaScript snippet to run 1216 | """ 1217 | return self.get_string("getEval", [script,]) 1218 | 1219 | 1220 | def is_checked(self,locator): 1221 | """ 1222 | Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button. 1223 | 1224 | 'locator' is an element locator pointing to a checkbox or radio button 1225 | """ 1226 | return self.get_boolean("isChecked", [locator,]) 1227 | 1228 | 1229 | def get_table(self,tableCellAddress): 1230 | """ 1231 | Gets the text from a cell of a table. The cellAddress syntax 1232 | tableLocator.row.column, where row and column start at 0. 1233 | 1234 | 'tableCellAddress' is a cell address, e.g. "foo.1.4" 1235 | """ 1236 | return self.get_string("getTable", [tableCellAddress,]) 1237 | 1238 | 1239 | def get_selected_labels(self,selectLocator): 1240 | """ 1241 | Gets all option labels (visible text) for selected options in the specified select or multi-select element. 1242 | 1243 | 'selectLocator' is an element locator identifying a drop-down menu 1244 | """ 1245 | return self.get_string_array("getSelectedLabels", [selectLocator,]) 1246 | 1247 | 1248 | def get_selected_label(self,selectLocator): 1249 | """ 1250 | Gets option label (visible text) for selected option in the specified select element. 1251 | 1252 | 'selectLocator' is an element locator identifying a drop-down menu 1253 | """ 1254 | return self.get_string("getSelectedLabel", [selectLocator,]) 1255 | 1256 | 1257 | def get_selected_values(self,selectLocator): 1258 | """ 1259 | Gets all option values (value attributes) for selected options in the specified select or multi-select element. 1260 | 1261 | 'selectLocator' is an element locator identifying a drop-down menu 1262 | """ 1263 | return self.get_string_array("getSelectedValues", [selectLocator,]) 1264 | 1265 | 1266 | def get_selected_value(self,selectLocator): 1267 | """ 1268 | Gets option value (value attribute) for selected option in the specified select element. 1269 | 1270 | 'selectLocator' is an element locator identifying a drop-down menu 1271 | """ 1272 | return self.get_string("getSelectedValue", [selectLocator,]) 1273 | 1274 | 1275 | def get_selected_indexes(self,selectLocator): 1276 | """ 1277 | Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element. 1278 | 1279 | 'selectLocator' is an element locator identifying a drop-down menu 1280 | """ 1281 | return self.get_string_array("getSelectedIndexes", [selectLocator,]) 1282 | 1283 | 1284 | def get_selected_index(self,selectLocator): 1285 | """ 1286 | Gets option index (option number, starting at 0) for selected option in the specified select element. 1287 | 1288 | 'selectLocator' is an element locator identifying a drop-down menu 1289 | """ 1290 | return self.get_string("getSelectedIndex", [selectLocator,]) 1291 | 1292 | 1293 | def get_selected_ids(self,selectLocator): 1294 | """ 1295 | Gets all option element IDs for selected options in the specified select or multi-select element. 1296 | 1297 | 'selectLocator' is an element locator identifying a drop-down menu 1298 | """ 1299 | return self.get_string_array("getSelectedIds", [selectLocator,]) 1300 | 1301 | 1302 | def get_selected_id(self,selectLocator): 1303 | """ 1304 | Gets option element ID for selected option in the specified select element. 1305 | 1306 | 'selectLocator' is an element locator identifying a drop-down menu 1307 | """ 1308 | return self.get_string("getSelectedId", [selectLocator,]) 1309 | 1310 | 1311 | def is_something_selected(self,selectLocator): 1312 | """ 1313 | Determines whether some option in a drop-down menu is selected. 1314 | 1315 | 'selectLocator' is an element locator identifying a drop-down menu 1316 | """ 1317 | return self.get_boolean("isSomethingSelected", [selectLocator,]) 1318 | 1319 | 1320 | def get_select_options(self,selectLocator): 1321 | """ 1322 | Gets all option labels in the specified select drop-down. 1323 | 1324 | 'selectLocator' is an element locator identifying a drop-down menu 1325 | """ 1326 | return self.get_string_array("getSelectOptions", [selectLocator,]) 1327 | 1328 | 1329 | def get_attribute(self,attributeLocator): 1330 | """ 1331 | Gets the value of an element attribute. The value of the attribute may 1332 | differ across browsers (this is the case for the "style" attribute, for 1333 | example). 1334 | 1335 | 'attributeLocator' is an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar" 1336 | """ 1337 | return self.get_string("getAttribute", [attributeLocator,]) 1338 | 1339 | 1340 | def is_text_present(self,pattern): 1341 | """ 1342 | Verifies that the specified text pattern appears somewhere on the rendered page shown to the user. 1343 | 1344 | 'pattern' is a pattern to match with the text of the page 1345 | """ 1346 | return self.get_boolean("isTextPresent", [pattern,]) 1347 | 1348 | 1349 | def is_element_present(self,locator): 1350 | """ 1351 | Verifies that the specified element is somewhere on the page. 1352 | 1353 | 'locator' is an element locator 1354 | """ 1355 | return self.get_boolean("isElementPresent", [locator,]) 1356 | 1357 | 1358 | def is_visible(self,locator): 1359 | """ 1360 | Determines if the specified element is visible. An 1361 | element can be rendered invisible by setting the CSS "visibility" 1362 | property to "hidden", or the "display" property to "none", either for the 1363 | element itself or one if its ancestors. This method will fail if 1364 | the element is not present. 1365 | 1366 | 'locator' is an element locator 1367 | """ 1368 | return self.get_boolean("isVisible", [locator,]) 1369 | 1370 | 1371 | def is_editable(self,locator): 1372 | """ 1373 | Determines whether the specified input element is editable, ie hasn't been disabled. 1374 | This method will fail if the specified element isn't an input element. 1375 | 1376 | 'locator' is an element locator 1377 | """ 1378 | return self.get_boolean("isEditable", [locator,]) 1379 | 1380 | 1381 | def get_all_buttons(self): 1382 | """ 1383 | Returns the IDs of all buttons on the page. 1384 | 1385 | 1386 | If a given button has no ID, it will appear as "" in this array. 1387 | 1388 | 1389 | """ 1390 | return self.get_string_array("getAllButtons", []) 1391 | 1392 | 1393 | def get_all_links(self): 1394 | """ 1395 | Returns the IDs of all links on the page. 1396 | 1397 | 1398 | If a given link has no ID, it will appear as "" in this array. 1399 | 1400 | 1401 | """ 1402 | return self.get_string_array("getAllLinks", []) 1403 | 1404 | 1405 | def get_all_fields(self): 1406 | """ 1407 | Returns the IDs of all input fields on the page. 1408 | 1409 | 1410 | If a given field has no ID, it will appear as "" in this array. 1411 | 1412 | 1413 | """ 1414 | return self.get_string_array("getAllFields", []) 1415 | 1416 | 1417 | def get_attribute_from_all_windows(self,attributeName): 1418 | """ 1419 | Returns every instance of some attribute from all known windows. 1420 | 1421 | 'attributeName' is name of an attribute on the windows 1422 | """ 1423 | return self.get_string_array("getAttributeFromAllWindows", [attributeName,]) 1424 | 1425 | 1426 | def dragdrop(self,locator,movementsString): 1427 | """ 1428 | deprecated - use dragAndDrop instead 1429 | 1430 | 'locator' is an element locator 1431 | 'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" 1432 | """ 1433 | self.do_command("dragdrop", [locator,movementsString,]) 1434 | 1435 | 1436 | def set_mouse_speed(self,pixels): 1437 | """ 1438 | Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10). 1439 | 1440 | Setting this value to 0 means that we'll send a "mousemove" event to every single pixel 1441 | in between the start location and the end location; that can be very slow, and may 1442 | cause some browsers to force the JavaScript to timeout. 1443 | 1444 | If the mouse speed is greater than the distance between the two dragged objects, we'll 1445 | just send one "mousemove" at the start location and then one final one at the end location. 1446 | 1447 | 1448 | 'pixels' is the number of pixels between "mousemove" events 1449 | """ 1450 | self.do_command("setMouseSpeed", [pixels,]) 1451 | 1452 | 1453 | def get_mouse_speed(self): 1454 | """ 1455 | Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10). 1456 | 1457 | """ 1458 | return self.get_number("getMouseSpeed", []) 1459 | 1460 | 1461 | def drag_and_drop(self,locator,movementsString): 1462 | """ 1463 | Drags an element a certain distance and then drops it 1464 | 1465 | 'locator' is an element locator 1466 | 'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" 1467 | """ 1468 | self.do_command("dragAndDrop", [locator,movementsString,]) 1469 | 1470 | 1471 | def drag_and_drop_to_object(self,locatorOfObjectToBeDragged,locatorOfDragDestinationObject): 1472 | """ 1473 | Drags an element and drops it on another element 1474 | 1475 | 'locatorOfObjectToBeDragged' is an element to be dragged 1476 | 'locatorOfDragDestinationObject' is an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped 1477 | """ 1478 | self.do_command("dragAndDropToObject", [locatorOfObjectToBeDragged,locatorOfDragDestinationObject,]) 1479 | 1480 | 1481 | def window_focus(self): 1482 | """ 1483 | Gives focus to the currently selected window 1484 | 1485 | """ 1486 | self.do_command("windowFocus", []) 1487 | 1488 | 1489 | def window_maximize(self): 1490 | """ 1491 | Resize currently selected window to take up the entire screen 1492 | 1493 | """ 1494 | self.do_command("windowMaximize", []) 1495 | 1496 | 1497 | def get_all_window_ids(self): 1498 | """ 1499 | Returns the IDs of all windows that the browser knows about. 1500 | 1501 | """ 1502 | return self.get_string_array("getAllWindowIds", []) 1503 | 1504 | 1505 | def get_all_window_names(self): 1506 | """ 1507 | Returns the names of all windows that the browser knows about. 1508 | 1509 | """ 1510 | return self.get_string_array("getAllWindowNames", []) 1511 | 1512 | 1513 | def get_all_window_titles(self): 1514 | """ 1515 | Returns the titles of all windows that the browser knows about. 1516 | 1517 | """ 1518 | return self.get_string_array("getAllWindowTitles", []) 1519 | 1520 | 1521 | def get_html_source(self): 1522 | """ 1523 | Returns the entire HTML source between the opening and 1524 | closing "html" tags. 1525 | 1526 | """ 1527 | return self.get_string("getHtmlSource", []) 1528 | 1529 | 1530 | def set_cursor_position(self,locator,position): 1531 | """ 1532 | Moves the text cursor to the specified position in the given input element or textarea. 1533 | This method will fail if the specified element isn't an input element or textarea. 1534 | 1535 | 'locator' is an element locator pointing to an input element or textarea 1536 | 'position' is the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field. 1537 | """ 1538 | self.do_command("setCursorPosition", [locator,position,]) 1539 | 1540 | 1541 | def get_element_index(self,locator): 1542 | """ 1543 | Get the relative index of an element to its parent (starting from 0). The comment node and empty text node 1544 | will be ignored. 1545 | 1546 | 'locator' is an element locator pointing to an element 1547 | """ 1548 | return self.get_number("getElementIndex", [locator,]) 1549 | 1550 | 1551 | def is_ordered(self,locator1,locator2): 1552 | """ 1553 | Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will 1554 | not be considered ordered. 1555 | 1556 | 'locator1' is an element locator pointing to the first element 1557 | 'locator2' is an element locator pointing to the second element 1558 | """ 1559 | return self.get_boolean("isOrdered", [locator1,locator2,]) 1560 | 1561 | 1562 | def get_element_position_left(self,locator): 1563 | """ 1564 | Retrieves the horizontal position of an element 1565 | 1566 | 'locator' is an element locator pointing to an element OR an element itself 1567 | """ 1568 | return self.get_number("getElementPositionLeft", [locator,]) 1569 | 1570 | 1571 | def get_element_position_top(self,locator): 1572 | """ 1573 | Retrieves the vertical position of an element 1574 | 1575 | 'locator' is an element locator pointing to an element OR an element itself 1576 | """ 1577 | return self.get_number("getElementPositionTop", [locator,]) 1578 | 1579 | 1580 | def get_element_width(self,locator): 1581 | """ 1582 | Retrieves the width of an element 1583 | 1584 | 'locator' is an element locator pointing to an element 1585 | """ 1586 | return self.get_number("getElementWidth", [locator,]) 1587 | 1588 | 1589 | def get_element_height(self,locator): 1590 | """ 1591 | Retrieves the height of an element 1592 | 1593 | 'locator' is an element locator pointing to an element 1594 | """ 1595 | return self.get_number("getElementHeight", [locator,]) 1596 | 1597 | 1598 | def get_cursor_position(self,locator): 1599 | """ 1600 | Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers. 1601 | 1602 | 1603 | Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to 1604 | return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as SEL-243. 1605 | 1606 | This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element. 1607 | 1608 | 'locator' is an element locator pointing to an input element or textarea 1609 | """ 1610 | return self.get_number("getCursorPosition", [locator,]) 1611 | 1612 | 1613 | def get_expression(self,expression): 1614 | """ 1615 | Returns the specified expression. 1616 | 1617 | 1618 | This is useful because of JavaScript preprocessing. 1619 | It is used to generate commands like assertExpression and waitForExpression. 1620 | 1621 | 1622 | 'expression' is the value to return 1623 | """ 1624 | return self.get_string("getExpression", [expression,]) 1625 | 1626 | 1627 | def get_xpath_count(self,xpath): 1628 | """ 1629 | Returns the number of nodes that match the specified xpath, eg. "//table" would give 1630 | the number of tables. 1631 | 1632 | 'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you. 1633 | """ 1634 | return self.get_number("getXpathCount", [xpath,]) 1635 | 1636 | 1637 | def assign_id(self,locator,identifier): 1638 | """ 1639 | Temporarily sets the "id" attribute of the specified element, so you can locate it in the future 1640 | using its ID rather than a slow/complicated XPath. This ID will disappear once the page is 1641 | reloaded. 1642 | 1643 | 'locator' is an element locator pointing to an element 1644 | 'identifier' is a string to be used as the ID of the specified element 1645 | """ 1646 | self.do_command("assignId", [locator,identifier,]) 1647 | 1648 | 1649 | def allow_native_xpath(self,allow): 1650 | """ 1651 | Specifies whether Selenium should use the native in-browser implementation 1652 | of XPath (if any native version is available); if you pass "false" to 1653 | this function, we will always use our pure-JavaScript xpath library. 1654 | Using the pure-JS xpath library can improve the consistency of xpath 1655 | element locators between different browser vendors, but the pure-JS 1656 | version is much slower than the native implementations. 1657 | 1658 | 'allow' is boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath 1659 | """ 1660 | self.do_command("allowNativeXpath", [allow,]) 1661 | 1662 | 1663 | def ignore_attributes_without_value(self,ignore): 1664 | """ 1665 | Specifies whether Selenium will ignore xpath attributes that have no 1666 | value, i.e. are the empty string, when using the non-native xpath 1667 | evaluation engine. You'd want to do this for performance reasons in IE. 1668 | However, this could break certain xpaths, for example an xpath that looks 1669 | for an attribute whose value is NOT the empty string. 1670 | 1671 | The hope is that such xpaths are relatively rare, but the user should 1672 | have the option of using them. Note that this only influences xpath 1673 | evaluation when using the ajaxslt engine (i.e. not "javascript-xpath"). 1674 | 1675 | 'ignore' is boolean, true means we'll ignore attributes without value at the expense of xpath "correctness"; false means we'll sacrifice speed for correctness. 1676 | """ 1677 | self.do_command("ignoreAttributesWithoutValue", [ignore,]) 1678 | 1679 | 1680 | def wait_for_condition(self,script,timeout): 1681 | """ 1682 | Runs the specified JavaScript snippet repeatedly until it evaluates to "true". 1683 | The snippet may have multiple lines, but only the result of the last line 1684 | will be considered. 1685 | 1686 | 1687 | Note that, by default, the snippet will be run in the runner's test window, not in the window 1688 | of your application. To get the window of your application, you can use 1689 | the JavaScript snippet ``selenium.browserbot.getCurrentWindow()``, and then 1690 | run your JavaScript in there 1691 | 1692 | 1693 | 'script' is the JavaScript snippet to run 1694 | 'timeout' is a timeout in milliseconds, after which this command will return with an error 1695 | """ 1696 | self.do_command("waitForCondition", [script,timeout,]) 1697 | 1698 | 1699 | def set_timeout(self,timeout): 1700 | """ 1701 | Specifies the amount of time that Selenium will wait for actions to complete. 1702 | 1703 | 1704 | Actions that require waiting include "open" and the "waitFor\*" actions. 1705 | 1706 | The default timeout is 30 seconds. 1707 | 1708 | 'timeout' is a timeout in milliseconds, after which the action will return with an error 1709 | """ 1710 | self.do_command("setTimeout", [timeout,]) 1711 | 1712 | 1713 | def wait_for_page_to_load(self,timeout): 1714 | """ 1715 | Waits for a new page to load. 1716 | 1717 | 1718 | You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc. 1719 | (which are only available in the JS API). 1720 | 1721 | Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded" 1722 | flag when it first notices a page load. Running any other Selenium command after 1723 | turns the flag to false. Hence, if you want to wait for a page to load, you must 1724 | wait immediately after a Selenium command that caused a page-load. 1725 | 1726 | 1727 | 'timeout' is a timeout in milliseconds, after which this command will return with an error 1728 | """ 1729 | self.do_command("waitForPageToLoad", [timeout,]) 1730 | 1731 | 1732 | def wait_for_frame_to_load(self,frameAddress,timeout): 1733 | """ 1734 | Waits for a new frame to load. 1735 | 1736 | 1737 | Selenium constantly keeps track of new pages and frames loading, 1738 | and sets a "newPageLoaded" flag when it first notices a page load. 1739 | 1740 | 1741 | See waitForPageToLoad for more information. 1742 | 1743 | 'frameAddress' is FrameAddress from the server side 1744 | 'timeout' is a timeout in milliseconds, after which this command will return with an error 1745 | """ 1746 | self.do_command("waitForFrameToLoad", [frameAddress,timeout,]) 1747 | 1748 | 1749 | def get_cookie(self): 1750 | """ 1751 | Return all cookies of the current page under test. 1752 | 1753 | """ 1754 | return self.get_string("getCookie", []) 1755 | 1756 | 1757 | def get_cookie_by_name(self,name): 1758 | """ 1759 | Returns the value of the cookie with the specified name, or throws an error if the cookie is not present. 1760 | 1761 | 'name' is the name of the cookie 1762 | """ 1763 | return self.get_string("getCookieByName", [name,]) 1764 | 1765 | 1766 | def is_cookie_present(self,name): 1767 | """ 1768 | Returns true if a cookie with the specified name is present, or false otherwise. 1769 | 1770 | 'name' is the name of the cookie 1771 | """ 1772 | return self.get_boolean("isCookiePresent", [name,]) 1773 | 1774 | 1775 | def create_cookie(self,nameValuePair,optionsString): 1776 | """ 1777 | Create a new cookie whose path and domain are same with those of current page 1778 | under test, unless you specified a path for this cookie explicitly. 1779 | 1780 | 'nameValuePair' is name and value of the cookie in a format "name=value" 1781 | 'optionsString' is options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail. 1782 | """ 1783 | self.do_command("createCookie", [nameValuePair,optionsString,]) 1784 | 1785 | 1786 | def delete_cookie(self,name,optionsString): 1787 | """ 1788 | Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you 1789 | need to delete it using the exact same path and domain that were used to create the cookie. 1790 | If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also 1791 | note that specifying a domain that isn't a subset of the current domain will usually fail. 1792 | 1793 | Since there's no way to discover at runtime the original path and domain of a given cookie, 1794 | we've added an option called 'recurse' to try all sub-domains of the current domain with 1795 | all paths that are a subset of the current path. Beware; this option can be slow. In 1796 | big-O notation, it operates in O(n\*m) time, where n is the number of dots in the domain 1797 | name and m is the number of slashes in the path. 1798 | 1799 | 'name' is the name of the cookie to be deleted 1800 | 'optionsString' is options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail. 1801 | """ 1802 | self.do_command("deleteCookie", [name,optionsString,]) 1803 | 1804 | 1805 | def delete_all_visible_cookies(self): 1806 | """ 1807 | Calls deleteCookie with recurse=true on all cookies visible to the current page. 1808 | As noted on the documentation for deleteCookie, recurse=true can be much slower 1809 | than simply deleting the cookies using a known domain/path. 1810 | 1811 | """ 1812 | self.do_command("deleteAllVisibleCookies", []) 1813 | 1814 | 1815 | def set_browser_log_level(self,logLevel): 1816 | """ 1817 | Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded. 1818 | Valid logLevel strings are: "debug", "info", "warn", "error" or "off". 1819 | To see the browser logs, you need to 1820 | either show the log window in GUI mode, or enable browser-side logging in Selenium RC. 1821 | 1822 | 'logLevel' is one of the following: "debug", "info", "warn", "error" or "off" 1823 | """ 1824 | self.do_command("setBrowserLogLevel", [logLevel,]) 1825 | 1826 | 1827 | def run_script(self,script): 1828 | """ 1829 | Creates a new "script" tag in the body of the current test window, and 1830 | adds the specified text into the body of the command. Scripts run in 1831 | this way can often be debugged more easily than scripts executed using 1832 | Selenium's "getEval" command. Beware that JS exceptions thrown in these script 1833 | tags aren't managed by Selenium, so you should probably wrap your script 1834 | in try/catch blocks if there is any chance that the script will throw 1835 | an exception. 1836 | 1837 | 'script' is the JavaScript snippet to run 1838 | """ 1839 | self.do_command("runScript", [script,]) 1840 | 1841 | 1842 | def add_location_strategy(self,strategyName,functionDefinition): 1843 | """ 1844 | Defines a new function for Selenium to locate elements on the page. 1845 | For example, 1846 | if you define the strategy "foo", and someone runs click("foo=blah"), we'll 1847 | run your function, passing you the string "blah", and click on the element 1848 | that your function 1849 | returns, or throw an "Element not found" error if your function returns null. 1850 | 1851 | We'll pass three arguments to your function: 1852 | 1853 | * locator: the string the user passed in 1854 | * inWindow: the currently selected window 1855 | * inDocument: the currently selected document 1856 | 1857 | 1858 | The function must return null if the element can't be found. 1859 | 1860 | 'strategyName' is the name of the strategy to define; this should use only letters [a-zA-Z] with no spaces or other punctuation. 1861 | 'functionDefinition' is a string defining the body of a function in JavaScript. For example: ``return inDocument.getElementById(locator);`` 1862 | """ 1863 | self.do_command("addLocationStrategy", [strategyName,functionDefinition,]) 1864 | 1865 | 1866 | def capture_entire_page_screenshot(self,filename,kwargs): 1867 | """ 1868 | Saves the entire contents of the current window canvas to a PNG file. 1869 | Contrast this with the captureScreenshot command, which captures the 1870 | contents of the OS viewport (i.e. whatever is currently being displayed 1871 | on the monitor), and is implemented in the RC only. Currently this only 1872 | works in Firefox when running in chrome mode, and in IE non-HTA using 1873 | the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly 1874 | borrowed from the Screengrab! Firefox extension. Please see 1875 | http://www.screengrab.org and http://snapsie.sourceforge.net/ for 1876 | details. 1877 | 1878 | 'filename' is the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code. 1879 | 'kwargs' is a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid options: 1880 | * background 1881 | the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text). 1882 | 1883 | 1884 | """ 1885 | self.do_command("captureEntirePageScreenshot", [filename,kwargs,]) 1886 | 1887 | 1888 | def rollup(self,rollupName,kwargs): 1889 | """ 1890 | Executes a command rollup, which is a series of commands with a unique 1891 | name, and optionally arguments that control the generation of the set of 1892 | commands. If any one of the rolled-up commands fails, the rollup is 1893 | considered to have failed. Rollups may also contain nested rollups. 1894 | 1895 | 'rollupName' is the name of the rollup command 1896 | 'kwargs' is keyword arguments string that influences how the rollup expands into commands 1897 | """ 1898 | self.do_command("rollup", [rollupName,kwargs,]) 1899 | 1900 | 1901 | def add_script(self,scriptContent,scriptTagId): 1902 | """ 1903 | Loads script content into a new script tag in the Selenium document. This 1904 | differs from the runScript command in that runScript adds the script tag 1905 | to the document of the AUT, not the Selenium document. The following 1906 | entities in the script content are replaced by the characters they 1907 | represent: 1908 | 1909 | < 1910 | > 1911 | & 1912 | 1913 | The corresponding remove command is removeScript. 1914 | 1915 | 'scriptContent' is the Javascript content of the script to add 1916 | 'scriptTagId' is (optional) the id of the new script tag. If specified, and an element with this id already exists, this operation will fail. 1917 | """ 1918 | self.do_command("addScript", [scriptContent,scriptTagId,]) 1919 | 1920 | 1921 | def remove_script(self,scriptTagId): 1922 | """ 1923 | Removes a script tag from the Selenium document identified by the given 1924 | id. Does nothing if the referenced tag doesn't exist. 1925 | 1926 | 'scriptTagId' is the id of the script element to remove. 1927 | """ 1928 | self.do_command("removeScript", [scriptTagId,]) 1929 | 1930 | 1931 | def use_xpath_library(self,libraryName): 1932 | """ 1933 | Allows choice of one of the available libraries. 1934 | 1935 | 'libraryName' is name of the desired library Only the following three can be chosen: 1936 | * "ajaxslt" - Google's library 1937 | * "javascript-xpath" - Cybozu Labs' faster library 1938 | * "default" - The default library. Currently the default library is "ajaxslt" . 1939 | 1940 | If libraryName isn't one of these three, then no change will be made. 1941 | """ 1942 | self.do_command("useXpathLibrary", [libraryName,]) 1943 | 1944 | 1945 | def set_context(self,context): 1946 | """ 1947 | Writes a message to the status bar and adds a note to the browser-side 1948 | log. 1949 | 1950 | 'context' is the message to be sent to the browser 1951 | """ 1952 | self.do_command("setContext", [context,]) 1953 | 1954 | 1955 | def attach_file(self,fieldLocator,fileLocator): 1956 | """ 1957 | Sets a file input (upload) field to the file listed in fileLocator 1958 | 1959 | 'fieldLocator' is an element locator 1960 | 'fileLocator' is a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator), Selenium RC may need to transfer the file to the local machine before attaching the file in a web page form. This is common in selenium grid configurations where the RC server driving the browser is not the same machine that started the test. Supported Browsers: Firefox ("\*chrome") only. 1961 | """ 1962 | self.do_command("attachFile", [fieldLocator,fileLocator,]) 1963 | 1964 | 1965 | def capture_screenshot(self,filename): 1966 | """ 1967 | Captures a PNG screenshot to the specified file. 1968 | 1969 | 'filename' is the absolute path to the file to be written, e.g. "c:\blah\screenshot.png" 1970 | """ 1971 | self.do_command("captureScreenshot", [filename,]) 1972 | 1973 | 1974 | def capture_screenshot_to_string(self): 1975 | """ 1976 | Capture a PNG screenshot. It then returns the file as a base 64 encoded string. 1977 | 1978 | """ 1979 | return self.get_string("captureScreenshotToString", []) 1980 | 1981 | 1982 | def captureNetworkTraffic(self, type): 1983 | """ 1984 | Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings. When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since the last call. 1985 | 1986 | 'type' is The type of data to return the network traffic as. Valid values are: json, xml, or plain. 1987 | """ 1988 | return self.get_string("captureNetworkTraffic", [type,]) 1989 | 1990 | def addCustomRequestHeader(self, key, value): 1991 | """ 1992 | Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only works if the browser is configured to use the built in Selenium proxy. 1993 | 1994 | 'key' the header name. 1995 | 'value' the header value. 1996 | """ 1997 | return self.do_command("addCustomRequestHeader", [key,value,]) 1998 | 1999 | def capture_entire_page_screenshot_to_string(self,kwargs): 2000 | """ 2001 | Downloads a screenshot of the browser current window canvas to a 2002 | based 64 encoded PNG file. The \ *entire* windows canvas is captured, 2003 | including parts rendered outside of the current view port. 2004 | 2005 | Currently this only works in Mozilla and when running in chrome mode. 2006 | 2007 | 'kwargs' is A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text). 2008 | """ 2009 | return self.get_string("captureEntirePageScreenshotToString", [kwargs,]) 2010 | 2011 | 2012 | def shut_down_selenium_server(self): 2013 | """ 2014 | Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be able to send 2015 | commands to the server; you can't remotely start the server once it has been stopped. Normally 2016 | you should prefer to run the "stop" command, which terminates the current browser session, rather than 2017 | shutting down the entire server. 2018 | 2019 | """ 2020 | self.do_command("shutDownSeleniumServer", []) 2021 | 2022 | 2023 | def retrieve_last_remote_control_logs(self): 2024 | """ 2025 | Retrieve the last messages logged on a specific remote control. Useful for error reports, especially 2026 | when running multiple remote controls in a distributed environment. The maximum number of log messages 2027 | that can be retrieve is configured on remote control startup. 2028 | 2029 | """ 2030 | return self.get_string("retrieveLastRemoteControlLogs", []) 2031 | 2032 | 2033 | def key_down_native(self,keycode): 2034 | """ 2035 | Simulates a user pressing a key (without releasing it yet) by sending a native operating system keystroke. 2036 | This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing 2037 | a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and 2038 | metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular 2039 | element, focus on the element first before running this command. 2040 | 2041 | 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! 2042 | """ 2043 | self.do_command("keyDownNative", [keycode,]) 2044 | 2045 | 2046 | def key_up_native(self,keycode): 2047 | """ 2048 | Simulates a user releasing a key by sending a native operating system keystroke. 2049 | This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing 2050 | a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and 2051 | metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular 2052 | element, focus on the element first before running this command. 2053 | 2054 | 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! 2055 | """ 2056 | self.do_command("keyUpNative", [keycode,]) 2057 | 2058 | 2059 | def key_press_native(self,keycode): 2060 | """ 2061 | Simulates a user pressing and releasing a key by sending a native operating system keystroke. 2062 | This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing 2063 | a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and 2064 | metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular 2065 | element, focus on the element first before running this command. 2066 | 2067 | 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! 2068 | """ 2069 | self.do_command("keyPressNative", [keycode,]) 2070 | 2071 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | django-nose-selenium 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A plugin to run selenium smoothly with nose. 7 | 8 | 9 | :copyright: 2010, Pascal Hartig 10 | :license: BSD, see LICENSE for more details 11 | """ 12 | 13 | import os 14 | from setuptools import setup 15 | from noseselenium import __version__ 16 | 17 | 18 | def read(fname): 19 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 20 | 21 | 22 | setup( 23 | name="django-nose-selenium", 24 | version=__version__, 25 | author="Pascal Hartig", 26 | author_email="phartig@weluse.de", 27 | description="A nose plugin to run selenium tests with django", 28 | long_description=read('README.rst'), 29 | url="http://github.com/weluse/django-nose-selenium", 30 | packages=['noseselenium', 'noseselenium.thirdparty'], 31 | requires=['Django (>=1.2)', 'nose (>=0.10)'], 32 | classifiers=[ 33 | "Development Status :: 4 - Beta", 34 | "Intended Audience :: Developers", 35 | "Programming Language :: Python :: 2.6", 36 | "Topic :: Software Development :: Testing", 37 | "Topic :: Software Development :: Libraries :: Python Modules" 38 | ], 39 | entry_points={ 40 | 'nose.plugins.0.10': [ 41 | 'selenium = noseselenium.plugins:SeleniumPlugin', 42 | 'selenium_fixtures = noseselenium.plugins:SeleniumFixturesPlugin', 43 | 'cherrypyliveserver = noseselenium.plugins:CherryPyLiveServerPlugin', 44 | 'djangoliveserver = noseselenium.plugins:DjangoLiveServerPlugin' 45 | ] 46 | } 47 | ) 48 | --------------------------------------------------------------------------------