pytest-dev / pytest-dev/pytest

unittest.addModuleCleanup has no effect

Open
#14,958 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

Given this test file:

from contextlib import contextmanager
import unittest

print("Module load")


def module_cleanup_hook():
    print("module_cleanup_hook")


@contextmanager
def module_cleanup_contextmanager():
    print("module_cleanup_contextmanager enter")
    yield
    print("module_cleanup_contextmanager exit")


def setUpModule():
    print("setUpModule")


def tearDownModule():
    print("tearDownModule")


unittest.addModuleCleanup(module_cleanup_hook)

unittest.enterModuleContext(module_cleanup_contextmanager())


class Test(unittest.TestCase):
    def test(self) -> None:
        pass

I get:

$ pytest test.py -qs
Module load
module_cleanup_contextmanager enter
setUpModule
.tearDownModule

1 passed in 0.11s

which show that while unittest-style setUpModule and tearDownModule get called, addModuleCleanup does not seem to be, which also breaks enterModuleContext, that is built on top of it.

I am using pytest 9.1.1-1~bpo13+1 from backports in a clean Debian Stable chroot, and the result is the same with 8.3.5-2.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the report with the shown test.py and run pytest test.py -qs. Trace pytest's unittest-style module setup and teardown handling, focusing on why unittest.addModuleCleanup is not executed. Done means the cleanup hook runs and the context manager prints its exit message after tearDownModule.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
72/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.