[{"data":1,"prerenderedAt":113},["ShallowReactive",2],{"topic-python-testing":3},{"framework":4,"topic":15,"subtopics":24},{"id":5,"description":6,"extension":7,"icon":8,"meta":9,"name":10,"order":11,"slug":8,"stem":12,"tier":13,"__hash__":14},"frameworks\u002Fframeworks\u002Fpython.yml","Python interview questions across language fundamentals, data structures and common gotchas for backend, data and automation roles.","yml","python",{},"Python",3,"frameworks\u002Fpython",1,"QsijsotyAr-3rnhJDWWZmc7hE6HAhylS5t1dKpigMOA",{"id":16,"description":17,"extension":7,"frameworkSlug":8,"meta":18,"name":19,"order":20,"slug":21,"stem":22,"__hash__":23},"topics\u002Ftopics\u002Fpython-testing.yml","pytest and unittest, fixtures and mocking — writing automated tests for Python code.",{},"Testing",13,"testing","topics\u002Fpython-testing","HwvMxQFl9E4PubF9w7vHbjXIlh3Y1LpYkOTKVAmw754",[25,74],{"id":26,"title":27,"body":28,"description":32,"difficulty":35,"extension":36,"framework":10,"frameworkSlug":8,"meta":37,"navigation":38,"order":13,"path":39,"questions":40,"related":67,"seo":68,"seoDescription":69,"stem":70,"subtopic":71,"topic":19,"topicSlug":21,"updated":72,"__hash__":73},"qa\u002Fpython\u002Ftesting\u002Fpytest.md","Pytest",{"type":29,"value":30,"toc":31},"minimark",[],{"title":32,"searchDepth":33,"depth":33,"links":34},"",2,[],"medium","md",{},true,"\u002Fpython\u002Ftesting\u002Fpytest",[41,46,50,54,59,63],{"id":42,"difficulty":43,"q":44,"a":45},"pytest-vs-unittest","easy","What is the difference between pytest and unittest?","**`unittest`** is the **standard-library** framework, modeled on xUnit: tests\nare **methods on a `TestCase` subclass** and you use `self.assertEqual`,\n`self.assertTrue`, etc. **`pytest`** is a **third-party** framework that runs\nplain functions using the bare `assert` statement, with rich failure\nintrospection, fixtures, and `parametrize`.\n\n```python\n# unittest\nimport unittest\nclass TestMath(unittest.TestCase):\n    def test_add(self):\n        self.assertEqual(1 + 1, 2)\n\n# pytest — just a function and assert\ndef test_add():\n    assert 1 + 1 == 2\n```\n\npytest can also **run existing unittest tests**, so adopting it is low-risk.\nRule of thumb: prefer pytest for new code — less boilerplate and better\noutput — while unittest is fine when you must avoid dependencies.\n",{"id":47,"difficulty":35,"q":48,"a":49},"fixtures-scope","What are pytest fixtures, and what does scope control?","A **fixture** is a function decorated with `@pytest.fixture` that provides\n**setup (and teardown) for tests**. A test requests it simply by naming it as\na **parameter**, and pytest injects the return value. Using `yield` lets code\nafter the `yield` run as **teardown**. The **`scope`** controls how often the\nfixture is created: `function` (default), `class`, `module`, or `session`.\n\n```python\nimport pytest\n\n@pytest.fixture(scope=\"module\")   # created once per module\ndef db():\n    conn = connect()\n    yield conn                    # value handed to tests\n    conn.close()                  # teardown after tests finish\n\ndef test_query(db):               # db injected by name\n    assert db.ping()\n```\n\nWider scopes share expensive resources (DB connections, servers) across many\ntests for speed; narrower scopes give better **isolation**. Rule of thumb:\ndefault to `function` scope and only widen when setup is costly.\n",{"id":51,"difficulty":35,"q":52,"a":53},"parametrize","How does @pytest.mark.parametrize work?","`@pytest.mark.parametrize` runs the **same test function multiple times** with\ndifferent arguments, generating **one separate test case per row**. Each case\npasses or fails independently, so a single bad input doesn't hide the others —\nfar cleaner than a loop inside one test.\n\n```python\nimport pytest\n\n@pytest.mark.parametrize(\"value, expected\", [\n    (2, 4),\n    (3, 9),\n    (4, 16),\n])\ndef test_square(value, expected):\n    assert value ** 2 == expected\n```\n\npytest reports each as `test_square[2-4]`, `test_square[3-9]`, etc., and you\ncan stack decorators to get the **cross product** of inputs. Rule of thumb:\nuse `parametrize` for the same logic across many inputs instead of copy-pasted\ntests or in-test loops.\n",{"id":55,"difficulty":56,"q":57,"a":58},"mocking-monkeypatch","hard","How do you mock with monkeypatch versus unittest.mock?","The built-in **`monkeypatch`** fixture **replaces attributes, dict items, or\nenv vars** for the duration of a test and **auto-restores** them afterward —\nideal for swapping out a function or setting `os.environ`. **`unittest.mock`**\n(`Mock`, `patch`) creates **mock objects** that record calls and let you set\nreturn values or side effects — best when you need to **assert how** a\ndependency was called.\n\n```python\nimport requests, mymodule\n\ndef test_with_monkeypatch(monkeypatch):\n    monkeypatch.setattr(requests, \"get\", lambda url: {\"ok\": True})\n    assert mymodule.fetch() == {\"ok\": True}\n\nfrom unittest.mock import patch\ndef test_with_mock():\n    with patch(\"mymodule.requests.get\") as mock_get:\n        mock_get.return_value = {\"ok\": True}\n        mymodule.fetch()\n        mock_get.assert_called_once()   # verify the interaction\n```\n\nA key gotcha: **patch where the name is looked up** (`mymodule.requests.get`),\nnot where it's defined. Rule of thumb: `monkeypatch` for simple replacements,\n`unittest.mock` when you need to **inspect calls**.\n",{"id":60,"difficulty":35,"q":61,"a":62},"pytest-raises","How do you assert that code raises an exception?","Use the **`pytest.raises`** context manager: the test **passes only if** the\nexpected exception is raised inside the `with` block, and **fails** if no\nexception (or the wrong one) occurs. You can capture the exception via\n`as excinfo` to assert on its message, and use `match=` for a regex check.\n\n```python\nimport pytest\n\ndef test_divide_by_zero():\n    with pytest.raises(ZeroDivisionError):\n        1 \u002F 0\n\ndef test_message():\n    with pytest.raises(ValueError, match=\"invalid\"):\n        int(\"not a number\")   # ValueError: invalid literal...\n    # or: assert \"invalid\" in str(excinfo.value)\n```\n\nIt cleanly replaces a `try\u002Fexcept\u002Fpytest.fail` dance. Rule of thumb: always\nassert on the **specific** exception type (and ideally the message) so the\ntest can't pass for the wrong reason.\n",{"id":64,"difficulty":35,"q":65,"a":66},"conftest","What is conftest.py used for?","**`conftest.py`** is a special pytest file for **shared fixtures and hooks**.\npytest **auto-discovers** it — no import needed — and any fixture defined\nthere is **available to every test** in that directory and its subdirectories.\nIt's the standard place to put fixtures used across multiple test files.\n\n```python\n# tests\u002Fconftest.py\nimport pytest\n\n@pytest.fixture\ndef client():\n    return create_test_client()\n\n# tests\u002Ftest_users.py — no import required\ndef test_login(client):           # 'client' resolved from conftest\n    assert client.login(\"ada\")\n```\n\nYou can also register plugins, define hooks like `pytest_addoption`, and place\na `conftest.py` at multiple levels for **scoped** sharing. Rule of thumb: put\na fixture in `conftest.py` once more than one test file needs it, instead of\nimporting it around.\n",null,{"description":32},"Python interview questions on pytest — pytest vs unittest, fixtures and scope, parametrize, mocking with monkeypatch and unittest.mock, pytest.raises, and conftest.py.","python\u002Ftesting\u002Fpytest","pytest Essentials","2026-06-18","k9bgHlANacbZ5kAs3vq6F-kv1RDc9uTZZ6pHwnijVHI",{"id":75,"title":76,"body":77,"description":32,"difficulty":35,"extension":36,"framework":10,"frameworkSlug":8,"meta":81,"navigation":38,"order":33,"path":82,"questions":83,"related":67,"seo":108,"seoDescription":109,"stem":110,"subtopic":111,"topic":19,"topicSlug":21,"updated":72,"__hash__":112},"qa\u002Fpython\u002Ftesting\u002Fmocking.md","Mocking",{"type":29,"value":78,"toc":79},[],{"title":32,"searchDepth":33,"depth":33,"links":80},[],{},"\u002Fpython\u002Ftesting\u002Fmocking",[84,88,92,96,100,104],{"id":85,"difficulty":43,"q":86,"a":87},"what-is-mocking","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":89,"difficulty":35,"q":90,"a":91},"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":93,"difficulty":56,"q":94,"a":95},"patch-where-used","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":97,"difficulty":35,"q":98,"a":99},"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":101,"difficulty":35,"q":102,"a":103},"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":105,"difficulty":35,"q":106,"a":107},"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",{"description":32},"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","BuZRYss6gdlr3knpMQwWz6MR4-fuMtldIPIpMqBQI_4",1781808675714]