From 1150e87e3127e16ce0215f119572ff1956826a17 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Wed, 16 Sep 2015 12:47:50 -0300 Subject: [PATCH] Extract get_user logic into a separate function --- _pytest/tmpdir.py | 19 +++++++++++++------ testing/test_tmpdir.py | 10 ++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/_pytest/tmpdir.py b/_pytest/tmpdir.py index cff39065f..a2a063200 100644 --- a/_pytest/tmpdir.py +++ b/_pytest/tmpdir.py @@ -54,13 +54,8 @@ class TempdirFactory: else: # use a sub-directory in the temproot to speed-up # make_numbered_dir() call - import getpass temproot = py.path.local.get_temproot() - try: - rootdir = temproot.join('pytest-of-%s' % getpass.getuser()) - except ImportError: - # see issue #1010 - rootdir = temproot.join('pytest-tox') + rootdir = temproot.join('pytest-of-%s' % get_user()) rootdir.ensure(dir=1) basetemp = py.path.local.make_numbered_dir(prefix='pytest-', rootdir=rootdir) @@ -71,6 +66,18 @@ class TempdirFactory: def finish(self): self.trace("finish") + +def get_user(): + """Return the current user name, falling back to using "tox" as user name + because getpass relies on environment variables which might not be + available in a tox environment (see #1010). + """ + import getpass + try: + return getpass.getuser() + except ImportError: + return 'tox' + # backward compatibility TempdirHandler = TempdirFactory diff --git a/testing/test_tmpdir.py b/testing/test_tmpdir.py index 0ea8e5263..2dc070bd6 100644 --- a/testing/test_tmpdir.py +++ b/testing/test_tmpdir.py @@ -133,3 +133,13 @@ def test_tmpdir_fallback_tox_env(testdir, monkeypatch): """) reprec = testdir.inline_run() reprec.assertoutcome(passed=1) + + +def test_get_user(monkeypatch): + """Test that get_user() function works even if environment variables + required by getpass module are missing from the environment (#1010). + """ + from _pytest.tmpdir import get_user + monkeypatch.delenv('USER', raising=False) + monkeypatch.delenv('USERNAME', raising=False) + assert get_user() == 'tox'