Use the appropriate user home directory.

This commit is contained in:
Pablo Lopez-Jamar 2021-08-31 14:35:21 -07:00 committed by sezanzeb
parent ba712652a1
commit 444342f5cc
2 changed files with 16 additions and 3 deletions

View File

@ -58,8 +58,12 @@ def get_user():
return user
def get_home(user):
"""Try to find the user's home directory."""
return pwd.getpwnam(user).pw_dir
USER = get_user()
HOME = '/root' if USER == 'root' else f'/home/{USER}'
HOME = get_home(USER)
CONFIG_PATH = os.path.join(HOME, '.config/key-mapper')

View File

@ -23,7 +23,7 @@ import os
import unittest
from unittest import mock
from keymapper.user import get_user
from keymapper.user import get_user, get_home
from tests.test import quick_cleanup
@ -43,7 +43,9 @@ class TestUser(unittest.TestCase):
with mock.patch('os.getlogin', lambda: 'root'):
self.assertEqual(get_user(), 'root')
with mock.patch('os.getlogin', lambda: _raise(OSError())):
property_mock = mock.Mock()
property_mock.configure_mock(pw_name='quix')
with mock.patch('os.getlogin', lambda: _raise(OSError())), mock.patch('pwd.getpwuid', return_value=property_mock):
os.environ['USER'] = 'root'
os.environ['SUDO_USER'] = 'qux'
self.assertEqual(get_user(), 'qux')
@ -52,3 +54,10 @@ class TestUser(unittest.TestCase):
del os.environ['SUDO_USER']
os.environ['PKEXEC_UID'] = '1000'
self.assertNotEqual(get_user(), 'root')
def test_get_home(self):
property_mock = mock.Mock()
property_mock.configure_mock(pw_dir='/custom/home/foo')
with mock.patch('pwd.getpwnam', return_value=property_mock):
self.assertEqual(get_home('foo'), '/custom/home/foo')