Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Mock with python
#1
Hello,

I want to know how I can mock an "if" condition on a method?

class FeatEng:

    @staticmethod
    def is_activated(feat_flag):
        client = app_client_instance
        if client.is_client_created():
            value = client.get_value(feat_flag)
            return "true" == value
        
------------------------------------------------------------------------------------------------
Test class sample code:

FeatEng.is_activated = MagicMock(name='is_activated')
FeatEng.is_activated.client = client
FeatEng.is_activated.value = client.get_value.return_value
FeatEng.is_activated.return_value = ("true" == FeatEng.is_activated.value)
Thanks
Reply
#2
What do you mean by that exactly? It isn't clear to me. Also, you seem to be mocking all the internals of the is_activated method. Why? What is it you're trying to do, really? You've provided very little code, so it's hard to guess. It would help if you showed the test code too, probably.

At a guess: do you actually want to provide a fake implementation of this is_activated method because you're testing some other class that needs to call it? What I mean is that you have some class, say Foo that you're testing and it uses a FeatEng to do its job and what you want is to use a fake version of it because you don't want to use the production implementation (which is entirely reasonable, because maybe it's expensive to do so, for example). Is that what you want? In that case, you don't need to mock the implementation like you're doing. Create a fake implementation of the function that doesn't do the expensive stuff and just pass it into the class that needs it (that is, inject the dependency):

def fake_is_activated():
    return true # Or whatever logic the fake should have
class Foo:
    def __init__(self, is_activated):
       self.is_activated = is_activated

    def some_method(self):
        if is_activated():
           # Whatever goes here
In the production code, you pass the FeatEng method:

foo = Foo(FeatEng.is_activated)
while in the test, you pass the fake:

foo = Foo(fake_is_activated)
If that's not what you're trying to do, please explain. If you're actually testing the is_activated method, then again, the answer is the same: pass the client as a parameter so you can swap it out for a fake one in the tests.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020