How to use split_class_and_test_names method in pytest-mozwebqa

Best Python code snippet using pytest-mozwebqa_python

pytest_mozwebqa.py

Source:pytest_mozwebqa.py Github

copy

Full Screen

...90 py.test.skip('This test is destructive and the target URL is '91 'considered a sensitive environment. If this test is '92 'not destructive, add the \'nondestructive\' marker to '93 'it. Sensitive URL: %s' % first_match.string)94 test_id = '.'.join(split_class_and_test_names(item.nodeid))95 if 'skip_selenium' not in item.keywords:96 from selenium_client import Client97 TestSetup.selenium_client = Client(98 test_id,99 item.config.option,100 item.keywords)101 TestSetup.selenium_client.start()102 item.session_id = TestSetup.selenium_client.session_id103 TestSetup.selenium = TestSetup.selenium_client.selenium104 TestSetup.timeout = TestSetup.selenium_client.timeout105 TestSetup.default_implicit_wait = TestSetup.selenium_client.default_implicit_wait106 else:107 TestSetup.timeout = item.config.option.webqatimeout108 TestSetup.selenium = None109def pytest_runtest_teardown(item):110 if hasattr(TestSetup, 'selenium') and TestSetup.selenium and 'skip_selenium' not in item.keywords:111 TestSetup.selenium.quit()112def pytest_runtest_makereport(__multicall__, item, call):113 pytest_html = item.config.pluginmanager.getplugin('html')114 extra_summary = []115 report = __multicall__.execute()116 extra = getattr(report, 'extra', [])117 try:118 report.public = item.keywords['privacy'].args[0] == 'public'119 except (IndexError, KeyError):120 # privacy mark is not present or has no value121 report.public = False122 if report.when == 'call':123 report.session_id = getattr(item, 'session_id', None)124 if hasattr(TestSetup, 'selenium') and TestSetup.selenium and 'skip_selenium' not in item.keywords:125 xfail = hasattr(report, 'wasxfail')126 if (report.skipped and xfail) or (report.failed and not xfail):127 url = TestSetup.selenium.current_url128 if url is not None:129 extra_summary.append('Failing URL: %s' % url)130 if pytest_html is not None:131 extra.append(pytest_html.extras.url(url))132 screenshot = TestSetup.selenium.get_screenshot_as_base64()133 if screenshot is not None and pytest_html is not None:134 extra.append(pytest_html.extras.image(screenshot, 'Screenshot'))135 html = TestSetup.selenium.page_source.encode('utf-8')136 if html is not None and pytest_html is not None:137 extra.append(pytest_html.extras.text(html, 'HTML'))138 if TestSetup.selenium_client.cloud is not None and report.session_id:139 cloud = TestSetup.selenium_client.cloud140 extra_summary.append('%s Job: %s' % (cloud.name, cloud.url(report.session_id)))141 if pytest_html is not None:142 extra.append(pytest_html.extras.url(cloud.url, '%s Job' % cloud.name))143 extra.append(pytest_html.extras.html(cloud.additional_html(report.session_id)))144 passed = report.passed or (report.failed and xfail)145 cloud.update_status(report.session_id, passed)146 report.sections.append(('pytest-mozwebqa', '\n'.join(extra_summary)))147 report.extra = extra148 return report149def pytest_funcarg__mozwebqa(request):150 return TestSetup(request)151def pytest_addoption(parser):152 config = ConfigParser.ConfigParser(defaults={'baseurl': ''})153 config.read('mozwebqa.cfg')154 group = parser.getgroup('selenium', 'selenium')155 group._addoption('--baseurl',156 action='store',157 dest='base_url',158 default=config.get('DEFAULT', 'baseurl'),159 metavar='url',160 help='base url for the application under test.')161 group._addoption('--skipurlcheck',162 action='store_true',163 dest='skip_url_check',164 default=False,165 help='skip the base url and sensitivity checks. (default: %default)')166 group._addoption('--host',167 action='store',168 default=os.environ.get('SELENIUM_HOST', 'localhost'),169 metavar='str',170 help='host that selenium server is listening on. (default: %default)')171 group._addoption('--port',172 action='store',173 type='int',174 default=os.environ.get('SELENIUM_PORT', 4444),175 metavar='num',176 help='port that selenium server is listening on. (default: %default)')177 group._addoption('--driver',178 action='store',179 dest='driver',180 default=os.environ.get('SELENIUM_DRIVER', 'Remote'),181 metavar='str',182 help='webdriver implementation. (default: %default)')183 group._addoption('--capability',184 action='append',185 dest='capabilities',186 metavar='str',187 help='additional capability to set in format "name:value".')188 group._addoption('--chromepath',189 action='store',190 dest='chrome_path',191 metavar='path',192 help='path to the google chrome driver executable.')193 group._addoption('--firefoxpath',194 action='store',195 dest='firefox_path',196 metavar='path',197 help='path to the target firefox binary.')198 group._addoption('--firefoxpref',199 action='append',200 dest='firefox_preferences',201 metavar='str',202 help='firefox preference name and value to set in format "name:value".')203 group._addoption('--profilepath',204 action='store',205 dest='profile_path',206 metavar='str',207 help='path to the firefox profile to use.')208 group._addoption('--extension',209 action='append',210 dest='extension_paths',211 metavar='str',212 help='path to browser extension to install.')213 group._addoption('--chromeopts',214 action='store',215 dest='chrome_options',216 metavar='str',217 help='json string of google chrome options to set.')218 group._addoption('--operapath',219 action='store',220 dest='opera_path',221 metavar='path',222 help='path to the opera driver.')223 group._addoption('--browsername',224 action='store',225 dest='browser_name',226 default=os.environ.get('SELENIUM_BROWSER'),227 metavar='str',228 help='target browser name (default: %default).')229 group._addoption('--browserver',230 action='store',231 dest='browser_version',232 default=os.environ.get('SELENIUM_VERSION'),233 metavar='str',234 help='target browser version (default: %default).')235 group._addoption('--platform',236 action='store',237 default=os.environ.get('SELENIUM_PLATFORM'),238 metavar='str',239 help='target platform (default: %default).')240 group._addoption('--webqatimeout',241 action='store',242 type='int',243 default=60,244 metavar='num',245 help='timeout (in seconds) for page loads, etc. (default: %default)')246 group._addoption('--build',247 action='store',248 dest='build',249 metavar='str',250 help='build identifier (for continuous integration).')251 group._addoption('--untrusted',252 action='store_true',253 dest='assume_untrusted',254 default=False,255 help='assume that all certificate issuers are untrusted. (default: %default)')256 group._addoption('--proxyhost',257 action='store',258 dest='proxy_host',259 metavar='str',260 help='use a proxy running on this host.')261 group._addoption('--proxyport',262 action='store',263 dest='proxy_port',264 metavar='int',265 help='use a proxy running on this port.')266 group._addoption('--eventlistener',267 action='store',268 dest='event_listener',269 metavar='str',270 help='selenium eventlistener class, e.g. package.module.EventListenerClassName.')271 group = parser.getgroup('safety', 'safety')272 group._addoption('--sensitiveurl',273 action='store',274 dest='sensitive_url',275 default='(firefox\.com)|(mozilla\.(com|org))',276 metavar='str',277 help='regular expression for identifying sensitive urls. (default: %default)')278 group._addoption('--destructive',279 action='store_true',280 dest='run_destructive',281 default=False,282 help='include destructive tests (tests not explicitly marked as \'nondestructive\'). (default: %default)')283def split_class_and_test_names(nodeid):284 names = nodeid.split("::")285 names[0] = names[0].replace("/", '.')286 names = [x.replace(".py", "") for x in names if x != "()"]287 classnames = names[:-1]288 classname = ".".join(classnames)289 name = names[-1]290 return (classname, name)291class TestSetup:292 '''293 This class is just used for monkey patching294 '''295 def __init__(self, request):...

Full Screen

Full Screen

pytest_selenium.py

Source:pytest_selenium.py Github

copy

Full Screen

...84 host=pytestconfig.getoption('host'),85 port=pytestconfig.getoption('port'),86 request=request,87 log_path=None,88 test='.'.join(split_class_and_test_names(request.node.nodeid))))89 pytestconfig._driver_log = driver_log90 return kwargs91@pytest.fixture92def driver_class(request):93 driver = request.config.getoption('driver')94 if driver is None:95 raise pytest.UsageError('--driver must be specified')96 return SUPPORTED_DRIVERS[driver]97@pytest.fixture98def driver_log(tmpdir):99 """Return path to driver log"""100 return str(tmpdir.join('driver.log'))101@pytest.fixture102def driver_path(request):103 return request.config.getoption('driver_path')104@pytest.yield_fixture105def driver(request, driver_class, driver_kwargs):106 """Returns a WebDriver instance based on options and capabilities"""107 driver = driver_class(**driver_kwargs)108 event_listener = request.config.getoption('event_listener')109 if event_listener is not None:110 # Import the specified event listener and wrap the driver instance111 mod_name, class_name = event_listener.rsplit('.', 1)112 mod = __import__(mod_name, fromlist=[class_name])113 event_listener = getattr(mod, class_name)114 if not isinstance(driver, EventFiringWebDriver):115 driver = EventFiringWebDriver(driver, event_listener())116 request.node._driver = driver117 yield driver118 driver.quit()119@pytest.yield_fixture120def selenium(driver):121 yield driver122@pytest.hookimpl(trylast=True)123def pytest_configure(config):124 capabilities = config._variables.get('capabilities', {})125 capabilities.update({k: v for k, v in config.getoption('capabilities')})126 config.addinivalue_line(127 'markers', 'capabilities(kwargs): add or change existing '128 'capabilities. specify capabilities as keyword arguments, for example '129 'capabilities(foo=''bar'')')130 if hasattr(config, '_metadata'):131 config._metadata['Driver'] = config.getoption('driver')132 config._metadata['Capabilities'] = capabilities133 if all((config.getoption('host'), config.getoption('port'))):134 config._metadata['Server'] = '{0}:{1}'.format(135 config.getoption('host'),136 config.getoption('port'))137 config._capabilities = capabilities138def pytest_report_header(config, startdir):139 driver = config.getoption('driver')140 if driver is not None:141 return 'driver: {0}'.format(driver)142@pytest.mark.hookwrapper143def pytest_runtest_makereport(item, call):144 outcome = yield145 report = outcome.get_result()146 summary = []147 extra = getattr(report, 'extra', [])148 driver = getattr(item, '_driver', None)149 xfail = hasattr(report, 'wasxfail')150 failure = (report.skipped and xfail) or (report.failed and not xfail)151 when = item.config.getini('selenium_capture_debug').lower()152 capture_debug = when == 'always' or (when == 'failure' and failure)153 if driver is not None:154 if capture_debug:155 exclude = item.config.getini('selenium_exclude_debug').lower()156 if 'url' not in exclude:157 _gather_url(item, report, driver, summary, extra)158 if 'screenshot' not in exclude:159 _gather_screenshot(item, report, driver, summary, extra)160 if 'html' not in exclude:161 _gather_html(item, report, driver, summary, extra)162 if 'logs' not in exclude:163 _gather_logs(item, report, driver, summary, extra)164 item.config.hook.pytest_selenium_capture_debug(165 item=item, report=report, extra=extra)166 item.config.hook.pytest_selenium_runtest_makereport(167 item=item, report=report, summary=summary, extra=extra)168 if summary:169 report.sections.append(('pytest-selenium', '\n'.join(summary)))170 report.extra = extra171def _gather_url(item, report, driver, summary, extra):172 try:173 url = driver.current_url174 except Exception as e:175 summary.append('WARNING: Failed to gather URL: {0}'.format(e))176 return177 pytest_html = item.config.pluginmanager.getplugin('html')178 if pytest_html is not None:179 # add url to the html report180 extra.append(pytest_html.extras.url(url))181 summary.append('URL: {0}'.format(url))182def _gather_screenshot(item, report, driver, summary, extra):183 try:184 screenshot = driver.get_screenshot_as_base64()185 except Exception as e:186 summary.append('WARNING: Failed to gather screenshot: {0}'.format(e))187 return188 pytest_html = item.config.pluginmanager.getplugin('html')189 if pytest_html is not None:190 # add screenshot to the html report191 extra.append(pytest_html.extras.image(screenshot, 'Screenshot'))192def _gather_html(item, report, driver, summary, extra):193 try:194 html = driver.page_source195 except Exception as e:196 summary.append('WARNING: Failed to gather HTML: {0}'.format(e))197 return198 pytest_html = item.config.pluginmanager.getplugin('html')199 if pytest_html is not None:200 # add page source to the html report201 extra.append(pytest_html.extras.text(html, 'HTML'))202def _gather_logs(item, report, driver, summary, extra):203 pytest_html = item.config.pluginmanager.getplugin('html')204 if item.config._driver_log and os.path.exists(item.config._driver_log):205 if pytest_html is not None:206 with open(item.config._driver_log, 'r') as f:207 extra.append(pytest_html.extras.text(f.read(), 'Driver Log'))208 summary.append('Driver log: {0}'.format(item.config._driver_log))209 try:210 types = driver.log_types211 except Exception as e:212 # note that some drivers may not implement log types213 summary.append('WARNING: Failed to gather log types: {0}'.format(e))214 return215 for name in types:216 try:217 log = driver.get_log(name)218 except Exception as e:219 summary.append('WARNING: Failed to gather {0} log: {1}'.format(220 name, e))221 return222 if pytest_html is not None:223 extra.append(pytest_html.extras.text(224 format_log(log), '%s Log' % name.title()))225def format_log(log):226 timestamp_format = '%Y-%m-%d %H:%M:%S.%f'227 entries = [u'{0} {1[level]} - {1[message]}'.format(228 datetime.utcfromtimestamp(entry['timestamp'] / 1000.0).strftime(229 timestamp_format), entry).rstrip() for entry in log]230 log = '\n'.join(entries)231 return log232def split_class_and_test_names(nodeid):233 """Returns the class and method name from the current test"""234 names = nodeid.split('::')235 names[0] = names[0].replace('/', '.')236 names = [x.replace('.py', '') for x in names if x != '()']237 classnames = names[:-1]238 classname = '.'.join(classnames)239 name = names[-1]240 return classname, name241class DriverAction(argparse.Action):242 def __call__(self, parser, namespace, values, option_string=None):243 setattr(namespace, self.dest, values)244 driver = getattr(drivers, values.lower())245 # set the default host and port if specified in the driver module246 namespace.host = namespace.host or getattr(driver, 'HOST', None)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-mozwebqa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful