class TestConsoleLogCapture(): def setup(self): try: self.client = Marionette(host='localhost', port=2828) self.client.start_session() self.client.set_pref('general.warnOnAboutConfig', False) except: sys.exit("Could not find Firefox browser running") def test_push_notification_received(self): self.client.navigate( "https://people.mozilla.org/~ewong2/push-notification-test/") unregister_button = self.client.find_element(By.ID, "unreg_btn") if unregister_button.is_displayed() == True: unregister_button.click() Wait(self.client, timeout=5, interval=1).until( expected.element_not_displayed(By.ID, "unreg_btn")) Wait(self.client).until(expected.element_displayed(By.ID, "reg_btn")) self.client.find_element(By.ID, "reg_btn").click() Wait(self.client).until( expected.element_displayed(By.ID, "subscribe_btn")) self.client.find_element(By.ID, "subscribe_btn").click() Wait(self.client).until(expected.element_displayed(By.ID, "doXhr_btn")) self.client.find_element(By.ID, "doXhr_btn").click() result = self.web_console_filter_for_string("Received a push message") assert result == 1 def web_console_filter_for_string(self, console_string=None): self.client.set_context(self.client.CONTEXT_CHROME) handles = self.client.window_handles chrome_handles = self.client.chrome_window_handles browser_handle = self.client.current_chrome_window_handle notifications = 0 for handle in chrome_handles: if handle != browser_handle: console_handle = handle self.client.switch_to_window(console_handle) time.sleep(1) results = self.client.find_elements(By.CLASS_NAME, "console-string") for result in results: if console_string in result.text: notifications = notifications + 1 self.client.find_element(By.CLASS_NAME, "webconsole-clear-console-button").click() return notifications def tear_down(self): self.client.close()
class TestConsoleLogCapture(): def setup(self): try: self.client = Marionette(host='localhost', port=2828) self.client.start_session() self.client.set_pref('general.warnOnAboutConfig', False) except: sys.exit("Could not find Firefox browser running") def test_push_notification_received(self): self.client.navigate("https://people.mozilla.org/~ewong2/push-notification-test/") unregister_button = self.client.find_element(By.ID, "unreg_btn") if unregister_button.is_displayed() == True: unregister_button.click() Wait(self.client, timeout=5, interval=1).until(expected.element_not_displayed(By.ID, "unreg_btn")) Wait(self.client).until(expected.element_displayed(By.ID, "reg_btn")) self.client.find_element(By.ID, "reg_btn").click() Wait(self.client).until(expected.element_displayed(By.ID, "subscribe_btn")) self.client.find_element(By.ID, "subscribe_btn").click() Wait(self.client).until(expected.element_displayed(By.ID, "doXhr_btn")) self.client.find_element(By.ID, "doXhr_btn").click() result = self.web_console_filter_for_string("Received a push message") assert result == 1 def web_console_filter_for_string(self, console_string=None): self.client.set_context(self.client.CONTEXT_CHROME) handles = self.client.window_handles chrome_handles = self.client.chrome_window_handles browser_handle = self.client.current_chrome_window_handle notifications = 0 for handle in chrome_handles: if handle != browser_handle: console_handle = handle self.client.switch_to_window(console_handle) time.sleep(1) results = self.client.find_elements(By.CLASS_NAME, "console-string") for result in results: if console_string in result.text: notifications = notifications + 1 self.client.find_element(By.CLASS_NAME, "webconsole-clear-console-button").click() return notifications def tear_down(self): self.client.close()
def runemulator(homedir=None, url=None, pidfile=None, arch='x86'): qemu = Emulator(homedir=homedir, arch=arch) qemu.start() port = qemu.setup_port_forwarding(2828) assert (qemu.wait_for_port()) if pidfile: f = open(pidfile, 'w') f.write("%d" % qemu.proc.pid) f.close() print 'emulator launched, pid:', qemu.proc.pid if url: marionette = Marionette(port=port) marionette.start_session() marionette.navigate(url) marionette.delete_session()
def runemulator(homedir=None, url=None, pidfile=None, arch='x86'): qemu = Emulator(homedir=homedir, arch=arch) qemu.start() port = qemu.setup_port_forwarding(2828) assert(qemu.wait_for_port()) if pidfile: f = open(pidfile, 'w') f.write("%d" % qemu.proc.pid) f.close() print 'emulator launched, pid:', qemu.proc.pid if url: marionette = Marionette(port=port) marionette.start_session() marionette.navigate(url) marionette.delete_session()
def dual_driving(): mm = Marionette(host='localhost', port=2829) mm.start_session() md = Marionette(host='localhost', port=2828) md.start_session() md.set_search_timeout(1000) # especially required for webcompat.com JS-driven loading ignored_bugs = [] buglist = [] for line in open(ignore_file, 'r'): if line[0] == '#': continue ignored_bugs.append(line.strip()) if start_url: print 'Starting from bug search %s' % start_url md.navigate(start_url) buglist = extract_buglist(md) else: buglist = extract_buglist_from_file(filename) i = 1 for item in buglist: if len(item) <= 1: print 'Warning: we expect data format ID Summary URL, something is missing' continue if '://' not in item[0]: # assuming this is Bugzilla data from a tab-separated file - in other words a plain bug number md.navigate('https://bugzilla.mozilla.org/show_bug.cgi?id=%s' % item[0]) else: # we've got a bug tracker URL (right?) md.navigate(item[0]) if len(item) == 2: # URL is not in the data - let's load the bug first and try to get it from there url = get_url_from_bugpage(md) else: url = item[2] if not url: i+=1 continue if i<start_at or url.strip() == '': i+=1 continue if '://' not in url: url = 'http://%s' % url url = url.strip().rstrip('\r\n') location = urlparse.urlparse(url) hostname = location.hostname.rstrip('\r\n') print str(i) + ' : ' + url reset_spoof(mm) mm.navigate(url) print 'READY to analyze %s, \n%s' % (item[0], item[1]) options_menu(mm, url, md) mm.delete_session() md.delete_session()
#encoding=utf-8 from marionette import Marionette client = Marionette('localhost', port=2828) client.start_session() client.navigate('http://finance.sina.com.cn/stock/s/20150714/070922678344.shtml')#访问当前访问的网址 elem = client.find_element('xpath',"//*[@id='wrapOuter']/div/div[4]/span") print(elem.text)
# run some trivial unit tests which just verify the protocol m = Marionette(host='localhost', port=2626) assert(m.status()['os']['arch'] == 'x86') assert(m.start_session()) assert(m.get_session_capabilities()['javascriptEnabled'] == True) assert(m.get_window() == server.TEST_CURRENT_WINDOW) assert(m.window == server.TEST_CURRENT_WINDOW) assert(m.get_windows() == server.TEST_WINDOW_LIST) assert(m.switch_to_window('window2')) assert(m.window == 'window2') assert(m.close_window('window2')) assert(m.set_script_timeout(1000)) assert(m.set_search_timeout(500)) assert(m.get_url() == server.TEST_URL) assert(m.navigate(server.TEST_URL)) assert(m.go_back()) assert(m.go_forward()) assert(m.refresh()) assert(m.execute_script(server.TEST_EXECUTE_SCRIPT)) assert(m.execute_js_script(server.TEST_EXECUTE_SCRIPT)) assert(m.execute_js_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS)) assert(m.execute_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS)) assert(m.execute_async_script(server.TEST_EXECUTE_SCRIPT)) assert(m.execute_async_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS)) assert(str(m.find_element(HTMLElement.CLASS, 'heading')) == server.TEST_FIND_ELEMENT) assert([str(x) for x in m.find_elements(HTMLElement.TAG, 'p')] == server.TEST_FIND_ELEMENTS) assert(str(m.find_element(HTMLElement.CLASS, 'heading').find_element(HTMLElement.TAG, 'h1')) == server.TEST_FIND_ELEMENT) assert([str(x) for x in m.find_element(HTMLElement.ID, 'div1').find_elements(HTMLElement.SELECTOR, '.main')] == \ server.TEST_FIND_ELEMENTS) assert(m.find_element(HTMLElement.ID, 'id1').click())
def dual_driving(): try: print('Will connect to mobile..') mm = Marionette(host='localhost', port=2829) mm.start_session() if disable_ua_overrides_by_default: set_mozilla_pref(mm, 'general.useragent.site_specific_overrides', False) set_mozilla_pref(mm, 'general.useragent.updates.enabled', False) print('Will connect to desktop...') md = Marionette(host='localhost', port=2828) md.start_session() md.set_search_timeout(1000) # especially required for webcompat.com JS-driven loading ignored_bugs = [] buglist = [] device_map = get_device_map() for line in open(ignore_file, 'r'): if line[0] == '#': continue ignored_bugs.append(line.strip()) if start_url: print 'Starting from bug search %s' % start_url md.navigate(start_url) buglist = extract_buglist(md) else: buglist = extract_buglist_from_file(filename) i = 1 #print(len(buglist)) for item in buglist: if len(item) <= 1: print 'Warning: we expect data format ID Summary URL, something is missing' continue if i<start_at: i+=1 continue buglink = '' if '://' not in item[0]: # assuming this is Bugzilla data from a tab-separated file - in other words a plain bug number # TODO: will we ever process lists of webcompat.com "plain numbers"?? buglink = 'https://bugzilla.mozilla.org/show_bug.cgi?id=%s' % item[0] else: # we've got a bug tracker URL (right?) buglink = item[0] # users who have bugzilla's "load next bug in search" don't need an extra navigate() call if buglink not in md.get_url(): print('Item %s, Loading bug %s'%(i,item[0])) md.navigate(item[0]) if len(item) == 2: # URL is not in the data - let's load the bug first and try to get it from there url = get_url_from_bugpage(md) else: url = item[2] if not url: i+=1 continue if url.strip() == '': i+=1 continue if '://' not in url: url = 'http://%s' % url url = url.strip().rstrip('\r\n') location = urlparse.urlparse(url) hostname = location.hostname.rstrip('\r\n') print str(i) + ' : ' + url reset_spoof(mm) try: mm.navigate(url) try_to_launch_url_in_android(device_map, url) print 'READY to analyze %s, \n%s' % (item[0], item[1]) except: print('could not load %s, try again by pressing u\n\n' % url) options_menu(mm, url, md, device_map) mm.delete_session() md.delete_session() except Exception as err: print err try: mm.delete_session() except: pass try: md.delete_session() except: pass
#/usr/bin/python import os from marionette import Marionette os.system("firefox -marionette &") cl = Marionette('localhost', port=2828) cl.start_session() cl.navigate("http://google.com")
class MatsRunner(object): def __init__(self, config_file = 'config.ini', url = 'about:blank'): self.config_file = config_file self.url = url def start(self): ''' This method starts MATS. ''' print 'Using ' + MatsController.__name__ + ' as controller.' print 'Loading config from "' + self.config_file + '"...', self.config = get_config(self.config_file) #get_config makes sure that the config makes sense. More details in get_config.py self.marionette_port = self.config['Marionette']['port'] print 'OK' print 'Starting Firefox/Nightly from "' + self.config['Firefox']['binary'] + '" with Marionette on port ' + str(self.marionette_port) + '.' self.FirefoxThread = FirefoxThread(self.config['Firefox']['binary'], self.marionette_port) self.FirefoxThread.start() print 'Creating controller' pid = self.FirefoxThread.getPID() # this function blocks until PID is available from FirefoxThread self.controller = MatsController(pid) print 'Starting controller' self.controller.start() self.controller.wait_for_ready() print 'Waiting for Marionette port to open (' + str(self.marionette_port) + ')' portReady = self.FirefoxThread.waitForMarionettePortOpenReady(self.config['Marionette']['port_timeout']) if portReady: print 'Marionette port open' else: print 'Error: timeout, shutting down MATS' self.controller.stop() self.FirefoxThread.stop() return #TODO: remove line below once https://bugzilla.mozilla.org/show_bug.cgi?id=753273 is fixed #sleep(10) try: print 'Starting Marionette' self.marionette = Marionette('localhost', self.marionette_port) #TODO: move starting session and navigation to separate methods print 'Starting session' sleep(5) #TODO temporary workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=757078 self.marionette_session = self.marionette.start_session() print 'Navigating to ' + self.url print self.marionette.navigate(self.url) except Exception as e: print 'Error starting Marionette' fall(e) self.controller.stop() self.FirefoxThread.stop() print 'MATS up and running. Waiting until Firefox/Nightly stops.' def wait_for_stop(self): self.FirefoxThread.join() print 'Stopping controller' self.controller.stop() self.controller.join() print 'MATS runner finishes.' def stop(self): self.FirefoxThread.stop() self.FirefoxThread.join() print 'Stopping controller' self.controller.stop() self.controller.join() print 'MATS runner finishes.' def instantiate_a11y(self): ''' runs via marionette script taken from http://dxr.lanedo.com/search.cgi?tree=mozilla-central&string=nsIAccessibleApplication to force A11y engine instantiation. sets context to content after doing it's stuff ''' script = \ ''' const nsIAccessibleRetrieval = Components.interfaces.nsIAccessibleRetrieval; const nsIAccessibleApplication = Components.interfaces.nsIAccessibleApplication; var gAccRetrieval = Components.classes["@mozilla.org/accessibleRetrieval;1"]. getService(nsIAccessibleRetrieval); app = gAccRetrieval.getApplicationAccessible(). QueryInterface(nsIAccessibleApplication); return (app) ? true : false; ''' self.marionette.set_context("chrome") notNull = self.marionette.execute_script(script) self.marionette.set_context("content") return notNull def is_a11y_instantiated(self): ''' runs via marionette script that checks if A11y engine is instantiated. and returns true if so. sets context to content after doing it's stuff ''' script = \ ''' var enabled; enabled = Components.manager.QueryInterface(Ci.nsIServiceManager) .isServiceInstantiatedByContractID( "@mozilla.org/accessibilityService;1", Ci.nsISupports); return enabled; ''' self.marionette.set_context('chrome') result = self.marionette.execute_script(script) self.marionette.set_context('content') return result def wait_for_event(self, event_string, callable, timeout = 60): ''' this method is the easiest interface to wait for an event. First, it registers listener. Second, it calls callable (TODO: add arguments) Third, it waits for the event or timeouts it returns True if the event was captured, and False if timeout occured TODO: abstract it to cross-platform ''' arrived = threading.Event() def callback(event): print 'got event! ' + str(event) arrived.set() self.controller.register_event_listener(event_string, callback) self.controller.unpause_event_loop() callable() result = arrived.wait(timeout) self.controller.pause_event_loop() self.controller.deregister_event_listener(event_string, callback) return result