Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock function arguments in python

Lets say I have this function

from datetime import date

def get_next_friday(base_date=date.today()):
   next_friday = ...
   return next_friday

Then I have a celery task to call this function without passing in the base_date

@celery_app.task
def refresh_settlement_date():
   Record.objects.update(process_date=get_next_friday())

In the unittest I am running the refresh_settlement_date() task, but it's not providing the base_date when it's calling the get_next_friday(), my question is how to mock that parameter to test the days in the future?

I am trying to avoid adding parameter to become refresh_settlement_date(base_date) as it doesn't serve real purpose but only for unittest.

like image 543
James Lin Avatar asked Jul 02 '26 21:07

James Lin


1 Answers

You need to @patch get_next_friday() function and substitute its return value with the one you need:

date_in_the_future = date.today() + timedelta(50)
next_friday_in_the_future = get_next_friday(base_date=date_in_the_future)

with patch('module_under_test.get_next_friday') as mocked_function:
    mocked_function.return_value = next_friday_in_the_future
    
    # call refresh_settlement_date
like image 170
alecxe Avatar answered Jul 05 '26 09:07

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!