对于测试,我想模拟 datetime.datetime.now()
以使测试不受时间变化的影响。这似乎与某些熊猫功能发生冲突:
import pytest
import datetime
import pandas as pd
mockdate = datetime.datetime(2000, 1, 1, 0, 0, 0)
def function_to_test():
date = datetime.datetime.now()
df = pd.DataFrame({'date': ['20000101', '20100101'],
'offset': [2, 3]})
df["date"] = df["date"].apply(lambda x: datetime.datetime.strptime(x, '%Y%m%d'))
b = pd.to_datetime(df["date"]) + pd.to_timedelta(df['offset'], "d")
return date, b
def test_function_to_test(mocker):
with patch(__name__ + '.datetime') as mock_date:
mock_date.datetime.now.return_value = mockdate
date, b = function_to_test()
assert date == mockdate
assert any(b)
这产生:
test.py:19: in function_to_test
b = pd.to_datetime(df["date"]) + pd.to_timedelta(df['offset'], "d")
/opt/miniconda/envs/AR_env3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py:451: in to_datetime
values = _convert_listlike(arg._values, True, format)
/opt/miniconda/envs/AR_env3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py:368: in _convert_listlike
require_iso8601=require_iso8601
pandas/_libs/tslib.pyx:492: in pandas._libs.tslib.array_to_datetime
???
pandas/_libs/tslib.pyx:744: in pandas._libs.tslib.array_to_datetime
???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E TypeError: <class 'unittest.mock.MagicMock'> is not convertible to datetime
我知道 strptime
可能不适合此目的,但我在其他地方需要它。
谢谢!!