P
P
prokoptsev2015-03-18 13:59:20
ORM
prokoptsev, 2015-03-18 13:59:20

How to change the date when autosaving an object to the database using mock and SQLAlchemy?

Good afternoon. In my Flask application, I use SQLAlchemy. I have a model like this:

class Entry(db.Model):
    __tablename__ = 'entries'
    name = db.Column(db.String(100))
    created = db.Column(db.DateTime(), default=datetime.now())
    updated = db.Column(db.DateTime(), default=datetime.now(), onupdate=datetime.now())

In my tests, I try to simulate saving to the database with the specified time. In the example below, I'm using freezegun , but the test doesn't work that way. The current creation time is returned.
class ViewTestCase(AppliactionTestCase):
    def test(self):
        with freeze_time("2014-06-01 16:00:00"):
            db.session.add(Entry(name="title"))
            db.session.commit()
        entry = db.session.query(Entry).first()
        self.assertEqual(entry.created, datetime(2014, 6, 1, 16, 0, 0))
        self.assertEqual(entry.updated, datetime(2014, 6, 1, 16, 0, 0))

        with freeze_time("2014-07-01 17:00:00"):
            entry.name = 'edited title'
            db.session.add(entry)
            db.session.commit()

       entry = db.session.query(Entry).first()
       self.assertEqual(entry.created, datetime(2014, 6, 1, 16, 0, 0))
       self.assertEqual(entry.created, datetime(2014, 7, 1, 17, 0, 0))

I also tried to patch with mock so that db.DateTime.python_type would return FakeDatetime, but the result is the same.
I haven't delved deeply into SQLAlchemy's design. If anyone has encountered this, tell me what needs to be redefined or how this issue can be resolved.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question