def session(capabilities, configuration, request): """Create and start a session for a test that does not itself test session creation. By default the session will stay open after each test, but we always try to start a new one and assume that if that fails there is already a valid session. This makes it possible to recover from some errors that might leave the session in a bad state, but does not demand that we start a new session per test.""" global _current_session # Update configuration capabilities with custom ones from the # capabilities fixture, which can be set by tests caps = copy.deepcopy(configuration["capabilities"]) caps.update(capabilities) caps = {"alwaysMatch": caps} # If there is a session with different capabilities active, end it now if _current_session is not None and ( caps != _current_session.requested_capabilities): _current_session.end() _current_session = None if _current_session is None: _current_session = webdriver.Session( configuration["host"], configuration["port"], capabilities=caps) try: _current_session.start() except webdriver.error.SessionNotCreatedException: if not _current_session.session_id: raise yield _current_session cleanup_session(_current_session)
def connect(self): """Connect to browser via WebDriver.""" self.session = webdriver.Session( self.host, self.port, extension=webdriver.servo.ServoCommandExtensions) self.session.start()
async def session(capabilities, configuration, request): """Create and start a session for a test that does not itself test session creation. By default the session will stay open after each test, but we always try to start a new one and assume that if that fails there is already a valid session. This makes it possible to recover from some errors that might leave the session in a bad state, but does not demand that we start a new session per test.""" global _current_session # Update configuration capabilities with custom ones from the # capabilities fixture, which can be set by tests caps = copy.deepcopy(configuration["capabilities"]) deep_update(caps, capabilities) caps = {"alwaysMatch": caps} await reset_current_session_if_necessary(caps, False) if _current_session is None: _current_session = webdriver.Session(configuration["host"], configuration["port"], capabilities=caps) try: _current_session.start() except webdriver.error.SessionNotCreatedException: if not _current_session.session_id: raise # Enforce a fixed default window size and position _current_session.window.size = defaults.WINDOW_SIZE _current_session.window.position = defaults.WINDOW_POSITION yield _current_session cleanup_session(_current_session)
def session(configuration, request): """Create and start a session for a test that does not itself test session creation. By default the session will stay open after each test, but we always try to start a new one and assume that if that fails there is already a valid session. This makes it possible to recover from some errors that might leave the session in a bad state, but does not demand that we start a new session per test.""" global _current_session if _current_session is None: _current_session = webdriver.Session( configuration["host"], configuration["port"], capabilities={"alwaysMatch": configuration["capabilities"]}) try: _current_session.start() except webdriver.errors.SessionNotCreatedException: if not _current_session.session_id: raise # finalisers are popped off a stack, # making their ordering reverse request.addfinalizer( lambda: _switch_to_top_level_browsing_context(_current_session)) request.addfinalizer( lambda: _restore_normal_window_state(_current_session)) request.addfinalizer(lambda: _restore_windows(_current_session)) request.addfinalizer(lambda: _dismiss_user_prompts(_current_session)) request.addfinalizer(lambda: _ensure_valid_window(_current_session)) return _current_session
def pytest_configure(config): config.proc = subprocess.Popen(["geckodriver"]) config.add_cleanup(config.proc.kill) capabilities = {"alwaysMatch": {"acceptInsecureCerts": True, "moz:firefoxOptions": {}}} if config.getoption("--binary"): capabilities["alwaysMatch"]["moz:firefoxOptions"]["binary"] = config.getoption("--binary") if config.getoption("--headless"): capabilities["alwaysMatch"]["moz:firefoxOptions"]["args"] = ["--headless"] config.driver = webdriver.Session("localhost", 4444, capabilities=capabilities) config.add_cleanup(config.driver.end) config.server = WPTServer(WPT_ROOT) config.server.start() # Although the name of the `_create_unverified_context` method suggests # that it is not intended for external consumption, the standard library's # documentation explicitly endorses its use: # # > To revert to the previous, unverified, behavior # > ssl._create_unverified_context() can be passed to the context # > parameter. # # https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection config.ssl_context = ssl._create_unverified_context() config.add_cleanup(config.server.stop)
def connect(self): """Connect to browser via WebDriver.""" wait_for_service((self.host, self.port), timeout=self.init_timeout) self.session = webdriver.Session(self.host, self.port, extension=ServoCommandExtensions) self.session.start()
def connect(self): """Connect to browser via WebDriver.""" self.logger.debug("Connecting to WebDriver on URL: %s" % self.url) host, port = self.url.split(":")[1].strip("/"), self.url.split(':')[-1].strip("/") capabilities = {"alwaysMatch": self.capabilities} self.webdriver = client.Session(host, port, capabilities=capabilities) self.webdriver.start()
def create_session(body): global _current_session _session = webdriver.Session(configuration["host"], configuration["port"], capabilities=None) value = _session.send_command("POST", "session", body=body) # Don't set the global session until we are sure this succeeded _current_session = _session _session.session_id = value["sessionId"] return value, _current_session
async def session(capabilities, configuration, request, bidi): """Create and start a session for a test that does not itself test session creation. By default the session will stay open after each test, but we always try to start a new one and assume that if that fails there is already a valid session. This makes it possible to recover from some errors that might leave the session in a bad state, but does not demand that we start a new session per test.""" global _current_session # Update configuration capabilities with custom ones from the # capabilities fixture, which can be set by tests caps = copy.deepcopy(configuration["capabilities"]) deep_update(caps, capabilities) caps = {"alwaysMatch": caps} is_cur_bidi = isinstance(_current_session, webdriver.BidiSession) # If there is a session with different capabilities active or the current session # is of different type than the one we would like to create, end it now. if _current_session is not None and ((not _current_session.match(caps)) or (is_cur_bidi != bidi)): if is_cur_bidi: await _current_session.end() else: _current_session.end() _current_session = None if _current_session is None: if bidi: _current_session = webdriver.BidiSession(configuration["host"], configuration["port"], capabilities=caps) else: _current_session = webdriver.Session(configuration["host"], configuration["port"], capabilities=caps) try: if type(_current_session) == webdriver.BidiSession: await _current_session.start() else: _current_session.start() except webdriver.error.SessionNotCreatedException: if not _current_session.session_id: raise # Enforce a fixed default window size and position _current_session.window.size = defaults.WINDOW_SIZE _current_session.window.position = defaults.WINDOW_POSITION yield _current_session cleanup_session(_current_session)
def setup_session(self): self.config = json.loads(open('config.json', 'r').read()) if self.headless: self.config['capabilities']['alwaysMatch']['moz:firefoxOptions']['args'].insert(1,'--headless') self.config['capabilities']['alwaysMatch']['moz:firefoxOptions']['args'].insert(1,'--height=1080') self.config['capabilities']['alwaysMatch']['moz:firefoxOptions']['args'].insert(1,'--width=1920') print(self.config['capabilities']) self.session = webdriver.Session(self.config['webdriverip'], self.config['webdriverport'], capabilities=self.config['capabilities']) return
def _session(request): host = os.environ.get("WD_HOST", default_host) port = int(os.environ.get("WD_PORT", default_port)) session = webdriver.Session(host, port) def destroy(): if session.session_id is not None: session.end() request.addfinalizer(destroy) return session
def create_session(body): global _current_session _session = webdriver.Session(configuration["host"], configuration["port"], capabilities=None) # TODO: merge in some capabilities from the confguration capabilities # since these might be needed to start the browser value = _session.send_command("POST", "session", body=body) # Don't set the global session until we are sure this succeeded _current_session = _session _session.session_id = value["sessionId"] return value, _current_session
def _session(request): host = os.environ.get("WD_HOST", default_host) port = int(os.environ.get("WD_PORT", default_port)) capabilities = json.loads(os.environ.get("WD_CAPABILITIES", "{}")) session = webdriver.Session(host, port, desired_capabilities=capabilities) def destroy(): if session.session_id is not None: session.end() request.addfinalizer(destroy) return session
def setup(self, runner): """Connect to browser via the Marionette HTTP server.""" try: self.server = GeckoDriverServer( self.logger, self.marionette_port, binary=self.webdriver_binary) self.server.start(block=False) self.logger.info( "WebDriver HTTP server listening at %s" % self.server.url) self.logger.info( "Establishing new WebDriver session with %s" % self.server.url) self.session = webdriver.Session( self.server.host, self.server.port, self.server.base_path) except Exception: self.logger.error(traceback.format_exc()) self.executor.runner.send_message("init_failed") else: self.executor.runner.send_message("init_succeeded")
def setup(self, runner): """Connect to browser via WebDriver.""" self.runner = runner session_started = False try: self.session = webdriver.Session(self.host, self.port) self.session.start() except: self.logger.warning("Connecting with WebDriver failed:\n%s" % traceback.format_exc()) else: self.logger.debug("session started") session_started = True if not session_started: self.logger.warning("Failed to connect via WebDriver") self.executor.runner.send_message("init_failed") else: self.executor.runner.send_message("init_succeeded")
def go_to_url(url, verbose=False): # TODO # should write a function to check that url is valid! session = webdriver.Session(config['webdriverip'], config['webdriverport'], capabilities=config['capabilities']) session.url = url session.window.fullscreen() sessionid = session.session_id some_string = input( "would you like to keep this session open for further debugging?") save_string = input("Would you like to take a screenshot?") if 'y' in save_string: save_screenshot(sessionid, fullscreen=True) if 'y' in some_string: pass else: session.close() return
async def bidi_session(capabilities, configuration): """Create and start a bidi session. Can be used for a test that does not itself test bidi session creation. By default the session will stay open after each test, but we always try to start a new one and assume that if that fails there is already a valid session. This makes it possible to recover from some errors that might leave the session in a bad state, but does not demand that we start a new session per test. """ global _current_session # Update configuration capabilities with custom ones from the # capabilities fixture, which can be set by tests caps = copy.deepcopy(configuration["capabilities"]) caps.update({"webSocketUrl": True}) deep_update(caps, capabilities) caps = {"alwaysMatch": caps} await reset_current_session_if_necessary(caps) if _current_session is None: _current_session = webdriver.Session(configuration["host"], configuration["port"], capabilities=caps, enable_bidi=True) _current_session.start() await _current_session.bidi_session.start() # Enforce a fixed default window size and position if _current_session.capabilities.get("setWindowRect"): _current_session.window.size = defaults.WINDOW_SIZE _current_session.window.position = defaults.WINDOW_POSITION yield _current_session.bidi_session await _current_session.bidi_session.end() cleanup_session(_current_session)
def lookup_url(url, save_text=False): with webdriver.Session(config['webdriverip'], config['webdriverport'], capabilities=config['capabilities']) as session: if url is not None: session.url = url else: session.url = "https://google.com" session.window.fullscreen() sessionid = session.session_id print("sessionID -------> {}".format(sessionid)) #find_page_element = session.find #element_selector = {'using': 'css selector', 'value': '#article-summary'} #query_results = find_page_element.css(element_selector=element_selector['value']) #for element in query_results: # print(dir(element)) #print(query_results) #input() #if save_text: # save_viewable_text(human_text=query_results.text,sessionid=sessionid,query=query) time.sleep(3) save_screenshot(sessionid, fullscreen=True)
def create_session(test_capabilities=None): host = os.environ.get("WD_HOST", default_host) port = int(os.environ.get("WD_PORT", default_port)) if test_capabilities is None: test_capabilities = {} env_capabilities = json.loads(os.environ.get("WD_CAPABILITIES", "{}")) capabilities = merge_dictionaries(env_capabilities, test_capabilities) session = webdriver.Session(host, port, capabilities=capabilities) def destroy(): if session.session_id is not None: session.end() # finalisers are popped off a stack, making their ordering reverse request.addfinalizer(destroy) request.addfinalizer( lambda: _switch_to_top_level_browsing_context(session)) request.addfinalizer(lambda: _restore_windows(session)) request.addfinalizer(lambda: _dismiss_user_prompts(session)) request.addfinalizer(lambda: _ensure_valid_window(session)) return session
def lookup_word(text, define=False, save_text=False, video=False, url=None, screenshot=True): oldsession = webdriver.Session(config['webdriverip'], config['webdriverport'], capabilities=config['capabilities']) #oldsession.session_id = "89cfc006-bba3-4ee5-9feb-ef13f5e8692e" if video: f_stop = threading.Event() with webdriver.Session(config['webdriverip'], config['webdriverport'], capabilities=config['capabilities']) as session: if url is not None: session.url = url else: session.url = "https://google.com" session.window.fullscreen() sessionid = session.session_id print("sessionID -------> {}".format(sessionid)) if video: f(f_stop, sessionid) time.sleep(random.randint(1, 99) * .01 + random.randint(0, 1)) texttotype = "{0}{search_text}" if define: query = texttotype.format('define: ', search_text=text) element_selector = { 'using': 'css selector', 'value': '#dictionary-modules' } else: query = texttotype.format("", search_text=text) element_selector = { 'using': 'css selector', 'value': '#searchform' } print("typing {query} in {url}".format(query=query, url=session.url)) typingaction = session.actions for letter in query: time.sleep(random.randint(1, 99) * .01) typingaction.sequence( 'key', 'id').key_down(letter).key_up(letter).perform() time.sleep(random.randint(1, 99) * .01 + 1) print("pressing Enter!!!!!!!!!!") typingaction.sequence( 'key', 'id').key_down('\uE007').key_up('\uE007').perform() time.sleep(2) # Wait until page loads find_page_element = session.find query_results = find_page_element.css( element_selector=element_selector['value']) if len(query_results) == 0: print("Nothing matched CSS element/selector") for element in query_results: print("element -> {} \n =======\n TEXT: {} \n =======".format( element, element.text)) if save_text: save_viewable_text(human_text=element.text, sessionid=sessionid, query=query) if screenshot: save_screenshot(sessionid, fullscreen=True) #wait_to_close_session() try: f_stop.set() except: pass return