patcher = patch
Testing Patterns

Meaning

Creates a mock object that replaces time.sleep in the specified module with a no-op that returns None, allowing tests to run without real delays.

Primary Function

Replace time.sleep with a harmless mock during unit testing to eliminate waiting time.

Communicative Purpose

Indicates that the code is setting up a test double for time.sleep to isolate the unit under test from real-time delays.

Pattern

patch('target.attribute', return_value=None) assigned to a variable (often named patcher).

Core Structure

patch(target, return_value=None) → patcher

Função primária

Replace time.sleep with a harmless mock during unit testing to eliminate waiting time.

Propósito comunicativo

Indicates that the code is setting up a test double for time.sleep to isolate the unit under test from real-time delays.

Situações de gatilho

When writing unit tests for code that invokes time.sleep (e.g., retry loops, throttling, delays) and you need to avoid actual waiting.

Contextos

Unit test modules using unittest.mock, typically in setUp, test methods, or tearDown to manage the patch lifecycle.

Padrão

patch('target.attribute', return_value=None) assigned to a variable (often named patcher).

Estrutura central

patch(target, return_value=None) → patcher

Slots de substituição

target: str (dotted path to attribute to patch), return_value: any (value returned when the patched attribute is called).

Colocados típicos

  • unittest.TestCase
  • setUp
  • tearDown
  • mock.patch
  • assert_called_once_with
  • side_effect
  • addCleanup

Substituições comuns

  • Using side_effect instead of return_value
  • employing patch as a context manager (with patch(...))
  • using patch.object
  • enabling autospec for stricter mocks.

Erros comuns

Failing to start/stop the patcher (when using patcher.start()/stop()) leading to leaked patches that affect other tests. Patching the wrong module path (e.g., 'time.sleep' instead of 'my_module.time.sleep'), causing the real sleep to still be called. Omitting return_value or side_effect, so the original sleep executes and slows down the test. Neglecting to add the patcher to addCleanup, resulting in insufficient cleanup after the test. Confusing patch.object with patch when targeting an attribute on an object versus a module-level attribute.

Similar / contraste

Using real time.sleep vs. mocked sleep – the former introduces real delays, the latter eliminates them. Using eventlet.sleep or gevent.sleep in coroutine‑based code versus mocking time.sleep in synchronous code. Using time.sleep(0) to yield the thread versus mocking to avoid any delay.

Interferências

Coming from Java: may attempt to use Thread.sleep(0) or a busy loop instead of employing a mocking framework like Mockito. Coming from C: might implement a busy‑wait loop to avoid sleeping, which wastes CPU cycles rather than isolating the unit under test.

Família do chunk

  • unittest.mock
  • mocking
  • test doubles
  • patching

Nuance

Do not use when you need to verify actual timing behavior or rate‑limiting logic. Performance impact is negligible; the mock introduces only minimal overhead. Be aware that patching time.sleep does not affect time.monotonic or time.perf_counter; if the code relies on those, you must patch the appropriate function.

Efeito pragmático

Enables fast, deterministic unit tests by removing real delays, allowing rapid test execution and reliable assertions about timing‑dependent code.

Dica de memória

Think of patch as a stunt double for time.sleep: it steps in and does nothing so your code can finish the scene instantly.

Nota

The returned patcher is a MagicMock; you can inspect call_count, call_args, etc., to verify that the patched function was invoked as expected.

Upgrade path

Advance to using patch as a context manager or decorator, and employ autospec for stricter, more realistic mocks.

Tipo de construção: Assignment statement that calls unittest.mock.patch with target and return_value=None, storing the patcher object.Tag de espaçamento: Medium-term

Log in to save chunks.