unittest.mock: How can I use datetime.datetime.now with different calls in the same method?

Asked

Viewed 27 times

0

How can I proceed with a mock test on datetime.datetime.now with different calls in the same method?

In my test is returned the current date.

Follow an example of the code, to facilitate help. Thanks in advance.

from datetime import datetime as dt

def metodo():
    return dt.today().strftime('%Y'), dt.today().strftime('%Y-%m-%d %X %z')


def test_metodo(self):
    expected = ('2018', "2018-12-14 12:34:56")
    mock_date = Mock(spec=mypackage.metodo)
    today.side_effect=list(expected)
    self.assertIsNotNone(metodo())
    self.assertEqual(expected, metodo())

1 answer

0

I was successful with this:

@patch('mypackage.dt')
def test_metodo(self, mock_date):
    expected = ('2018', "2018-12-14 12:34:56")
    mock_date.today.return_value = mypackage.dt(2018, 12, 14, 12, 34, 56)
    mock_date.today.return_value.strftime.side_effect = list(expected)
    self.assertIsNotNone(metodo())
    self.assertEqual(expected, metodo())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.