How to use pytest_sessionfinish method in Pytest

Best Python code snippet using pytest

spydist.py

Source:spydist.py Github

copy

Full Screen

...80 filename = os.path.join(self.logs_path, "batch.server")81 utils.write_file(filename, str(self.server.port))82 self.thread = threading.Thread(target=self.server.start)83 self.thread.start()84 def pytest_sessionfinish(self, session):85 debug("master: pytest_sessionfinish", session)86 def pytest_runtestloop(self):87 if wa.start_slaves_from_master:88 slaves_init(self.logs_path)89 try:90 conn = rpyc.connect("127.0.0.1", self.port)91 while 1:92 if not getattr(conn.root, "has_pending")():93 break94 debug("master: pytest_runtestloop")95 time.sleep(5)96 except KeyboardInterrupt:97 trace("master: interrupted")98 getattr(conn.root, "shutdown")()99 time.sleep(5)100 os._exit(0)101 def pytest_terminal_summary(self, terminalreporter):102 debug("master: pytest_terminal_summary", terminalreporter)103class BatchSlave(object):104 def __init__(self, config, logs_path):105 self.config = config106 self.items = []107 self.logs_path = logs_path108 @pytest.mark.trylast109 def pytest_sessionstart(self, session):110 debug("slave: pytest_sessionstart", session)111 def pytest_sessionfinish(self, session):112 debug("slave: pytest_sessionfinish", session)113 @pytest.hookimpl(trylast=True)114 def pytest_collection_modifyitems(self, session, config, items):115 debug("slave: pytest_collection_modifyitems", session, config, items)116 self.items = items117 def pytest_runtestloop(self):118 def search_nodeid(entries, nodeid):119 for ent in entries:120 if nodeid == ent.nodeid:121 return ent122 return None123 def finish_test(item):124 getattr(conn.root, "finish_test")(item.nodeid)125 def get_test(entries):...

Full Screen

Full Screen

html_mpi.py

Source:html_mpi.py Github

copy

Full Screen

...21 Do not report cause you redo it after the gather22 """23 # HTMLReport.pytest_runtest_logreport(self, report)24 pass25 def pytest_sessionfinish(self, session):26 """27 """28 # print("pytest_sessionfinish:: ", len(self.mpi_reporter.mpi_reports.items()))29 assert(self.mpi_reporter.post_done == True)30 # print("\n", self.comm.Get_rank(), "HTMLReportMPI::pytest_sessionfinish flag 4")31 for i_report, report in self.mpi_reporter.reports_gather.items():32 # print(i_report, " ---> ", report)33 #Copy is mandatory because pytest-html v3.1.1 refill test_report.longrepr with a string instead34 #of tuple (see pytest_html/plugin.py, l730)35 HTMLReport.pytest_runtest_logreport(self, copy(report[0]))36 HTMLReport.pytest_sessionfinish(self, session)37# ------------------------------------------------------------------------38 # def pytest_sessionfinish(self, session):39 # # -----------------------------------------------------------------40 # for nodeid, report_list in self.mpi_reporter.mpi_reports.items():41 # # print("nodeid::", nodeid)42 # assert(len(report_list) > 0)43 # # > Initialize with the first reporter44 # i_rank_report_init, report_init = report_list[0]45 # greport = TestReport(nodeid,46 # report_init.location,47 # report_init.keywords,48 # report_init.outcome,49 # None, # longrepr50 # report_init.when)51 # # print("report_init.location::", report_init.location)52 # # print("report_init.longrepr::", type(report_init.longrepr), report_init.longrepr)53 # collect_longrepr = []54 # # i_rank_report_init55 # # if(report_init.longrepr):56 # # greport.longrepr = report_init.longrepr57 # # fake_trace_back_init = ReprTraceback([ReprEntryNative(f"\n\n ----------------------- On rank {i_rank_report_init} ----------------------- \n\n")], None, None)58 # # # greport.longrepr = ExceptionChainRepr([(fake_trace_back_init, None, None)])59 # # collect_longrepr.append( (fake_trace_back_init, None, None) )60 # # collect_longrepr.append( (report_init.longrepr, None, None))61 # # > We need to rebuild a TestReport object, location can be false62 # # > Report appears in rank increasing order63 # for i_rank_report, test_report in report_list:64 # # for i_rank_report, test_report in report_list:65 # # print("test_report::", i_rank_report, test_report)66 # if(test_report.outcome == 'failed'):67 # greport.outcome = test_report.outcome68 # if(test_report.longrepr):69 # fake_trace_back = ReprTraceback([ReprEntryNative(f"\n\n----------------------- On rank {i_rank_report} ----------------------- \n\n")], None, None)70 # collect_longrepr.append((fake_trace_back , None, None))71 # collect_longrepr.append((test_report.longrepr, None, None))72 # # print("******")73 # # for i_collect in collect_longrepr:74 # # print(" -----> ", type(i_collect), i_collect)75 # # print("******")76 # if(len(collect_longrepr) > 0):77 # greport.longrepr = ExceptionChainRepr(collect_longrepr)78 # self.reports[nodeid] = [greport]79 # # -----------------------------------------------------------------80 # print("len(self.reports)::", len(self.reports))81 # HTMLReport.pytest_sessionfinish(self, session)82 # return83 # # ooooooooooooooooooooooooooooooooooooooooooooooooooooooo84 # # > On gather tout85 # # Il faut trier d'abord, pour un test la liste des rang.86 # # Puis on refait depuis le debut le rapport87 # for test_name, test_reports in self.mpi_reporter.mpi_reports.items():88 # # print("test_name::", test_name)89 # for test_report in test_reports:90 # print("test_report::", test_report)91 # if(test_report is None):92 # continue93 # # Seek the current report94 # lreports = self.reports[test_name[1]]95 # greport = None96 # for lreport in lreports:97 # print("test_report.when == ", test_report.when )98 # print("lreport .when == ", lreport.when )99 # print("lreport .location == ", lreport.location )100 # if(test_report.when == lreport.when ):101 # greport = lreport102 # # Il serai préférable de tout refaire :103 # # TestReport() ...104 # # see junitxml :: filename, lineno, skipreason = report.longrepr105 # # > We find out the good report - Append106 # if(test_report.longrepr):107 # # print("type(test_report.longrepr) :: ", type(test_report.longrepr))108 # # print("test_report.longrepr :: ", test_report.longrepr)109 # # greport.longrepr.addsection(f" rank {test_name[0]}", test_report.longrepr)110 # # greport.longrepr.addsection(f" rank {test_name[0]}", "oooo")111 # # if greport.longrepr and not isinstance(greport.longrepr, tuple): # A regarder112 # # print("type(greport.longrepr) = ", type(greport.longrepr))113 # # print("type(greport) = ", type(greport))114 # # filename, lineno, skipreason = greport.longrepr115 # # print("filename, lineno, skipreason::", filename, lineno, skipreason)116 # if not greport:117 # continue118 # elif greport.longrepr:119 # greport.longrepr.addsection(f" rank {test_name[0]}", str(test_report.longrepr))120 # else:121 # greport.longrepr = test_report.longrepr122 # if(test_report.outcome == 'failed'):123 # greport.outcome = test_report.outcome124 # # ooooooooooooooooooooooooooooooooooooooooooooooooooooooo125 # HTMLReport.pytest_sessionfinish(self, session)126 # tmp = report_init.longrepr.chain[0]127 # tmp[2] = "titit"128 # report_init.longrepr.chain.append( report_init.longrepr.chain[0])129 # report_init.longrepr.chain.append( (tmp[0], tmp[1], "-"*100))130 # greport.longrepr.addsection(f" rank {i_rank_report_init}", str(report_init.longrepr))131 # greport.longrepr.addsection(f" rank {i_rank_report_init}", str(report_init.longrepr))132 # print("report_init.longrepr.chain::", type(report_init.longrepr), report_init.longrepr.chain)133 # print("*"*100)134 # print("report_init.longrepr.chain[0][0]::", type(report_init.longrepr.chain[0][0]), report_init.longrepr.chain[0][0].reprentries)135 # print("*"*100)136 # print("*"*100)137 # print("report_init.longrepr.chain[0][0]::", type(report_init.longrepr.chain[0][0]), report_init.longrepr.chain[0][0].extraline)138 # print("*"*100)139 # print("*"*100)...

Full Screen

Full Screen

test_profile.py

Source:test_profile.py Github

copy

Full Screen

...17def test_combines_profs():18 plugin = Profiling(False)19 plugin.profs = [sentinel.prof0, sentinel.prof1]20 with patch('pstats.Stats') as Stats:21 plugin.pytest_sessionfinish(Mock(), Mock())22 Stats.assert_called_once_with(sentinel.prof0)23 Stats.return_value.add.assert_called_once_with(sentinel.prof1)24 assert Stats.return_value.dump_stats.called25def test_generates_svg():26 plugin = Profiling(True)27 plugin.profs = [sentinel.prof]28 with patch('pstats.Stats'):29 with patch('pipes.Template') as Template:30 plugin.pytest_sessionfinish(Mock(), Mock())31 assert any('gprof2dot' in args[0][0] for args in Template.return_value.append.call_args_list)32 assert Template.return_value.copy.called33def test_writes_summary():34 plugin = Profiling(False)35 plugin.profs = [sentinel.prof]36 terminalreporter, stats = Mock(), Mock()37 with patch('pstats.Stats', return_value=stats) as Stats:38 plugin.pytest_sessionfinish(Mock(), Mock())39 plugin.pytest_terminal_summary(terminalreporter)40 assert 'Profiling' in terminalreporter.write.call_args[0][0]41 assert Stats.called_with(stats, stream=terminalreporter)42def test_writes_summary_svg():43 plugin = Profiling(True)44 plugin.profs = [sentinel.prof]45 terminalreporter = Mock()46 with patch('pstats.Stats'):47 with patch('pipes.Template'):48 plugin.pytest_sessionfinish(Mock(), Mock())49 plugin.pytest_terminal_summary(terminalreporter)50 assert 'SVG' in terminalreporter.write.call_args[0][0]51def test_adds_options():52 parser = Mock()53 pytest_addoption(parser)54 parser.getgroup.assert_called_with('Profiling')55 group = parser.getgroup.return_value56 group.addoption.assert_any_call('--profile', action='store_true', help=ANY)57 group.addoption.assert_any_call('--profile-svg', action='store_true', help=ANY)58def test_configures():59 config = Mock(getvalue=lambda x: x == 'profile')60 with patch('pytest_profiling.Profiling') as Profiling:61 pytest_configure(config)62 config.pluginmanager.register.assert_called_with(Profiling.return_value)...

Full Screen

Full Screen

conftest.py

Source:conftest.py Github

copy

Full Screen

...15 """ pytest_sessionstart hook16 This runs *before* import and collection of tests.17 This is *THE* place to do mocking of things that are global,18 such as `appdirs`.19 Do teardown in `pytest_sessionfinish()`20 """21 print("Pre-Session Setup..")22 # Looks like there's no public API to get the resolved value of pytest base temp dir23 # (https://docs.pytest.org/en/6.2.x/tmpdir.html#the-default-base-temporary-directory).24 Vars.tmpdir_home = pathlib.Path(tempfile.mkdtemp(prefix='pytest-fake_home'))25 Vars.tmpdir_data = Vars.tmpdir_home / 'appdirs_datadir'26 Vars.tmpdir_data.mkdir()27 Vars.tmpdir_cache = Vars.tmpdir_home / 'appdirs_cachedir'28 Vars.tmpdir_cache.mkdir()29 # Mockers that need to be loaded before any of our code30 Vars.extrasession_mockers.extend([31 mock.patch('appdirs.user_data_dir', lambda *x: str(Vars.tmpdir_data / x[0] if x else Vars.tmpdir_data)),32 mock.patch('appdirs.user_cache_dir', lambda *x: str(Vars.tmpdir_cache / x[0] if x else Vars.tmpdir_cache)),33 ])34 for mocker in Vars.extrasession_mockers:35 mocker.start()36def pytest_sessionfinish(session, exitstatus):37 """ pytest_sessionfinish hook38 This runs *after* any finalizers or other session activities.39 Performs teardown for `pytest_sessionstart()`40 """41 print("\nPost-session Teardown..")42 shutil.rmtree(Vars.tmpdir_home)43 for mocker in Vars.extrasession_mockers:44 mocker.stop()45# scope: function, class, module, or session46# autouse: boolean. Apply to all instances of the given scope.47@pytest.fixture(scope='session', autouse=True)48def each_session(request):49 print("\nSetup session..")50 def teardown(): # can be named whatever...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest 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