I have some issues to mock a SQLAlchemy object when using the default and onupdate fields in my models :
def get_uuid(): return str(uuid.uuid4())def get_now():
return db.func.now()class BaseModel(db.Model):
abstract = Trueid = db.Column(UUIDType(binary=False), primary_key=True, nullable=False, default=get_uuid) created_at = db.Column(db.DateTime(timezone=True), default=get_now(), nullable=False, index=True)
The get_now() and get_uuid() behaviour do not change even when I try to mock them in my tests :
def test_create_source(client, mocker):mock = mocker.MagicMock(return_value='123e4567-e89b-12d3-a456-426655440000') mocker.patch('myproject.models.get_uuid', mock) mock = mocker.MagicMock(return_value=datetime.datetime(2019, 1, 1)) mocker.patch('myproject.models.get_now', mock) resp = client.post('/sources', json={'name': 'My source'}) assert resp.json == { 'name': 'My source', 'id': '123e4567-e89b-12d3-a456-426655440000', 'createdAt': 'Tue, 01 Jan 2019 00:00:00 GMT', 'updatedAt': 'Tue, 01 Jan 2019 00:00:00 GMT' }
Results :
> assert resp.json == {
‘name’: ‘My source’,
‘id’: ‘123e4567-e89b-12d3-a456-426655440000’,
‘createdAt’: ‘Tue, 01 Jan 2019 00:00:00 GMT’,
‘updatedAt’: ‘Tue, 01 Jan 2019 00:00:00 GMT’
}
E AssertionError: assert {‘createdAt’:…17:38:38 GMT’} == {‘createdAt’: …00:00:00 GMT’}
E Omitting 1 identical items, use -vv to show
E Differing items:
E {‘id’: ‘8eb074c0-41e9-436c-8f71-b4c6842f4809’} != {‘id’: ‘123e4567-e89b-12d3-a456-426655440000’}
E {‘createdAt’: ‘Fri, 18 Jan 2019 17:38:38 GMT’} != {‘createdAt’: ‘Tue, 01 Jan 2019 00:00:00 GMT’}
E {‘updatedAt’: ‘Fri, 18 Jan 2019 17:38:38 GMT’} != {‘updatedAt’: ‘Tue, 01 Jan 2019 00:00:00 GMT’}
E Use -v to get the full difftests/test_sources.py:17: AssertionError
I think it’s because my models and its attributes are already imported and evaluated before doing my test, so the mock is useless here. It’s explained in the “Mocking class helpers” part of this post but I still was not able to fix my issue :(
The full runnable code to reproduce the problem is available here : https://github.com/ncrocfer/flaskmock
Do you have some ideas please ?
#python #testing #flask #sql