file.py
import datetime ENV_NUMBER_DAYS_RESERVED = 3 def check_date(entity): entity_created_date = entity.get('createdDatetime').date() utc_date = datetime.datetime.utcnow().date() print((utc_date - entity_created_date).days) #<MagicMock name='datetime.datetime.utcnow().date().__sub__().days' id='4899349456'> print(type((utc_date - entity_created_date).days))#<class 'unittest.mock.MagicMock'> return True if (utc_date - entity_created_date).days > int(ENV_NUMBER_DAYS_RESERVED) else False
test.py
import file @patch('file.datetime') def test_check_date_False(self, date_now): entity = MagicMock() entity.get.return_value = datetime.datetime(2022,1,1) date_now.datetime.utcnow.date.return_value = datetime.datetime(2022,1,1) self.assertFalse(check_date(entity=entity))
I get an Error: TypeError: ‘>’ not supported between instances of ‘MagicMock’ and ‘int’
Is there anyway to test this function?
Probably the problem is with this part of the last line:
(utc_date - namespace_created_date).days
Advertisement
Answer
I could reproduce and fix.
Here is a working unittest file (assuming file.py is accessible):
import unittest from unittest.mock import patch, MagicMock import datetime import file class TestFile(unittest.TestCase): @patch('file.datetime') def test_check_date_False(self, date_now): entity = MagicMock() entity.get.return_value = datetime.datetime(2022,1,1) date_now.datetime.utcnow.return_value = datetime.datetime(2022,1,1) self.assertFalse(file.check_date(None, entity=entity)) unittest.main(verbosity=2)
If I use date_now.datetime.utcnow.date.return_value = datetime.datetime(2022,1,1)
I have the same error as you have, but removing .date
is enough to have the test to pass.