Skip to content
Advertisement

Unittesting python?

I have some function with api

def is_car_exist(make, model):
    
    
    url = f'https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMake/
    {make.capitalize()}?format=json'
    data = requests.get(url).json()['Results']
    return any(model.capitalize() == car['Model_Name'] for car in data)

I have some integration tests:

class TestCar(unittest.TestCase):
    def test_is_car_exist(self):
        self.assertTrue(car.is_car_exist('honda', 'civic'))
        self.assertFalse(car.is_car_exist('Mars', 'merana'))

Please could you show how Unittest will look like relatively mine function .

Advertisement

Answer

Solution

Use unittest.mock module. More details can be found here.

import unittest
from unittest.mock import patch

import car


class TestCar(unittest.TestCase):
    @patch("requests.get")
    def test_is_car_exist(self, requests_get):
        requests_get.return_value.json.return_value = {"Results": [{"Model_Name": "Civic"}]}

        self.assertTrue(car.is_car_exist('honda', 'civic'))
        self.assertFalse(car.is_car_exist('Mars', 'merana'))

Explanation

patch replaces a real object or function with a mock one. It requires a positional argument target to be filled. This target needs to be importable by using path.to.module notation like normal import.

One way of using it is by using it as a decorator. When using as a decorator, you need to add a parameter to a decorated function. In this case, it is requests_get.

.return_value is used for function call and what you want it to return.

requests_get.return_value.json.return_value means that you want the return value of requests.get to be an object which has a method called json that returns {"Results": [{"Model_Name": "Civic"}]}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement