Best Python code snippet using pytest
pytester.py
Source:pytester.py
...36 log.info("çé¢æ§è¡pytestç¨ä¾æ件:{}".format(case_file))37 conf = config.get_config(os.path.dirname(case_file))38 pm = conf.pluginmanager39 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:...
pytestrunner.py
Source:pytestrunner.py
...25 def main():26 _pluginmanager = get_plugin_manager()27 hook = _pluginmanager.hook28 try:29 config = hook.pytest_cmdline_parse(30 pluginmanager=_pluginmanager, args=args)31 exitstatus = hook.pytest_cmdline_main(config=config)32 except pytest.UsageError:33 e = sys.exc_info()[1]34 sys.stderr.write("ERROR: %s\n" %(e.args[0],))35 exitstatus = 336 return exitstatus37else:38 def main():39 config = py.test.config40 try:41 config.parse(args)42 config.pluginmanager.do_configure(config)43 session = config.initsession()...
_pytest.py
Source:_pytest.py
2import sys3def run_pytest():4 class EditConfig:5 @pytest.hookimpl(hookwrapper=True)6 def pytest_cmdline_parse(pluginmanager, args):7 args.extend(8 [9 "--tb=short",10 "-o",11 "console_output_style=classic",12 "-o",13 "default_alt_async_timeout=1",14 "-p",15 "helpers_namespace",16 ]17 )18 yield...
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!!