[Python] How to patch global class in python correctly

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    My project structure- project/

    │ ├── core/ │

    └── service/ │

    └── file.py │
    | └── tests/
    └── test_file.py


    I have a function fun that uses a class method

    file.py-

    from another_module import myClass
    cls_instance=myClass()

    def fun():
    return cls_instance.request()


    And I want to test the fun with patch , like ->

    test_file.py-

    from core.service.file import fun
    class TestCase(unittest.TestCase):
    @patch("core.service.file.cls_instance")
    def setUp(self, mock):
    self.mock = mock.return_value


    def test_fun(self):
    self.mock.request.return_value = 1
    resp=fun()
    self.assertEqual(resp, 1)


    Test Failed with -
    Expected : None

    Actual :1

    What am I doing wrong here?

    Continue reading...

Compartilhe esta Página