0

consider this method in manager.py

def get_start_end_time_for(user, year, month):
    today = datetime.today()
    if today.day  < user.financial_day_of_month:
        if month == 1:
            month = 12
            year -= 1
        else:
            month -= 1

    time_from = date(day=user.financial_day_of_month,
                     month=month, year=year)
    time_to = time_from + relativedelta(months=+1)

    return time_from, time_to

consider the following in test.py

def test_get_start_end_time_for(user, year, month):
    # mock datetime.datetime.today in manager.py
    # do further steps

I looked at Python: Trying to mock datetime.date.today() but not working but it seems you can only mock something with in the test method

How can I mock datetime.datetime.today in manager.py?

Community
  • 1
  • 1
daydreamer
  • 87,243
  • 191
  • 450
  • 722

1 Answers1

1

One of the simplest strategies is to wrap datetime.today() in a method. It could look something like this:

def get_start_end_time_for(user, year, month):
    today = get_today()
    ...

def get_today():
    return datetime.today()

Then in test.py, you would mock it by mocking the getToday() method as follows:

@patch('get_today')
def test_get_start_end_time_for(user, year, month, get_today_mock):
    get_today_mock.return_value = #whatever date you want to use for your test
Rob Watts
  • 6,866
  • 3
  • 39
  • 58