[Interview Qn] What Is Monkey Patching?
Monkey patching refers to a technique where we dynamically modify code behaviour at runtime.
We probably use this the most during testing rather than in the actual application code (doing monkey patching in app code is bad practice)
A simple dummy example
Let’s say we have some API endpoint that gives us some fruits eg. https://fruits.com/api/fruits
which returns something like:
{
"fruits": ["apple", "orange", "pear"]
}
^ tho this fruits list might change once per few days
And we have a dummy function that uses this API.
import requests
def check_fruit(fruit: str):
URL = 'https://fruits.com/api/fruits'
fruits_data = requests.get(URL).json()['fruits']
return {
'valid': fruit in fruits_data,
'fruits': fruits_data
}
x = check_fruit('pineapple')
print(x)
# {'valid': False, 'fruits': ['apple', 'orange', 'pear']}
Next, we want to test the check_fruit() function
Let’s assume we use pytest for unit testing.
We could write some function like this:
from somewhere import check_fruit
def test_check_fruit():
res = check_fruit('apple')…