一个快速的替代冷冻枪包装利百吉时间。
libfaketime的Python项目详细描述
python libfaketime是python的libfaketime包装器。 一些简短的细节:
- Linux和OS X、pythons 2.7和3.4到3.7、pypy和pypy3
- 主要与freezegun兼容。
- 微秒分辨率。
- 接受DateTimes和DateUtil可以解析的字符串。
- 不是线程安全的。
- 会破坏分析。解决方法:使用libfaketime.{begin, end}_callback禁用/启用探查器(nosetest example)。
安装
$ pip install libfaketime
用法
importdatetimefromlibfaketimeimportfake_time,reexec_if_needed# libfaketime needs to be preloaded by the dynamic linker.# This will exec the same command, but with the proper environment variables set.# You can also skip this and manually manage your env (see "How to avoid re-exec").reexec_if_needed()deftest_datetime_now():# fake_time can be used as a context_managerwithfake_time('1970-01-01 00:00:01'):# Every calls to a date or datetime function returns the mocked dateassertdatetime.datetime.utcnow()==datetime.datetime(1970,1,1,0,0,1)assertdatetime.datetime.now()==datetime.datetime(1970,1,1,0,0,1)asserttime.time()==1# fake_time can also be used as a decorator@fake_time('1970-01-01 00:00:01',tz_offset=12)deftest_datetime_now_with_offset():# datetime.utcnow returns the mocked datetime without offsetassertdatetime.datetime.utcnow()==datetime.datetime(1970,1,1,0,0,1)# datetime.now returns the mocked datetime with the offset passed to fake_timeassertdatetime.datetime.now()==datetime.datetime(1970,1,1,12,0,1)
性能
libfaketime往往比freezegun快得多。 这是我笔记本电脑上的totally unscientific benchmark输出:
$ python benchmark.py re-exec with libfaketime dependencies timing 1000 executions of <class 'libfaketime.fake_time'> 0.021755 seconds $ python benchmark.py freezegun timing 1000 executions of <function freeze_time at 0x10aaa1140> 6.561472 seconds
与py.test一起使用
pytest-libfaketime插件将自动为您配置python libfaketime:
$ pip install pytest-libfaketime
或者,您可以从pytest_configure钩子内部手动执行c:
# conftest.pyimportosimportlibfaketimedefpytest_configure():libfaketime.reexec_if_needed()_,env_additions=libfaketime.get_reload_information()os.environ.update(env_additions)
从冷冻枪迁移
当在支持的代码上运行时,python libfaketime应该具有与freezegun相同的行为。要迁移到它,您可以运行:
find . -type f -name "*.py" -exec sed -i 's/freezegun/libfaketime/g'"{}"\;
如何避免重新执行
在某些情况下,特别是当您的测试启动其他进程时,重新执行可能会导致意外的问题。为了避免这种情况,您可以自己预加载必要的环境变量。通过在命令行上运行python-libfaketime,可以找到系统所需的环境:
$ python-libfaketime exportLD_PRELOAD="/home/foo/<snip>/vendor/libfaketime/src/libfaketime.so.1"exportDONT_FAKE_MONOTONIC="1"exportFAKETIME_DID_REEXEC=true
您可以很容易地将其放入如下脚本中:
$ eval$(python-libfaketime) $ pytest # ...or any other code that imports libfaketime
贡献和测试
欢迎投稿!在运行测试之前,应该编译libfaketime:
make -C libfaketime/vendor/libfaketime
然后可以使用pip install -r requirements.txt安装需求,并使用pytest和tox运行测试。
Uuid1死锁
在假时间上下文中多次调用uuid.uuid1()可能会在操作系统级uuid库可用时导致死锁。 为了避免这种情况,python libtaketime将在一个伪时间上下文中把uuid.uuid生成的时间(或类似的,根据版本而变化)修改为none。 这可能会减慢Uuid1的生成,但不应影响正确性。
更改日志
^使用{a10}。
1.2.1
发布日期:2019-01-20
- 修复Python3.7+上的死锁
0.3.0
发布日期:2016-03-04
- 从命令行调用libfaketime现在将打印必要的环境以避免重新执行。
0.2.1
发布日期:2016-03-01
- python 3支持
0.1.0
发布日期:2015-06-23
- 添加全局启动/停止回调
0.0.3
发布日期:2015-03-28
- 初始打包版本