# MayhemMonkey
MayhemMonkey is a testing tool designed to simulate how your program might react to unexpected errors that can occur when executing basic built-in functions in Python. It helps ensure that your code is robust enough to handle a variety of errors gracefully.
## Goal
The main goal of MayhemMonkey is to simulate errors in basic built-in functions to test how your program responds to unexpected failures. With mayhemmonkey, you can introduce different types of errors in critical Python functions like `open`, `print`, `eval`, etc., and ensure your application remains stable under these conditions.
## Installation
Install MayhemMonkey easily using pip:
```bash
pip3 install mayhemmonkey
```
## Usage
Here is a simple example of how to use MayhemMonkey in a Python project:
```
from mayhemmonkey import MayhemMonkey
mayhemmonkey = MayhemMonkey()
mayhemmonkey.set_function_error_rate("open", 0.5)
mayhemmonkey.set_function_group_error_rate("io", 0.3)
mayhemmonkey.install_faulty()
with open("test.txt", "w") as f: # 50% Chance that it'll fail. Error rate for specific function overrides general error of group
f.write("Hello world!")
print("This should be printed.") # 30% it'll fail because it's in the group "io"
```
You can also set specific functions to fail after a certain amount of calls:
```
from mayhemmonkey import MayhemMonkey
mayhemmonkey = MayhemMonkey()
mayhemmonkey.set_function_fail_after_count("print", 3)
mayhemmonkey.install_faulty()
print("This should be printed.")
print("This should be printed.")
try:
print("This shouldn't be printed.")
except Exception as e:
print(f"Error: {e}")
print("This should be printed.")
```
Here, the 3rd print fails with some random error that print can give in real life.
### Functions and configuration
MayhemMonkey allows you to configure the error probability for various functions, function groups, or globally. The error probability is given as a decimal number between `0` and `1`, where `0` means no errors and `1` guarantees an error.
#### Methods of the MayhemMonkey-object
| Function | Description | Parameters |
|-----------------------------------|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| `get_function_categories` | Returns a dictionary of all function categories and their respective functions. | No parameters. |
| `get_function_categories_as_list` | Returns a list of tuples where each tuple contains the category name and its associated functions. | No parameters. |
| `install_faulty` | Patches built-in functions to introduce errors. Can only be called once. | No parameters. |
| `set_function_error_rate` | Sets the error probability for an individual function. | `name` (str or list): The function name, or a list of function names.<br>`rate` (float): The error rate between 0 and 1. |
| `set_function_group_error_rate` | Sets the error probability for a group of functions. | `group` (str or list): The function group, or a list of group names.<br>`rate` (float): The error rate between 0 and 1. |
| `is_valid_exception_tuple_list` | Checks if the provided object is a valid list of tuples with exception types and messages. | `obj` (list): A list of tuples of the form (ExceptionType, String). |
| `add_exception_to_function` | Adds a list of exceptions (tuples) to a function to simulate specific errors. | `name` (str): The function name.<br>`list_of_tuples_of_exceptions` (list): List of tuples (ExceptionType, String). |
| `set_function_fail_after_count` | Sets the count after which a function will start failing with errors. | `name` (str): The function name.<br>`cnt` (int): The count after which it will fail. |
| `generate_function_categories_markdown_table` | Generates a markdown table for function categories and their functions. | No parameters. |
| `generate_function_errors_markdown_table` | Generates a markdown table for functions and their associated errors. | No parameters. |
#### Function Groups and Their Functions
| Category | Functions |
| --- | --- |
| attributes | `delattr`, `getattr`, `hasattr`, `property`, `setattr` |
| collections | `dict`, `frozenset`, `list`, `set`, `tuple` |
| conversion | `ascii`, `bin`, `bool`, `bytearray`, `bytes`, `chr`, `complex`, `float`, `format`, `hex`, `int`, `oct`, `ord`, `repr`, `str` |
| evaluation | `compile`, `eval`, `exec` |
| exceptions | `compile`, `eval`, `exec` |
| functional | `breakpoint`, `classmethod`, `staticmethod`, `super` |
| hashing | `hash` |
| io | `input`, `open`, `print` |
| iteration | `all`, `any`, `enumerate`, `filter`, `iter`, `len`, `map`, `next`, `range`, `reversed`, `sorted`, `zip` |
| math | `abs`, `divmod`, `max`, `min`, `pow`, `round`, `sum` |
| reflection | `__import__`, `callable`, `globals`, `id`, `isinstance`, `issubclass`, `locals`, `type`, `vars` |
| slicing | `slice` |
#### Error Types for Functions
MayhemMonkey can generate specific types of errors for each function. Here’s a list of the possible errors and their meanings:
| Function | Errors |
| --- | --- |
| `__import__` | `ImportError: Module not found`<br>`TypeError: Invalid module name` |
| `abs` | `TypeError: Bad operand type for abs()` |
| `all` | `TypeError: Argument must be iterable` |
| `any` | `TypeError: Argument must be iterable` |
| `ascii` | `None` |
| `bin` | `TypeError: Object cannot be interpreted as an integer` |
| `bool` | `None` |
| `breakpoint` | `RuntimeError: Cannot start debugger` |
| `bytearray` | `TypeError: Invalid argument type`<br>`ValueError: Negative size not allowed` |
| `bytes` | `TypeError: Invalid argument type`<br>`ValueError: Negative size not allowed` |
| `callable` | `None` |
| `chr` | `ValueError: Argument out of range`<br>`TypeError: Integer argument required` |
| `classmethod` | `TypeError: Invalid method reference` |
| `compile` | `SyntaxError: Compilation error`<br>`TypeError: Invalid code object` |
| `complex` | `ValueError: Could not convert string to complex`<br>`TypeError: Invalid type for complex()` |
| `delattr` | `AttributeError: Object has no such attribute`<br>`TypeError: Invalid attribute name` |
| `dict` | `TypeError: Invalid dictionary construction` |
| `dir` | `TypeError: Invalid argument type` |
| `divmod` | `ZeroDivisionError: division by zero`<br>`TypeError: Unsupported operand type` |
| `enumerate` | `TypeError: Object is not iterable` |
| `eval` | `SyntaxError: Invalid syntax`<br>`TypeError: Expression not allowed`<br>`RuntimeError: Unexpected runtime error` |
| `exec` | `SyntaxError: Invalid syntax`<br>`RuntimeError: Unexpected runtime error` |
| `filter` | `TypeError: Function must be callable` |
| `float` | `ValueError: Could not convert string to float`<br>`TypeError: Invalid type for float()` |
| `format` | `ValueError: Invalid format string` |
| `frozenset` | `TypeError: Invalid argument type` |
| `getattr` | `AttributeError: Object has no such attribute`<br>`TypeError: Invalid attribute name` |
| `globals` | `None` |
| `hasattr` | `None` |
| `hash` | `TypeError: Unhashable type` |
| `hex` | `TypeError: Object cannot be interpreted as an integer` |
| `id` | `None` |
| `input` | `EOFError: End of file reached`<br>`KeyboardInterrupt: Input interrupted` |
| `int` | `ValueError: Invalid literal for int()`<br>`TypeError: Invalid type for int()` |
| `isinstance` | `TypeError: Second argument must be a type or tuple of types` |
| `issubclass` | `TypeError: Second argument must be a type or tuple of types` |
| `iter` | `TypeError: Object is not iterable` |
| `len` | `TypeError: Object has no len()` |
| `list` | `TypeError: Invalid argument for list()` |
| `locals` | `None` |
| `map` | `TypeError: Function must be callable` |
| `max` | `ValueError: Empty sequence`<br>`TypeError: Cannot compare different types` |
| `memoryview` | `TypeError: Invalid memory buffer` |
| `min` | `ValueError: Empty sequence`<br>`TypeError: Cannot compare different types` |
| `next` | `StopIteration: Iterator exhausted`<br>`TypeError: Object is not an iterator` |
| `object` | `None` |
| `oct` | `TypeError: Object cannot be interpreted as an integer` |
| `open` | `FileNotFoundError: No such file or directory`<br>`PermissionError: Permission denied`<br>`IsADirectoryError: Is a directory`<br>`OSError: Too many open files` |
| `ord` | `TypeError: Argument must be a character`<br>`ValueError: Character out of range` |
| `pow` | `ZeroDivisionError: 0.0 cannot be raised to a negative power`<br>`TypeError: Unsupported operand type` |
| `print` | `OSError: Output error` |
| `property` | `None` |
| `range` | `TypeError: Invalid argument type`<br>`ValueError: Step argument must not be zero` |
| `repr` | `None` |
| `reversed` | `TypeError: Object is not reversible` |
| `round` | `TypeError: Second argument must be an integer` |
| `set` | `TypeError: Invalid argument for set()` |
| `setattr` | `AttributeError: Cannot set attribute`<br>`TypeError: Invalid attribute name` |
| `slice` | `TypeError: Invalid slice indices` |
| `sorted` | `TypeError: Invalid key function` |
| `staticmethod` | `None` |
| `str` | `TypeError: Invalid type for str()` |
| `sum` | `TypeError: Object in iterable is not summable` |
| `super` | `TypeError: Invalid superclass reference` |
| `tuple` | `TypeError: Invalid argument for tuple()` |
| `type` | `TypeError: Invalid arguments for type()` |
| `vars` | `TypeError: Object must have __dict__ attribute` |
| `zip` | `None` |
## What happens if an error occurs?
When an error occurs due to the configured error probability, an exception will be raised that you can handle with a try-except block. You can ensure that your application is prepared for these errors by adding appropriate error handling.
## Contributing
If you want to contribute to the development of MayhemMonkey, you can open a pull request or file an issue on GitHub.
Raw data
{
"_id": null,
"home_page": "https://github.com/NormanTUD/MayhemMonkey/",
"name": "mayhemmonkey",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": null,
"author": "Norman Koch",
"author_email": "norman.koch@tu-dresden.de",
"download_url": "https://files.pythonhosted.org/packages/18/a5/014127dbb48f3921895477acf4349b271635dd78f20170d8121a10b60a5d/mayhemmonkey-2025.2.20.post9.tar.gz",
"platform": "Linux",
"description": "# MayhemMonkey\n\nMayhemMonkey is a testing tool designed to simulate how your program might react to unexpected errors that can occur when executing basic built-in functions in Python. It helps ensure that your code is robust enough to handle a variety of errors gracefully.\n\n## Goal\n\nThe main goal of MayhemMonkey is to simulate errors in basic built-in functions to test how your program responds to unexpected failures. With mayhemmonkey, you can introduce different types of errors in critical Python functions like `open`, `print`, `eval`, etc., and ensure your application remains stable under these conditions.\n\n## Installation\n\nInstall MayhemMonkey easily using pip:\n\n```bash\npip3 install mayhemmonkey\n```\n\n## Usage\n\nHere is a simple example of how to use MayhemMonkey in a Python project:\n\n```\nfrom mayhemmonkey import MayhemMonkey\n\nmayhemmonkey = MayhemMonkey()\n\nmayhemmonkey.set_function_error_rate(\"open\", 0.5)\nmayhemmonkey.set_function_group_error_rate(\"io\", 0.3)\n\nmayhemmonkey.install_faulty()\n\nwith open(\"test.txt\", \"w\") as f: # 50% Chance that it'll fail. Error rate for specific function overrides general error of group\n f.write(\"Hello world!\")\n\nprint(\"This should be printed.\") # 30% it'll fail because it's in the group \"io\"\n```\n\nYou can also set specific functions to fail after a certain amount of calls:\n\n```\nfrom mayhemmonkey import MayhemMonkey\n\nmayhemmonkey = MayhemMonkey()\n\nmayhemmonkey.set_function_fail_after_count(\"print\", 3)\n\nmayhemmonkey.install_faulty()\n\nprint(\"This should be printed.\")\nprint(\"This should be printed.\")\ntry:\n print(\"This shouldn't be printed.\")\nexcept Exception as e:\n print(f\"Error: {e}\")\n\nprint(\"This should be printed.\")\n```\n\nHere, the 3rd print fails with some random error that print can give in real life.\n\n### Functions and configuration\n\nMayhemMonkey allows you to configure the error probability for various functions, function groups, or globally. The error probability is given as a decimal number between `0` and `1`, where `0` means no errors and `1` guarantees an error.\n\n#### Methods of the MayhemMonkey-object\n\n| Function | Description | Parameters |\n|-----------------------------------|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|\n| `get_function_categories` | Returns a dictionary of all function categories and their respective functions. | No parameters. |\n| `get_function_categories_as_list` | Returns a list of tuples where each tuple contains the category name and its associated functions. | No parameters. |\n| `install_faulty` | Patches built-in functions to introduce errors. Can only be called once. | No parameters. |\n| `set_function_error_rate` | Sets the error probability for an individual function. | `name` (str or list): The function name, or a list of function names.<br>`rate` (float): The error rate between 0 and 1. |\n| `set_function_group_error_rate` | Sets the error probability for a group of functions. | `group` (str or list): The function group, or a list of group names.<br>`rate` (float): The error rate between 0 and 1. |\n| `is_valid_exception_tuple_list` | Checks if the provided object is a valid list of tuples with exception types and messages. | `obj` (list): A list of tuples of the form (ExceptionType, String). |\n| `add_exception_to_function` | Adds a list of exceptions (tuples) to a function to simulate specific errors. | `name` (str): The function name.<br>`list_of_tuples_of_exceptions` (list): List of tuples (ExceptionType, String). |\n| `set_function_fail_after_count` | Sets the count after which a function will start failing with errors. | `name` (str): The function name.<br>`cnt` (int): The count after which it will fail. |\n| `generate_function_categories_markdown_table` | Generates a markdown table for function categories and their functions. | No parameters. |\n| `generate_function_errors_markdown_table` | Generates a markdown table for functions and their associated errors. | No parameters. |\n\n\n#### Function Groups and Their Functions\n\n| Category | Functions |\n| --- | --- |\n| attributes | `delattr`, `getattr`, `hasattr`, `property`, `setattr` |\n| collections | `dict`, `frozenset`, `list`, `set`, `tuple` |\n| conversion | `ascii`, `bin`, `bool`, `bytearray`, `bytes`, `chr`, `complex`, `float`, `format`, `hex`, `int`, `oct`, `ord`, `repr`, `str` |\n| evaluation | `compile`, `eval`, `exec` |\n| exceptions | `compile`, `eval`, `exec` |\n| functional | `breakpoint`, `classmethod`, `staticmethod`, `super` |\n| hashing | `hash` |\n| io | `input`, `open`, `print` |\n| iteration | `all`, `any`, `enumerate`, `filter`, `iter`, `len`, `map`, `next`, `range`, `reversed`, `sorted`, `zip` |\n| math | `abs`, `divmod`, `max`, `min`, `pow`, `round`, `sum` |\n| reflection | `__import__`, `callable`, `globals`, `id`, `isinstance`, `issubclass`, `locals`, `type`, `vars` |\n| slicing | `slice` |\n\n#### Error Types for Functions\n\nMayhemMonkey can generate specific types of errors for each function. Here\u2019s a list of the possible errors and their meanings:\n\n| Function | Errors |\n| --- | --- |\n| `__import__` | `ImportError: Module not found`<br>`TypeError: Invalid module name` |\n| `abs` | `TypeError: Bad operand type for abs()` |\n| `all` | `TypeError: Argument must be iterable` |\n| `any` | `TypeError: Argument must be iterable` |\n| `ascii` | `None` |\n| `bin` | `TypeError: Object cannot be interpreted as an integer` |\n| `bool` | `None` |\n| `breakpoint` | `RuntimeError: Cannot start debugger` |\n| `bytearray` | `TypeError: Invalid argument type`<br>`ValueError: Negative size not allowed` |\n| `bytes` | `TypeError: Invalid argument type`<br>`ValueError: Negative size not allowed` |\n| `callable` | `None` |\n| `chr` | `ValueError: Argument out of range`<br>`TypeError: Integer argument required` |\n| `classmethod` | `TypeError: Invalid method reference` |\n| `compile` | `SyntaxError: Compilation error`<br>`TypeError: Invalid code object` |\n| `complex` | `ValueError: Could not convert string to complex`<br>`TypeError: Invalid type for complex()` |\n| `delattr` | `AttributeError: Object has no such attribute`<br>`TypeError: Invalid attribute name` |\n| `dict` | `TypeError: Invalid dictionary construction` |\n| `dir` | `TypeError: Invalid argument type` |\n| `divmod` | `ZeroDivisionError: division by zero`<br>`TypeError: Unsupported operand type` |\n| `enumerate` | `TypeError: Object is not iterable` |\n| `eval` | `SyntaxError: Invalid syntax`<br>`TypeError: Expression not allowed`<br>`RuntimeError: Unexpected runtime error` |\n| `exec` | `SyntaxError: Invalid syntax`<br>`RuntimeError: Unexpected runtime error` |\n| `filter` | `TypeError: Function must be callable` |\n| `float` | `ValueError: Could not convert string to float`<br>`TypeError: Invalid type for float()` |\n| `format` | `ValueError: Invalid format string` |\n| `frozenset` | `TypeError: Invalid argument type` |\n| `getattr` | `AttributeError: Object has no such attribute`<br>`TypeError: Invalid attribute name` |\n| `globals` | `None` |\n| `hasattr` | `None` |\n| `hash` | `TypeError: Unhashable type` |\n| `hex` | `TypeError: Object cannot be interpreted as an integer` |\n| `id` | `None` |\n| `input` | `EOFError: End of file reached`<br>`KeyboardInterrupt: Input interrupted` |\n| `int` | `ValueError: Invalid literal for int()`<br>`TypeError: Invalid type for int()` |\n| `isinstance` | `TypeError: Second argument must be a type or tuple of types` |\n| `issubclass` | `TypeError: Second argument must be a type or tuple of types` |\n| `iter` | `TypeError: Object is not iterable` |\n| `len` | `TypeError: Object has no len()` |\n| `list` | `TypeError: Invalid argument for list()` |\n| `locals` | `None` |\n| `map` | `TypeError: Function must be callable` |\n| `max` | `ValueError: Empty sequence`<br>`TypeError: Cannot compare different types` |\n| `memoryview` | `TypeError: Invalid memory buffer` |\n| `min` | `ValueError: Empty sequence`<br>`TypeError: Cannot compare different types` |\n| `next` | `StopIteration: Iterator exhausted`<br>`TypeError: Object is not an iterator` |\n| `object` | `None` |\n| `oct` | `TypeError: Object cannot be interpreted as an integer` |\n| `open` | `FileNotFoundError: No such file or directory`<br>`PermissionError: Permission denied`<br>`IsADirectoryError: Is a directory`<br>`OSError: Too many open files` |\n| `ord` | `TypeError: Argument must be a character`<br>`ValueError: Character out of range` |\n| `pow` | `ZeroDivisionError: 0.0 cannot be raised to a negative power`<br>`TypeError: Unsupported operand type` |\n| `print` | `OSError: Output error` |\n| `property` | `None` |\n| `range` | `TypeError: Invalid argument type`<br>`ValueError: Step argument must not be zero` |\n| `repr` | `None` |\n| `reversed` | `TypeError: Object is not reversible` |\n| `round` | `TypeError: Second argument must be an integer` |\n| `set` | `TypeError: Invalid argument for set()` |\n| `setattr` | `AttributeError: Cannot set attribute`<br>`TypeError: Invalid attribute name` |\n| `slice` | `TypeError: Invalid slice indices` |\n| `sorted` | `TypeError: Invalid key function` |\n| `staticmethod` | `None` |\n| `str` | `TypeError: Invalid type for str()` |\n| `sum` | `TypeError: Object in iterable is not summable` |\n| `super` | `TypeError: Invalid superclass reference` |\n| `tuple` | `TypeError: Invalid argument for tuple()` |\n| `type` | `TypeError: Invalid arguments for type()` |\n| `vars` | `TypeError: Object must have __dict__ attribute` |\n| `zip` | `None` |\n\n## What happens if an error occurs?\n\nWhen an error occurs due to the configured error probability, an exception will be raised that you can handle with a try-except block. You can ensure that your application is prepared for these errors by adding appropriate error handling.\n\n## Contributing\n\nIf you want to contribute to the development of MayhemMonkey, you can open a pull request or file an issue on GitHub.\n",
"bugtrack_url": null,
"license": null,
"summary": "A tool for testing what happens if base functions of python except",
"version": "2025.2.20.post9",
"project_urls": {
"Homepage": "https://github.com/NormanTUD/MayhemMonkey/"
},
"split_keywords": [],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "3cf7b718a2b0a08d999450090c40918b13583f91d2b0cafb9b69cceb748d8b12",
"md5": "dc86fb33a2e133a2c40ce1f7560d4e25",
"sha256": "c0d35e0faa1c028d16e2c74568bed3076ccc4d8b06451ada31535533b1b03009"
},
"downloads": -1,
"filename": "mayhemmonkey-2025.2.20.post9-py3-none-any.whl",
"has_sig": false,
"md5_digest": "dc86fb33a2e133a2c40ce1f7560d4e25",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 41951,
"upload_time": "2025-02-20T08:55:40",
"upload_time_iso_8601": "2025-02-20T08:55:40.470356Z",
"url": "https://files.pythonhosted.org/packages/3c/f7/b718a2b0a08d999450090c40918b13583f91d2b0cafb9b69cceb748d8b12/mayhemmonkey-2025.2.20.post9-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "18a5014127dbb48f3921895477acf4349b271635dd78f20170d8121a10b60a5d",
"md5": "9bb698752353a2788ac4018a9b0053b6",
"sha256": "ad0338ad5ea5f7d9ccfc0762386045e638b2ff07fe56ff343f78ffef500340cf"
},
"downloads": -1,
"filename": "mayhemmonkey-2025.2.20.post9.tar.gz",
"has_sig": false,
"md5_digest": "9bb698752353a2788ac4018a9b0053b6",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 15920,
"upload_time": "2025-02-20T08:55:42",
"upload_time_iso_8601": "2025-02-20T08:55:42.357394Z",
"url": "https://files.pythonhosted.org/packages/18/a5/014127dbb48f3921895477acf4349b271635dd78f20170d8121a10b60a5d/mayhemmonkey-2025.2.20.post9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-20 08:55:42",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "NormanTUD",
"github_project": "MayhemMonkey",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "mayhemmonkey"
}