Skip to content

Commit 6d80cc6

Browse files
authored
Improve GetModuleFileName tests and clarify virtual environment behavior. (#875)
* Add the `GetModuleFileName(None, ...)` test for virtual environments. * Add a `skipUnless` marker to the `GetModuleFileName` test. * Rename `GetModuleFileName` tests for clarity. * Fix `GetModuleFileNameW` API reference URL. * Clarify `GetModuleFileNameW` behavior in virtual environments.
1 parent fb8fd58 commit 6d80cc6

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

comtypes/test/test_typeinfo.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import ctypes
2+
import os
23
import sys
34
import unittest
45
from ctypes.wintypes import MAX_PATH
@@ -96,9 +97,19 @@ def test_TypeInfo(self):
9697

9798

9899
class Test_GetModuleFileName(unittest.TestCase):
99-
def test_null_handler(self):
100+
@unittest.skipUnless(
101+
sys.prefix == sys.base_prefix,
102+
"This will fail in a virtual environment.",
103+
)
104+
def test_null_handler_sys_executable(self):
100105
self.assertEqual(GetModuleFileName(None, MAX_PATH), sys.executable)
101106

107+
def test_null_handler_sys_base_prefix(self):
108+
self.assertEqual(
109+
os.path.commonpath([GetModuleFileName(None, MAX_PATH), sys.base_prefix]),
110+
sys.base_prefix,
111+
)
112+
102113
def test_loaded_module_handle(self):
103114
import _ctypes
104115

comtypes/typeinfo.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -765,9 +765,13 @@ def GetModuleFileName(handle: Optional[int], maxsize: int) -> str:
765765
"""Returns the fullpath of the loaded module specified by the handle.
766766
If the handle is NULL, returns the executable file path of the current process.
767767
768-
https://learn.microsoft.com/ja-jp/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryw
768+
https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamew
769769
"""
770770
buf = create_unicode_buffer(maxsize)
771+
# In a Python virtual environment on Windows, the Windows API
772+
# `GetModuleFileNameW(NULL, ..., ...)` returns the path to the base
773+
# `python.exe` (located within `sys.base_prefix`, not same as
774+
# `sys.executable`).
771775
length = _GetModuleFileNameW(handle, buf, maxsize)
772776
if not length:
773777
raise ctypes.WinError()

0 commit comments

Comments
 (0)