Random HTTP Request Simulation with Pytest and Pytest-Mock

  • Share this:

Code introduction


This function uses pytest and pytest-mock libraries to randomly simulate HTTP requests and assert the response.


Technology Stack : pytest, pytest-mock

Code Type : The type of code

Code Difficulty :


                
                    
import random
import pytest
from pytest_mock import MockerFixture

def random_test_case(mock: MockerFixture):
    # This function generates a random test case using pytest and pytest-mock libraries
    # It randomly selects a method to mock and calls it with random arguments

    # Select a random method to mock
    methods = ['get', 'post', 'put', 'delete']
    method = random.choice(methods)

    # Create a random URL
    url = f"http://example.com/{random.randint(1000, 9999)}"

    # Create a random response
    response = {"status_code": 200, "body": "Random Response"}

    # Mock the method
    mock.request(method=method, url=url).return_value.json.return_value = response

    # Call the mocked method
    result = mock.request(method=method, url=url).json()

    # Assert the result
    assert result == response

# JSON Explanation