diff --git a/_pytest/tmpdir.py b/_pytest/tmpdir.py index b90e35948..ebc48dbe5 100644 --- a/_pytest/tmpdir.py +++ b/_pytest/tmpdir.py @@ -78,7 +78,7 @@ def get_user(): import getpass try: return getpass.getuser() - except ImportError: + except (ImportError, KeyError): return None # backward compatibility diff --git a/testing/test_tmpdir.py b/testing/test_tmpdir.py index 9bc0cf40a..6ac3a0a21 100644 --- a/testing/test_tmpdir.py +++ b/testing/test_tmpdir.py @@ -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