[Python] Working with python unit tests, tring to patch a class but is not working

Discussão em 'Python' iniciado por Stack, Fevereiro 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have code with below functionality

    src/client.py

    class Client1(object):
    def foo(self, t):
    return f"foo-{t}"

    def get_foo(self, type):
    return self.foo(type)


    src/get_foos.py


    from .src import Client1

    client = Client1()

    def get_foo():
    foo = client.get_foo("foo")
    return foo

    def get_bar():
    bar = client.get_foo("bar")
    return bar



    I am trying to create a unit test for get_foo() and get_bar().

    I do following

    src/test/test_get_foos.py

    from src.get_foos import get_foo

    @patch(src.get_store.Client1)
    def test_get_store(self,mock_client)
    mock_client.get_foo.return_value = 'myfoo'
    result = get_foo()
    assert result === 'myfoo'


    But I observe that the patch does not work and the test fails. I checked all the resources online and everywhere I see the same pattern to mock a class class which is outside a function.

    I have more than 6 methods in my actual code and I don't want to make a new instance of Client1 everywhere.

    Continue reading...

Compartilhe esta Página