dimanche 19 juillet 2015

Running tests over SQLite using Flask. (Involving dates)

I am working on an API using Python/Flask, the API runs over a MySQL database but the tests are executed over a SQLite one. Everything works good but last week I faced next scenario:

The API records dates fields using strings like '2015-10-10 23:23:12', since the database for production is MySQL it works very good, but it does not work for tests because SQLite does not allow strings for recording dates.

Here the code:

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')

I was searching a lot in forums and in the official docs for similar situations and I did not find anything helpful. Since it is not allowed to change the engine for the tests (requirement) I have added this section as a provisional solution:

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')

So, if the engine is SQLite I translate the date to python time (datetime), and if it is not, I just record the dates as string (as usual).

I don't know if that is the best approach, I mean, modifying your base code for getting running your tests feels like a bad practice. I was wondering what you would do in a similar context.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire