'How to mock a class call in Python?
I am trying to test a function which contain a class call, like this :
def products_list_creator(self, category, number_of_pages):
products_list = []
api_request = dict(requests.get(f"https://fr-en.openfoodfacts.org/category/{category}/{number_of_pages}.json").json())
for json_product in api_request["products"]:
product = ApiProduct(json_product)
print(product)
if self.product_data_validity(product):
products_list.append(product)
return products_list
So I tried to mock it in my test.py like this :
@patch('requests.get')
def test_products_list_creator(self, mock_get):
test_json_product = dumps({"products":
[
{
"name": "apple",
},
{
"name": "banana",
}
]
}).encode('ascii')
resp = Response()
resp.encoding = 'ascii'
resp._content = test_json_product
mock_get.return_value = resp
_product_maker.ApiProduct = MagicMock(return_value="product")
self.command.product_data_validity = MagicMock(return_value=True)
response = self.command.products_list_creator(None,None)
assert [["product"],["product"]] == [response]
This doesn't worked so I decided to add a print in my function to know what is the value of product when I test and I got this response :
<main_site.management.commands._product_maker.ApiProduct object at 0x058C8190>
Here is my ApiProduct :
class ApiProduct:
"""This class create a product"""
def __init__(self, json_product):
self.json_product = json_product
def name(self):
"""Search for name"""
try:
if self.json_product["product_name"] != "":
return self.json_product["product_name"]
else:
return None
except KeyError:
print("Name not found")
return None
So how to mock a class ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
