Mocking instance attributes

2024/11/13 5:11:21

Please help me understand why the following doesn't work. In particular - instance attributes of a tested class are not visible to Python's unittest.Mock.

In the example below bar instance attribute is not accessible. The error returned is:

AttributeError: <class 'temp.Foo'> does not have the attribute 'bar'
import unittest
from unittest.mock import patchclass Foo:def __init__(self):super().__init__(self)self.bar = some_external_function_returning_list()def do_someting(self):calculate(self.bar)class TestFoo(unittest.TestCase):@patch('temp.Foo.bar')def test_do_something(self, patched_bar):patched_bar.return_value = ['list_elem1', 'list_elem2']
Answer

Patching is used to modify name or attribute lookup. In this case, there is no bar attribute of the class temp.Foo.

If the intent is to patch the instance variable, you either need an existing instance to modify

def test(self):f = Foo()with patch.object(f, 'bar', 3):self.assertEqual(f.bar, 3)

or you may want to patch the function call that initializes the instance attribute in the first place.

def test(self):with patch('some_external_function_returning_list', return_value=3):f = Foo()self.assertEqual(f.bar, 3)
https://en.xdnf.cn/q/72336.html

Related Q&A

Are there any good 3rd party GUI products for Python? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

not able to get root window resize event

im trying to display the size(dimension) of the root window (top level window) on a label. whenever the user resize the window, new window dimensions should be displayed on the label. I tried to bind t…

Inverting large sparse matrices with scipy

I have to invert a large sparse matrix. I cannot escape from the matrix inversion, the only shortcut would be to just get an idea of the main diagonal elements, and ignore the off-diagonal elements (Id…

Error with tweepy OAuthHandler

Im new here and kind of unexperienced with python, so sorry if the question is trivial.I have this simple script, to fetch followers of a given twitter user:import time import tweepyconsumer_key="…

Overriding __or__ operator on python classes

As a contrived example, suppose Im generating a random fruit basket in python. I create the basket:basket = FruitBasket()Now I want to specify specific combinations of fruit that can occur in the baske…

python charmap codec cant decode byte X in position Y character maps to undefined

Im experimenting with python libraries for data analysis,the problem im facing is this exceptionUnicodeDecodeError was unhandled by user code Message: charmap codeccant decode byte 0x81 in position 165…

get icloud web service endpoints to fetch data

My question may look silly but I am asking this after too much search on Google, yet not have any clue.I am using iCloud web services. For that I have converted this Python code to PHP. https://github.…

How to put result of JavaScript function into python variable. PyQt

I want to make a function in PyQt evaluateJavaScript() (or may be similar one) and than display a result of evaluated function. Real function will be much bigger, and it might not be a string.Im only …

Wrap multiple tags with BeautifulSoup

Im writing a python script that allow to convert a html doc into a reveal.js slideshow. To do this, I need to wrap multiple tags inside a <section> tag. Its easy to wrap a single tag inside anoth…

How to permanently delete a file in python 3 and higher?

I want to permanently delete a file i have created with my python code. I know the os.remove() etc but cant find anything specific to delete a file permanently.(Dont want to fill Trash with unused file…