Use unittest.mock.patch to replace a dependency where the code under test looks it up, then configure the replacement with return_value or side_effect. Keep the patch scoped to the test, and use autospec when you want the mock to enforce the real API’s attributes and call signature.
A minimal example: patch the name the code uses
Suppose service.py imports a function directly from another module:
# service.py
from gateway import fetch_record
def label_for(record_id):
record = fetch_record(record_id)
return record["label"].upper()
Test it by patching service.fetch_record, not gateway.fetch_record. After the direct import, label_for resolves the name in the service module.
# test_service.py
from unittest import TestCase
from unittest.mock import patch
from service import label_for
class LabelTests(TestCase):
@patch("service.fetch_record", autospec=True)
def test_label_for_uppercases_label(self, fetch_record):
fetch_record.return_value = {"label": "sample"}
result = label_for("r-17")
self.assertEqual(result, "SAMPLE")
fetch_record.assert_called_once_with("r-17")
patch temporarily substitutes the target for the duration of the decorated test and restores it afterward. It can also be used as a context manager for a narrower scope.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Choose a mock that fits the dependency
Mock for calls and configured attributes
Mock records how it is called and creates attributes as they are accessed. It is suitable when the dependency is called or when you explicitly configure the attributes the code needs.
MagicMock for Python protocols
MagicMock is a Mock variant with common magic methods pre-created. Use it when the replacement must behave like an iterable, support indexing, or respond to len() through methods such as __iter__, __getitem__, or __len__.
Use a fake when it makes the behavior clearer
If a small deterministic object can express the dependency behavior directly, a handwritten fake may be easier to understand than a configurable mock. Choose based on which approach makes the test’s intent most legible.
Set return values, errors, and changing outcomes
Return a fixed value
Assign return_value when the dependency should produce one predictable result:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
fetch_record.return_value = {"label": "sample"}
Raise an exception
Set side_effect to an exception class or instance to test an error path:
fetch_record.side_effect = TimeoutError("gateway timed out")
Calculate a result from arguments
A function assigned to side_effect can vary the result based on the call arguments:
def response_for(record_id):
return {"label": f"record {record_id}"}
fetch_record.side_effect = response_for
Provide successive results
An iterable assigned to side_effect supplies one outcome per call:
fetch_record.side_effect = [
{"label": "first"},
{"label": "second"},
]
If the code calls the mock more times than there are iterable values, the next call raises StopIteration.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Choose the right patching surface
patch("package.module.name")replaces a name addressed by its import path. Patch the name in the module where the system under test looks it up.patch.object(obj, "attribute")replaces an attribute on an object you already hold.patch.dict(mapping, ...)temporarily changes a mapping’s contents.patch.multiplecan replace several attributes in one operation.
Use a decorator when the replacement is needed throughout a test method, or a context manager when only a portion of the test should see the substitution. The original target is restored when the patch scope ends.
Make mocks stricter with autospec
A bare mock is permissive: it can allow misspelled attributes and calls that the real dependency would reject. Use autospec=True with patch, or create_autospec(), to constrain available attributes and check function signatures. Use spec_set=True when setting attributes absent from the specification should also fail.
from unittest.mock import create_autospec
mock_fetch = create_autospec(fetch_record)
Autospec relies on introspection. It may not fit objects that create attributes dynamically or whose attribute access has side effects; in those cases, use a more suitable specification or a simpler fake.
Mock asynchronous dependencies
When patch creates a replacement for an asynchronous function and no replacement is supplied, it uses AsyncMock by default. Async mocking details can vary by Python version, so consult the documentation for the version installed in your project.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Assert behavior and meaningful interactions
Start with the observable result of the code under test. Add call assertions when the interaction is itself part of the contract—for example, ensuring the correct identifier is passed or that a second request is avoided. Avoid making a test depend on incidental implementation details that can change without changing the behavior users rely on.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshoot common mocking failures
The real dependency still runs
The patch may target the definition rather than the lookup. If the module under test used from gateway import fetch_record, patch its local name, such as service.fetch_record.
A later test sees a patched dependency
Check that patching is scoped with a decorator or context manager rather than leaving a manual replacement active beyond the test. Scoped patches restore the original target when they end.
The mock accepts an impossible call
A plain mock does not enforce the dependency’s full interface. Try autospec or spec_set=True, unless dynamic attributes or unsafe introspection make those unsuitable.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
A later call raises StopIteration
An iterable side_effect has been exhausted. Add another outcome or use a function side effect if the number or arguments of calls are variable.
Magic-method behavior is missing
If the code iterates, indexes, or takes the length of a replacement, use MagicMock or provide an appropriate fake that implements the protocol.
Or skip the browser setup
For browser screenshots in a Python workflow, ScreenshotNeo provides a website screenshot API and MCP server. A single GET request can return an image or PDF; the example below saves a WebP screenshot.
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for request options. ScreenshotNeo can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers identifying the page verdict and whether the request was billed. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Sign up free for 1,000 screenshots a month, with no card required.
Cost and reliability notes
unittest.mock is part of Python’s standard library, and mocking dependencies avoids making a unit test depend on a live external service. It does not prove that the real service works or that its integration is correct; keep tests of real boundaries separate from isolated unit tests. For the installed Python version’s exact API behavior, use its matching official documentation rather than relying on development-version details.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




