def open_browser(bs_device, project_name, run_id): desired_cap = { 'build': project_name, 'project': project_name, 'name': run_id, 'device': bs_device, 'real_mobile': 'true', 'browserstack.local': BuiltIn().get_variable_value('${BSLOCAL}') or 'false', 'browserstack.localIdentifier': BuiltIn().get_variable_value('${BSLOCALID}') or '' } bs_key = BuiltIn().get_variable_value('${APIKEY}') or os.environ.get( 'bskey') bs_user = BuiltIn().get_variable_value('${USERNAME}') or os.environ.get( 'bsuser') try: driver = webdriver.Remote( command_executor='http://{}:{}@hub.browserstack.com:80/wd/hub'. format(bs_user, bs_key), desired_capabilities=desired_cap) except WebDriverException as e: logger.error(e) raise exceptions.QWebException('Incorrect Browserstack capabilities.') browser.cache_browser(driver) return driver
def open_browser(url, browser_alias, options=None, **kwargs): r"""Open new browser to given url. Uses the Selenium2Library open_browser method if the browser is not Chrome. For Chrome, recognizes if we are inside docker container and sets chrome capabilities accordingly. Browser options can also be given in the robot command, for example: robot -v browser_options:"--kiosk, --disable-gpu" testytest.robot Examples -------- .. code-block:: robotframework OpenBrowser http://google.com chrome #Use Chromium instead of Chrome: OpenBrowser http://google.com chrome chrome_path=/path/to/chromium/chrome.exe OpenBrowser http://google.com chrome executable_path=/path/to/my/chromedriver.exe OpenBrowser file://resources/window.html firefox OpenBrowser http://google.com chrome --allow-running-insecure-content, --xyz OpenBrowser http://google.com chrome prefs="opt1":"True", "opt2":"False" OpenBrowser http://google.com firefox -headless, -private, -xyz OpenBrowser http://google.com firefox prefs="option1":"value1", "option2":"value2" OpenBrowser http://google.com firefox -profile /path/to/profile OpenBrowser http://google.com firefox -private prefs="option1":"value1" #Supply preferences from a dictionary ${prefs_d}= Create Dictionary option1 value1 option2 value2 OpenBrowser http://google.com firefox prefs=${prefs_d} Experimental feature for test debugging (for Chrome only): ---------------------------------------------------------- To re-use existing Chrome browser session, you need to set variable BROWSER_REUSE_SESSION to True. Next you need to run the first test suite normally including `OpenBrowser` AND excluding `CloseBrowser` (e.g. in Tear Down section). The first run will result to arguments file in defined output directory. The file name is by default `browser_session.arg`. For the next runs, which re-use the existing browser session, you need to specify the argument file in robot command-line using `--argumentfile` parameter. Additionally, test suites (or debugger) has to run `OpenBrowser` normally. QWeb will automatically override normal parameters and use argument file's values instead, thus re-using the existing browser. In the first test suite open Chrome browser normally without closing it at the tear down: .. code-block:: robotframework Set Global Variable ${BROWSER_REUSE_ENABLED} True OpenBrowser http://google.com chrome By running above, an argument file `browser_session.arg` is created to the output directory or current working directory. To re-use the existing browser session, use following command line examples: .. code-block:: text robot --argumentfile <path>/browser_session.arg ... example.robot rfdebug --argumentfile <path>/browser_session.arg Parameters ---------- url : str URL of the website that will be opened. browser_alias : str Browser name. For example chrome, firefox or ie. options Arguments for initialization of WebDriver objects(chrome). Some available opts: https://peter.sh/experiments/chromium-command-line-switches/ kwargs prefs=args: Experimental options for chrome browser. Raises ------ ValueError Unknown browser type Related keywords ---------------- \`Back\`, \`CloseAllBrowsers\`, \`CloseBrowser\`, \`GetTitle\`, \`GetUrl\`, \`GoTo\`, \`RefreshPage\`, \`ReturnBrowser\`, \`SwitchWindow\`, \`VerifyTitle\`, \`VerifyUrl\` """ try: logger.info('\nQWeb version number: {}'.format( pkg_resources.get_distribution('QWeb').version), also_console=True) except pkg_resources.DistributionNotFound: logger.info('Could not find QWeb version number.') number_of_open_sessions = _sessions_open() if number_of_open_sessions > 0: logger.warn('You have {} browser sessions already open'.format( number_of_open_sessions)) options = util.option_handler(options) b_lower = browser_alias.lower() bs_project_name = BuiltIn().get_variable_value('${PROJECTNAME}') or "" bs_run_id = BuiltIn().get_variable_value('${RUNID}') or "" if os.getenv('QWEB_HEADLESS'): kwargs = dict(headless=True) if os.getenv('CHROME_ARGS') is not None: if options is None: options = os.getenv('CHROME_ARGS').split(',') else: options = options + os.getenv('CHROME_ARGS').split(',') logger.debug('Options: {}'.format(options)) provider = BuiltIn().get_variable_value('${PROVIDER}') if provider in ('bs', 'browserstack'): bs_device = BuiltIn().get_variable_value('${DEVICE}') if not bs_device and b_lower in bs_desktop.NAMES: driver = bs_desktop.open_browser(b_lower, bs_project_name, bs_run_id) elif bs_device: driver = bs_mobile.open_browser(bs_device, bs_project_name, bs_run_id) else: raise exceptions.QWebException( 'Unknown browserstack browser {}'.format(browser_alias)) else: driver = _browser_checker(b_lower, options, **kwargs) util.initial_logging(driver.capabilities) # If user wants to re-use Chrome browser then he/she has to give # variable BROWSER_REUSE=True. In that case no URL loaded needed as # user wants to continue with the existing browser session is_browser_reused = util.par2bool( BuiltIn().get_variable_value('${BROWSER_REUSE}')) or False if not (is_browser_reused and b_lower == 'chrome'): driver.get(url) xhr.setup_xhr_monitor()
def verify_links(url='current', log_all=False, header_only=True): r"""Verify that all links on a given website return good HTTP status codes. Examples -------- .. code-block:: robotframework VerifyLinks https://qentinel.com/ The above example verifies that all links work on qentinel.com .. code-block:: robotframework VerifyLinks https://qentinel.com/ True The above example verifies that all links work on qentinel.com and logs the status of all the checked links. .. code-block:: robotframework VerifyLinks The above example verifies that all links work on on the current website. .. code-block:: robotframework VerifyLinks header_only=False The above example verifies that all links work on on the current website. Argument **header_only=False** instructs QWeb to double-check 404/405's using GET method (by default only headers are checked). Headers should normally return same code as GET, but in some cases header can be configured intentionally to return something else. Parameters ---------- url : str URL of the website that will be opened. log_all : bool Browser name. For example chrome, firefox or ie. header_only : bool True: check headers only (default) False: In case of header returning 404 or 405, double-check with GET Related keywords ---------------- \`GoTo\`,\`VerifyTitle\`, \`VerifyUrl\` """ if url == 'current': driver = browser.get_current_browser() else: window.go_to(url) driver = browser.get_current_browser() elements = driver.find_elements_by_xpath("//a[@href]") headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36" } checked = [] broken = [] logger.info('\nVerifying links on {}'.format(driver.current_url), also_console=True) for elem in elements: url = elem.get_attribute("href") if util.url_validator(url) and url not in checked: try: r = requests.head(url, headers=headers) status = r.status_code if not header_only and status in [404, 405]: r = requests.get(url, headers=headers) status = r.status_code except requests.exceptions.ConnectionError as e: logger.error("{} can't be reached. Error message: {}".format( url, e)) broken.append(url) continue if 399 < status < 600: error = 'Status of {} = {}'.format(url, status) logger.error(error) broken.append(url) elif status == 999: logger.info('Status of {} = {} (Linkedin specific error code. ' 'Everything is probably fine.)'.format( url, status), also_console=True) elif log_all: logger.info('Status of {} = {}'.format(url, status), also_console=True) checked.append(url) errors = len(broken) if len(checked) == 0: logger.warn('No links found.') if errors > 0: raise exceptions.QWebException('Found {} broken link(s): {}'.format( errors, broken))
def verify_links(url='current', log_all=False): """Verify that all links on a given website return good HTTP status codes. Examples -------- .. code-block:: robotframework VerifyLinks https://qentinel.com/ The above example verifies that all links work on qentinel.com .. code-block:: robotframework VerifyLinks https://qentinel.com/ True The above example verifies that all links work on qentinel.com and logs the status of all the checked links. .. code-block:: robotframework VerifyLinks The above example verifies that all links work on on the current website. """ if url == 'current': driver = browser.get_current_browser() else: window.go_to(url) driver = browser.get_current_browser() elements = driver.find_elements_by_xpath("//a[@href]") headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36" } checked = [] broken = [] logger.info('\nVerifying links on {}'.format(driver.current_url), also_console=True) for elem in elements: url = elem.get_attribute("href") if util.url_validator(url) and url not in checked: try: r = requests.head(url, headers=headers) status = r.status_code if status == 405: r = requests.get(url, headers=headers) status = r.status_code except requests.exceptions.ConnectionError: logger.error("{} can't be reached.".format(url)) broken.append(url) continue if 399 < status < 600: error = 'Status of {} = {}'.format(url, status) logger.error(error) broken.append(url) elif status == 999: logger.info('Status of {} = {} (Linkedin specific error code. ' 'Everything is probably fine.)'.format( url, status), also_console=True) elif log_all: logger.info('Status of {} = {}'.format(url, status), also_console=True) checked.append(url) errors = len(broken) if len(checked) == 0: logger.warn('No links found.') if errors > 0: raise exceptions.QWebException('Found {} broken link(s): {}'.format( errors, broken))