Usage#

Installation#

This plugin can be installed using pip:

pip install pytest-memray

pytest-memray is a pytest plugin. It is enabled when you pass --memray to pytest:

pytest tests/ --memray

Allocation tracking#

By default, the plugin will track allocations in all tests. This information is reported after tests run ends:

$ pytest --memray /w/demo 
=================================== test session starts ====================================
platform linux -- Python 3.11.0, pytest-7.2.0, pluggy-1.0.0
rootdir: /w
plugins: memray-1.3.1
collected 2 items

demo/test_ok.py .M                                                                   [100%]

========================================= FAILURES =========================================
____________________________________ test_memory_exceed ____________________________________
Test was limited to 100.0KiB but allocated 117.2KiB
------------------------------------ memray-max-memory -------------------------------------
Test is using 117.2KiB out of limit of 100.0KiB
List of allocations: 
	- <listcomp>:/w/demo/test_ok.py:17 -> 117.2KiB

====================================== MEMRAY REPORT =======================================
Allocations results for demo/test_ok.py::test_memory_exceed

	 📦 Total memory allocated: 117.2KiB
	 📏 Total allocations: 30
	 📊 Histogram of allocation sizes: |█|
	 🥇 Biggest allocating functions:
		- <listcomp>:/w/demo/test_ok.py:17 -> 117.2KiB


Allocations results for demo/test_ok.py::test_track

	 📦 Total memory allocated: 39.1KiB
	 📏 Total allocations: 2
	 📊 Histogram of allocation sizes: |█|
	 🥇 Biggest allocating functions:
		- test_track:/w/demo/test_ok.py:12 -> 39.1KiB


================================= short test summary info ==================================
MEMORY PROBLEMS demo/test_ok.py::test_memory_exceed
=============================== 1 failed, 1 passed in 0.02s ================================

Markers#

This plugin provides markers that can be used to enforce additional checks and validations on tests when this plugin is enabled.

Important

These markers do nothing when the plugin is not enabled.

limit_memory#

When this marker is applied to a test, it will cause the test to fail if the execution of the test allocates more memory than allowed. It takes a single argument with a string indicating the maximum memory that the test can allocate.

The format for the string is <NUMBER> ([KMGTP]B|B). The marker will raise ValueError if the string format cannot be parsed correctly.

Warning

As the Python interpreter has its own object allocator is possible that memory is not immediately released to the system when objects are deleted, so tests using this marker may need to give some room to account for this.

Example of usage:

@pytest.mark.limit_memory("24 MB")
def test_foobar():
    pass # do some stuff that allocates memory