Skip to content

Instantly share code, notes, and snippets.

@bukzor
Last active January 18, 2024 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bukzor/085b1c2bdaa5bc6033db50d718c48bd3 to your computer and use it in GitHub Desktop.
Save bukzor/085b1c2bdaa5bc6033db50d718c48bd3 to your computer and use it in GitHub Desktop.
Why is there a random unexpected chdir on ctrl+c??
"""this test passes if you let it run, but fails assert_pwd if you ctrl-c"""
from __future__ import annotations
import contextlib
import typing
from os import chdir, environ, getcwd
from pathlib import Path
from time import sleep
from pytest import fixture
T = typing.TypeVar("T")
Generator = typing.Generator[T, None, None] # py313/PEP696 shim
def assert_pwd(msg: object) -> Path:
"""double-check that $PWD stays accurate"""
pwd = Path(environ["PWD"])
cwd = Path.cwd()
same = pwd.samefile(cwd)
print("ASSERT_PWD", msg, "OK" if same else "FAIL!")
if not same:
print(" ", pwd)
print(" ", cwd)
assert pwd.samefile(cwd), (pwd, cwd)
return pwd
@contextlib.contextmanager
def cd(
dirname: Path,
) -> Generator[Path]:
assert_pwd("cwd")
oldpwd = environ["PWD"]
environ["PWD"] = str(dirname)
chdir(dirname)
assert_pwd("cwd up")
try:
yield oldpwd
finally:
assert_pwd("cwd downing...")
chdir(oldpwd)
environ["PWD"] = oldpwd
assert_pwd("cwd down")
@fixture
def cwd(tmp_path: Path) -> Generator[Path]:
"""prevent cross-test pollution of cwd"""
with cd(tmp_path):
yield tmp_path
def test(cwd):
assert_pwd("sleepies")
try:
sleep(2)
finally:
assert_pwd("teardown")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment