app_client.py ------------- class AppClient: def __init__(self): self.val = "true" def get_value(self, feature_eng): return self.val .................................................... app_client_instance.py ---------------------- from app_client import AppClient app_client_instance = AppClient() .................................................... feat_eng.py ----------- from app_client_instance import app_client_instance class FeatEng: @staticmethod def is_activ(feature_eng): client = app_client_instance value = client.get_value(feature_eng) return "true" == value .................................................... test.py ------- import unittest from unittest.mock import MagicMock from app_client import AppClient from app_client_instance import app_client_instance from feat_eng import FeatEng class FeatEngShould(unittest.TestCase): def test_mockmagshouldFalse(self): client = MagicMock(spec=AppClient, name=AppClient) client.get_value.return_value = "false" instance = MagicMock() instance.app_client_instance.return_value = client result = FeatEng.is_activ("MIG_ENG") self.assertFalse(result)
I want to make the mock client returning false to make success the test but instead it failed Mocking in Python can be initially confusing and the official docs, while informative, don’t make learning it any easier for newcomers. In my case, I came across it when I was still transitioning from Ruby which, I believe, contributed to the confusion. This article takes a gentler approach to learning Python’s mocking library to help you get productive sooner. Importing Objects: A ReviewThe unittest.mock library builds on top of how Python implements the import statement so it’s imperative that we have a solid understanding of how it works before we can continue. Let’s say we have a file named
|