Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion aiomysql/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@

try:
DEFAULT_USER = getpass.getuser()
except KeyError:
except (KeyError, OSError):
# KeyError is raised on Python < 3.13, OSError on Python 3.13+, when
# there's no entry in the OS user database for the current uid.
DEFAULT_USER = "unknown"


Expand Down
19 changes: 19 additions & 0 deletions tests/test_connection.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import asyncio
import gc
import importlib
import os

import pytest

import aiomysql
from aiomysql import connection as aiomysql_connection


@pytest.fixture()
Expand Down Expand Up @@ -263,3 +265,20 @@ async def test_commit_during_multi_result(connection_creator):
await cur.execute("SELECT 3;")
resp = await cur.fetchone()
assert resp[0] == 3


@pytest.mark.parametrize("exc_type", [KeyError, OSError])
def test_default_user_falls_back_when_getuser_fails(monkeypatch, exc_type):
# Regression test: getpass.getuser() raises KeyError on Python < 3.13 and
# OSError on Python 3.13+ when there's no entry in the OS user database
# for the current uid (e.g. an arbitrary uid in a container). Either way,
# importing aiomysql must not crash.
def raise_exc():
raise exc_type("no such user")

monkeypatch.setattr("getpass.getuser", raise_exc)
importlib.reload(aiomysql_connection)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

woah, this doesn't appear safe..

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, reloading modules during the test run isn't safe. The test now does the import in a separate Python process (f242454), so nothing in the test session is touched. It still fails without the fix.

try:
assert aiomysql_connection.DEFAULT_USER == "unknown"
finally:
importlib.reload(aiomysql_connection)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Loading