Say I have a unit test which mocks out some class A to return a custom value. I want to be able to change the value returned by the mocked A instance but I definitely don't want to accidentally change the type of the return value and cause my test to inadvertently check for the wrong thing.
For example, take the below code:
import datetime
import unittest
import unittest.mock
class A:
def foo(self, getter):
return getter.get_time() == '2020-01-01'
class Getter:
def get_time(self) -> datetime.datetime:
return datetime.datetime(2020,1,1)
@unittest.mock.patch("__main__.Getter", autospec=True)
class MyTestCase(unittest.TestCase):
def test_case_1(self, Getter):
getter = Getter()
getter.get_time.return_value = '2020-01-01'
a = A()
self.assertTrue(a.foo(getter))
test_case = MyTestCase()
test_case.test_case_1()
In the above unit test, we are supposed to check that the time matches '2020-01-01', but we've set the return_value of get_time to be a string, so the test succeeds even though that violates the return type hint of get_time (which returns a datetime) so the actual code could never work. Is there a way for unittest/mock to pick this up and tell me that I've incorrectly set return_type to a value that's incompatible with the type hint on the method?