How to use pytest_runtest_makereport method in localstack

Best Python code snippet using localstack_python

test_pytest_html.py

Source:test_pytest_html.py Github

copy

Full Screen

...222 content = str(random.random())223 testdir.makeconftest("""224 import pytest225 @pytest.mark.hookwrapper226 def pytest_runtest_makereport(item, call):227 outcome = yield228 report = outcome.get_result()229 if report.when == 'call':230 from pytest_html import extras231 report.extra = [extras.html('<div>{0}</div>')]232 """.format(content))233 testdir.makepyfile('def test_pass(): pass')234 result, html = run(testdir)235 assert result.ret == 0236 assert content in html237 @pytest.mark.parametrize('content, encoded', [238 ("u'\u0081'", 'woE='),239 ("'foo'", 'Zm9v'),240 ("b'\\xe2\\x80\\x93'", '4oCT')])241 def test_extra_text(self, testdir, content, encoded):242 testdir.makeconftest("""243 import pytest244 @pytest.mark.hookwrapper245 def pytest_runtest_makereport(item, call):246 outcome = yield247 report = outcome.get_result()248 if report.when == 'call':249 from pytest_html import extras250 report.extra = [extras.text({0})]251 """.format(content))252 testdir.makepyfile('def test_pass(): pass')253 result, html = run(testdir, 'report.html', '--self-contained-html')254 assert result.ret == 0255 href = 'data:text/plain;charset=utf-8;base64,{0}'.format(encoded)256 link = '<a class="text" href="{0}" target="_blank">Text</a>'.format(257 href)258 assert link in html259 def test_extra_json(self, testdir):260 content = {str(random.random()): str(random.random())}261 testdir.makeconftest("""262 import pytest263 @pytest.mark.hookwrapper264 def pytest_runtest_makereport(item, call):265 outcome = yield266 report = outcome.get_result()267 if report.when == 'call':268 from pytest_html import extras269 report.extra = [extras.json({0})]270 """.format(content))271 testdir.makepyfile('def test_pass(): pass')272 result, html = run(testdir, 'report.html', '--self-contained-html')273 assert result.ret == 0274 content_str = json.dumps(content)275 if PY3:276 data = b64encode(content_str.encode('utf-8')).decode('ascii')277 else:278 data = b64encode(content_str)279 href = 'data:application/json;charset=utf-8;base64,{0}'.format(data)280 link = '<a class="json" href="{0}" target="_blank">JSON</a>'.format(281 href)282 assert link in html283 def test_extra_url(self, testdir):284 content = str(random.random())285 testdir.makeconftest("""286 import pytest287 @pytest.mark.hookwrapper288 def pytest_runtest_makereport(item, call):289 outcome = yield290 report = outcome.get_result()291 if report.when == 'call':292 from pytest_html import extras293 report.extra = [extras.url('{0}')]294 """.format(content))295 testdir.makepyfile('def test_pass(): pass')296 result, html = run(testdir)297 assert result.ret == 0298 link = '<a class="url" href="{0}" target="_blank">URL</a>'.format(299 content)300 assert link in html301 @pytest.mark.parametrize('mime_type, extension',302 [('image/png', 'png'),303 ('image/png', 'image'),304 ('image/jpeg', 'jpg'),305 ('image/svg+xml', 'svg')])306 def test_extra_image(self, testdir, mime_type, extension):307 content = str(random.random())308 testdir.makeconftest("""309 import pytest310 @pytest.mark.hookwrapper311 def pytest_runtest_makereport(item, call):312 outcome = yield313 report = outcome.get_result()314 if report.when == 'call':315 from pytest_html import extras316 report.extra = [extras.{0}('{1}')]317 """.format(extension, content))318 testdir.makepyfile('def test_pass(): pass')319 result, html = run(testdir, 'report.html', '--self-contained-html')320 assert result.ret == 0321 src = 'data:{0};base64,{1}'.format(mime_type, content)322 assert '<img src="{0}"/>'.format(src) in html323 def test_extra_image_windows(self, mocker, testdir):324 mock_isfile = mocker.patch('pytest_html.plugin.isfile')325 mock_isfile.side_effect = ValueError('stat: path too long for Windows')326 self.test_extra_image(testdir, 'image/png', 'png')327 assert mock_isfile.call_count == 1328 @pytest.mark.parametrize('content', [329 ("u'\u0081'"),330 ("'foo'"),331 ("b'\\xe2\\x80\\x93'")])332 def test_extra_text_separated(self, testdir, content):333 testdir.makeconftest("""334 import pytest335 @pytest.mark.hookwrapper336 def pytest_runtest_makereport(item, call):337 outcome = yield338 report = outcome.get_result()339 if report.when == 'call':340 from pytest_html import extras341 report.extra = [extras.text({0})]342 """.format(content))343 testdir.makepyfile('def test_pass(): pass')344 result, html = run(testdir)345 hash_key = ('test_extra_text_separated.py::'346 'test_pass00').encode('utf-8')347 hash_generator = hashlib.md5()348 hash_generator.update(hash_key)349 assert result.ret == 0350 src = '{0}/{1}'.format('assets', '{0}.txt'.351 format(hash_generator.hexdigest()))352 link = ('<a class="text" href="{0}" target="_blank">'.format(src))353 assert link in html354 assert os.path.exists(src)355 @pytest.mark.parametrize('file_extension, extra_type', [356 ('png', 'image'),357 ('png', 'png'),358 ('svg', 'svg'),359 ('jpg', 'jpg')])360 def test_extra_image_separated(self, testdir, file_extension, extra_type):361 content = b64encode('foo'.encode('utf-8')).decode('ascii')362 testdir.makeconftest("""363 import pytest364 @pytest.mark.hookwrapper365 def pytest_runtest_makereport(item, call):366 outcome = yield367 report = outcome.get_result()368 if report.when == 'call':369 from pytest_html import extras370 report.extra = [extras.{0}('{1}')]371 """.format(extra_type, content))372 testdir.makepyfile('def test_pass(): pass')373 result, html = run(testdir)374 hash_key = ('test_extra_image_separated.py::'375 'test_pass00').encode('utf-8')376 hash_generator = hashlib.md5()377 hash_generator.update(hash_key)378 assert result.ret == 0379 src = '{0}/{1}'.format('assets', '{0}.{1}'.380 format(hash_generator.hexdigest(),381 file_extension))382 link = ('<a class="image" href="{0}" target="_blank">'.format(src))383 assert link in html384 assert os.path.exists(src)385 @pytest.mark.parametrize('file_extension, extra_type', [386 ('png', 'image'),387 ('png', 'png'),388 ('svg', 'svg'),389 ('jpg', 'jpg')])390 def test_extra_image_separated_rerun(self, testdir, file_extension,391 extra_type):392 content = b64encode('foo'.encode('utf-8')).decode('ascii')393 testdir.makeconftest("""394 import pytest395 @pytest.mark.hookwrapper396 def pytest_runtest_makereport(item, call):397 outcome = yield398 report = outcome.get_result()399 if report.when == 'call':400 from pytest_html import extras401 report.extra = [extras.{0}('{1}')]402 """.format(extra_type, content))403 testdir.makepyfile("""404 import pytest405 @pytest.mark.flaky(reruns=2)406 def test_fail():407 assert False""")408 result, html = run(testdir)409 for i in range(1, 4):410 hash_key = ('test_extra_image_separated_rerun.py::'411 'test_fail0{0}'.format(i)).encode('utf-8')412 hash_generator = hashlib.md5()413 hash_generator.update(hash_key)414 src = 'assets/{0}.{1}'.format(hash_generator.hexdigest(),415 file_extension)416 link = ('<a class="image" href="{0}" target="_blank">'.format(src))417 assert result.ret418 assert link in html419 assert os.path.exists(src)420 @pytest.mark.parametrize('src_type', ["https://", "file://", "image.png"])421 def test_extra_image_non_b64(self, testdir, src_type):422 content = src_type423 testdir.makeconftest("""424 import pytest425 @pytest.mark.hookwrapper426 def pytest_runtest_makereport(item, call):427 outcome = yield428 report = outcome.get_result()429 if report.when == 'call':430 from pytest_html import extras431 report.extra = [extras.image('{0}')]432 """.format(content))433 testdir.makepyfile('def test_pass(): pass')434 if src_type == "image.png":435 testdir.makefile('.png', image='pretty picture')436 result, html = run(testdir, 'report.html')437 assert result.ret == 0438 assert '<a href="{0}"><img src="{0}"/>'.format(content) in html439 def test_no_environment(self, testdir):440 testdir.makeconftest("""441 def pytest_configure(config):442 config._metadata = None443 """)444 testdir.makepyfile('def test_pass(): pass')445 result, html = run(testdir)446 assert result.ret == 0447 assert 'Environment' not in html448 def test_environment(self, testdir):449 content = str(random.random())450 testdir.makeconftest("""451 def pytest_configure(config):452 config._metadata['content'] = '{0}'453 """.format(content))454 testdir.makepyfile('def test_pass(): pass')455 result, html = run(testdir)456 assert result.ret == 0457 assert 'Environment' in html458 assert len(re.findall(content, html)) == 1459 def test_environment_xdist(self, testdir):460 content = str(random.random())461 testdir.makeconftest("""462 def pytest_configure(config):463 for i in range(2):464 config._metadata['content'] = '{0}'465 """.format(content))466 testdir.makepyfile('def test_pass(): pass')467 result, html = run(testdir, 'report.html', '-n', '1')468 assert result.ret == 0469 assert 'Environment' in html470 assert len(re.findall(content, html)) == 1471 def test_environment_xdist_reruns(self, testdir):472 content = str(random.random())473 testdir.makeconftest("""474 def pytest_configure(config):475 for i in range(2):476 config._metadata['content'] = '{0}'477 """.format(content))478 testdir.makepyfile('def test_fail(): assert False')479 result, html = run(testdir, 'report.html', '-n', '1', '--reruns', '1')480 assert result.ret481 assert 'Environment' in html482 assert len(re.findall(content, html)) == 1483 def test_environment_list_value(self, testdir):484 content = tuple(str(random.random()) for i in range(10))485 content += tuple(random.random() for i in range(10))486 expected_content = ', '.join((str(i) for i in content))487 expected_html_re = r'<td>content</td>\n\s+<td>{}</td>'.format(488 expected_content489 )490 testdir.makeconftest("""491 def pytest_configure(config):492 for i in range(2):493 config._metadata['content'] = {0}494 """.format(content))495 testdir.makepyfile('def test_pass(): pass')496 result, html = run(testdir)497 assert result.ret == 0498 assert 'Environment' in html499 assert len(re.findall(expected_html_re, html)) == 1500 def test_environment_ordered(self, testdir):501 testdir.makeconftest("""502 from collections import OrderedDict503 def pytest_configure(config):504 config._metadata = OrderedDict([('ZZZ', 1), ('AAA', 2)])505 """)506 testdir.makepyfile('def test_pass(): pass')507 result, html = run(testdir)508 assert result.ret == 0509 assert 'Environment' in html510 assert len(re.findall('ZZZ.+AAA', html, re.DOTALL)) == 1511 @pytest.mark.xfail(512 sys.version_info < (3, 2) and513 LooseVersion(pytest.__version__) >= LooseVersion('2.8.0'),514 reason='Fails on earlier versions of Python and pytest',515 run=False)516 def test_xdist_crashing_slave(self, testdir):517 """https://github.com/pytest-dev/pytest-html/issues/21"""518 testdir.makepyfile("""519 import os520 def test_exit():521 os._exit(0)522 """)523 result, html = run(testdir, 'report.html', '-n', '1')524 assert 'INTERNALERROR>' not in result.stdout.str()525 def test_utf8_surrogate(self, testdir):526 testdir.makepyfile(r"""527 import pytest528 @pytest.mark.parametrize('val', ['\ud800'])529 def test_foo(val):530 pass531 """)532 result, html = run(testdir)533 assert result.ret == 0534 assert_results(html, passed=1)535 def test_ansi_color(self, testdir):536 try:537 import ansi2html # NOQA538 ANSI = True539 except ImportError:540 # ansi2html is not installed541 ANSI = False542 pass_content = ["<span class=\"ansi31\">RCOLOR",543 "<span class=\"ansi32\">GCOLOR",544 "<span class=\"ansi33\">YCOLOR"]545 testdir.makepyfile(r"""546 def test_ansi():547 colors = ['\033[31mRCOLOR\033[0m', '\033[32mGCOLOR\033[0m',548 '\033[33mYCOLOR\033[0m']549 for color in colors:550 print(color)551 """)552 result, html = run(testdir, 'report.html', '--self-contained-html')553 assert result.ret == 0554 for content in pass_content:555 if ANSI:556 assert content in html557 else:558 assert content not in html559 @pytest.mark.parametrize('content', [("'foo'"), ("u'\u0081'")])560 def test_utf8_longrepr(self, testdir, content):561 testdir.makeconftest("""562 import pytest563 @pytest.mark.hookwrapper564 def pytest_runtest_makereport(item, call):565 outcome = yield566 report = outcome.get_result()567 if report.when == 'call':568 report.longrepr = 'utf8 longrepr: ' + {0}569 """.format(content))570 testdir.makepyfile("""571 def test_fail():572 testtext = 'utf8 longrepr: '573 assert False574 """)575 result, html = run(testdir, 'report.html', '--self-contained-html')576 assert result.ret577 assert 'utf8 longrepr' in html578 def test_collect_error(self, testdir):...

Full Screen

Full Screen

conftest.py

Source:conftest.py Github

copy

Full Screen

...60 )616263@pytest.mark.hookwrapper(tryfirst=True, hookwrapper=True)64def pytest_runtest_makereport(item, call):65 pytest_html = item.config.pluginmanager.getplugin('html')66 outcome = yield67 report = outcome.get_result()68 extra = getattr(report, 'extra', [])69 if report.when == 'call':70 if 'app' in item.fixturenames:71 driver = item.funcargs['app']72 xfail = hasattr(report, 'wasxfail')73 # create file74 add_name = '{}_{}'.format(report.nodeid.split("::")[1],75 datetime.now().strftime("%Y-%m-%d_%H.%M.%S"))76 file_name = PATH(os.path.abspath(os.curdir) + '/' + add_name + '.png')77 driver.wd.get_screenshot_as_file(file_name)78 if (report.skipped and xfail) or (report.failed and not xfail):79 cp_file_name = add_name + ".png"80 # only add additional html on failure81 html = '<div><img src=' + cp_file_name + ' alt="screenshot" style="width:304px;height:228px;" '82 extra.append(pytest_html.extras.html(html))83 report.extra = extra848586@pytest.hookimpl(tryfirst=True, hookwrapper=True)87def pytest_runtest_makereport(item, call):88 outcome = yield89 rep = outcome.get_result()90 if rep.when == 'call' and rep.failed:91 mode = 'a' if os.path.exists('failures') else 'w'92 try:93 with open('failures', mode) as f:94 if 'app' in item.fixturenames:95 web_driver = item.funcargs['app']96 else:97 print('Fail to take screen-shot')98 return99 allure.attach(100 web_driver.wd.get_screenshot_as_png(),101 name='screenshot',102 attachment_type=allure.attachment_type.PNG103 )104 except Exception as e:105 print('Fail to take screen-shot: {}'.format(e))106107108@pytest.hookimpl(tryfirst=True, hookwrapper=True)109def pytest_runtest_makereport(item, call):110 outcome = yield111 rep = outcome.get_result()112 if rep.when == 'call' and rep.failed:113 mode = 'a' if os.path.exists('failures') else 'w'114 try:115 with open('failures', mode) as f:116 if 'app' in item.fixturenames:117 web_driver = item.funcargs['app']118 else:119 print('Fail to take screen-shot')120 return121 allure.attach(122 web_driver.wd.get_screenshot_as_png(),123 name='screenshot', ...

Full Screen

Full Screen

conftest(1).py

Source:conftest(1).py Github

copy

Full Screen

...18 parser.addoption(19 "--host", action="store", default="http://127.0.0.1:80", help="test host->http://127.0.0.1:80"20 )21@pytest.mark.hookwrapper22def pytest_runtest_makereport(item):23 """24 当测试失败的时候,自动截图,展示到html报告中25 :param item:26 """27 pytest_html = item.config.pluginmanager.getplugin('html')28 outcome = yield29 report = outcome.get_result()30 extra = getattr(report, 'extra', [])31 if report.when == 'call' or report.when == "setup":32 xfail = hasattr(report, 'wasxfail')33 if (report.skipped and xfail) or (report.failed and not xfail):34 file_name = report.nodeid.replace("::", "_")+".png"35 screen_img = _capture_screenshot()36 if file_name:37 html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \38 'onclick="window.open(this.src)" align="right"/></div>' % screen_img39 extra.append(pytest_html.extras.html(html))40 report.extra = extra41 report.description = str(item.function.__doc__)42 report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")43@pytest.mark.optionalhook44def pytest_html_results_table_header(cells):45 cells.insert(1, html.th('Description'))46 cells.insert(2, html.th('Test_nodeid'))47 cells.pop(2)48@pytest.mark.optionalhook49def pytest_html_results_table_row(report, cells):50 cells.insert(1, html.td(report.description))51 cells.insert(2, html.td(report.nodeid))52 cells.pop(2)53# @pytest.mark.hookwrapper54# def pytest_runtest_makereport(item, call):55# outcome = yield56# report = outcome.get_result()57# report.description = str(item.function.__doc__)58def _capture_screenshot():59 '''60 截图保存为base6461 :return:62 '''63 return _driver.get_screenshot_as_base64()64@pytest.fixture(scope='session')65def driver(request):66 '''定义全局driver参数'''67 global _driver68 if _driver is None:...

Full Screen

Full Screen

report_base.py

Source:report_base.py Github

copy

Full Screen

...27 self.failed_tests.append(report)28 def append_skipped(self, report):29 self.skipped += 130 self.append(report)31 def pytest_runtest_makereport(self, item, call):32 demo_util.pause_show_info("pytest_runtest_makereport in {0}".format(self))33 report = _pytest.runner.pytest_runtest_makereport(item, call)34 if "__author__" not in dir(item.module):35 report.keywords["author"] = "unknown"36 else:37 report.keywords["author"] = item.module.__author__.decode("utf8").encode("gbk")38 return report39 def pytest_runtest_logreport(self, report):40 """41 每个testcase执行完的report处理42 """43 demo_util.pause_show_info("pytest_runtest_logreport at {0} in {1}".format(report.when, self))44 if report.passed:45 if report.when == "call": # ignore setup/teardown46 self.append_pass(report)47 elif report.failed:...

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 localstack 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