pytest-mock automation testing framework index.

Test More In Less Time

Run Automation Testing In Parallel On The LambdaTest Cloud

Start for free

Description

Thin-wrapper around the mock package for easier use with pytest

Support and updates

  • pytest-mock has 1403 stars, 110 forks.
  • It has 4 major releases in the past 6 months.
  • It has 6 commits and there are 0 open pull requests.
  • It has 13 open issues and 108 have been closed.

Code statistics

  • pytest-mock has 31 methods.

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Handle Dynamic Dropdowns In Selenium WebDriver With Java

Joseph, who has been working as a Quality Engineer, was assigned to perform web automation for the company’s website.

Options for Manual Test Case Development & Management

The purpose of developing test cases is to ensure the application functions as expected for the customer. Test cases provide basic application documentation for every function, feature, and integrated connection. Test case development often detects defects in the design or missing requirements early in the development process. Additionally, well-written test cases provide internal documentation for all application processing. Test case development is an important part of determining software quality and keeping defects away from customers.

What exactly do Scrum Masters perform throughout the course of a typical day

Many theoretical descriptions explain the role of the Scrum Master as a vital member of the Scrum team. However, these descriptions do not provide an honest answer to the fundamental question: “What are the day-to-day activities of a Scrum Master?”

Get A Seamless Digital Experience With #LambdaTestYourBusiness????

The holidays are just around the corner, and with Christmas and New Year celebrations coming up, everyone is busy preparing for the festivities! And during this busy time of year, LambdaTest also prepped something special for our beloved developers and testers – #LambdaTestYourBusiness

How to Position Your Team for Success in Estimation

Estimates are critical if you want to be successful with projects. If you begin with a bad estimating approach, the project will almost certainly fail. To produce a much more promising estimate, direct each estimation-process issue toward a repeatable standard process. A smart approach reduces the degree of uncertainty. When dealing with presales phases, having the most precise estimation findings can assist you to deal with the project plan. This also helps the process to function more successfully, especially when faced with tight schedules and the danger of deviation.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

License

pytest-mock is lincensed under the MIT License

LambdaTest Community Discussions

Questions
Discussion

How to correctly use pytest mocker to patch a function?

How to send a POST request with data in Node.js?

What is the correct way to use pytest mocker to patch a function?

I have installed pytest-mock and am trying to use the mocker fixture to patch a function, but I am getting the error "TypeError: Need a valid target to patch. You supplied 'return a + b'".

Here is the code I am working with:

# test_capitalize.py
import time

def sum(a, b):
    time.sleep(10)
    return a + b

def test_sum(mocker):
    mocker.patch('return a + b')  # This is where I get the error
    assertEqual(sum(2, 3), 9)

Can you help me understand how to correctly use pytest mocker to patch the sum function and avoid this error?

https://community.lambdatest.com/t/35326

I’ve worked with pytest mocker quite a bit, and the key to using it correctly is ensuring you’re patching the right function with the correct path. Here’s a simple example of patching with return_value to override a function’s output:

:small_blue_diamond: Patching with a return_value to Simulate a Fixed Result:

You can make a function return a fixed value, regardless of its input:

import pytest

def sum(a, b):
    return a + b

def test_sum1(mocker):
    mocker.patch(__name__ + ".sum", return_value=9)
    assert sum(2, 3) == 9  # This will pass because 'sum' always returns 9 now

Here, pytest mocker ensures sum() always returns 9, making the test predictable.

https://community.lambdatest.com/t/35326

@joe-elmoufak nailed the basics! But sometimes, you need more flexibility than a fixed return value. That’s where side_effect comes in.

:small_blue_diamond: Patching with a side_effect to Change Function Behavior Dynamically:

Instead of returning a fixed value, you can provide a custom function to control behavior:

def test_sum2(mocker):
    def crazy_sum(a, b):
        return b + b  # A different behavior, summing only 'b'

    mocker.patch(__name__ + ".sum", side_effect=crazy_sum)
    assert sum(2, 3) == 6  # This will pass because the new behavior sums 'b + b'

Now, pytest mocker replaces sum() with crazy_sum(), changing the behavior dynamically. Super useful for simulating complex logic!

https://community.lambdatest.com/t/35326

Great points so far! But what if you’re testing code that interacts with an external API or service? You don’t want tests to depend on real API calls, so let’s patch an external function instead.

:small_blue_diamond: Using pytest mocker to Patch an External Function (for APIs & Services):

import requests
import pytest

def get_weather(city):
    response = requests.get(f"https://api.weather.com/{city}")
    return response.json()

def test_weather(mocker):
    mock_response = mocker.Mock()
    mock_response.json.return_value = {"temperature": 72}
    
    # Patching 'requests.get' to return our mock response
    mocker.patch('requests.get', return_value=mock_response)

    weather = get_weather("New York")
    assert weather["temperature"] == 72  # Test runs without hitting the actual API

This is a lifesaver when dealing with APIs. pytest mocker ensures your tests are isolated and fast!

https://community.lambdatest.com/t/35326

Test case code snippets

Accessibility testing - lang attribute for different language sections

Description:

Provide a lang attribute on the page's HTML element. When a visual label is present for an interactive element (e.g., link or form control), the accessible name of the element should contain the visual label.

API Testing - Check version handling

Description:

Verify that the API correctly handles versioning and returns the correct HTTP status code.

Accessibility testing - Suggestions for input error correction

Description:

If an input error is detected and if suggestions for correction are known, provide suggestions for fixing the submission.

Downloads

pytest-mock can be downloaded from it’s GitHub repository - https://github.com/pytest-dev/pytest-mock

Other similar frameworks

keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

pyresttest

A Python REST testing and API

pyatom

Python Automated Testing on Mac

lettuce-tools

Set of utilities and tools to extend Lettuce framework functionality and fill missing gaps in projects

Django Test Plus

Useful additions to Django's default TestCase

Frameworks to try

Cerberus-source

The Open Source Test Automation Platform.

Hikaku

Hikaku library tests if a REST-API implementation meets its specification without having to create requests which are fired against a mock server.

Mockito

Mockito is the most popular Mocking framework for unit tests written in Java. It lets you write beautiful tests with a readable, clean and simple API.

Galen

Galen is an open-source tool for testing layout and responsive design of web applications. It is also a powerfull functional testing framework. (no image, use default java)

Atoum

The modern, simple and intuitive PHP unit testing framework.

Run pytest-mock scripts on 3000+ browsers online

Perform automation testing with pytest-mock on LambdaTest, the most powerful, fastest, and secure cloud-based platform to accelerate test execution speed.

Test Now