self.addCleanup
Testing Patterns

Meaning

Registers a cleanup function to clean up a temporary directory after a test.

Primary Function

Registers a cleanup callback to be executed after a test method finishes, ensuring temporary resources are cleaned up.

Communicative Purpose

Ensures cleanup of temporary resources after a test, preventing resource leaks.

Pattern

self.addCleanup(callable)

Core Structure

self.addCleanup(callable)

Função primária

Registers a cleanup callback to be executed after a test method finishes, ensuring temporary resources are cleaned up.

Propósito comunicativo

Ensures cleanup of temporary resources after a test, preventing resource leaks.

Situações de gatilho

Used in unit test setUp methods when a temporary directory or resource needs automatic cleanup after the test.

Contextos

Inside unittest.TestCase setUp methods when creating temporary directories or resources that must be cleaned up after each test.

Padrão

self.addCleanup(callable)

Estrutura central

self.addCleanup(callable)

Slots de substituição

callable: callable object (e.g., method, function, lambda) that performs cleanup

Colocados típicos

  • tempfile.TemporaryDirectory
  • unittest.TestCase
  • setUp
  • tearDown
  • shutil.rmtree
  • os.remove

Substituições comuns

  • addCleanup(lambda: shutil.rmtree(path)) instead of addCleanup(path.cleanup)
  • addCleanup(lambda: os.remove(path)) for file removal

Erros comuns

Forgot to call addCleanup, leaving temporary files after tests – causes disk space leaks.; Using addCleanup with a method that requires arguments without binding them, leading to TypeError at teardown.; Passing a non‑callable object to addCleanup, resulting in AttributeError during test teardown.; Adding cleanup after the test has already run, causing the cleanup to never run.; Using addCleanup for resources already managed by a context manager, leading to double cleanup.

Similar / contraste

addCleanup vs addCleanup with lambda: lambda allows passing arguments; addClassCleanup vs addCleanup: class‑level cleanup runs once per test class vs per test method; using try/finally vs addCleanup: try/finally runs immediately after the block, addCleanup runs after the test method.

Interferências

Coming from Java: may rely on finally blocks for cleanup, forgetting that unittest’s addCleanup defers execution until after the test method – use addCleanup for deferred cleanup.; Coming from C++: may rely on RAII destructors, but Python’s unittest does not call __del__ deterministically – prefer addCleanup or context managers.

Família do chunk

  • unittest cleanup patterns

Nuance

Do not use addCleanup for resources that must be released immediately within the test method; use try/finally or a context manager instead.; The cleanup functions are called in reverse order of registration, which can matter for dependent resources.; If the cleanup function raises an exception, the test will be marked as error but other cleanups still run.

Efeito pragmático

Guarantees that temporary files and directories are removed after each test, preventing test‑suite‑induced disk‑space exhaustion and ensuring test isolation.

Dica de memória

Think of addCleanup as hiring a janitor who shows up after your experiment to clean up the mess, no matter how the experiment ends.

Nota

The cleanup function is called even if the test fails or is skipped, making it safer than overriding tearDown.

Upgrade path

Replace ad‑hoc addCleanup calls with context managers (with statement) for deterministic, immediate resource management.

Tipo de construção: idiomatic patternTag de espaçamento: Short-term

Log in to save chunks.