【问题标题】:Running tests over SQLite using Flask. (Involving dates)使用 Flask 在 SQLite 上运行测试。 (涉及日期)
【发布时间】:2015-07-20 03:38:13
【问题描述】:

我正在使用 Python/Flask 开发一个 API,该 API 运行在 MySQL 数据库上,但测试是通过 SQLite 执行的。一切正常,但上周我面临下一个场景:

API 使用诸如“2015-10-10 23:23:12”之类的字符串记录日期字段,因为用于生产的数据库是 MySQL,它工作得很好,但它不适用于测试,因为 SQLite 不允许字符串用于记录日期。

代码如下:

if mh.get('start_time', None) and mh.get('end_time', None):
    start_time = datetime.strptime(
        mh.get('start_time', None), 
        '%a, %d %b %Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
    end_time = datetime.strptime(
        mh.get('end_time', None), 
       '%a, %d %b %Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')

我在论坛和官方文档中搜索了很多类似情况,但没有发现任何有用的信息。由于不允许更改测试引擎(要求),我已将此部分添加为临时解决方案:

if 'sqlite' in SQLALCHEMY_DATABASE_URI:
    start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
    end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')

所以,如果引擎是 SQLite,我将日期转换为 python 时间(日期时间),如果不是,我只是将日期记录为字符串(像往常一样)。

我不知道这是否是最好的方法,我的意思是,修改基本代码以运行测试感觉是一种不好的做法。我想知道你会在类似的情况下做什么。

提前致谢。

【问题讨论】:

    标签: python sqlite flask


    【解决方案1】:

    我已经修复了这个不好的做法,解决方案就是将字符串转换为日期时间:

    if mh.get('start_time', None) and mh.get('end_time', None):
        start_time = datetime.strptime(
            mh.get('start_time', None), '%a, %d %b %Y %H:%M:%S')
        end_time = datetime.strptime(
            mh.get('end_time', None), '%a, %d %b %Y %H:%M:%S')
    

    然后在您的单元测试中使用字符串作为日期。

    end_time": start_time.strftime('%a, %d %b %Y %H:%M:%S')
    

    结论:在模型中使用日期作为日期。现在 API 和单元测试运行良好。

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多