Best Python code snippet using pytest
udir.py
Source: udir.py
...3# This is copied from PyPy's vendored py lib. The latest py lib release4# (1.8.1) contains a bug and crashes if it sees another temporary directory5# in which we don't have write permission (e.g. because it's owned by someone6# else).7def make_numbered_dir(prefix='session-', rootdir=None, keep=3,8 lock_timeout = 172800, # two days9 min_timeout = 300): # five minutes10 """ return unique directory with a number greater than the current11 maximum one. The number is assumed to start directly after prefix.12 if keep is true directories with a number less than (maxnum-keep)13 will be removed.14 """15 if rootdir is None:16 rootdir = py.path.local.get_temproot()17 def parse_num(path):18 """ parse the number out of a path (if it matches the prefix) """19 bn = path.basename20 if bn.startswith(prefix):21 try:22 return int(bn[len(prefix):])23 except ValueError:24 pass25 # compute the maximum number currently in use with the26 # prefix27 lastmax = None28 while True:29 maxnum = -130 for path in rootdir.listdir():31 num = parse_num(path)32 if num is not None:33 maxnum = max(maxnum, num)34 # make the new directory35 try:36 udir = rootdir.mkdir(prefix + str(maxnum+1))37 except py.error.EEXIST:38 # race condition: another thread/process created the dir39 # in the meantime. Try counting again40 if lastmax == maxnum:41 raise42 lastmax = maxnum43 continue44 break45 # put a .lock file in the new directory that will be removed at46 # process exit47 if lock_timeout:48 lockfile = udir.join('.lock')49 mypid = os.getpid()50 if hasattr(lockfile, 'mksymlinkto'):51 lockfile.mksymlinkto(str(mypid))52 else:53 lockfile.write(str(mypid))54 def try_remove_lockfile():55 # in a fork() situation, only the last process should56 # remove the .lock, otherwise the other processes run the57 # risk of seeing their temporary dir disappear. For now58 # we remove the .lock in the parent only (i.e. we assume59 # that the children finish before the parent).60 if os.getpid() != mypid:61 return62 try:63 lockfile.remove()64 except py.error.Error:65 pass66 atexit.register(try_remove_lockfile)67 # prune old directories68 if keep:69 for path in rootdir.listdir():70 num = parse_num(path)71 if num is not None and num <= (maxnum - keep):72 if min_timeout:73 # NB: doing this is needed to prevent (or reduce74 # a lot the chance of) the following situation:75 # 'keep+1' processes call make_numbered_dir() at76 # the same time, they create dirs, but then the77 # last process notices the first dir doesn't have78 # (yet) a .lock in it and kills it.79 try:80 t1 = path.lstat().mtime81 t2 = lockfile.lstat().mtime82 if abs(t2-t1) < min_timeout:83 continue # skip directories too recent84 except py.error.Error:85 continue # failure to get a time, better skip86 lf = path.join('.lock')87 try:88 t1 = lf.lstat().mtime89 t2 = lockfile.lstat().mtime90 if not lock_timeout or abs(t2-t1) < lock_timeout:91 continue # skip directories still locked92 except py.error.Error:93 pass # assume that it means that there is no 'lf'94 try:95 path.remove(rec=1)96 except KeyboardInterrupt:97 raise98 except: # this might be py.error.Error, WindowsError ...99 pass100 # make link...101 try:102 username = os.environ['USER'] #linux, et al103 except KeyError:104 try:105 username = os.environ['USERNAME'] #windows106 except KeyError:107 username = 'current'108 src = str(udir)109 dest = src[:src.rfind('-')] + '-' + username110 try:111 os.unlink(dest)112 except OSError:113 pass114 try:115 os.symlink(src, dest)116 except (OSError, AttributeError, NotImplementedError):117 pass118 return udir119udir = make_numbered_dir(prefix = 'ffi-')120# Windows-only workaround for some configurations: see121# https://bugs.python.org/issue23246 (Python 2.7.9)122if sys.platform == 'win32':123 try:124 import setuptools125 except ImportError:...
tmpdir.py
Source: tmpdir.py
...28 basetemp = self.getbasetemp()29 if not numbered:30 p = basetemp.mkdir(basename)31 else:32 p = py.path.local.make_numbered_dir(prefix=basename,33 keep=0, rootdir=basetemp, lock_timeout=None)34 self.trace("mktemp", p)35 return p36 def getbasetemp(self):37 """ return base temporary directory. """38 try:39 return self._basetemp40 except AttributeError:41 basetemp = self.config.option.basetemp42 if basetemp:43 basetemp = py.path.local(basetemp)44 if basetemp.check():45 basetemp.remove()46 basetemp.mkdir()47 else:48 temproot = py.path.local.get_temproot()49 user = get_user()50 if user:51 # use a sub-directory in the temproot to speed-up52 # make_numbered_dir() call53 rootdir = temproot.join('pytest-of-%s' % user)54 else:55 rootdir = temproot56 rootdir.ensure(dir=1)57 basetemp = py.path.local.make_numbered_dir(prefix='pytest-',58 rootdir=rootdir)59 self._basetemp = t = basetemp.realpath()60 self.trace("new basetemp", t)61 return t62 def finish(self):63 self.trace("finish")64def get_user():65 """Return the current user name, or None if getuser() does not work66 in the current environment (see #1010).67 """68 import getpass69 try:70 return getpass.getuser()71 except (ImportError, KeyError):...
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!!