Skip to content
Advertisement

Tag: mocking

How to mock a function that is not part of any class using monkeypatch in Python?

Consider a function: and it’s mock function: How do I mock some_function() function using monkeypath.setattr()? Something similar to: monkeypatch.setattr(<class name>, “some_function”, dummy_function) Not sure what <class name> here should be. Answer obj should be the current module: If some_function is inside another file, you need to import this file to your current module:

What does the instance argument in Python’s create_autospec do?

I’m playing around with mock autospecs in Python. Here’s a basic test case where I’m autospecing the Django User class using create_autospec. The test passes when I set both instance=True and instance=False, so what exactly does this parameter do? What’s its purpose? I’ve seen multiple blog posts set it to True (here and here) so I feel like it’s important.

Unable to mock os name with Python on Windows

I have the following method: I’m trying to test it like this: But then the following error is raised: What is happening exactly? Answer What is happening here is that pytest internally uses a pathlib.Path object, which upon initialization asks for os.name to define which Path implementation to use. There are two internal implementations for Path, PosixPath and WindowsPath, which

Pytest + mock: patch does not work without with clause

I’m testing complex logic that require joining of central fact table with 10-20 smaller dimensional tables. I want to mock that 10-20 smaller tables. How to patch methods return values in a for loop? See code below. tables.py: test_logic.py P.S. alternatively I can try to mock the BaseClass.load, but then I don’t know how to return the different data set

Changing monkeypatch setattr multiple times

I am trying to test code that depends on a third party and would like to use monkeypatch to replicate what I expect a request will return. Here is a minimal example of the code that I have. For my tests, I have something like the following: How can I monkeypatch each of the calls to requests.get using monkeypatch.setattr? The

Advertisement