Make tmpdir resiliant to user ids that do not exist

Previously, the tmpdir fixture would fail if the current process's user
id does not correspond to a valid user (e.g. running pytest in a Docker
container with 'docker run -u').
This commit is contained in:
Andy Freeland 2015-09-18 21:06:13 -04:00
parent f02d9425f9
commit b1c9b8b415
2 changed files with 35 additions and 1 deletions

View File

@ -78,7 +78,7 @@ def get_user():
import getpass
try:
return getpass.getuser()
except ImportError:
except (ImportError, KeyError):
return None
# backward compatibility

View File

@ -136,6 +136,40 @@ def test_tmpdir_fallback_tox_env(testdir, monkeypatch):
reprec.assertoutcome(passed=1)
@pytest.mark.skipif(sys.platform.startswith('win'), reason='no os.getuid on windows')
def test_tmpdir_fallback_uid_not_found(testdir, monkeypatch):
"""Test that tmpdir works even if the current process's user id does not
correspond to a valid user.
"""
import os
monkeypatch.setattr(os, 'getuid', lambda: -1)
monkeypatch.delenv('USER', raising=False)
monkeypatch.delenv('USERNAME', raising=False)
testdir.makepyfile("""
import pytest
def test_some(tmpdir):
assert tmpdir.isdir()
""")
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)
@pytest.mark.skipif(sys.platform.startswith('win'), reason='no os.getuid on windows')
def test_get_user_uid_not_found(monkeypatch):
"""Test that get_user() function works even if the current process's
user id does not correspond to a valid user (e.g. running pytest in a
Docker container with 'docker run -u'.
"""
import os
monkeypatch.setattr(os, 'getuid', lambda: -1)
monkeypatch.delenv('USER', raising=False)
monkeypatch.delenv('USERNAME', raising=False)
from _pytest.tmpdir import get_user
assert get_user() is None
@pytest.mark.skipif(not sys.platform.startswith('win'), reason='win only')
def test_get_user(monkeypatch):
"""Test that get_user() function works even if environment variables