How to Write Unit Tests for Custom Context Manager in Python: An Example
The aim of this page📝 is to explain how to write a pytest unittest for a context manager that changes the current working directory. For the intro to the subject see How to Use contextmanager Decorator To Create Custom with Statements in Python
1 min readJul 12, 2023
- Here is an example of a context manager that changes the current working directory:
import os
from contextlib import contextmanager
@contextmanager
def push_and_pop_path(new_path):
try:
old_path = os.getcwd()
os.chdir(new_path)
yield
finally:
os.chdir(old_path)
- To test this context manager, we can write a pytest unittest like this:
import os
from contextlib import contextmanager
import pytest
@contextmanager
def push_and_pop_path(new_path):
try:
old_path = os.getcwd()
os.chdir(new_path)
yield
finally:
os.chdir(old_path)
def test_push_and_pop_path(tmpdir):
old_path = os.getcwd()
with push_and_pop_path(tmpdir):
assert os.getcwd() == tmpdir
assert os.getcwd() == old_path
- The test creates a temporary directory using the
tmpdir
fixture provided by pytest. - The test uses the
push_and_pop_path
context manager to change the current working directory to the temporary directory and asserts that the current working directory has been changed. - After exiting the context manager, the test asserts that the current working directory has been changed back to its original value.
This example demonstrates how to write a unittest for a context manager using pytest. It shows how to use fixtures and asserts to verify that the context manager is functioning as expected. This can be useful when writing tests for code that relies on changing the current working directory.