Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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 comtypes/test/find_memleak.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import gc
from collections.abc import Callable
from ctypes import POINTER, Structure, WinDLL, WinError, byref, c_size_t, sizeof
from ctypes.wintypes import BOOL, DWORD, HANDLE
from typing import Any

################################################################

Expand Down Expand Up @@ -45,7 +47,7 @@ def wss():
LOOPS = 10, 1000


def find_memleak(func, loops=LOOPS):
def find_memleak(func: Callable[[], Any], loops: tuple[int, int] = LOOPS) -> int:
# call 'func' several times, so that memory consumption
# stabilizes:
for j in range(loops[0]):
Expand Down
48 changes: 48 additions & 0 deletions comtypes/test/test_find_memleak.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import gc
import unittest

from comtypes.malloc import CoGetMalloc
from comtypes.test.find_memleak import find_memleak, wss


class Test_find_memleak(unittest.TestCase):
def setUp(self):
gc.collect()
gc.collect()
gc.collect()

def tearDown(self):
gc.collect()
gc.collect()
gc.collect()

def test_find_memleak_working_set_no_leak(self):
def no_leak():
malloc = CoGetMalloc()
ptr = malloc.Alloc(1024)
malloc.Free(ptr)

# `find_memleak()` takes its baseline with one `wss()` call and its
# final reading with another. The first `wss()` call in a process
# incurs one-time costs (e.g. first-time code paths faulting in
# pages) that land between those two readings, so a cold probe can
# make an otherwise leak-free function look like it grew by a page.
# Calling `wss()` once here pays that cost beforehand.
#
# Note that this only warms up the probe itself. The warmup of
# `no_leak()` is already done by `find_memleak()`.
#
# This is a workaround that makes the measurement stable in practice.
# It does not address the fundamental limitation of Working Set
# based measurement (see https://github.com/enthought/comtypes/issues/971):
# the Working Set is the amount of resident pages, not the amount of
# unreleased memory, so a stable result does not prove the absence of
# a leak.
_ = wss()
# Actual measurement. `find_memleak` already warms up `no_leak`.
leak_amount = find_memleak(no_leak)
self.assertEqual(leak_amount, 0)


if __name__ == "__main__":
unittest.main()
Loading