Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite: Can I mock the current time `now()` for testing?

I build a test suite for a program that runs a lot of SQL statements with now() against a sqlite data base. I would like to mock the sqlite clock --- to test behaviour that is designed to take several days within one second. I do not want to touch the system clock.

Is this possible with sqlite?

like image 604
Yaakov Belch Avatar asked Dec 06 '25 08:12

Yaakov Belch


1 Answers

Example in Python:

import sqlite3
def mock(*_):
    return '1984-01-02 11:22:33'
connection = sqlite3.connect(':memory:')
print(connection.execute('SELECT DATETIME()').fetchone()[0])
connection.create_function('DATETIME', -1, mock)
print(connection.execute('SELECT DATETIME()').fetchone()[0])

Output

2022-03-01 11:23:05
1984-01-02 11:22:33
like image 106
eternauta3k Avatar answered Dec 08 '25 02:12

eternauta3k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!