[{"data":1,"prerenderedAt":63},["ShallowReactive",2],{"qa-\u002Fpython\u002Ftesting\u002Fpytest":3},{"page":4,"siblings":58,"blog":49},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":49,"seo":50,"seoDescription":51,"stem":52,"subtopic":53,"topic":54,"topicSlug":55,"updated":56,"__hash__":57},"qa\u002Fpython\u002Ftesting\u002Fpytest.md","Pytest",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,1,"\u002Fpython\u002Ftesting\u002Fpytest",[23,28,32,36,41,45],{"id":24,"difficulty":25,"q":26,"a":27},"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":29,"difficulty":14,"q":30,"a":31},"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":33,"difficulty":14,"q":34,"a":35},"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":37,"difficulty":38,"q":39,"a":40},"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":42,"difficulty":14,"q":43,"a":44},"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":46,"difficulty":14,"q":47,"a":48},"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":11},"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","Testing","testing","2026-06-18","k9bgHlANacbZ5kAs3vq6F-kv1RDc9uTZZ6pHwnijVHI",[59,60],{"subtopic":53,"path":21,"order":20},{"subtopic":61,"path":62,"order":12},"Mocking & Patching","\u002Fpython\u002Ftesting\u002Fmocking",1781808682066]