Mocking (Python)

Mocking (Python)

When I write code I like to include tests. Tests help me to reduce the risk of code breaking changes and give me the reassurance that what I have coded does what I need it to do.

I’m currently writing a backend (Django/Python) that serves some APIs and a frontend (Flask/Python) to consume those APIs, and treating both as independent projects.. This gives me a little bit of a challenge as my tests generally run as GitHub Actions automatically when carrying out merges. However, in this case the backend will not be available to the frontend for the frontend’s tests.

Mocking

Mocking to the rescue. The frontend generates its content based on calling the APIs and using the results. Instead of calling the backend API I can get Python to mock the API call and generate results that meet the same criteria.

For example, I have a route (“/cases”) that calls on a function I’ve called getData to get data from the API.

@main.route('/cases', methods=['GET'])
def cases():
    apiURL = "http://localhost:8000/api/v1/tasks/"
    cases = getData.get_data(apiURL)
    response = make_response(render_template('views/cases.html', cases = cases))
    return response

In my test files I can use unitest.mock to patch getData and return a mock result of data that is similar to what the web application is expecting.

   @patch('app.main.views.getData.get_data')
    def test_caselist_with_mocked_data(self, mock_getData):
        '''
        /cases uses mocked getData and renders expected content
        '''
        mock_cases = [
            {
                "id": 1,
                "cmTitle": "Mocked Title",
                "cmDescription": "Mocked Description",
                "cmStatus": "Open",
                "cmDueDate": "2025-05-06T20:30:00Z"
            }
        ]
        mock_getData.return_value = mock_cases
        response = self.client.get('/cases')
        self.assertIn("Mocked Title", response.get_data(as_text=True))

The Flask frontend can then be tested independently of the Django backend. This practice could also be used to mock an API whilst producing an application, reducing the number of API calls needed during early programming.

The code for the Flask frontend, including the tests and GitHub Actions are at my GitHub.

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect