How to use mangle_test_address method in Pytest

Best Python code snippet using pytest

junitxml.py

Source:junitxml.py Github

copy

Full Screen

...72 ])73 return ''74 def record_testreport(self, testreport):75 assert not self.testcase76 names = mangle_test_address(testreport.nodeid)77 classnames = names[:-1]78 if self.xml.prefix:79 classnames.insert(0, self.xml.prefix)80 attrs = {81 "classname": ".".join(classnames),82 "name": bin_xml_escape(names[-1]),83 "file": testreport.location[0],84 }85 if testreport.location[1] is not None:86 attrs["line"] = testreport.location[1]87 self.attrs = attrs88 def to_xml(self):89 testcase = Junit.testcase(time=self.duration, **self.attrs)90 testcase.append(self.make_properties_node())91 for node in self.nodes:92 testcase.append(node)93 return testcase94 def _add_simple(self, kind, message, data=None):95 data = bin_xml_escape(data)96 node = kind(data, message=message)97 self.append(node)98 def _write_captured_output(self, report):99 for capname in ('out', 'err'):100 content = getattr(report, 'capstd' + capname)101 if content:102 tag = getattr(Junit, 'system-' + capname)103 self.append(tag(bin_xml_escape(content)))104 def append_pass(self, report):105 self.add_stats('passed')106 self._write_captured_output(report)107 def append_failure(self, report):108 # msg = str(report.longrepr.reprtraceback.extraline)109 if hasattr(report, "wasxfail"):110 self._add_simple(111 Junit.skipped,112 "xfail-marked test passes unexpectedly")113 else:114 if hasattr(report.longrepr, "reprcrash"):115 message = report.longrepr.reprcrash.message116 elif isinstance(report.longrepr, (unicode, str)):117 message = report.longrepr118 else:119 message = str(report.longrepr)120 message = bin_xml_escape(message)121 fail = Junit.failure(message=message)122 fail.append(bin_xml_escape(report.longrepr))123 self.append(fail)124 self._write_captured_output(report)125 def append_collect_error(self, report):126 # msg = str(report.longrepr.reprtraceback.extraline)127 self.append(Junit.error(bin_xml_escape(report.longrepr),128 message="collection failure"))129 def append_collect_skipped(self, report):130 self._add_simple(131 Junit.skipped, "collection skipped", report.longrepr)132 def append_error(self, report):133 self._add_simple(134 Junit.error, "test setup failure", report.longrepr)135 self._write_captured_output(report)136 def append_skipped(self, report):137 if hasattr(report, "wasxfail"):138 self._add_simple(139 Junit.skipped, "expected test failure", report.wasxfail140 )141 else:142 filename, lineno, skipreason = report.longrepr143 if skipreason.startswith("Skipped: "):144 skipreason = bin_xml_escape(skipreason[9:])145 self.append(146 Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason),147 type="pytest.skip",148 message=skipreason))149 self._write_captured_output(report)150 def finalize(self):151 data = self.to_xml().unicode(indent=0)152 self.__dict__.clear()153 self.to_xml = lambda: py.xml.raw(data)154@pytest.fixture155def record_xml_property(request):156 """Add extra xml properties to the tag for the calling test.157 The fixture is callable with ``(name, value)``, with value being automatically158 xml-encoded.159 """160 request.node.warn(161 code='C3',162 message='record_xml_property is an experimental feature',163 )164 xml = getattr(request.config, "_xml", None)165 if xml is not None:166 node_reporter = xml.node_reporter(request.node.nodeid)167 return node_reporter.add_property168 else:169 def add_property_noop(name, value):170 pass171 return add_property_noop172def pytest_addoption(parser):173 group = parser.getgroup("terminal reporting")174 group.addoption(175 '--junitxml', '--junit-xml',176 action="store",177 dest="xmlpath",178 metavar="path",179 default=None,180 help="create junit-xml style report file at given path.")181 group.addoption(182 '--junitprefix', '--junit-prefix',183 action="store",184 metavar="str",185 default=None,186 help="prepend prefix to classnames in junit-xml output")187def pytest_configure(config):188 xmlpath = config.option.xmlpath189 # prevent opening xmllog on slave nodes (xdist)190 if xmlpath and not hasattr(config, 'slaveinput'):191 config._xml = LogXML(xmlpath, config.option.junitprefix)192 config.pluginmanager.register(config._xml)193def pytest_unconfigure(config):194 xml = getattr(config, '_xml', None)195 if xml:196 del config._xml197 config.pluginmanager.unregister(xml)198def mangle_test_address(address):199 path, possible_open_bracket, params = address.partition('[')200 names = path.split("::")201 try:202 names.remove('()')203 except ValueError:204 pass205 # convert file path to dotted path206 names[0] = names[0].replace("/", '.')207 names[0] = _py_ext_re.sub("", names[0])208 # put any params back209 names[-1] += possible_open_bracket + params210 return names211class LogXML(object):212 def __init__(self, logfile, prefix):...

Full Screen

Full Screen

mproc.py

Source:mproc.py Github

copy

Full Screen

...72 testcase.append(node)73 return str(testcase.unicode(indent=0))74 def record_testreport(self, testreport):75 assert not self.testcase76 names = mangle_test_address(testreport.nodeid)77 classnames = names[:-1]78 if self.xml.prefix:79 classnames.insert(0, self.xml.prefix)80 attrs = {81 "classname": ".".join(classnames),82 "name": bin_xml_escape(names[-1]),83 "file": testreport.location[0],84 }85 if testreport.location[1] is not None:86 attrs["line"] = testreport.location[1]87 if hasattr(testreport, "url"):88 attrs["url"] = testreport.url89 self.attrs = attrs90 def finalize(self):...

Full Screen

Full Screen

plugin.py

Source:plugin.py Github

copy

Full Screen

...35 json = getattr(config, "json", None)36 if json:37 del config.json38 config.pluginmanager.unregister(json)39def mangle_test_address(address):40 """Split and modify test address to required format"""41 path, brack, params = address.partition("[")42 names = path.split("::")43 try:44 names.remove("()")45 except ValueError:46 pass47 names[0] = names[0].replace("/", ".")48 names[0] = _py_ext_re.sub("", names[0])49 names[-1] += brack + params50 return names51def restructure(data):52 restructured_list = []53 temp_list = []54 for i in data:55 if isinstance(i, OrderedDict):56 restructured_dict = OrderedDict(57 [("railflow_test_attributes", OrderedDict(temp_list))]58 )59 restructured_dict.update(i)60 restructured_list.append(restructured_dict)61 temp_list = []62 else:63 temp_list.append(i)64 return restructured_list65class JiraJsonReport(object):66 """67 Creates Json report68 """69 def __init__(self, jsonpath):70 self.results = []71 self.jsonpath = jsonpath72 self.class_list = [73 "testrail_user",74 "testrail_project",75 "case_fields",76 "result_fields",77 "test_path",78 "case_type",79 "case_priority",80 "assign",81 ]82 self.fun_list = [83 "author",84 "description",85 "jira_id",86 "test_path",87 "case_fields",88 "result_fields",89 "id_mappings",90 "case_type",91 "case_priority",92 ]93 def append(self, result):94 self.results.append(result)95 def build_result(self, report, status, message):96 """97 Builds test results98 """99 result = OrderedDict()100 names = mangle_test_address(report.nodeid)101 result["suite_name"] = names[-2]102 result["test_name"] = names[-1]103 if report.test_doc is None:104 result["details"] = report.test_doc105 else:106 result["details"] = report.test_doc.strip()107 result["markers"] = report.test_marker108 result["result"] = status109 result["duration"] = getattr(report, "duration", 0.0)110 result["timestamp"] = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")111 result["message"] = message112 result["file_name"] = report.location[0]113 self.append(result)114 def append_pass(self, report):...

Full Screen

Full Screen

pytest_excel.py

Source:pytest_excel.py Github

copy

Full Screen

...22 excel = getattr(config, '_excel', None)23 if excel:24 del config._excel25 config.pluginmanager.unregister(excel)26def mangle_test_address(address):27 path, possible_open_bracket, params = address.partition('[')28 names = path.split("::")29 try:30 names.remove('()')31 except ValueError:32 pass33 names[0] = names[0].replace("/", '.')34 names[0] = _py_ext_re.sub("", names[0])35 names[-1] += possible_open_bracket + params36 return names37class ExcelReporter(object):38 def __init__(self, excelpath):39 self.results = []40 self.wbook = Workbook()41 self.rc = 142 self.excelpath = datetime.now().strftime(excelpath) 43 def append(self, result):44 self.results.append(result)45 def create_sheet(self, column_heading):46 self.wsheet = self.wbook.create_sheet(index=0)47 for heading in column_heading:48 index_value = column_heading.index(heading) + 149 heading = heading.replace("_", " ").upper()50 self.wsheet.cell(row=self.rc, column=index_value).value = heading51 self.rc = self.rc + 152 def update_worksheet(self):53 for data in self.results:54 for key, value in data.items():55 try:56 self.wsheet.cell(row=self.rc, column=list(data).index(key) + 1).value = value57 except ValueError:58 self.wsheet.cell(row=self.rc, column=list(data).index(key) + 1).value = str(vars(value))59 self.rc = self.rc + 160 def save_excel(self):61 self.wbook.save(filename=self.excelpath)62 def build_result(self, report, status, message):63 result = OrderedDict()64 names = mangle_test_address(report.nodeid)65 result['suite_name'] = names[-2]66 result['test_name'] = names[-1]67 if report.test_doc is None:68 result['description'] = report.test_doc69 else:70 result['description'] = report.test_doc.strip()71 result['result'] = status72 result['duration'] = getattr(report, 'duration', 0.0)73 result['timestamp'] = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')74 result['message'] = message75 result['file_name'] = report.location[0]76 result['markers'] = report.test_marker77 self.append(result)78 def append_pass(self, report):79 status = "PASSED"80 message = None81 self.build_result(report, status, message)82 def append_failure(self, report):83 if hasattr(report, "wasxfail"):84 status = "XPASSED"85 message = "xfail-marked test passes Reason: %s " % report.wasxfail86 else:87 if hasattr(report.longrepr, "reprcrash"):88 message = report.longrepr.reprcrash.message89 elif isinstance(report.longrepr, (unicode, str)):90 message = report.longrepr91 else:92 message = str(report.longrepr)93 status = "FAILED"94 self.build_result(report, status, message)95 def append_error(self, report):96 message = report.longrepr97 status = "ERROR"98 self.build_result(report, status, message)99 def append_skipped(self, report):100 if hasattr(report, "wasxfail"):101 status = "XFAILED"102 message = "expected test failure Reason: %s " % report.wasxfail103 else:104 status = "SKIPPED"105 _, _, message = report.longrepr106 if message.startswith("Skipped: "):107 message = message[9:]108 self.build_result(report, status, message)109 def build_tests(self, item):110 result = OrderedDict()111 names = mangle_test_address(item.nodeid)112 result['suite_name'] = names[-2]113 result['test_name'] = names[-1]114 if item.obj.__doc__ is None:115 result['description'] = item.obj.__doc__116 else:117 result['description'] = item.obj.__doc__.strip()118 result['file_name'] = item.location[0]119 test_marker = []120 test_message = []121 for k, v in item.keywords.items():122 if isinstance(v, list):123 for x in v:124 if isinstance(x, Mark):125 if x.name != 'usefixtures':...

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