【问题标题】:sqlite: Can I mock the current time `now()` for testing?sqlite:我可以模拟当前时间`now()`进行测试吗?
【发布时间】:2014-12-16 07:15:22
【问题描述】:

我为一个程序构建了一个测试套件,该程序使用now() 针对 sqlite 数据库运行大量 SQL 语句。我想模拟 sqlite 时钟 --- 测试设计为在一秒钟内花费几天的行为。我不想碰系统时钟。

这可以用 sqlite 实现吗?

【问题讨论】:

    标签: unit-testing sqlite


    【解决方案1】:

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

    输出

    2022-03-01 11:23:05
    1984-01-02 11:22:33
    

    【讨论】:

      【解决方案2】:

      SQLite 的内置函数可以用sqlite3_create_function 重新定义。

      [由 Yaakov Belch 编辑 --- 附加信息:]

      【讨论】:

      • 为了让您的答案更有用,请考虑提供一个如何实施的示例。
      猜你喜欢
      • 2018-06-22
      • 2011-12-18
      • 2011-02-11
      • 1970-01-01
      • 2018-12-27
      • 2023-04-07
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      相关资源
      最近更新 更多