2015-07-20 79 views
1

我正在使用Python/Flask的API工作,API運行在MySQL數據庫上,但測試是通過SQLite執行的。一切工作不錯,但上週我面對未來的場景:使用Flask在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我翻譯日期蟒蛇時間(日期時間),如果不是,我只是將日期記錄爲字符串(如往常一樣)。

我不知道這是否是最好的方法,我的意思是,修改你的基本代碼用於獲取運行測試的感覺就像一個不好的做法。我想知道你會在類似的情況下做什麼。

在此先感謝。

回答

0

我有固定的不好的做法,該解決方案只是翻譯字符串日期時間:

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和單元測試運行良好。