close

How to mock requests using pytest?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to mock requests using pytest in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to mock requests using pytest?

  1. How to mock requests using pytest?

    You can use requests-mock (PyPI), there is a fixture for a pytest usage.

  2. mock requests using pytest

    You can use requests-mock (PyPI), there is a fixture for a pytest usage.

Method 1

You can use requests-mock (PyPI), there is a fixture for a pytest usage.

For your example:

from correct.package import __BASE_URL
from requests import HTTPError


def test_get_employee(requests_mock):
    test_id = 'random-id'
    requests_mock.get(f'{__BASE_URL}/employee/{test_id}', json= {'name': 'awesome-mock'})
    resp = get_employee('random-id')
    assert resp == {'name': 'awesome-mock'}

def test_absent_employee(requests_mock):
    test_id = 'does_not_exist'
    requests_mock.get(f'{__BASE_URL}/employee/{test_id}', status_code=404)
    with pytest.raises(HTTPError):
        resp = get_employee(test_id)

Method 2

This may help

from unittest import TestCase

import requests
import requests_mock


class TestHTTPRequest(TestCase):
    def test_context_manager(self):
        with requests_mock.Mocker() as mock_request:
            mock_request.get("http://123-fake-api.com", text="Hello!")
            response = requests.get("http://123-fake-api.com")

        assert response.text == "Hello!"

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read