[Concept,10/17] test: py: Add --leak-check option to pytest

Message ID 20260316183050.3855921-11-sjg@u-boot.org
State New
Headers
Series Add automatic memory-leak detection to U-Boot tests |

Commit Message

Simon Glass March 16, 2026, 6:30 p.m. UTC
  From: Simon Glass <sjg@chromium.org>

Add a --leak-check flag to the pytest command line that passes -L to
every ut invocation, enabling per-test heap-leak detection. Leaked
allocations are printed with their address, size and caller backtrace.

For example:

  test/py/test.py -B sandbox --leak-check -k dm_test_acpi_bgrt

Signed-off-by: Simon Glass <sjg@chromium.org>
---

 test/py/conftest.py      | 3 +++
 test/py/tests/test_ut.py | 6 ++++--
 2 files changed, 7 insertions(+), 2 deletions(-)
  

Patch

diff --git a/test/py/conftest.py b/test/py/conftest.py
index 47a0d112e51..303a697d76a 100644
--- a/test/py/conftest.py
+++ b/test/py/conftest.py
@@ -106,6 +106,8 @@  def pytest_addoption(parser):
                      help='Disable console timeout (useful for debugging)')
     parser.addoption('--no-full', default=False, action='store_true',
                      help='Skip flat-tree tests (run live-tree only)')
+    parser.addoption('--leak-check', default=False, action='store_true',
+                     help='Check for memory leaks around each unit test')
     parser.addoption('--malloc-dump', default=None,
                      help='Write malloc dump to file on exit')
 
@@ -364,6 +366,7 @@  def pytest_configure(config):
     ubconfig.allow_exceptions = config.getoption('allow_exceptions')
     ubconfig.no_timeout = config.getoption('no_timeout')
     ubconfig.no_full = config.getoption('no_full')
+    ubconfig.leak_check = config.getoption('leak_check')
     ubconfig.malloc_dump = config.getoption('malloc_dump')
 
     env_vars = (
diff --git a/test/py/tests/test_ut.py b/test/py/tests/test_ut.py
index e64ccd407a0..21a948b4ac6 100644
--- a/test/py/tests/test_ut.py
+++ b/test/py/tests/test_ut.py
@@ -142,11 +142,13 @@  def test_ut(ubman, ut_subtest):
             execute command 'ut foo bar'
     """
 
+    flags = '-L ' if ubman.config.leak_check else ''
+
     if ut_subtest == 'hush hush_test_simple_dollar':
         # ut hush hush_test_simple_dollar prints "Unknown command" on purpose.
         with ubman.disable_check('unknown_command'):
-            output = ubman.run_command('ut ' + ut_subtest)
+            output = ubman.run_command(f'ut {flags}' + ut_subtest)
         assert 'Unknown command \'quux\' - try \'help\'' in output
     else:
-        output = ubman.run_command('ut ' + ut_subtest)
+        output = ubman.run_command(f'ut {flags}' + ut_subtest)
     assert output.endswith('failures: 0')