marionette_driver package

Submodules

marionette_driver.addons module

class marionette_driver.addons.Addons(marionette)

Bases: object

An API for installing and inspecting addons during Gecko runtime. This is a partially implemented wrapper around Gecko’s AddonManager API.

For example:

from marionette_driver.addons import Addons
addons = Addons(marionette)
addons.install("/path/to/extension.xpi")
install(path, temp=False)

Install a Firefox addon.

If the addon is restartless, it can be used right away. Otherwise a restart using restart() will be needed.

Parameters:
  • path – A file path to the extension to be installed.
  • temp – Install a temporary addon. Temporary addons will automatically be uninstalled on shutdown and do not need to be signed, though they must be restartless.
Returns:

The addon ID string of the newly installed addon.

Raises:

AddonInstallException

uninstall(addon_id)

Uninstall a Firefox addon.

If the addon is restartless, it will be uninstalled right away. Otherwise a restart using restart() will be needed.

If the call to uninstall is resulting in a ScriptTimeoutException, an invalid ID is likely being passed in. Unfortunately due to AddonManager’s implementation, it’s hard to retrieve this error from Python.

Parameters:addon_id – The addon ID string to uninstall.
exception marionette_driver.addons.AddonInstallException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

marionette_driver.by module

class marionette_driver.by.By

Bases: object

CLASS_NAME = 'class name'
CSS_SELECTOR = 'css selector'
ID = 'id'
NAME = 'name'
TAG_NAME = 'tag name'
XPATH = 'xpath'

marionette_driver.date_time_value module

class marionette_driver.date_time_value.DateTimeValue(element)

Bases: object

Interface for setting the value of HTML5 “date” and “time” input elements.

Simple usage example:

element = marionette.find_element(By.ID, "date-test")
dt_value = DateTimeValue(element)
dt_value.date = datetime(1998, 6, 2)
date

Retrieve the element’s string value

time

Retrieve the element’s string value

marionette_driver.decorators module

marionette_driver.decorators.do_process_check(func)

Decorator which checks the process status after the function has run.

marionette_driver.decorators.uses_marionette(func)

Decorator which creates a marionette session and deletes it afterwards if one doesn’t already exist.

marionette_driver.decorators.using_context(context)

Decorator which allows a function to execute in certain scope using marionette.using_context functionality and returns to old scope once the function exits. :param context: Either ‘chrome’ or ‘content’.

marionette_driver.errors module

exception marionette_driver.errors.ElementClickInterceptedException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'element click intercepted'
exception marionette_driver.errors.ElementNotAccessibleException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'element not accessible'
exception marionette_driver.errors.ElementNotInteractableException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'element not interactable'
exception marionette_driver.errors.ElementNotSelectableException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'element not selectable'
exception marionette_driver.errors.ElementNotVisibleException(message='Element is not currently visible and may not be manipulated', stacktrace=None, cause=None)

Bases: marionette_driver.errors.MarionetteException

Deprecated. Will be removed with the release of Firefox 54.

status = 'element not visible'
exception marionette_driver.errors.InsecureCertificateException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'insecure certificate'
exception marionette_driver.errors.InvalidArgumentException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid argument'
exception marionette_driver.errors.InvalidCookieDomainException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid cookie domain'
exception marionette_driver.errors.InvalidElementCoordinates(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid element coordinates'
exception marionette_driver.errors.InvalidElementStateException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid element state'
exception marionette_driver.errors.InvalidSelectorException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid selector'
exception marionette_driver.errors.InvalidSessionIdException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'invalid session id'
exception marionette_driver.errors.JavascriptException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'javascript error'
exception marionette_driver.errors.MarionetteException(message=None, cause=None, stacktrace=None)

Bases: exceptions.Exception

Raised when a generic non-recoverable exception has occured.

status = 'webdriver error'
exception marionette_driver.errors.MoveTargetOutOfBoundsException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'move target out of bounds'
exception marionette_driver.errors.NoAlertPresentException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'no such alert'
exception marionette_driver.errors.NoSuchElementException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'no such element'
exception marionette_driver.errors.NoSuchFrameException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'no such frame'
exception marionette_driver.errors.NoSuchWindowException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'no such window'
exception marionette_driver.errors.ScriptTimeoutException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'script timeout'
exception marionette_driver.errors.SessionNotCreatedException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'session not created'
exception marionette_driver.errors.StaleElementException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'stale element reference'
exception marionette_driver.errors.TimeoutException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'timeout'
exception marionette_driver.errors.UnableToSetCookieException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'unable to set cookie'
exception marionette_driver.errors.UnexpectedAlertOpen(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'unexpected alert open'
exception marionette_driver.errors.UnknownCommandException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'unknown command'
exception marionette_driver.errors.UnknownException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'unknown error'
exception marionette_driver.errors.UnresponsiveInstanceException

Bases: exceptions.Exception

exception marionette_driver.errors.UnsupportedOperationException(message=None, cause=None, stacktrace=None)

Bases: marionette_driver.errors.MarionetteException

status = 'unsupported operation'
marionette_driver.errors.e

alias of marionette_driver.errors.SessionNotCreatedException

marionette_driver.errors.lookup(identifier)

Finds error exception class by associated Selenium JSON wire protocol number code, or W3C WebDriver protocol string.

marionette_driver.expected module

class marionette_driver.expected.element_displayed(*args)

Bases: object

An expectation for checking that an element is visible.

Visibility means that the element is not only displayed, but also has a height and width that is greater than 0 pixels.

Stale elements, meaning elements that have been detached from the DOM of the current context are treated as not being displayed, meaning this expectation is not analogous to the behaviour of calling is_displayed() on an HTMLElement.

You can select which element to be checked for visibility by supplying a locator:

displayed = Wait(marionette).until(expected.element_displayed(By.ID, "foo"))

Or by supplying an element:

el = marionette.find_element(By.ID, "foo")
displayed = Wait(marionette).until(expected.element_displayed(el))
Parameters:args – locator or web element
Returns:True if element is displayed, False if hidden
class marionette_driver.expected.element_enabled(element)

Bases: object

An expectation for checking that the given element is enabled.

Parameters:element – the element to check if enabled
Returns:True if element is enabled, False otherwise
class marionette_driver.expected.element_not_displayed(*args)

Bases: marionette_driver.expected.element_displayed

An expectation for checking that an element is not visible.

Visibility means that the element is not only displayed, but also has a height and width that is greater than 0 pixels.

Stale elements, meaning elements that have been detached fom the DOM of the current context are treated as not being displayed, meaning this expectation is not analogous to the behaviour of calling is_displayed() on an HTMLElement.

You can select which element to be checked for visibility by supplying a locator:

hidden = Wait(marionette).until(expected.element_not_displayed(By.ID, "foo"))

Or by supplying an element:

el = marionette.find_element(By.ID, "foo")
hidden = Wait(marionette).until(expected.element_not_displayed(el))
Parameters:args – locator or web element
Returns:True if element is hidden, False if displayed
class marionette_driver.expected.element_not_enabled(element)

Bases: marionette_driver.expected.element_enabled

An expectation for checking that the given element is disabled.

Parameters:element – the element to check if disabled
Returns:True if element is disabled, False if enabled
class marionette_driver.expected.element_not_present(*args)

Bases: marionette_driver.expected.element_present

Checks that a web element is not present in the DOM of the current context.

You can select which element to be checked for lack of presence by supplying a locator:

r = Wait(marionette).until(expected.element_not_present(By.ID, "foo"))

Or by using a function/lambda returning an element:

r = Wait(marionette).until(
    expected.element_present(lambda m: m.find_element(By.ID, "foo")))
Parameters:args – locator or function returning web element
Returns:True if element is not present, or False if it is present
class marionette_driver.expected.element_not_selected(element)

Bases: marionette_driver.expected.element_selected

An expectation for checking that the given element is not selected.

Parameters:element – the element to not be selected
Returns:True if element is not selected, False if selected
class marionette_driver.expected.element_present(*args)

Bases: object

Checks that a web element is present in the DOM of the current context. This does not necessarily mean that the element is visible.

You can select which element to be checked for presence by supplying a locator:

el = Wait(marionette).until(expected.element_present(By.ID, "foo"))

Or by using a function/lambda returning an element:

el = Wait(marionette).until(
    expected.element_present(lambda m: m.find_element(By.ID, "foo")))
Parameters:args – locator or function returning web element
Returns:the web element once it is located, or False
class marionette_driver.expected.element_selected(element)

Bases: object

An expectation for checking that the given element is selected.

Parameters:element – the element to be selected
Returns:True if element is selected, False otherwise
class marionette_driver.expected.element_stale(element)

Bases: object

Check that the given element is no longer attached to DOM of the current context.

This can be useful for waiting until an element is no longer present.

Sample usage:

el = marionette.find_element(By.ID, "foo")
# ...
Wait(marionette).until(expected.element_stale(el))
Parameters:element – the element to wait for
Returns:False if the element is still attached to the DOM, True otherwise
class marionette_driver.expected.elements_not_present(*args)

Bases: marionette_driver.expected.elements_present

Checks that web elements are not present in the DOM of the current context.

You can select which elements to be checked for not being present by supplying a locator:

r = Wait(marionette).until(expected.elements_not_present(By.TAG_NAME, "a"))

Or by using a function/lambda returning a list of elements:

r = Wait(marionette).until(
    expected.elements_not_present(lambda m: m.find_elements(By.TAG_NAME, "a")))
Parameters:args – locator or function returning a list of web elements
Returns:True if elements are missing, False if one or more are present
class marionette_driver.expected.elements_present(*args)

Bases: object

Checks that web elements are present in the DOM of the current context. This does not necessarily mean that the elements are visible.

You can select which elements to be checked for presence by supplying a locator:

els = Wait(marionette).until(expected.elements_present(By.TAG_NAME, "a"))

Or by using a function/lambda returning a list of elements:

els = Wait(marionette).until(
    expected.elements_present(lambda m: m.find_elements(By.TAG_NAME, "a")))
Parameters:args – locator or function returning a list of web elements
Returns:list of web elements once they are located, or False

marionette_driver.geckoinstance module

class marionette_driver.geckoinstance.DesktopInstance(*args, **kwargs)

Bases: marionette_driver.geckoinstance.GeckoInstance

desktop_prefs = {'app.update.auto': False, 'app.update.checkInstallTime': False, 'app.update.disabledForTesting': True, 'browser.EULA.override': True, 'browser.contentblocking.introCount': 99, 'browser.dom.window.dump.enabled': True, 'browser.download.panel.shown': True, 'browser.newtabpage.enabled': False, 'browser.pagethumbnails.capturing_disabled': True, 'browser.safebrowsing.blockedURIs.enabled': False, 'browser.safebrowsing.downloads.enabled': False, 'browser.safebrowsing.malware.enabled': False, 'browser.safebrowsing.passwords.enabled': False, 'browser.safebrowsing.phishing.enabled': False, 'browser.search.update': False, 'browser.sessionstore.resume_from_crash': False, 'browser.shell.checkDefaultBrowser': False, 'browser.startup.homepage_override.mstone': 'ignore', 'browser.startup.page': 0, 'browser.tabs.remote.autostart': False, 'browser.tabs.remote.separatePrivilegedContentProcess': False, 'browser.tabs.unloadOnLowMemory': False, 'browser.tabs.warnOnClose': False, 'browser.tabs.warnOnCloseOtherTabs': False, 'browser.tabs.warnOnOpen': False, 'browser.uitour.enabled': False, 'browser.urlbar.suggest.searches': False, 'browser.warnOnQuit': False, 'devtools.console.stdout.chrome': True, 'startup.homepage_welcome_url': 'about:blank', 'startup.homepage_welcome_url.additional': '', 'toolkit.cosmeticAnimations.enabled': False}
class marionette_driver.geckoinstance.FennecInstance(emulator_binary=None, avd_home=None, avd=None, adb_path=None, serial=None, connect_to_running_emulator=False, package_name=None, env=None, *args, **kwargs)

Bases: marionette_driver.geckoinstance.GeckoInstance

close(clean=False)

Close the managed Gecko process.

If clean is True and the Fennec instance is running in an emulator managed by mozrunner, this will stop the emulator.

Parameters:clean – If True, also perform runner cleanup.
fennec_prefs = {'browser.dom.window.dump.enabled': True, 'browser.safebrowsing.blockedURIs.enabled': False, 'browser.safebrowsing.downloads.enabled': False, 'browser.safebrowsing.malware.enabled': False, 'browser.safebrowsing.passwords.enabled': False, 'browser.safebrowsing.phishing.enabled': False, 'browser.sessionstore.resume_from_crash': False, 'browser.tabs.disableBackgroundZombification': True, 'browser.tabs.remote.autostart': False, 'devtools.console.stdout.chrome': True}
package_name

Name of app to run on emulator.

Note that FennecInstance does not use self.binary

start()
class marionette_driver.geckoinstance.GeckoInstance(host=None, port=None, bin=None, profile=None, addons=None, app_args=None, symbols_path=None, gecko_log=None, prefs=None, workspace=None, verbose=0, headless=False, enable_webrender=False)

Bases: object

close(clean=False)

Close the managed Gecko process.

Depending on self.runner_class, setting clean to True may also kill the emulator process in which this instance is running.

Parameters:clean – If True, also perform runner cleanup.
classmethod create(app=None, *args, **kwargs)
gecko_log
profile
profile_args
required_prefs = {'app.normandy.api_url': '', 'apz.content_response_timeout': 60000, 'datareporting.healthreport.about.reportUrl': 'http://%(server)s/dummy/abouthealthreport/', 'datareporting.healthreport.documentServerURI': 'http://%(server)s/dummy/healthreport/', 'datareporting.policy.dataSubmissionPolicyBypassNotification': True, 'dom.disable_beforeunload': True, 'dom.file.createInChild': True, 'dom.ipc.reportProcessHangs': False, 'dom.max_chrome_script_run_time': 0, 'dom.max_script_run_time': 0, 'dom.push.connection.enabled': False, 'extensions.autoDisableScopes': 0, 'extensions.enabledScopes': 5, 'extensions.getAddons.cache.enabled': False, 'extensions.installDistroAddons': False, 'extensions.update.enabled': False, 'extensions.update.notifyUser': False, 'extensions.webservice.discoverURL': 'http://%(server)s/dummy/discoveryURL', 'focusmanager.testmode': True, 'general.useragent.updates.enabled': False, 'geo.provider.testing': True, 'geo.wifi.scan': False, 'javascript.options.showInConsole': True, 'marionette.defaultPrefs.enabled': True, 'marionette.enabled': True, 'marionette.prefs.recommended': False, 'media.gmp-manager.updateEnabled': False, 'media.volume_scale': '0.01', 'network.http.prompt-temp-redirect': False, 'network.http.speculative-parallel-limit': 0, 'network.manage-offline-status': False, 'network.sntp.pools': '%(server)s', 'privacy.trackingprotection.enabled': False, 'security.certerrors.mitm.priming.enabled': False, 'security.notification_enable_delay': 0, 'services.settings.server': 'http://%(server)s/dummy/blocklist/', 'signon.rememberSignons': False, 'toolkit.startup.max_resumed_crashes': -1, 'toolkit.telemetry.server': 'https://%(server)s/dummy/telemetry/'}
restart(prefs=None, clean=True)

Close then start the managed Gecko process.

Parameters:
  • prefs – Dictionary of preference names and values.
  • clean – If True, reset the profile before starting.
start()
switch_profile(profile_name=None, clone_from=None)

Switch the profile by using the given name, and optionally clone it.

Compared to profile this method allows to switch the profile by giving control over the profile name as used for the new profile. It also always creates a new blank profile, or as clone of an existent one.

Parameters:profile_name – Optional, name of the profile, which will be used as part of the profile path (folder name containing the profile).
Clone_from:Optional, if specified the new profile will be cloned based on the given profile. This argument can be an instance of mozprofile.Profile, or the path of the profile.
class marionette_driver.geckoinstance.NullOutput

Bases: object

class marionette_driver.geckoinstance.ThunderbirdInstance(*args, **kwargs)

Bases: marionette_driver.geckoinstance.GeckoInstance

marionette_driver.gestures module

marionette_driver.gestures.long_press_without_contextmenu(marionette_session, element, time_in_seconds, x=None, y=None)
Parameters:
  • element – The element to press.
  • time_in_seconds – Time in seconds to wait before releasing the press.

#x: Optional, x-coordinate to tap, relative to the top-left corner of the element. #y: Optional, y-coordinate to tap, relative to the top-leftcorner of the element.

marionette_driver.gestures.pinch(marionette_session, element, x1, y1, x2, y2, x3, y3, x4, y4, duration=200)
Parameters:
  • element – target
  • y1 (x1,) – 1st finger starting position relative to the target
  • y3 (x3,) – 1st finger ending position relative to the target
  • y2 (x2,) – 2nd finger starting position relative to the target
  • y4 (x4,) – 2nd finger ending position relative to the target
  • duration – Amount of time in milliseconds to complete the pinch.
marionette_driver.gestures.smooth_scroll(marionette_session, start_element, axis, direction, length, increments=None, wait_period=None, scroll_back=None)
Parameters:
  • axis – y or x
  • direction – 0 for positive, and -1 for negative
  • length – total length of scroll scroll
  • increments – Amount to be moved per scrolling
  • wait_period – Seconds to wait between scrolling
  • scroll_back – Scroll back to original view?

marionette_driver.keys module

class marionette_driver.keys.Keys

Bases: object

ADD = u'\ue025'
ALT = u'\ue00a'
ARROW_DOWN = u'\ue015'
ARROW_LEFT = u'\ue012'
ARROW_RIGHT = u'\ue014'
ARROW_UP = u'\ue013'
BACK_SPACE = u'\ue003'
CANCEL = u'\ue001'
CLEAR = u'\ue005'
COMMAND = u'\ue03d'
CONTROL = u'\ue009'
DECIMAL = u'\ue028'
DELETE = u'\ue017'
DIVIDE = u'\ue029'
DOWN = u'\ue015'
END = u'\ue010'
ENTER = u'\ue007'
EQUALS = u'\ue019'
ESCAPE = u'\ue00c'
F1 = u'\ue031'
F10 = u'\ue03a'
F11 = u'\ue03b'
F12 = u'\ue03c'
F2 = u'\ue032'
F3 = u'\ue033'
F4 = u'\ue034'
F5 = u'\ue035'
F6 = u'\ue036'
F7 = u'\ue037'
F8 = u'\ue038'
F9 = u'\ue039'
HELP = u'\ue002'
HOME = u'\ue011'
INSERT = u'\ue016'
LEFT = u'\ue012'
LEFT_ALT = u'\ue00a'
LEFT_CONTROL = u'\ue009'
LEFT_SHIFT = u'\ue008'
META = u'\ue03d'
MULTIPLY = u'\ue024'
NULL = u'\ue000'
NUMPAD0 = u'\ue01a'
NUMPAD1 = u'\ue01b'
NUMPAD2 = u'\ue01c'
NUMPAD3 = u'\ue01d'
NUMPAD4 = u'\ue01e'
NUMPAD5 = u'\ue01f'
NUMPAD6 = u'\ue020'
NUMPAD7 = u'\ue021'
NUMPAD8 = u'\ue022'
NUMPAD9 = u'\ue023'
PAGE_DOWN = u'\ue00f'
PAGE_UP = u'\ue00e'
PAUSE = u'\ue00b'
RETURN = u'\ue006'
RIGHT = u'\ue014'
SEMICOLON = u'\ue018'
SEPARATOR = u'\ue026'
SHIFT = u'\ue008'
SPACE = u'\ue00d'
SUBTRACT = u'\ue027'
TAB = u'\ue004'
UP = u'\ue013'

marionette_driver.legacy_actions module

class marionette_driver.legacy_actions.Actions(marionette)

Bases: object

Represent a set of actions that are executed in a particular order.

All action methods (press, etc.) return the Actions object itself, to make it easy to create a chain of events.

Example usage:

# get html file
testAction = marionette.absolute_url("testFool.html")
# navigate to the file
marionette.navigate(testAction)
# find element1 and element2
element1 = marionette.find_element(By.ID, "element1")
element2 = marionette.find_element(By.ID, "element2")
# create action object
action = Actions(marionette)
# add actions (press, wait, move, release) into the object
action.press(element1).wait(5). move(element2).release()
# fire all the added events
action.perform()
cancel()

Sends ‘touchcancel’ event to the target of the original ‘touchstart’ event.

May only be called if press() has already be called.

click(element, button=0, count=1)

Performs a click with additional parameters to allow for double clicking, right click, middle click, etc.

Parameters:
  • element – The element to click.
  • button – The mouse button to click (indexed from 0, left to right).
  • count – Optional, the count of clicks to synthesize (for double click events).
context_click(element)

Performs a context click on the specified element.

Parameters:element – The element to context click.
double_click(element)

Performs a double click on the specified element.

Parameters:element – The element to double click.
double_tap(element, x=None, y=None)

Performs a double tap on the target element.

Parameters:
  • element – The element to double tap.
  • x – Optional, x-coordinate of double tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate of double tap, relative to the top-left corner of the element.
flick(element, x1, y1, x2, y2, duration=200)

Performs a flick gesture on the target element.

Parameters:
  • element – The element to perform the flick gesture on.
  • x1 – Starting x-coordinate of flick, relative to the top left corner of the element.
  • y1 – Starting y-coordinate of flick, relative to the top left corner of the element.
  • x2 – Ending x-coordinate of flick, relative to the top left corner of the element.
  • y2 – Ending y-coordinate of flick, relative to the top left corner of the element.
  • duration – Time needed for the flick gesture for complete (in milliseconds).
key_down(key_code)

Perform a “keyDown” action for the given key code. Modifier keys are respected by the server for the course of an action chain.

Parameters:key_code – The key to press as a result of this action.
key_up(key_code)

Perform a “keyUp” action for the given key code. Modifier keys are respected by the server for the course of an action chain.

Parameters:key_up – The key to release as a result of this action.
long_press(element, time_in_seconds, x=None, y=None)

Performs a long press gesture on the target element.

Parameters:
  • element – The element to press.
  • time_in_seconds – Time in seconds to wait before releasing the press.
  • x – Optional, x-coordinate to tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate to tap, relative to the top-left corner of the element.

This is equivalent to calling:

action.press(element, x, y).wait(time_in_seconds).release()
middle_click(element)

Performs a middle click on the specified element.

Parameters:element – The element to middle click.
move(element)

Sends a ‘touchmove’ event at the center of the target element.

Parameters:element – Element to move towards.

May only be called if press() has already be called.

move_by_offset(x, y)

Sends ‘touchmove’ event to the given x, y coordinates relative to the top-left of the currently touched element.

May only be called if press() has already be called.

Parameters:
  • x – Specifies x-coordinate of move event, relative to the top-left corner of the element.
  • y – Specifies y-coordinate of move event, relative to the top-left corner of the element.
perform()

Sends the action chain built so far to the server side for execution and clears the current chain of actions.

press(element, x=None, y=None)

Sends a ‘touchstart’ event to this element.

If no coordinates are given, it will be targeted at the center of the element. If given, it will be targeted at the (x,y) coordinates relative to the top-left corner of the element.

Parameters:
  • element – The element to press on.
  • x – Optional, x-coordinate to tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate to tap, relative to the top-left corner of the element.
release()

Sends a ‘touchend’ event to this element.

May only be called if press() has already be called on this element.

If press and release are chained without a move action between them, then it will be processed as a ‘tap’ event, and will dispatch the expected mouse events (‘mousemove’ (if necessary), ‘mousedown’, ‘mouseup’, ‘mouseclick’) after the touch events. If there is a wait period between press and release that will trigger a contextmenu, then the ‘contextmenu’ menu event will be fired instead of the touch/mouse events.

tap(element, x=None, y=None)

Performs a quick tap on the target element.

Parameters:
  • element – The element to tap.
  • x – Optional, x-coordinate of tap, relative to the top-left corner of the element. If not specified, default to center of element.
  • y – Optional, y-coordinate of tap, relative to the top-left corner of the element. If not specified, default to center of element.

This is equivalent to calling:

action.press(element, x, y).release()
wait(time=None)

Waits for specified time period.

Parameters:time – Time in seconds to wait. If time is None then this has no effect for a single action chain. If used inside a multi-action chain, then time being None indicates that we should wait for all other currently executing actions that are part of the chain to complete.
class marionette_driver.legacy_actions.MultiActions(marionette)

Bases: object

Represent a sequence of actions that may be performed at the same time.

Its intent is to allow the simulation of multi-touch gestures.

Usage example:

# create multiaction object
multitouch = MultiActions(marionette)
# create several action objects
action_1 = Actions(marionette)
action_2 = Actions(marionette)
# add actions to each action object/finger
action_1.press(element1).move_to(element2).release()
action_2.press(element3).wait().release(element3)
# fire all the added events
multitouch.add(action_1).add(action_2).perform()
add(action)

Add a set of actions to perform.

Parameters:action – An Actions object.
perform()

Perform all the actions added to this object.

marionette_driver.localization module

class marionette_driver.localization.L10n(marionette)

Bases: object

An API which allows Marionette to handle localized content.

The localization of UI elements in Gecko based applications is done via entities and properties. For static values entities are used, which are located in .dtd files. Whereby for dynamically updated content the values come from .property files. Both types of elements can be identifed via a unique id, and the translated content retrieved.

For example:

from marionette_driver.localization import L10n
l10n = L10n(marionette)

l10n.localize_entity(["chrome://branding/locale/brand.dtd"], "brandShortName")
l10n.localize_property(["chrome://global/locale/findbar.properties"], "FastFind"))
localize_entity(dtd_urls, entity_id)

Retrieve the localized string for the specified entity id.

Parameters:
  • dtd_urls – List of .dtd URLs which will be used to search for the entity.
  • entity_id – ID of the entity to retrieve the localized string for.
Returns:

The localized string for the requested entity.

Raises:

NoSuchElementException

localize_property(properties_urls, property_id)

Retrieve the localized string for the specified property id.

Parameters:
  • properties_urls – List of .properties URLs which will be used to search for the property.
  • property_id – ID of the property to retrieve the localized string for.
Returns:

The localized string for the requested property.

Raises:

NoSuchElementException

marionette_driver.marionette module

class marionette_driver.marionette.ActionSequence(marionette, action_type, input_id, pointer_params=None)

Bases: object

API for creating and performing action sequences.

Each action method adds one or more actions to a queue. When perform() is called, the queued actions fire in order.

May be chained together as in:

ActionSequence(self.marionette, "key", id) \
   .key_down("a") \
   .key_up("a") \
   .perform()
click(element=None, button=0)

Queue a click with the specified button.

If an element is given, move the pointer to that element first, otherwise click current pointer coordinates.

Parameters:
  • element – Optional element to click.
  • button – Integer representing pointer button to perform action with. Default: 0, which represents main device button.
dict
key_down(value)

Queue a keyDown action for value.

Parameters:value – Single character to perform key action with.
key_up(value)

Queue a keyUp action for value.

Parameters:value – Single character to perform key action with.
pause(duration)
perform()

Perform all queued actions.

pointer_down(button=0)

Queue a pointerDown action for button.

Parameters:button – Pointer button to perform action with. Default: 0, which represents main device button.
pointer_move(x, y, duration=None, origin=None)

Queue a pointerMove action.

Parameters:
  • x – Destination x-axis coordinate of pointer in CSS pixels.
  • y – Destination y-axis coordinate of pointer in CSS pixels.
  • duration – Number of milliseconds over which to distribute the move. If None, remote end defaults to 0.
  • origin – Origin of coordinates, either “viewport”, “pointer” or an Element. If None, remote end defaults to “viewport”.
pointer_up(button=0)

Queue a pointerUp action for button.

Parameters:button – Pointer button to perform action with. Default: 0, which represents main device button.
send_keys(keys)

Queue a keyDown and keyUp action for each character in keys.

Parameters:keys – String of keys to perform key actions with.
class marionette_driver.marionette.Actions(marionette)

Bases: object

perform(actions=None)

Perform actions by tick from each action sequence in actions.

Parameters:actions – List of input source action sequences. A single action sequence may be created with the help of ActionSequence.dict.
release()
sequence(*args, **kwargs)

Return an empty ActionSequence of the designated type.

See ActionSequence for parameter list.

class marionette_driver.marionette.Alert(marionette)

Bases: object

A class for interacting with alerts.

Alert(marionette).accept()
Alert(marionette).dismiss()
accept()

Accept a currently displayed modal dialog.

dismiss()

Dismiss a currently displayed modal dialog.

send_keys(*string)

Send keys to the currently displayed text input area in an open tab modal dialog.

text

Return the currently displayed text in a tab modal.

class marionette_driver.marionette.HTMLElement(marionette, id)

Bases: object

Represents a DOM Element.

clear()

Clears the input of the element.

click()

Simulates a click on the element.

find_element(method, target)

Returns an HTMLElement instance that matches the specified method and target, relative to the current element.

For more details on this function, see the find_element() method in the Marionette class.

find_elements(method, target)

Returns a list of all HTMLElement instances that match the specified method and target in the current context.

For more details on this function, see the find_elements() method in the Marionette class.

get_attribute(name)

Returns the requested attribute, or None if no attribute is set.

get_property(name)

Returns the requested property, or None if the property is not set.

identifiers = ('chromeelement-9fc5-4b51-a3c8-01716eedeb04', 'frame-075b-4da1-b6ba-e579c2d3230a', 'window-fcc6-11e5-b4f8-330a88ab9d7f', 'element-6066-11e4-a52e-4f735466cecf')
is_displayed()

Returns True if the element is displayed, False otherwise.

is_enabled()

This command will return False if all the following criteria are met otherwise return True:

  • A form control is disabled.
  • A HTMLElement has a disabled boolean attribute.
is_selected()

Returns True if the element is selected.

rect

Gets the element’s bounding rectangle.

This will return a dictionary with the following:

  • x and y represent the top left coordinates of the HTMLElement relative to top left corner of the document.
  • height and the width will contain the height and the width of the DOMRect of the HTMLElement.
send_keys(*strings)

Sends the string via synthesized keypresses to the element. If an array is passed in like marionette.send_keys(Keys.SHIFT, “a”) it will be joined into a string. If an integer is passed in like marionette.send_keys(1234) it will be coerced into a string.

tag_name

The tag name of the element.

tap(x=None, y=None)

Simulates a set of tap events on the element.

Parameters:
  • x – X coordinate of tap event. If not given, default to the centre of the element.
  • y – Y coordinate of tap event. If not given, default to the centre of the element.
text

Returns the visible text of the element, and its child elements.

value_of_css_property(property_name)

Gets the value of the specified CSS property name.

Parameters:property_name – Property name to get the value of.
class marionette_driver.marionette.Marionette(host='127.0.0.1', port=2828, app=None, bin=None, baseurl=None, socket_timeout=None, startup_timeout=None, **instance_args)

Bases: object

Represents a Marionette connection to a browser or device.

CONTEXT_CHROME = 'chrome'
CONTEXT_CONTENT = 'content'
DEFAULT_SHUTDOWN_TIMEOUT = 70
DEFAULT_SOCKET_TIMEOUT = 360
DEFAULT_STARTUP_TIMEOUT = 120
absolute_url(relative_url)

Returns an absolute url for files served from Marionette’s www directory.

Parameters:relative_url – The url of a static file, relative to Marionette’s www directory.

Adds a cookie to your current session.

Parameters:cookie – A dictionary object, with required keys - “name” and “value”; optional keys - “path”, “domain”, “secure”, “expiry”.

Usage example:

driver.add_cookie({"name": "foo", "value": "bar"})
driver.add_cookie({"name": "foo", "value": "bar", "path": "/"})
driver.add_cookie({"name": "foo", "value": "bar", "path": "/",
                   "secure": True})
check_for_crash()

Check if the process crashed.

Returns:True, if a crash happened since the method has been called the last time.
static check_port_available(port, host='')

Check if “host:port” is available.

Raise socket.error if port is not available.

chrome_window_handles

Get a list of currently open chrome windows.

Each window handle is assigned by the server, and the list of strings returned does not have a guaranteed ordering.

Returns:Unordered list of unique chrome window handles as strings
cleanup()
clear_pref(pref)

Clear the user-defined value from the specified preference.

Parameters:pref – Name of the preference.
close()

Close the current window, ending the session if it’s the last window currently open.

Returns:Unordered list of remaining unique window handles as strings
close_chrome_window()

Close the currently selected chrome window, ending the session if it’s the last window open.

Returns:Unordered list of remaining unique chrome window handles as strings
static convert_keys(*string)
current_chrome_window_handle

Get the current chrome window’s handle. Corresponds to a chrome window that may itself contain tabs identified by window_handles.

Returns an opaque server-assigned identifier to this window that uniquely identifies it within this Marionette instance. This can be used to switch to this window at a later point.

Returns:unique window handle
Return type:string
current_window_handle

Get the current window’s handle.

Returns an opaque server-assigned identifier to this window that uniquely identifies it within this Marionette instance. This can be used to switch to this window at a later point.

Returns:unique window handle
Return type:string
delete_all_cookies()

Delete all cookies in the scope of the current session.

Usage example:

driver.delete_all_cookies()

Delete a cookie by its name.

Parameters:name – Name of cookie to delete.

Usage example:

driver.delete_cookie("foo")
delete_session(send_request=True)

Close the current session and disconnect from the server.

Parameters:send_request – Optional, if True a request to close the session on the server side will be sent. Use False in case of eg. in_app restart() or quit(), which trigger a deletion themselves. Defaults to True.
enforce_gecko_prefs(**kwargs)

Checks if the running instance has the given prefs. If not, it will kill the currently running instance, and spawn a new instance with the requested preferences.

Parameters:prefs – A dictionary whose keys are preference names.
execute_async_script(script, script_args=(), new_sandbox=True, sandbox='default', script_timeout=None)

Executes an asynchronous JavaScript script, and returns the result (or None if the script does return a value).

The script is executed in the context set by the most recent set_context() call, or to the CONTEXT_CONTENT context if set_context() has not been called.

Parameters:
  • script – A string containing the JavaScript to execute.
  • script_args – An interable of arguments to pass to the script.
  • new_sandbox – If False, preserve global variables from the last execute_*script call. This is True by default, in which case no globals are preserved.
  • sandbox – A tag referring to the sandbox you wish to use; if you specify a new tag, a new sandbox will be created. If you use the special tag system, the sandbox will be created using the system principal which has elevated privileges.
  • script_timeout – Timeout in milliseconds, overriding the session’s default script timeout.

Usage example:

marionette.timeout.script = 10
result = self.marionette.execute_async_script('''
  // this script waits 5 seconds, and then returns the number 1
  let [resolve] = arguments;
  setTimeout(function() {
    resolve(1);
  }, 5000);
''')
assert result == 1
execute_script(script, script_args=(), new_sandbox=True, sandbox='default', script_timeout=None)

Executes a synchronous JavaScript script, and returns the result (or None if the script does return a value).

The script is executed in the context set by the most recent set_context() call, or to the CONTEXT_CONTENT context if set_context() has not been called.

Parameters:
  • script – A string containing the JavaScript to execute.
  • script_args – An interable of arguments to pass to the script.
  • new_sandbox – If False, preserve global variables from the last execute_*script call. This is True by default, in which case no globals are preserved.
  • sandbox – A tag referring to the sandbox you wish to use; if you specify a new tag, a new sandbox will be created. If you use the special tag system, the sandbox will be created using the system principal which has elevated privileges.
  • script_timeout – Timeout in milliseconds, overriding the session’s default script timeout.

Simple usage example:

result = marionette.execute_script("return 1;")
assert result == 1

You can use the script_args parameter to pass arguments to the script:

result = marionette.execute_script("return arguments[0] + arguments[1];",
                                   script_args=(2, 3,))
assert result == 5
some_element = marionette.find_element(By.ID, "someElement")
sid = marionette.execute_script("return arguments[0].id;", script_args=(some_element,))
assert some_element.get_attribute("id") == sid

Scripts wishing to access non-standard properties of the window object must use window.wrappedJSObject:

result = marionette.execute_script('''
  window.wrappedJSObject.test1 = "foo";
  window.wrappedJSObject.test2 = "bar";
  return window.wrappedJSObject.test1 + window.wrappedJSObject.test2;
  ''')
assert result == "foobar"

Global variables set by individual scripts do not persist between script calls by default. If you wish to persist data between script calls, you can set new_sandbox to False on your next call, and add any new variables to a new ‘global’ object like this:

marionette.execute_script("global.test1 = 'foo';")
result = self.marionette.execute_script("return global.test1;", new_sandbox=False)
assert result == "foo"
find_element(method, target, id=None)

Returns an HTMLElement instance that matches the specified method and target in the current context.

An HTMLElement instance may be used to call other methods on the element, such as click(). If no element is immediately found, the attempt to locate an element will be repeated for up to the amount of time set by marionette_driver.timeout.Timeouts.implicit. If multiple elements match the given criteria, only the first is returned. If no element matches, a NoSuchElementException will be raised.

Parameters:
  • method – The method to use to locate the element; one of: “id”, “name”, “class name”, “tag name”, “css selector”, “link text”, “partial link text” and “xpath”. Note that the “name”, “link text” and “partial link test” methods are not supported in the chrome DOM.
  • target – The target of the search. For example, if method = “tag”, target might equal “div”. If method = “id”, target would be an element id.
  • id – If specified, search for elements only inside the element with the specified id.
find_elements(method, target, id=None)

Returns a list of all HTMLElement instances that match the specified method and target in the current context.

An HTMLElement instance may be used to call other methods on the element, such as click(). If no element is immediately found, the attempt to locate an element will be repeated for up to the amount of time set by marionette_driver.timeout.Timeouts.implicit.

Parameters:
  • method – The method to use to locate the elements; one of: “id”, “name”, “class name”, “tag name”, “css selector”, “link text”, “partial link text” and “xpath”. Note that the “name”, “link text” and “partial link test” methods are not supported in the chrome DOM.
  • target – The target of the search. For example, if method = “tag”, target might equal “div”. If method = “id”, target would be an element id.
  • id – If specified, search for elements only inside the element with the specified id.
fullscreen()

Synchronously sets the user agent window to full screen as if the user had done “View > Enter Full Screen”, or restores it if it is already in full screen.

Returns:Window rect.
get_active_element()
get_active_frame()

Returns an HTMLElement representing the frame Marionette is currently acting on.

Get a single cookie by name. Returns the cookie if found, None if not.

Parameters:name – Name of cookie to get.
get_cookies()

Get all the cookies for the current domain.

This is the equivalent of calling document.cookie and parsing the result.

Returns:A list of cookies for the current domain.
get_pref(pref, default_branch=False, value_type='unspecified')

Get the value of the specified preference.

Parameters:
  • pref – Name of the preference.
  • default_branch – Optional, if True the preference value will be read from the default branch. Otherwise the user-defined value if set is returned. Defaults to False.
  • value_type – Optional, XPCOM interface of the pref’s complex value. Possible values are: nsIFile and nsIPrefLocalizedString.

Usage example:

marionette.get_pref("browser.tabs.warnOnClose")
get_url()

Get a string representing the current URL.

On Desktop this returns a string representation of the URL of the current top level browsing context. This is equivalent to document.location.href.

When in the context of the chrome, this returns the canonical URL of the current resource.

Returns:string representation of URL
get_window_type()

Gets the windowtype attribute of the window Marionette is currently acting on.

This command only makes sense in a chrome context. You might use this method to distinguish a browser window from an editor window.

go_back()

Causes the browser to perform a back navigation.

go_forward()

Causes the browser to perform a forward navigation.

maximize_window()

Resize the browser window currently receiving commands. The action should be equivalent to the user pressing the maximize button in the OS window.

Note that this command is not available on Fennec. It may also not be available in certain window managers.

Returns:Window rect.
minimize_window()

Iconify the browser window currently receiving commands. The action should be equivalent to the user pressing the minimize button in the OS window.

Note that this command is not available on Fennec. It may also not be available in certain window managers.

:returns Window rect.

navigate(url)

Navigate to given url.

Navigates the current top-level browsing context’s content frame to the given URL and waits for the document to load or the session’s page timeout duration to elapse before returning.

The command will return with a failure if there is an error loading the document or the URL is blocked. This can occur if it fails to reach the host, the URL is malformed, the page is restricted (about:* pages), or if there is a certificate issue to name some examples.

The document is considered successfully loaded when the DOMContentLoaded event on the frame element associated with the window triggers and document.readyState is “complete”.

In chrome context it will change the current window’s location to the supplied URL and wait until document.readyState equals “complete” or the page timeout duration has elapsed.

Parameters:url – The URL to navigate to.
open(type=None, focus=False)

Open a new window, or tab based on the specified context type.

If no context type is given the application will choose the best option based on tab and window support.

Parameters:
  • type – Type of window to be opened. Can be one of “tab” or “window”
  • focus – If true, the opened window will be focused
Returns:

Dict with new window handle, and type of opened window

orientation

Get the current browser orientation.

Will return one of the valid primary orientation values portrait-primary, landscape-primary, portrait-secondary, or landscape-secondary.

page_source

A string representation of the DOM.

profile_path
quit(**kwargs)

Terminate the currently running instance.

This command will delete the active marionette session. It also allows manipulation of eg. the profile data while the application is not running. To start the application again, start_session() has to be called.

Parameters:
  • clean – If False the same profile will be used after the next start of the application. Note that the in app initiated restart always maintains the same profile.
  • in_app – If True, marionette will cause a quit from within the browser. Otherwise the browser will be quit immediately by killing the process.
  • callback – If provided and in_app is True, the callback will be used to trigger the shutdown.
raise_for_port(timeout=None, check_process_status=True)

Raise socket.timeout if no connection can be established.

Parameters:
  • timeout – Optional timeout in seconds for the server to be ready.
  • check_process_status – Optional, if True the process will be continuously checked if it has exited, and the connection attempt will be aborted.
refresh()

Causes the browser to perform to refresh the current page.

restart(**kwargs)

This will terminate the currently running instance, and spawn a new instance with the same profile and then reuse the session id when creating a session again.

Parameters:
  • clean – If False the same profile will be used after the restart. Note that the in app initiated restart always maintains the same profile.
  • in_app – If True, marionette will cause a restart from within the browser. Otherwise the browser will be restarted immediately by killing the process.
  • callback – If provided and in_app is True, the callback will be used to trigger the restart.
save_screenshot(fh, element=None, full=True, scroll=True)

Takes a screenhot of a web element or the current frame and saves it in the filehandle.

It is a wrapper around screenshot() :param fh: The filehandle to save the screenshot at.

The rest of the parameters are defined like in screenshot()

screenshot(element=None, format='base64', full=True, scroll=True)

Takes a screenshot of a web element or the current frame.

The screen capture is returned as a lossless PNG image encoded as a base 64 string by default. If the element argument is defined the capture area will be limited to the bounding box of that element. Otherwise, the capture area will be the bounding box of the current frame.

Parameters:
  • element – The element to take a screenshot of. If None, will take a screenshot of the current frame.
  • format – if “base64” (the default), returns the screenshot as a base64-string. If “binary”, the data is decoded and returned as raw binary. If “hash”, the data is hashed using the SHA-256 algorithm and the result is returned as a hex digest.
  • full – If True (the default), the capture area will be the complete frame. Else only the viewport is captured. Only applies when element is None.
  • scroll – When element is provided, scroll to it before taking the screenshot (default). Otherwise, avoid scrolling element into view.
session_capabilities

A JSON dictionary representing the capabilities of the current session.

set_context(context)

Sets the context that Marionette commands are running in.

Parameters:context – Context, may be one of the class properties CONTEXT_CHROME or CONTEXT_CONTENT.

Usage example:

marionette.set_context(marionette.CONTEXT_CHROME)
set_orientation(orientation)

Set the current browser orientation.

The supplied orientation should be given as one of the valid orientation values. If the orientation is unknown, an error will be raised.

Valid orientations are “portrait” and “landscape”, which fall back to “portrait-primary” and “landscape-primary” respectively, and “portrait-secondary” as well as “landscape-secondary”.

Parameters:orientation – The orientation to lock the screen in.
set_pref(pref, value, default_branch=False)

Set the value of the specified preference.

Parameters:
  • pref – Name of the preference.
  • value – The value to set the preference to. If the value is None, reset the preference to its default value. If no default value exists, the preference will cease to exist.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

marionette.set_pref("browser.tabs.warnOnClose", True)
set_prefs(prefs, default_branch=False)

Set the value of a list of preferences.

Parameters:
  • prefs – A dict containing one or more preferences and their values to be set. See set_pref() for further details.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

marionette.set_prefs({"browser.tabs.warnOnClose": True})
set_window_rect(x=None, y=None, height=None, width=None)

Set the position and size of the current window.

The supplied width and height values refer to the window outerWidth and outerHeight values, which include scroll bars, title bars, etc.

An error will be returned if the requested window size would result in the window being in the maximised state.

Parameters:
  • x – x coordinate for the top left of the window
  • y – y coordinate for the top left of the window
  • width – The width to resize the window to.
  • height – The height to resize the window to.
start_binary(timeout)
start_session(**kwargs)

Create a new WebDriver session. This method must be called before performing any other action.

Parameters:
  • capabilities – An optional dictionary of Marionette-recognised capabilities. It does not accept a WebDriver conforming capabilities dictionary (including alwaysMatch, firstMatch, desiredCapabilities, or requriedCapabilities), and only recognises extension capabilities that are specific to Marionette.
  • timeout – Optional timeout in seconds for the server to be ready.
Returns:

A dictionary of the capabilities offered.

switch_to_alert()

Returns an Alert object for interacting with a currently displayed alert.

alert = self.marionette.switch_to_alert()
text = alert.text
alert.accept()
switch_to_default_content()

Switch the current context to page’s default content.

switch_to_frame(frame=None, focus=True)

Switch the current context to the specified frame. Subsequent commands will operate in the context of the specified frame, if applicable.

Parameters:
  • frame – A reference to the frame to switch to. This can be an HTMLElement, an integer index, string name, or an ID attribute. If you call switch_to_frame without an argument, it will switch to the top-level frame.
  • focus – A boolean value which determins whether to focus the frame that we just switched to.
switch_to_parent_frame()

Switch to the Parent Frame

switch_to_shadow_root(host=None)

Switch the current context to the specified host’s Shadow DOM. Subsequent commands will operate in the context of the specified Shadow DOM, if applicable.

Parameters:host – A reference to the host element containing Shadow DOM. This can be an HTMLElement. If you call switch_to_shadow_root without an argument, it will switch to the parent Shadow DOM or the top-level frame.
switch_to_window(handle, focus=True)

Switch to the specified window; subsequent commands will be directed at the new window.

Parameters:
  • handle – The id or name of the window to switch to.
  • focus – A boolean value which determins whether to focus the window that we just switched to.
test_name
title

Current title of the active window.

using_context(**kwds)

Sets the context that Marionette commands are running in using a with statement. The state of the context on the server is saved before entering the block, and restored upon exiting it.

Parameters:context – Context, may be one of the class properties CONTEXT_CHROME or CONTEXT_CONTENT.

Usage example:

with marionette.using_context(marionette.CONTEXT_CHROME):
    # chrome scope
    ... do stuff ...
using_prefs(**kwds)

Set preferences for code executed in a with block, and restores them on exit.

Parameters:
  • prefs – A dict containing one or more preferences and their values to be set. See set_prefs() for further details.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

with marionette.using_prefs({"browser.tabs.warnOnClose": True}):
    # ... do stuff ...
window_handles

Get list of windows in the current context.

If called in the content context it will return a list of references to all available browser windows. Called in the chrome context, it will list all available windows, not just browser windows (e.g. not just navigator.browser).

Each window handle is assigned by the server, and the list of strings returned does not have a guaranteed ordering.

Returns:Unordered list of unique window handles as strings
window_rect
class marionette_driver.marionette.MouseButton

Bases: object

Enum-like class for mouse button constants.

LEFT = 0
MIDDLE = 1
RIGHT = 2

marionette_driver.timeout module

class marionette_driver.timeout.Timeouts(marionette)

Bases: object

Manage timeout settings in the Marionette session.

Usage:

marionette = Marionette(...)
marionette.start_session()
marionette.timeout.page_load = 10
marionette.timeout.page_load
# => 10
implicit

Get the session’s implicit wait timeout. This specifies the time to wait for the implicit element location strategy when retrieving elements. It is by default disabled (0 seconds).

page_load

Get the session’s page load timeout. This specifies the time to wait for the page loading to complete. It is by default 5 minutes (or 300 seconds).

reset()

Resets timeouts to their default values.

script

Get the session’s script timeout. This specifies the time to wait for injected scripts to finished before interrupting them. It is by default 30 seconds.

marionette_driver.transport module

class marionette_driver.transport.Command(msgid, name, params)

Bases: marionette_driver.transport.Message

TYPE = 0
static from_msg(payload)
to_msg()
class marionette_driver.transport.Message(msgid)

Bases: object

class marionette_driver.transport.Response(msgid, error, result)

Bases: marionette_driver.transport.Message

TYPE = 1
static from_msg(payload)
to_msg()
class marionette_driver.transport.SocketTimeout(socket, timeout)

Bases: object

class marionette_driver.transport.TcpTransport(host, port, socket_timeout=60.0)

Bases: object

Socket client that communciates with Marionette via TCP.

It speaks the protocol of the remote debugger in Gecko, in which messages are always preceded by the message length and a colon, e.g.:

7:MESSAGE

On top of this protocol it uses a Marionette message format, that depending on the protocol level offered by the remote server, varies. Supported protocol levels are min_protocol_level and above.

close()

Close the socket.

First forces the socket to not send data anymore, and then explicitly close it to free up its resources.

See: https://docs.python.org/2/howto/sockets.html#disconnecting

connect()

Connect to the server and process the hello message we expect to receive in response.

Returns a tuple of the protocol level and the application type.

max_packet_length = 4096
min_protocol_level = 3
receive(unmarshal=True)

Wait for the next complete response from the remote.

Parameters:unmarshal – Default is to deserialise the packet and return a Message type. Setting this to false will return the raw packet.
request(name, params)

Sends a message to the remote server and waits for a response to come back.

respond(obj)

Send a response to a command. This can be an arbitrary JSON serialisable object or an Exception.

send(obj)

Send message to the remote server. Allowed input is a Message instance or a JSON serialisable object.

socket_timeout

marionette_driver.wait module

class marionette_driver.wait.SystemClock

Bases: object

now
sleep(duration)
class marionette_driver.wait.Wait(marionette, timeout=None, interval=None, ignored_exceptions=None, clock=None)

Bases: object

An explicit conditional utility class for waiting until a condition evaluates to true or not null.

This will repeatedly evaluate a condition in anticipation for a truthy return value, or its timeout to expire, or its waiting predicate to become true.

A Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as errors.NoSuchElementException when searching for an element on the page.

until(condition, is_true=None, message='')

Repeatedly runs condition until its return value evaluates to true, or its timeout expires or the predicate evaluates to true.

This will poll at the given interval until the given timeout is reached, or the predicate or conditions returns true. A condition that returns null or does not evaluate to true will fully elapse its timeout before raising an errors.TimeoutException.

If an exception is raised in the condition function and it’s not ignored, this function will raise immediately. If the exception is ignored, it will continue polling for the condition until it returns successfully or a TimeoutException is raised.

Parameters:
  • condition – A callable function whose return value will be returned by this function if it evaluates to true.
  • is_true – An optional predicate that will terminate and return when it evaluates to False. It should be a function that will be passed clock and an end time. The default predicate will terminate a wait when the clock elapses the timeout.
  • message – An optional message to include in the exception’s message if this function times out.
marionette_driver.wait.until_pred(clock, end)

Module contents