Disregard the patch decorator at the class level for a specific test

I am currently dealing with a class in a module structured like this:

class Foo:
    def bar1(self) -> str:
        return "bar1"

    def bar2(self) -> str:
        bar = bar1()
        return bar

    def bar3(self) -> str:
        bar = bar1()
        return bar

    def bar4(self) -> str:
        bar = bar1()
        return bar

In another module, I have a test class where I need to mock the bar1 method for each function like barX, except when testing the bar1 method itself. Since there are numerous barX methods and tests, it is not ideal to individually apply the patch decorator above each of the barX test methods (excluding the test_bar1 function).

To address this issue, I decided to patch the bar1 method at the class level using a @patch decorator. However, how can I override this decorator for a specific test method (in this case, my test for bar1())?

Below is my test code:

foo = Foo()

def mock_bar1() -> str:
    return "mocked_bar1"

@patch("foo_module.Foo.bar1", mock_bar1)
class FooTest(TestCase):
    def test_bar1(self) -> None:
        # This fails because bar1() is mocked. I want to disable the mock here.
        self.assertEqual("bar1", foo.bar1())

    def test_bar2(self) -&> None:
        self.assertEqual("mocked_bar1", foo.bar2())

    def test_bar3(self) -&­gt; None:
        self.assertEqual("mocked_bar1", foo.bar3())
  
    def test_bar4(self) -&­gt; None:
        self.assertEqual("mocked_bar1", foo.bar4())

How can I exclude/negate the patched method for my test_bar1 method?

Answer №1

Consider creating a separate class within the test module for handling bar1 tests:

foo = Foo()

def mock_bar1() -> str:
    return "mocked_bar1"

@patch("foo_module.Foo.bar1", mock_bar1)
class FooTest(TestCase):
    def test_bar2(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar2())

    def test_bar3(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar3())

    def test_bar4(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar4())

class FooBar1Test(TestCase):
    def test_bar1(self) -> None:
        self.assertEqual("bar1", foo.bar1())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining data on specified columns with missing values in the primary columns using pandas

Looking for a solution to merge two data frames with null values in key columns and select specific columns from one of the data frames. import pandas as pd import numpy as np data = { 'Email': ['example1@example.com', 'exampl ...

PhantomJS occasionally fails to close (while using Python with Selenium)

Currently, I am utilizing selenium-python in combination with PhantomJS. The code structure is as follows: from selenium.webdriver import PhantomJS from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from se ...

"Utilize Python's Regex.split function to break down text and save each split as a .txt file, with each word in the split

Breaking Down Text Using Python Regex and Exporting Each part as a .txt File to a Specific Folder Hello everyone! I am currently learning Python and experimenting with different text operations: Splitting text using NLTK regex.split Applying regex.spl ...

Using Selenium in Python to extract information from a dynamic table with various dropdown menus

Recently, I've delved into the world of web scraping and am currently in the process of extracting data on various water utilities from a website. This site offers options to select different regions, and my goal is to output this information into a c ...

Combine two data sets by matching their time columns

Please note: I previously posted a similar question with the same dataset on this link, but now I am exploring a different approach to merge the data frames. I have two separate data frames that house diverse types of medical information for patients. The ...

Encountered an issue when locating element in Python Selenium webdriver

After starting with Selenium Webdriver, my goal was to open google.com and click on the button "Google search". Using chropath, I obtained the button element and here is the code snippet: from selenium import webdriver b = webdriver.Chrome() b.get("http:/ ...

Fetch all items in JSON and store them in a Python list

Extracted from the JSON response obtained from this link {'batchcomplete': '', 'query': {'pages': {'24482718': {'pageid': 24482718, 'ns': 0, 'title': 'Web Bot', &apo ...

Not all HREF links are being captured by BeautifulSoup while scraping this website... no results are being returned

My goal is to extract all the links from a specific website in order to compile a comprehensive repository of its associated products. import requests from bs4 import BeautifulSoup import pandas as pd baseurl = "https://www.examplewebsite.com/&quo ...

What could be causing Selenium to fail in loading the link text?

I am attempting to automate the process of clicking on the Accept button for the cookie policy using Selenium before accessing the signup form. The waiting list functionality at this GYM is always a race, so I want to make it automated. However, I have hit ...

ERROR: Cannot call the LIST object

https://i.stack.imgur.com/jOSgE.png Can someone assist me in resolving this issue with my code: "I'm getting an error message saying 'TypeError: 'list' object is not callable'" ...

Tips for dispersing a Python application as a standalone:

My goal is to share my Python application with my colleagues for use on Linux systems. However, they do not have admin privileges to install the necessary module dependencies. I want them to be able to simply extract the application and run the main.py scr ...

Error encountered: When attempting to use ChromeOptions for headless Google Chrome in Selenium Python, an AttributeError was raised indicating that the 'Options' object does not possess the attribute 'self'

For days, I've been attempting to set up headless chrome without any luck. It's frustrating not knowing what's causing the issue!! I've exhaustively searched through forums and tried every solution mentioned. Currently, I'm using ...

Python BeautifulSoup for isolating specific tags in XML documents

In my metadata file, the structure is as follows: <?xml version='1.0' encoding='utf-8'?> <package xmlns="http://www.idpf.org/2007/opf" unique-identifier="uuid_id" version="2.0"> <metadata ...

The certificate verification process encountered an error: unable to retrieve the local issuer certificate

I am seeking assistance for an issue I encountered while installing a module. An error message certificate verify failed: unable to get local issuer certificate appeared. Upon attempting to resolve this by running the Install Certificates.command file in ...

python asyncio.gather incorporates user input into the final result

My function looks something like this: async def funcn(input: input_type) -> output_type: .... return output I am using asyncio.gather to call it in the following way: output = await asyncio.gather(*[funcn(input) for input in input_list]) The retu ...

What is the process of transforming a tree into a straightforward equation?

After analyzing the program here, it is possible to create a tree structure resembling this: https://i.stack.imgur.com/MwbLl.png Main code: def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y FUNCTIONS = [add, sub, mul] TER ...

Calling NVIDIA Performance Primitives in Python: A Comprehensive Guide

How can we utilize the NVIDIA Performance Primitives (NPP) library in Python? ...

When I attempted to extract data with selenium through web scraping, the data stored in my csv file appeared unusual. Instead of the expected content, all I found were j

from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time import cs ...

Finding the maximum element in two separate lists and determining its index

Suppose I have two separate lists and I want to determine the maximum element between those two lists. To accomplish this task, I am leveraging the numpy module in Python. Assuming that n and c are the names of the lists where: n = [7, 1, 54, 812, 124, 6 ...

Python code to verify if a specific condition is satisfied within a certain time period

Seeking to determine if certain conditions are met over a period of time. The data is structured as follows: Datetime Valve1 Valve2 01/01/2020 11:00:01 1 0 The condition being evaluated is: (Valve1=1 for 1h) and (Valve-0 for 1h) Utilizing rolling ...