pytest-memray
pytest-memray is a pytest plugin for easy integration of memray, a powerful memory profiler for Python. It allows developers to analyze memory allocations, detect memory leaks, and identify memory-intensive hotspots directly within their pytest test suite. The current version, 1.8.0, supports Python 3.8 and higher, and is actively maintained with regular releases.
Warnings
- gotcha Python's internal object allocators, caches (e.g., `re`, `logging`), and pytest's output capturing can result in reported allocations that are not true application-level memory leaks. Interpreting memory reports requires understanding these internal behaviors.
- gotcha The underlying `memray` library, which `pytest-memray` integrates with, primarily supports Linux and macOS. While the Python package can be installed elsewhere, full functionality and development might be limited or require a POSIX-compliant system, especially for native-level tracking.
- gotcha Prior to version 1.3.2, `pytest-memray` had compatibility issues with `pytest-xdist` when running tests in parallel, potentially leading to incorrect or failed memory tracking. Users on older versions might experience instability.
- gotcha Using very long test names or file paths can lead to `OSError` exceptions due to file system limitations when `memray` attempts to write its binary capture files. This can prevent reports from being generated.
- breaking The `limit_memory` and `limit_leaks` markers in versions prior to 1.6.0 tracked all memory allocations across all threads. Version 1.6.0 introduced a `current_thread_only=True` keyword argument to these markers, allowing more precise tracking of allocations solely within the test's thread. Existing tests on older versions might report higher memory usage if other threads were active.
Install
-
pip install pytest-memray
Imports
- pytest.mark.limit_memory
import pytest @pytest.mark.limit_memory('100 MB') def test_something_memory_intensive(): # ... test code ... - pytest.mark.limit_leaks
import pytest @pytest.mark.limit_leaks('5 MB') def test_something_that_might_leak(): # ... test code ...
Quickstart
import pytest
@pytest.mark.limit_memory('24 MB')
def test_foobar():
data = [i for i in range(1_000_000)] # Allocates ~8MB
assert len(data) == 1_000_000
# To run this test with memory profiling:
# pytest --memray your_test_file.py