Skip to content
Advertisement

Mock object without fields and methods

I have for example:

class City:
    field = "bbb"

    def __init__(self):
        some_action()

    def street(self):
        return "aaa"

Is possible to mock City object and still use street method as in other programming languages?

I would like to achieve something like this:

from unittest.mock import patch

@patch("classes.City")
def test_city(city):
    assert city.street() = "aaa"
    assert city.field = "bbb"

In short, I would like to mock the entire object so that it does not execute the constructor and that all fields and methods in the object work as before.

Advertisement

Answer

If you need everything else to occur but some_action, mock it to do nothing.

(so73635578 happens to be the name of this module. You’d replace it with wherever destroy_universe actually is.)

from unittest import mock


def destroy_universe():
    raise ZeroDivisionError("Oh no, you did it again.")


class City:
    field = "bbb"

    def __init__(self):
        destroy_universe()

    def street(self):
        return "aaa"

def test_city():
    with mock.patch('so73635578.destroy_universe'):
        city = City()
        assert city.street() == "aaa"
        assert city.field == "bbb"

To wit:

$ py.test -v so73635578.py
platform darwin -- Python 3.10.6, pytest-7.1.3, pluggy-1.0.0 -- /Users/akx/envs/so-misc/bin/python
cachedir: .pytest_cache
rootdir: /Users/akx/build/so-misc
plugins: anyio-3.6.1
collected 1 item

so73635578.py::test_city PASSED
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement