[{"data":1,"prerenderedAt":63},["ShallowReactive",2],{"qa-\u002Fpython\u002Ftesting\u002Fmocking":3},{"page":4,"siblings":57,"blog":48},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"related":48,"seo":49,"seoDescription":50,"stem":51,"subtopic":52,"topic":53,"topicSlug":54,"updated":55,"__hash__":56},"qa\u002Fpython\u002Ftesting\u002Fmocking.md","Mocking",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,"\u002Fpython\u002Ftesting\u002Fmocking",[22,27,31,36,40,44],{"id":23,"difficulty":24,"q":25,"a":26},"what-is-mocking","easy","What is mocking and why do you use it?","**Mocking** replaces a real dependency with a **fake stand-in object** that records\nhow it was called and returns whatever you tell it to. You use it to **isolate the\ncode under test** from slow, unreliable, or side-effecting collaborators — network\ncalls, databases, the clock, third-party APIs.\n\n```python\nfrom unittest.mock import Mock\n\nservice = Mock()\nservice.fetch.return_value = {\"id\": 1}    # canned response\n\nresult = service.fetch(\"\u002Fusers\u002F1\")        # no real network call\nresult                                    # {\"id\": 1}\nservice.fetch.assert_called_once()        # verify it happened\n```\n\nMocking makes tests **fast, deterministic, and focused** on your logic rather than\nthe dependency's. Rule of thumb: mock at the **boundaries** of your system (I\u002FO,\nexternal services), not your own pure functions.\n",{"id":28,"difficulty":14,"q":29,"a":30},"mock-vs-magicmock","What is the difference between Mock and MagicMock?","Both auto-create attributes and methods on access. The difference: **`MagicMock`**\nadditionally supports **magic (dunder) methods** — `__len__`, `__iter__`,\n`__getitem__`, `__enter__`\u002F`__exit__`, etc. — so it can stand in for objects used\nwith `len()`, iteration, indexing, or `with`. A plain **`Mock`** raises on dunder\naccess.\n\n```python\nfrom unittest.mock import Mock, MagicMock\n\nm = Mock()\nlen(m)                  # TypeError — Mock has no __len__\n\nmm = MagicMock()\nmm.__len__.return_value = 3\nlen(mm)                 # 3 — magic methods supported\nlist(mm)                # works — __iter__ is mocked too\n```\n\n`patch()` uses `MagicMock` by default, which is why patched objects \"just work\" in\nmost cases. Use `MagicMock` when the dependency relies on protocols\u002Fdunders; `Mock`\nis fine for plain method calls.\n",{"id":32,"difficulty":33,"q":34,"a":35},"patch-where-used","hard","How does unittest.mock.patch work, and what does \"patch where it's used\" mean?","**`patch`** temporarily replaces an object with a mock for the duration of a test,\nas a **decorator** or a **context manager**, restoring the original afterward. The\ncritical rule is **\"patch where it's looked up, not where it's defined\"** — you patch\nthe name in the **module that imports and uses it**.\n\n```python\n# app.py\nfrom time import time\ndef stamp(): return time()\n\n# test.py — patch the reference INSIDE app, not 'time.time'\nfrom unittest.mock import patch\n\n@patch(\"app.time\")                 # where it's USED\ndef test_stamp(mock_time):\n    mock_time.return_value = 123\n    assert stamp() == 123\n\nwith patch(\"app.time\") as mock_time:   # context-manager form\n    mock_time.return_value = 123\n```\n\nPatching `\"time.time\"` here would fail, because `app` already bound its own `time`\nname at import. Always target the **importing module's namespace** — this is the\nsingle most common mocking mistake.\n",{"id":37,"difficulty":14,"q":38,"a":39},"return-value-side-effect","What is the difference between return_value and side_effect?","**`return_value`** sets a **single fixed value** the mock returns on every call.\n**`side_effect`** is more powerful: assign a **function** (called with the same args),\nan **exception** (which gets raised), or an **iterable** (returning a different value\nper successive call).\n\n```python\nfrom unittest.mock import Mock\n\nm = Mock(return_value=42)\nm(); m()                       # 42, 42 — always the same\n\nm.side_effect = [1, 2, 3]      # one per call\nm(); m()                       # 1, then 2\n\nm.side_effect = ValueError(\"boom\")\nm()                            # raises ValueError\n\nm.side_effect = lambda x: x * 2\nm(10)                          # 20 — computed from the arg\n```\n\nUse `return_value` for a constant stub, and `side_effect` to **raise errors**,\n**vary results across calls**, or **compute** based on arguments. If both are set,\n`side_effect` wins (unless it returns the sentinel `DEFAULT`).\n",{"id":41,"difficulty":14,"q":42,"a":43},"call-assertions","How do you assert a mock was called correctly?","Mocks **record every call**, so you verify interactions with the `assert_called*`\nfamily. Check **whether\u002Fhow many times** it was called and **with what arguments**,\nand inspect history via `call_args` \u002F `call_args_list`.\n\n```python\nfrom unittest.mock import Mock, call\n\nm = Mock()\nm(1, 2)\nm(3, key=\"v\")\n\nm.assert_called()                       # at least once\nm.assert_called_once()                  # exactly once -> would FAIL here\nm.assert_called_with(3, key=\"v\")        # the MOST RECENT call\nm.assert_any_call(1, 2)                 # any call matched\nm.assert_has_calls([call(1, 2), call(3, key=\"v\")])\nm.call_count                            # 2\n```\n\nNote `assert_called_with` checks only the **last** call — use `assert_any_call` or\n`assert_has_calls` for earlier ones. Beware typos: a misspelled assertion (e.g.\n`assert_called_once_with` -> `assert_called_onced_with`) silently passes, so spell\nthese carefully.\n",{"id":45,"difficulty":14,"q":46,"a":47},"autospec","What is autospec and why is it useful?","A normal mock accepts **any** attribute access or call signature, so it can hide bugs\n— a test passes even if you call a method that doesn't exist or with wrong arguments.\n**Autospec** (`autospec=True`, or `create_autospec`) builds the mock to **match the\nreal object's API**, so it rejects nonexistent attributes and mismatched signatures.\n\n```python\nfrom unittest.mock import patch, create_autospec\n\nclass Api:\n    def fetch(self, url): ...\n\n@patch(\"app.Api\", autospec=True)\ndef test_it(MockApi):\n    api = MockApi()\n    api.fetch(\"\u002Fx\")          # OK — matches real signature\n    api.fetch()              # TypeError — missing 'url'!\n    api.delete()             # AttributeError — no such method\n```\n\nAutospec makes mocks **stay in sync with the real interface**, catching drift when\nthe real API changes. The tradeoff is a small overhead, but it's strongly\nrecommended for non-trivial dependencies.\n",null,{"description":11},"Python interview questions on mocking and why it matters, Mock vs MagicMock, unittest.mock.patch and patching where it's used, return_value vs side_effect, call assertions, and autospec.","python\u002Ftesting\u002Fmocking","Mocking & Patching","Testing","testing","2026-06-18","BuZRYss6gdlr3knpMQwWz6MR4-fuMtldIPIpMqBQI_4",[58,62],{"subtopic":59,"path":60,"order":61},"pytest Essentials","\u002Fpython\u002Ftesting\u002Fpytest",1,{"subtopic":52,"path":20,"order":12},1781808682084]