Best Python code snippet using pytest
pytester.py
Source:pytester.py
...39 ext_args = [case_file]40 conf = pm.hook.pytest_cmdline_parse(pluginmanager=pm, args=ext_args)41 s = main.Session.from_config(conf)42 conf.hook.pytest_sessionstart(session=s)43 conf.hook.pytest_collection(session=s)44 session = s45 reports = []46 for i, item in enumerate(session.items):47 nextitem = session.items[i + 1] if i + 1 < len(session.items) else None48 reports.append(runner.runtestprotocol(item=item, log=False, nextitem=nextitem))49 call_pass = 050 call_fail = 051 html = ""52 for r in reports:53 output = """54 <tr><td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td></tr>55 <tr><td></td> <td>{}</td> <td>{}</td> <td>{}</td></tr>56 <tr><td></td> <td>{}</td> <td>{}</td> <td>{}</td></tr>57 """.format(r[0].head_line, r[0].when, r[0].outcome, r[0].longreprtext,58 r[1].when, r[1].outcome, r[1].longreprtext,59 r[2].when, r[2].outcome, r[2].longreprtext, )60 html += output61 if r[1].outcome == "passed":62 call_pass += 163 else:64 call_fail += 165 head = """66 <html>67 <body>68 <p>{}</p>69 <table border="1">70 <tr>71 <th>Case Name</th>72 <th>Stage</th>73 <th>Result</th>74 <th>Info</th>75 </tr>76 """.format(case_file)77 tail = """78 </table>79 </body>80 </html>81 """82 with open(outputdir + '/log.html', 'w') as af:83 af.write(head + html + tail)84 return {"result": "[ PASSED ]" if call_fail == 0 else "[ FAILED ]",85 "PASS": call_pass, "FAIL": call_fail, "log": "api_report/" + jobid + "/log.html"}86def get_pytest_data(path):87 """88 pytest testcase finder89 :param app: app90 :param path: pytest '.py' file91 :return:92 """93 log.info("解æè·¯å¾ä¸çæµè¯ç¨ä¾:{}".format(path))94 children = []95 conf = config.get_config(os.path.dirname(path))96 pm = conf.pluginmanager97 args = ["--co", path]98 conf = pm.hook.pytest_cmdline_parse(pluginmanager=pm, args=args)99 s = main.Session.from_config(conf)100 # conf._do_configure() :May be needed101 conf.hook.pytest_sessionstart(session=s)102 conf.hook.pytest_collection(session=s)103 for it in s.items:104 case_name = it.nodeid.split("::", maxsplit=1)[1]105 status = db_cli.get_casestatus(path, case_name)106 print("status:{} {} :{}".format(path,case_name,status))107 icons = 'icon-step'108 if status == 'FAIL':109 icons = 'icon-step_fail'110 if status == 'PASS':111 icons = 'icon-step_pass'112 children.append({113 "text": case_name, "iconCls": icons, "state": "open",114 "attributes": {115 "name": case_name, "category": "step", "key": path,116 },117 "children": []118 })119 return children120def debug_pytest_run(path, user="unknown", is_api=False):121 """122 editorçé¢è°è¯è¿è¡ pytest æµè¯ç¨ä¾123 :param user: run user124 :param path: pytest file125 :return: output->str126 """127 log.info("çé¢æ§è¡pytestç¨ä¾æ件:{}".format(path))128 conf = config.get_config(os.path.dirname(path))129 pm = conf.pluginmanager130 args = [path]131 conf = pm.hook.pytest_cmdline_parse(pluginmanager=pm, args=args)132 s = main.Session.from_config(conf)133 conf.hook.pytest_sessionstart(session=s)134 conf.hook.pytest_collection(session=s)135 session = s136 reports = []137 for i, item in enumerate(session.items):138 nextitem = session.items[i + 1] if i + 1 < len(session.items) else None139 reports.append(runner.runtestprotocol(item=item, log=False, nextitem=nextitem))140 html = ""141 for r in reports:142 output = """143 <tr><td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td></tr>144 <tr><td></td> <td>{}</td> <td>{}</td> <td>{}</td></tr>145 <tr><td></td> <td>{}</td> <td>{}</td> <td>{}</td></tr>146 """.format(r[0].head_line, r[0].when, r[0].outcome, r[0].longreprtext,147 r[1].when, r[1].outcome, r[1].longreprtext,148 r[2].when, r[2].outcome, r[2].longreprtext,)149 html += output150 head = """151 <html>152 <body>153 <p>{}</p>154 <table border="1">155 <tr>156 <th>Case Name</th>157 <th>Stage</th>158 <th>Result</th>159 <th>Info</th>160 </tr>161 """.format(path)162 tail = """163 </table>164 </body>165 </html>166 """167 return head + html + tail168def pytest_run(case_key, args="", user='', catigory=''):169 log.info("å¼å§è¿è¡pytestç¨ä¾ï¼{}".format(case_key))170 username = user if user != '' else 'unknown'171 driver = catigory if catigory != '' else username172 project = os.environ["PROJECT_NAME"]173 output = os.environ["AUTO_HOME"] + "/jobs/%s/%s" % (username, project)174 if not exists_path(output):175 mk_dirs(output)176 (out, index) = reset_next_build_numb(output)177 log.info("out:{} , index:{}".format(out, index))178 mk_dirs(out) if not exists_path(out) else None179 from _pytest import config180 from _pytest import main181 from _pytest import runner182 conf = config.get_config(os.path.dirname(case_key))183 pm = conf.pluginmanager184 args = [case_key]185 print("pytest config args: {}".format(args))186 conf = pm.hook.pytest_cmdline_parse(pluginmanager=pm, args=args)187 s = main.Session.from_config(conf)188 conf.hook.pytest_sessionstart(session=s)189 conf.hook.pytest_collection(session=s)190 with open(out + "/cmd.txt", 'w') as f:191 f.write("{}|pytest|{}|--outputdir={}|{}\n".format(driver, ','.join(args),out,case_key))192 log.info("Write: {}/cmd.txt".format(out))193 reports = []194 for i, item in enumerate(s.items):195 log.info("name: {} ,fspath: {}".format(item.name, item.fspath))196 nextitem = s.items[i + 1] if i + 1 < len(s.items) else None197 reports.append(runner.runtestprotocol(item=item, log=False, nextitem=nextitem))198 db_cli.insert_loginfo(username, 'task', 'run', case_key, 'OK')199 html = ""200 for r in reports:201 output = """202 <tr><td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td></tr>203 <tr><td></td> <td>{}</td> <td>{}</td> <td>{}</td></tr>...
hookspec.py
Source:hookspec.py
...35pytest_runtestloop.firstresult = True36# -------------------------------------------------------------------------37# collection hooks38# -------------------------------------------------------------------------39def pytest_collection(session):40 """ perform the collection protocol for the given session. """41pytest_collection.firstresult = True42def pytest_collection_modifyitems(session, config, items):43 """ called after collection has been performed, may filter or re-order44 the items in-place."""45def pytest_collection_finish(session):46 """ called after collection has been performed and modified. """47def pytest_ignore_collect(path, config):48 """ return True to prevent considering this path for collection.49 This hook is consulted for all files and directories prior to calling50 more specific hooks.51 """52pytest_ignore_collect.firstresult = True53def pytest_collect_directory(path, parent):...
plugin.py
Source:plugin.py
...22 self.durations["pytest_sessionstart"] = end - start23 # === Collection Hooks ===24 # https://docs.pytest.org/en/stable/reference.html#collection-hooks25 @pytest.hookimpl(hookwrapper=True, tryfirst=True)26 def pytest_collection(self, session):27 start = time.time()28 yield29 end = time.time()30 self.durations["pytest_collection"] = end - start31 @pytest.hookimpl(hookwrapper=True, tryfirst=True)32 def pytest_collect_file(self, path, parent):33 start = time.time()34 yield35 end = time.time()36 self.durations[f"pytest_collect_file:{path}"] = end - start37 @pytest.hookimpl(hookwrapper=True, tryfirst=True)38 def pytest_itemcollected(self, item):39 start = time.time()40 yield...
worker.py
Source:worker.py
...59 def pytest_collectreport(self, report):60 pass61 def report_collect(self, final=False):62 pass63 def pytest_collection(self):...
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.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!