56 lines
2 KiB
Python
56 lines
2 KiB
Python
|
|
"""Tests for GECOS / passwd parsing."""
|
||
|
|
|
||
|
|
from unittest.mock import patch, MagicMock
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from local_identity.gecos import get_gecos_fullname, current_username
|
||
|
|
|
||
|
|
|
||
|
|
def _mock_entry(gecos: str) -> MagicMock:
|
||
|
|
entry = MagicMock()
|
||
|
|
entry.pw_gecos = gecos
|
||
|
|
return entry
|
||
|
|
|
||
|
|
|
||
|
|
class TestGetGecosFullname:
|
||
|
|
def test_simple_name(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry("Bernd Worsch")):
|
||
|
|
assert get_gecos_fullname("tegwick") == "Bernd Worsch"
|
||
|
|
|
||
|
|
def test_name_with_comma_fields(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry("Bernd Worsch,Room 42,+49-555-1234")):
|
||
|
|
assert get_gecos_fullname("tegwick") == "Bernd Worsch"
|
||
|
|
|
||
|
|
def test_empty_gecos_falls_back_to_username(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry("")):
|
||
|
|
assert get_gecos_fullname("tegwick") == "tegwick"
|
||
|
|
|
||
|
|
def test_only_commas(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry(",,,,")):
|
||
|
|
assert get_gecos_fullname("tegwick") == "tegwick"
|
||
|
|
|
||
|
|
def test_whitespace_stripped(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry(" Bernd Worsch ,,")):
|
||
|
|
assert get_gecos_fullname("tegwick") == "Bernd Worsch"
|
||
|
|
|
||
|
|
def test_non_ascii_name(self):
|
||
|
|
with patch("pwd.getpwnam", return_value=_mock_entry("Ärger Müller,,")):
|
||
|
|
assert get_gecos_fullname("amueller") == "Ärger Müller"
|
||
|
|
|
||
|
|
def test_user_not_in_passwd(self):
|
||
|
|
with patch("pwd.getpwnam", side_effect=KeyError("nobody")):
|
||
|
|
assert get_gecos_fullname("nobody") == "nobody"
|
||
|
|
|
||
|
|
|
||
|
|
class TestCurrentUsername:
|
||
|
|
def test_reads_user_env_var(self, monkeypatch):
|
||
|
|
monkeypatch.setenv("USER", "tegwick")
|
||
|
|
monkeypatch.delenv("LOGNAME", raising=False)
|
||
|
|
assert current_username() == "tegwick"
|
||
|
|
|
||
|
|
def test_falls_back_to_logname(self, monkeypatch):
|
||
|
|
monkeypatch.delenv("USER", raising=False)
|
||
|
|
monkeypatch.setenv("LOGNAME", "tegwick")
|
||
|
|
assert current_username() == "tegwick"
|