How to Create a Dummy Context Manager for Python/Pytest Unit Tests
The aim of this page📝 is to explain how to use the nullcontext
context manager in Python to fix a common error that occurs when testing code that uses context managers.
2 min readJul 17, 2023
- The error message
TypeError: 'dict' object does not support the context manager protocol
indicates that a dictionary object is being used as a context manager, but dictionaries do not support the context manager protocol. - This error can occur when testing code that uses context managers if the context manager is replaced with a dummy object that does not support the context manager protocol.
from contextlib import nullcontext
def test_patch_schema_usual(monkeypatch, iglu):
monkeypatch.setattr(schema_patcher, "get_env", mock_get_env)
monkeypatch.setattr(schema_patcher, "get_schema_endpoint",
mock_get_schema_endpoint)
monkeypatch.setattr(bdp_console_handlers, "sync_UI",
mock_sync_schema_in_env)
monkeypatch.setattr(schema_patcher, "handle_patching", lambda _: _) # HERE
with push_and_pop_path(MODULE_PATH):
schema_patcher.patch_schema(iglu)
- To fix this error, you can use the
nullcontext
context manager from thecontextlib
module as a stand-in for the context manager being tested. - The
nullcontext
context manager does nothing but returns the value passed to itsenter_result
parameter from its__enter__
method.
Here’s an example of how you can use the nullcontext
context manager to fix this error:
from contextlib import nullcontext
def test_patch_schema_usual(monkeypatch, iglu):
monkeypatch.setattr(schema_patcher, "get_env", mock_get_env)
monkeypatch.setattr(schema_patcher, "get_schema_endpoint",
mock_get_schema_endpoint)
monkeypatch.setattr(bdp_console_handlers, "sync_UI",
mock_sync_schema_in_env)
monkeypatch.setattr(schema_patcher, "handle_patching", lambda _: nullcontext()) # HERE
with push_and_pop_path(MODULE_PATH):
schema_patcher.patch_schema(iglu
In this example, we’re testing the patch_schema
function, which uses the handle_patching
context manager. To prevent the error from occurring, we replace the handle_patching
function with a lambda function that returns a nullcontext
object.
I hope this helps you understand how to use the nullcontext
context manager to fix this common error when testing code that uses context managers.