diff --git a/_pytest/tmpdir.py b/_pytest/tmpdir.py index 44e980e2e..b90e35948 100644 --- a/_pytest/tmpdir.py +++ b/_pytest/tmpdir.py @@ -52,11 +52,14 @@ class TempdirFactory: basetemp.remove() basetemp.mkdir() else: - # use a sub-directory in the temproot to speed-up - # make_numbered_dir() call - import getpass temproot = py.path.local.get_temproot() - rootdir = temproot.join('pytest-of-%s' % getpass.getuser()) + user = get_user() + if user: + # use a sub-directory in the temproot to speed-up + # make_numbered_dir() call + rootdir = temproot.join('pytest-of-%s' % user) + else: + rootdir = temproot rootdir.ensure(dir=1) basetemp = py.path.local.make_numbered_dir(prefix='pytest-', rootdir=rootdir) @@ -67,6 +70,17 @@ class TempdirFactory: def finish(self): self.trace("finish") + +def get_user(): + """Return the current user name, or None if getuser() does not work + in the current environment (see #1010). + """ + import getpass + try: + return getpass.getuser() + except ImportError: + return None + # backward compatibility TempdirHandler = TempdirFactory diff --git a/testing/test_tmpdir.py b/testing/test_tmpdir.py index 05b24fc59..9bc0cf40a 100644 --- a/testing/test_tmpdir.py +++ b/testing/test_tmpdir.py @@ -1,3 +1,4 @@ +import sys import py import pytest @@ -117,4 +118,31 @@ def test_tmpdir_factory(testdir): session_dir.isdir() """) reprec = testdir.inline_run() - reprec.assertoutcome(passed=1) \ No newline at end of file + reprec.assertoutcome(passed=1) + + +def test_tmpdir_fallback_tox_env(testdir, monkeypatch): + """Test that tmpdir works even if environment variables required by getpass + module are missing (#1010). + """ + 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(not sys.platform.startswith('win'), reason='win only') +def test_get_user(monkeypatch): + """Test that get_user() function works even if environment variables + required by getpass module are missing from the environment on Windows + (#1010). + """ + from _pytest.tmpdir import get_user + monkeypatch.delenv('USER', raising=False) + monkeypatch.delenv('USERNAME', raising=False) + assert get_user() is None