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):...
Can I make the pytest doctest module ignore a file?
Python2: Get longest Common Prefix path
How do I check if a string represents a number (float or int)?
How to pass multiple arguments in pytest using command line?
How to link PyCharm with PySpark?
Python order Dict with a pre-defined order
Is there a way to specify which pytest tests to run from a file?
What are metaclasses in Python?
Closing a file so I can delete it on Windows in Python?
Eclipse (with Pydev) keeps throwing SyntaxError
As MasterAndrey has mentioned, pytest_ignore_collect
should do the trick. Important to note that you should put conftest.py
to root folder (the one you run tests from).
Example:
import sys
def pytest_ignore_collect(path):
if sys.version_info[0] > 2:
if str(path).endswith("__py2.py"):
return True
else:
if str(path).endswith("__py3.py"):
return True
Since pytest v4.3.0 there is also --ignore-glob
flag which allows to ignore by pattern. Example:
pytest --doctest-modules --ignore-glob="*__py3.py" dir/
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial.
It has been around a year since we went live with the first iteration of LambdaTest Platform. We started off our product offering manual cross browser testing solutions and kept expanding our platform. We were asked many feature requests, and we implemented quite a lot of them. However, the biggest demand was to bring automation testing to the platform. Today we deliver on this feature.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.
There are many software products that are built for a global audience. In my tenure as a developer, I have worked on multiple web (website or web app) projects that supported different languages. Though the Selenium framework was used for automation testing, using Internationalization in Selenium WebDriver Tutorial posed a huge challenge.
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!!