MCPcopy Create free account
hub / github.com/pytest-dev/pytest / getbasetemp

Method getbasetemp

src/_pytest/tmpdir.py:102–155  ·  view source on GitHub ↗

Return the base temporary directory, creating it if needed.

(self)

Source from the content-addressed store, hash-verified

100 return p
101
102 def getbasetemp(self) -> Path:
103 """Return the base temporary directory, creating it if needed."""
104 if self._basetemp is not None:
105 return self._basetemp
106
107 if self._given_basetemp is not None:
108 basetemp = self._given_basetemp
109 if basetemp.exists():
110 rm_rf(basetemp)
111 basetemp.mkdir(mode=0o700)
112 basetemp = basetemp.resolve()
113 else:
114 from_env = os.environ.get("PYTEST_DEBUG_TEMPROOT")
115 temproot = Path(from_env or tempfile.gettempdir()).resolve()
116 user = get_user() or "unknown"
117 # use a sub-directory in the temproot to speed-up
118 # make_numbered_dir() call
119 rootdir = temproot.joinpath(f"pytest-of-{user}")
120 try:
121 rootdir.mkdir(mode=0o700, exist_ok=True)
122 except OSError:
123 # getuser() likely returned illegal characters for the platform, use unknown back off mechanism
124 rootdir = temproot.joinpath("pytest-of-unknown")
125 rootdir.mkdir(mode=0o700, exist_ok=True)
126 # Because we use exist_ok=True with a predictable name, make sure
127 # we are the owners, to prevent any funny business (on unix, where
128 # temproot is usually shared).
129 # Also, to keep things private, fixup any world-readable temp
130 # rootdir's permissions. Historically 0o755 was used, so we can't
131 # just error out on this, at least for a while.
132 if sys.platform != "win32":
133 uid = os.getuid()
134 rootdir_stat = rootdir.stat()
135 # getuid shouldn't fail, but cpython defines such a case.
136 # Let's hope for the best.
137 if uid != -1:
138 if rootdir_stat.st_uid != uid:
139 raise OSError(
140 f"The temporary directory {rootdir} is not owned by the current user. "
141 "Fix this and try again."
142 )
143 if (rootdir_stat.st_mode & 0o077) != 0:
144 os.chmod(rootdir, rootdir_stat.st_mode & ~0o077)
145 basetemp = make_numbered_dir_with_cleanup(
146 prefix="pytest-",
147 root=rootdir,
148 keep=3,
149 lock_timeout=LOCK_TIMEOUT,
150 mode=0o700,
151 )
152 assert basetemp is not None, basetemp
153 self._basetemp = basetemp
154 self._trace("new basetemp", basetemp)
155 return basetemp
156
157
158def get_user() -> Optional[str]:

Calls 5

rm_rfFunction · 0.85
get_userFunction · 0.85
mkdirMethod · 0.45
getMethod · 0.45