Python Forum

Full Version: unittest for nested function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

Have to write couple unittests for nested function.
This is simplified version

def processSubscription(
        self,
        command,
        **conditions
):
    def _matchConditions(request_conditions, command_conditions):
        if request_conditions in command_conditions:
            return True
        else
            return False

    if _matchConditions(conditions, command_conditions):
        subscribers = subscription['emails']
        send_mail(subscribers)

I want to capture the return value from _matchConditions
for my tests and also mock send_mail function,
so mails are not actually send on match.
Create a mock send_mail function. That will prevent sending the actual mails, and you can use whether it was triggered or not to test whether _matchConditions was True or False.
You might try to isolate the behavior of the parts you want to test. Since you are using direct references to the parts of the the function you would like to test, this is a problem.

One possible way to reorganize your functions:

def processSubscription(
        self,
        mail_send_function,
        command,
        **conditions
):
    
    def _matchConditions(request_conditions, command_conditions):
        if request_conditions in command_conditions:
            return True
        else
            return False
 
    if _matchConditions(conditions, command_conditions):
        subscribers = subscription['emails']
        mail_send_function(subscribers)
In this case, we're just moving the definition of the activity for sending an email from the processSubscription definition. You can supply the behavior at runtime, or if you are running a test, provide a function that does nothing.

You can also do the same process for _matchConditions.

The advantage is that while you are testing processSubscription you can supply the behavior to test what ever scenarios you have in mind.