我使用以下模型创建了一个 SQLAlchemy 应用程序:
class MyObject(db.Model):
__tablename__ = 'my_object'
id = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=True)
some_string = db.Column(db.String(20), nullable=False)
created = db.Column(db.DateTime, default=datetime.datetime.now)
updated = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
我创建了这个迁移文件来配合它:
"""
Junk
Revision ID: 4b6fffffffff_
Revises: 4b6e7775856f
Create Date: 2019-11-08 00:31:13.297355
"""
# revision identifiers, used by Alembic.
revision = '4b6fffffffff_'
down_revision = '4b6e7775856f'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
from sqlalchemy import false
def upgrade():
op.create_table(
'my_object',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('some_string', sa.String(length=20), nullable=False),
sa.PrimaryKeyConstraint('id')
)
现在我有这个使用Freezegun的单元测试用例:
def test_freeze_gun_on_sql_alchemy(self):
now_time = datetime.datetime(year=2012, month=4, day=1, hour=5, minute=12, second=32, microsecond=543)
freezer = freeze_time(now_time)
freezer.start()
print 'datetime.datetime.now() = {}'.format(datetime.datetime.now())
m = MyObject(some_string="Hello World")
db.session.add(m)
db.session.commit()
freezer.stop()
print 'm.created = {}'.format(m.created)
此测试用例产生以下输出:
datetime.datetime.now() = 2012-04-01 05:12:32.000543
m.created = 2019-11-09 04:04:55
为什么是m.created
当前挂钟时间而不是 FreezeGun 时间?两者应该是一样的。
根据this answer,Freezegun补丁datetime.datetime.now()
。我的测试用例证实了这一点。那么为什么/如何将不同的值存储在数据库中?