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):...
Deleting py.test tmpdir directory after successful test case
Determine if variable is defined in Python
pytest fixture not found (pytest-bdd)
Don't show long options twice in print_help() from argparse
pytest -k expression failing when trying to match multiple parameterized tests
Python Unit Testing: Automatically Running the Debugger when a test fails
Python pathlib.unlink: 'str' object has no attribute '_accessor'
How do I merge two dictionaries in a single expression?
How to access NodeJS GraphQL service in Python
Get statistics for each group (such as count, mean, etc) using pandas GroupBy?
You should create a tmpdir fixture that creates the tempdir, passes it into your code and afterwards deletes it.
Additionally, the fixture must be set to always delete the tempdir, even on failure. Otherwise you may leave behind an unclean state, which could cause other tests to fail (without the user noticing).
Instead I recommend either
--pdb
to drop into Python Debugger on errors. The fixture will not yet have cleaned up and you can inspect the files.In any case an unclean tmpdir state will be a conscious decision by the user and will prevent unexpected sideeffects.
Check out the latest blogs from LambdaTest on this topic:
Automation testing is vital to the entire process of delivering a successful web product. The challenge associated with testing a web site or web app grows manifolds if it’s built for a global audience (particularly non-English audience). Automation tests have to be performed to ensure that the product features (including the content) cater to specific locales. That’s why Localization testing using Selenium WebDriver has become increasingly relevant when a plethora of software products are being built for the “world”!
When anyone refers to automated browser testing, it somehow means that the testing will be performed on the latest browsers like Chrome, Firefox, etc. It would come as a surprise if someone from your team meant that the testing should be done on IE (or Internet Explorer) using Selenium IE Driver or Selenium Internet Explorer Driver.
A web product’s user experience is one of the key elements that help in user acquisition and user retention. Though immense focus should be given to the design & development of new product features, a continuous watch should be kept on the overall user experience. Like 404 pages (or dead links), broken images on a website (or web app) could also irk the end-users. Manual inspection and removal of broken images is not a feasible and scalable approach. Instead of using third-party tools to inspect broken images, you should leverage Selenium automation testing and see how to find broken images using Selenium WebDriver on your website.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium 4 and Selenium Python Tutorial
Although browsers such as Firefox and Chrome have made downloading files easier, these downloads depend on users visiting a website and manually clicking a download button. This can be a problem if the user is interested in downloading multiple files.
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!!