file.py
JavaScript
x
13
13
1
import datetime
2
ENV_NUMBER_DAYS_RESERVED = 3
3
4
def check_date(entity):
5
entity_created_date = entity.get('createdDatetime').date()
6
utc_date = datetime.datetime.utcnow().date()
7
8
print((utc_date - entity_created_date).days) #<MagicMock name='datetime.datetime.utcnow().date().__sub__().days' id='4899349456'>
9
print(type((utc_date - entity_created_date).days))#<class 'unittest.mock.MagicMock'>
10
11
12
return True if (utc_date - entity_created_date).days > int(ENV_NUMBER_DAYS_RESERVED) else False
13
test.py
JavaScript
1
10
10
1
import file
2
3
@patch('file.datetime')
4
def test_check_date_False(self, date_now):
5
entity = MagicMock()
6
entity.get.return_value = datetime.datetime(2022,1,1)
7
date_now.datetime.utcnow.date.return_value = datetime.datetime(2022,1,1)
8
9
self.assertFalse(check_date(entity=entity))
10
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):
JavaScript
1
17
17
1
import unittest
2
from unittest.mock import patch, MagicMock
3
4
import datetime
5
import file
6
7
class TestFile(unittest.TestCase):
8
@patch('file.datetime')
9
def test_check_date_False(self, date_now):
10
entity = MagicMock()
11
entity.get.return_value = datetime.datetime(2022,1,1)
12
date_now.datetime.utcnow.return_value = datetime.datetime(2022,1,1)
13
14
self.assertFalse(file.check_date(None, entity=entity))
15
16
unittest.main(verbosity=2)
17
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.