qmo
qmo

Reputation: 3198

Mocking timedelta.total_seconds()

Is there any way to mock total_seconds() from the following code?

start = datetime.now()
...
end = datetime.now()
diff = (end - start).total_seconds()

I've tried it but getting this error

TypeError: unorderable types: MagicMock() > int()

Upvotes: 1

Views: 828

Answers (1)

Yuriy Leonov
Yuriy Leonov

Reputation: 504

It is durty example, but it could give some hints:

from datetime import datetime
import unittest


def need_test():
    start = datetime.datetime.now()
    end = datetime.datetime.now()
    diff = (end - start).total_seconds()
    return diff


class SimpleTestCase(unittest.TestCase):

    def setUp(self):
        datetime_mock = mock.patch(__name__ + ".datetime")
        self.datetime_mock = datetime_mock.start()

    def test_need_test(self):
        self.datetime_mock.datetime.now().__sub__().total_seconds.return_value = 123
        self.assertEqual(need_test(), 123)

First of all mock.patch(__name__ + ".datetime") should be changed on mock.patch.object(module.where.is.your.function, "datetime"). And after that self.datetime_mock.datetime.now() (maybe) could be replaced with self.datetime_mock.now()

This example is not a propper way to do such testing, but it could resolve your question.

Upvotes: 1

Related Questions