{"name":"Mocket: A Comprehensive Socket Mocking Framework for Python","description":"Mocket is a powerful Python framework designed for monkey-patching the `socket` and `ssl` modules, enabling robust testing of network-dependent applications. It serves as both a low-level framework for building custom clients and a ready-to-use mock for HTTP/HTTPS calls, supporting various environments including asyncio and MicroPython. This tool simplifies the process of isolating and testing Python clients that communicate over the socket protocol.","github":"https://github.com/mindflayer/python-mocket","url":"https://osrepos.com/repo/mindflayer-python-mocket","source":"osrepos.com","sourceDescription":"This repository profile is provided by osrepos.com, an open source repository discovery platform.","repositoryProfile":"https://osrepos.com/repo/mindflayer-python-mocket","generatedFor":"open source discovery and AI-assisted research","markdown":"https://osrepos.com/repo/mindflayer-python-mocket.md","json":"https://osrepos.com/repo/mindflayer-python-mocket.json","topics":["python","testing","mocking","socket","http","asyncio","framework","tdd"],"keywords":["python","testing","mocking","socket","http","asyncio","framework","tdd"],"stars":null,"summary":"Mocket is a powerful Python framework designed for monkey-patching the `socket` and `ssl` modules, enabling robust testing of network-dependent applications. It serves as both a low-level framework for building custom clients and a ready-to-use mock for HTTP/HTTPS calls, supporting various environments including asyncio and MicroPython. This tool simplifies the process of isolating and testing Python clients that communicate over the socket protocol.","content":"## Introduction\nMocket is a versatile socket mock framework for Python, designed to simplify testing of applications that interact with network services. By monkey-patching the `socket` and `ssl` modules, Mocket allows developers to intercept and control network communication, making it ideal for unit and integration tests. It supports a wide range of scenarios, from mocking simple HTTP/HTTPS requests to complex custom protocols, and integrates seamlessly with asyncio, gevent, and even MicroPython's `urequests`.\n\n## Installation\nInstalling Mocket is straightforward using pip:\n\nbash\npip install mocket\n\n\nFor enhanced performance, Mocket can utilize `xxhash` instead of `hashlib.md5` for creating hashes. Install with speedups:\n\nbash\npip install mocket[speedups]\n\n\n## Examples\nMocket provides flexible ways to mock network interactions, whether through decorators, context managers, or direct API calls.\n\n### Mocking HTTP[S] Calls\nHere's how to mock an HTTP[S] request using Mocket's decorator or context manager:\n\npython\nimport json\n\nfrom mocket import mocketize, Mocketizer\nfrom mocket.mocks.mockhttp import Entry\nimport requests\nimport pytest\n\n\n@pytest.fixture\ndef response():\n    return {\n        \"integer\": 1,\n        \"string\": \"asd\",\n        \"boolean\": False,\n    }\n\n\n@mocketize  # Use its decorator\ndef test_json(response):\n    url_to_mock = 'https://testme.org/json'\n\n    Entry.single_register(\n        Entry.GET,\n        url_to_mock,\n        body=json.dumps(response),\n        headers={'content-type': 'application/json'}\n    )\n\n    mocked_response = requests.get(url_to_mock).json()\n\n    assert response == mocked_response\n\n# OR use its context manager\ndef test_json_with_context_manager(response):\n    url_to_mock = 'https://testme.org/json'\n\n    Entry.single_register(\n        Entry.GET,\n        url_to_mock,\n        body=json.dumps(response),\n        headers={'content-type': 'application/json'}\n    )\n\n    with Mocketizer():\n        mocked_response = requests.get(url_to_mock).json()\n\n    assert response == mocked_response\n\n\n### Preventing Real Network Access (Strict Mode)\nTo ensure your tests do not accidentally hit the real network, Mocket offers a strict mode:\n\npython\nfrom mocket import Mocketizer, mocketize\nimport requests\nimport pytest\nfrom mocket.exceptions import StrictMocketException\n\nwith Mocketizer(strict_mode=True):\n    with pytest.raises(StrictMocketException):\n        requests.get(\"https://duckduckgo.com/\")\n\n# OR\n\n@mocketize(strict_mode=True)\ndef test_get():\n    with pytest.raises(StrictMocketException):\n        requests.get(\"https://duckduckgo.com/\")\n\nYou can also specify allowed hosts in strict mode:\npython\nfrom mocket import Mocketizer\n\nwith Mocketizer(strict_mode=True, strict_mode_allowed=[\"localhost\", (\"intake.ourmetrics.net\", 443)]):\n    # Your test code here\n    pass\n\n\n### Faking Socket Errors\nTesting error paths is crucial. Mocket allows you to simulate socket errors:\n\npython\nimport socket\nimport requests\nfrom unittest import TestCase\nfrom mocket import mocketize\nfrom mocket.mocks.mockhttp import Entry\n\nclass ErrorHandlingTestCase(TestCase):\n    @mocketize\n    def test_raise_exception(self):\n        url = \"http://github.com/fluidicon.png\"\n        Entry.single_register(Entry.GET, url, exception=socket.error())\n        with self.assertRaises(requests.exceptions.ConnectionError):\n            requests.get(url)\n\n\n### Custom Request Matching Logic\nFor complex scenarios, `can_handle_fun` allows defining custom logic for matching requests:\n\npython\nimport json\nimport re\n\nfrom mocket import mocketize\nfrom mocket.mocks.mockhttp import Entry\nimport requests\n\n\n@mocketize\ndef test_can_handle():\n    url = \"https://httpbin.org\"\n\n    Entry.single_register(\n        Entry.GET,\n        url,\n        body=json.dumps({\"message\": \"Nope... not this time!\"}),\n        headers={\"content-type\": \"application/json\"},\n        can_handle_fun=lambda path, qs_dict: path == \"/ip\" and qs_dict,\n    )\n    Entry.single_register(\n        Entry.GET,\n        url,\n        body=json.dumps({\"message\": \"There you go!\"}),\n        headers={\"content-type\": \"application/json\"},\n        can_handle_fun=lambda path, qs_dict: path == \"/ip\" and not qs_dict,\n    )\n\n    resp = requests.get(\"https://httpbin.org/ip\")\n    assert resp.status_code == 200\n    assert resp.json() == {\"message\": \"There you go!\"}\n\n# Example of regex path matching\nEntry.single_register(\n    Entry.GET,\n    \"https://api.example.com\",\n    body=\"ok\",\n    can_handle_fun=lambda path, qs_dict: bool(re.match(r\"^/users/\\\\d+$\", path)),\n)\n\n\n### Recording Real Socket Traffic\nMocket can also record real socket traffic, similar to VCRpy, for later playback or analysis:\n\npython\nimport json\nimport os\nimport tempfile\nimport io\nimport requests\n\nfrom mocket import mocketize, Mocket\n\n@mocketize(truesocket_recording_dir=tempfile.mkdtemp())\ndef test_truesendall_with_recording_https():\n    url = 'https://httpbin.org/ip'\n\n    requests.get(url, headers={\"Accept\": \"application/json\"})\n    resp = requests.get(url, headers={\"Accept\": \"application/json\"})\n    assert resp.status_code == 200\n\n    dump_filename = os.path.join(\n        Mocket.get_truesocket_recording_dir(),\n        Mocket.get_namespace() + '.json',\n    )\n    with io.open(dump_filename) as f:\n        response = json.load(f)\n\n    assert len(response['httpbin.org']['443'].keys()) == 1\n\n\n### HTTPretty Compatibility\nMocket offers a compatibility layer for HTTPretty, allowing for an easier migration:\n\npython\nimport json\nimport aiohttp\nimport asyncio\nfrom unittest import TestCase\n\nfrom mocket.plugins.httpretty import httpretty, httprettified\n\n\nclass AioHttpEntryTestCase(TestCase):\n    @httprettified\n    def test_https_session(self):\n        url = 'https://httpbin.org/ip'\n        httpretty.register_uri(\n            httpretty.GET,\n            url,\n            body=json.dumps(dict(origin='127.0.0.1')),\n        )\n\n        async def main(l):\n            async with aiohttp.ClientSession(\n                loop=l, timeout=aiohttp.ClientTimeout(total=3)\n            ) as session:\n                async with session.get(url) as get_response:\n                    assert get_response.status == 200\n                    assert await get_response.text() == '{\"origin\": \"127.0.0.1\"}'\n\n            loop = asyncio.new_event_loop()\n            loop.set_debug(True)\n            loop.run_until_complete(main(loop))\n\n\n### Asyncio Integration\nMocket works seamlessly with asyncio-based clients like `aiohttp`:\n\npython\nimport json\nimport aiohttp\nimport pytest\n\nfrom mocket import async_mocketize\nfrom mocket.mocks.mockhttp import Entry\nfrom mocket.plugins.aiohttp_connector import MocketTCPConnector\n\n\n@pytest.mark.asyncio\n@async_mocketize\nasync def test_aiohttp():\n    \"\"\"\n    The alternative to using the custom `connector` would be importing\n    `aiohttp` when Mocket is already in control (inside the decorated test).\n    \"\"\"\n\n    url = \"https://bar.foo/\"\n    data = {\"message\": \"Hello\"}\n\n    Entry.single_register(\n        Entry.GET,\n        url,\n        body=json.dumps(data),\n        headers={\"content-type\": \"application/json\"},\n    )\n\n    async with aiohttp.ClientSession(\n        timeout=aiohttp.ClientTimeout(total=3), connector=MocketTCPConnector()\n    ) as session, session.get(url) as response:\n        response = await response.json()\n        assert response == data\n\n\n### Pook Integration\nMocket can also be used as the mocking engine for `pook`:\n\npython\nimport pook\nfrom mocket.plugins.pook_mock_engine import MocketEngine\nimport requests\n\npook.set_mock_engine(MocketEngine)\npook.on()\n\nurl = 'http://twitter.com/api/1/foobar'\nstatus = 404\nresponse_json = {'error': 'foo'}\n\nmock = pook.get(\n    url,\n    headers={'content-type': 'application/json'},\n    reply=status,\n    response_json=response_json,\n)\nmock.persist()\n\nrequests.get(url)\nassert mock.calls == 1\n\nresp = requests.get(url)\nassert resp.status_code == status\nassert resp.json() == response_json\nassert mock.calls == 2\n\n\n## Why Use Mocket?\nMocket stands out as a robust solution for testing network-dependent Python applications due to its comprehensive features:\n*   **Versatile Mocking**: It can mock any socket communication, not just HTTP, making it suitable for a wide array of protocols and clients.\n*   **Flexibility**: With features like `can_handle_fun`, you have fine-grained control over request matching, allowing for complex testing scenarios.\n*   **Strict Mode**: Prevents accidental external network calls, ensuring true isolation for your tests.\n*   **Compatibility**: Offers compatibility layers for popular libraries like HTTPretty and integrates well with asyncio, gevent, and pook.\n*   **Error Simulation**: Easily simulate network errors to test the robustness of your application's error handling.\n*   **Recording**: Ability to record and replay real network traffic for advanced testing and debugging.\n\n## Links\nExplore Mocket further through these resources:\n\n*   **GitHub Repository**: [https://github.com/mindflayer/python-mocket](https://github.com/mindflayer/python-mocket)\n*   **PyPI**: [https://pypi.org/project/mocket/](https://pypi.org/project/mocket/)\n*   **openSUSE**: [https://software.opensuse.org/search?baseproject=ALL&q=mocket](https://software.opensuse.org/search?baseproject=ALL&q=mocket)\n*   **NixOS**: [https://search.nixos.org/packages?query=mocket](https://search.nixos.org/packages?query=mocket)\n*   **ALT Linux**: [https://packages.altlinux.org/en/sisyphus/srpms/python3-module-mocket/](https://packages.altlinux.org/en/sisyphus/srpms/python3-module-mocket/)\n*   **NetBSD**: [https://cdn.netbsd.org/pub/pkgsrc/current/pkgsrc/devel/py-mocket/index.html](https://cdn.netbsd.org/pub/pkgsrc/current/pkgsrc/devel/py-mocket/index.html)\n*   **AUR Arch Linux**: [https://aur.archlinux.org/packages/python-mocket](https://aur.archlinux.org/packages/python-mocket)\n*   **Mocketoy (Custom Mock Example)**: [https://github.com/mindflayer/mocketoy](https://github.com/mindflayer/mocketoy)\n*   **EuroPython 2013 Video**: [https://www.youtube.com/watch?v=-LvXbl5d02U](https://www.youtube.com/watch?v=-LvXbl5d02U)\n*   **EuroPython 2013 Slides (PDF)**: [https://ep2013.europython.eu/media/conference/slides/mocket-a-socket-mock-framework.pdf](https://ep2013.europython.eu/media/conference/slides/mocket-a-socket-mock-framework.pdf)\n*   **Blog Post: Mocket is alive and is fighting with us**: [https://medium.com/p/mocket-is-alive-and-is-fighting-with-us-b2810d52597a](https://medium.com/p/mocket-is-alive-and-is-fighting-with-us-b2810d52597a)\n*   **Blog Post: Make development great again**: [https://hackernoon.com/make-development-great-again-faab769d264e](https://hackernoon.com/make-development-great-again-faab769d264e)\n*   **Blog Post: HTTPretty now supports asyncio**: [https://hackernoon.com/httpretty-now-supports-asyncio-e310814704c6](https://hackernoon.com/httpretty-now-supports-asyncio-e310814704c6)\n*   **Blog Post: How to make your tests fail when they try to access the network**: [https://medium.com/@mindflayer/how-to-make-your-tests-fail-when-they-try-to-access-the-network-python-eb80090a6d24](https://medium.com/@mindflayer/how-to-make-your-tests-fail-when-they-try-to-access-the-network-python-eb80090a6d24)\n*   **Blog Post: Testing in an asyncio world**: [https://medium.com/@mindflayer/testing-in-an-asyncio-world-a9a0ad41b0c5](https://medium.com/@mindflayer/testing-in-an-asyncio-world-a9a0ad41b0c5)","metrics":{"detailViews":2,"githubClicks":1},"dates":{"published":null,"modified":"2026-08-03T12:19:24.000Z"}}