{"id":13772786,"url":"https://github.com/pksol/pytest-mock-generator","last_synced_at":"2025-08-13T03:33:19.365Z","repository":{"id":38827309,"uuid":"391848294","full_name":"pksol/pytest-mock-generator","owner":"pksol","description":"A pytest fixture wrapper for https://pypi.org/project/mock-generator","archived":false,"fork":false,"pushed_at":"2024-06-02T17:45:59.000Z","size":123,"stargazers_count":31,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-07-22T22:48:21.997Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pksol.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-08-02T07:08:52.000Z","updated_at":"2024-06-06T23:23:21.000Z","dependencies_parsed_at":"2024-04-03T06:29:42.185Z","dependency_job_id":"7b3464aa-cca1-4e93-805c-18134206d834","html_url":"https://github.com/pksol/pytest-mock-generator","commit_stats":{"total_commits":49,"total_committers":2,"mean_commits":24.5,"dds":"0.18367346938775508","last_synced_commit":"77622de063a874a9e7b89c95fae476c5d431c02a"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/pksol/pytest-mock-generator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pksol%2Fpytest-mock-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pksol%2Fpytest-mock-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pksol%2Fpytest-mock-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pksol%2Fpytest-mock-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pksol","download_url":"https://codeload.github.com/pksol/pytest-mock-generator/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pksol%2Fpytest-mock-generator/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270175834,"owners_count":24540095,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-13T02:00:09.904Z","response_time":66,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T17:01:07.768Z","updated_at":"2025-08-13T03:33:19.111Z","avatar_url":"https://github.com/pksol.png","language":"Python","funding_links":[],"categories":["Python","Tools"],"sub_categories":[],"readme":"# pytest-mock-generator\n\n\u003cdiv align=\"center\"\u003e\n\n[![Build status](https://github.com/pksol/pytest-mock-generator/workflows/build/badge.svg?branch=master\u0026event=push)](https://github.com/pksol/pytest-mock-generator/actions?query=workflow%3Abuild)\n[![Python Version](https://img.shields.io/pypi/pyversions/pytest-mock-generator.svg)](https://pypi.org/project/pytest-mock-generator/)\n\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Security: bandit](https://img.shields.io/badge/security-bandit-green.svg)](https://github.com/PyCQA/bandit)\n[![Pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit\u0026logoColor=white)](https://github.com/pksol/pytest-mock-generator/blob/master/.pre-commit-config.yaml)\n[![Semantic Versions](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--versions-e10079.svg)](https://github.com/pksol/pytest-mock-generator/releases)\n[![License](https://img.shields.io/github/license/pksol/pytest-mock-generator)](https://github.com/pksol/pytest-mock-generator/blob/master/LICENSE)\n\nA pytest fixture wrapper for https://pypi.org/project/mock-generator\n\n\u003c/div\u003e\n\n## Installation\n\n```bash\npip install pytest-mock-generator\n```\n\nor install with [poetry](https://github.com/python-poetry/poetry):\n\n```bash\npoetry add pytest-mock-generator\n```\n\n## Usage\nThis [pytest plugin](https://docs.pytest.org/en/latest/how-to/writing_plugins.html) \nadds the `mg` [fixture](https://docs.pytest.org/en/latest/reference/fixtures.html#fixture)\nwhich helps when writing tests that use [python mocks](https://docs.python.org/3.7/library/unittest.mock.html).\n\nLet's start with an easy example. Assume you have a module named `tested_module.py` which holds a function\nto process a string sent to it and then add it to a zip file:\n```python\nimport zipfile\n\ndef process_and_zip(zip_path, file_name, contents):\n    processed_contents = \"processed \" + contents  # some complex logic\n    with zipfile.ZipFile(zip_path, 'w') as zip_container:\n        zip_container.writestr(file_name, processed_contents)\n```\nThis is the function that you want to test (aka Unit Under Test or UUT). \nYou don't want to create a file on the hard drive and wish to mock it instead.\n\nAlthough this is a very short function, \nwriting the test code takes a lot of time. It's the fact that the function uses\na context manager makes the testing more complex than it should be.\n*If you don't believe me, try to manually write mocks and asserts which verify\nthat `zip_container.writestr` was called with the right parameters.*\n\n### Generating the 'Arrange' and 'Assert' sections using Mock Generator\nTo generate the 'Arrange' and 'Assert' sections, simply put this code at the beginning of \nyour test function skeleton and run it (make sure to add the `mg` fixture):\n\n```python\nfrom tests.sample.code.tested_module import process_and_zip\n\ndef test_process_and_zip(mocker, mg):\n    # arrange: todo  \n    mg.generate_uut_mocks_with_asserts(process_and_zip)\n    \n    # act: invoking the tested code\n    process_and_zip('/path/to.zip', 'in_zip.txt', 'foo bar')\n    \n    # assert: todo\n```\nThis will generate the sections for you:\n```python\n# mocked dependencies\nmock_ZipFile = mocker.MagicMock(name='ZipFile')\nmocker.patch('tests.sample.code.tested_module.zipfile.ZipFile', new=mock_ZipFile)\n# calls to generate_asserts, put this after the 'act'\nmg.generate_asserts(mock_ZipFile, name='mock_ZipFile')\n```\n\u003cb\u003eThe generated code is returned, printed to the console and also copied to the\nclipboard for your convenience. \nJust paste it (as simple as ctrl+V) to your test function:\u003c/b\u003e\n```python\nfrom tests.sample.code.tested_module import process_and_zip\n\ndef test_process_and_zip(mocker, mg):\n    # arrange:  \n    # mocked dependencies\n    mock_ZipFile = mocker.MagicMock(name='ZipFile')\n    mocker.patch('tests.sample.code.tested_module.zipfile.ZipFile', new=mock_ZipFile)\n    \n    # act: invoking the tested code\n    process_and_zip('/path/to.zip', 'in_zip.txt', 'foo bar')\n    \n    # assert: todo\n    # calls to generate_asserts, put this after the 'act'\n    mg.generate_asserts(mock_ZipFile, name='mock_ZipFile')\n```\n\nExcellent! Arrange section is ready. Run the test function once more to get the asserts:\n```python\nassert 1 == mock_ZipFile.call_count\nmock_ZipFile.assert_called_once_with('/path/to.zip', 'w')\nmock_ZipFile.return_value.__enter__.assert_called_once_with()\nmock_ZipFile.return_value.__enter__.return_value.writestr.assert_called_once_with('in_zip.txt', 'processed foo bar')\nmock_ZipFile.return_value.__exit__.assert_called_once_with(None, None, None)\n```\nWow, that's a handful of asserts! Some are very useful: \n* Checking that we opened the zip file with the right parameters.\n* Checking that we wrote the correct data to the proper file.\n* Finally, ensuring that `__enter__` and `__exit__` are called, so there \nare no open file handles which could cause problems.\n\nYou can remove any generated lines which you find unnecessary.   \n\nPaste that code right after the act phase, and you're done!\n\nThe complete test function:\n```python\nfrom tests.sample.code.tested_module import process_and_zip\n\ndef test_process_and_zip(mocker):\n    # arrange:  \n    # mocked dependencies\n    mock_ZipFile = mocker.MagicMock(name='ZipFile')\n    mocker.patch('tests.sample.code.tested_module.zipfile.ZipFile', new=mock_ZipFile)\n    \n    # act: invoking the tested code\n    process_and_zip('/path/to.zip', 'in_zip.txt', 'foo bar')\n    \n    # assert:\n    assert 1 == mock_ZipFile.call_count\n    mock_ZipFile.assert_called_once_with('/path/to.zip', 'w')\n    mock_ZipFile.return_value.__enter__.assert_called_once_with()\n    mock_ZipFile.return_value.__enter__.return_value.writestr.assert_called_once_with('in_zip.txt', 'processed foo bar')\n    mock_ZipFile.return_value.__exit__.assert_called_once_with(None, None, None)\n```\nCan you imagine the time it would have taken you to code this on your own?\n\n### What's Next\n#### Asserting Existing Mocks\nAt times, you may be editing a test function already containing mocks, or\nyou choose to write the mocks yourself, to gain some extra control.\n\nMock Generator can generate the assert section for standard \nPython mocks, even if they were not created using the Mock Generator. \n\nPut this after the 'Act' (replace `mock_obj` with your mock object name): \n```python\nmg.generate_asserts(mock_obj)\n```\nTake the generated code and paste it at the 'Assert' section. \n\n## Troubleshooting\n### No output is printed to the console when running Pytest\nBe sure to run Pytest with appropriate flags to print the output: `pytest -rA`.\n\n### No output is copied to the clipboard\nMock Generator uses [pyperclip](https://github.com/asweigart/pyperclip) for clipboard \nmanipulations, look for errors / warnings printed to the console, similar to this one: \n```commandline\nWARNING mock_autogen.utils:utils.py:28 \nCould not copy func results to clipboard Traceback (most recent call last): \n    File \"/home/username/Documents/code/test_mock_gen/.envtest/lib/python3.6/site-packages/mock_autogen/utils.py\", line 25, in to_clipboard \n        pyperclip.copy(result) \n    File \"/home/username/Documents/code/test_mock_gen/.envtest/lib/python3.6/site-packages/pyperclip/__init__.py\", line 659, in lazy_load_stub_copy \n        return copy(text) \n    File \"/home/username/Documents/code/test_mock_gen/.envtest/lib/python3.6/site-packages/pyperclip/__init__.py\", line 336, in __call__\n        raise PyperclipException(EXCEPT_MSG) pyperclip.PyperclipException: \n        \n    Pyperclip could not find a copy/paste mechanism for your system. \n    For more information, please visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error\n```\n\nIt's possible that your system lacks some dependency, visit \nhttps://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error for \nadditional troubleshooting steps.\n\n\n## More information\nAdditional documentation can be found in the [mock-generator pypi](https://pypi.org/project/mock-generator).\n\n## 📈 Releases\n\nYou can see the list of available releases on the [GitHub Releases](https://github.com/pksol/pytest-mock-generator/releases) page.\n\nWe follow [Semantic Versions](https://semver.org/) specification.\n\n## 🛡 License\n\n[![License](https://img.shields.io/github/license/pksol/pytest-mock-generator)](https://github.com/pksol/pytest-mock-generator/blob/master/LICENSE)\n\nThis project is licensed under the terms of the `MIT` license. See [LICENSE](https://github.com/pksol/pytest-mock-generator/blob/master/LICENSE) for more details.\n\n## 📃 Citation\n\n```bibtex\n@misc{pytest-mock-generator,\n  author = {Peter Kogan},\n  title = {A pytest fixture wrapper for https://pypi.org/project/mock-generator},\n  year = {2021},\n  publisher = {GitHub},\n  journal = {GitHub repository},\n  howpublished = {\\url{https://github.com/pksol/pytest-mock-generator}}\n}\n```\n\n## Credits [![🚀 Your next Python package needs a bleeding-edge project structure.](https://img.shields.io/badge/python--package--template-%F0%9F%9A%80-brightgreen)](https://github.com/TezRomacH/python-package-template)\n\nThis project was generated with [`python-package-template`](https://github.com/TezRomacH/python-package-template)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpksol%2Fpytest-mock-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpksol%2Fpytest-mock-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpksol%2Fpytest-mock-generator/lists"}