Python Pytest:集合错误,函数未使用参数';日期';
为什么Pytest返回集合错误“在test\u billing\u month\u year:函数未使用参数“date”,即使使用并定义了date 函数billing_month_year()只返回当前日期的上一个月和年份Python Pytest:集合错误,函数未使用参数';日期';,python,pytest,Python,Pytest,为什么Pytest返回集合错误“在test\u billing\u month\u year:函数未使用参数“date”,即使使用并定义了date 函数billing_month_year()只返回当前日期的上一个月和年份 import datetime as dt import pytest from mock import patch def billing_month_year(): today = dt.datetime.utcnow() #last month fr
import datetime as dt
import pytest
from mock import patch
def billing_month_year():
today = dt.datetime.utcnow()
#last month from current date
last_month = today.month - 1 if today.month>1 else 12
#last year from current date
last_month_year = today.year if today.month > last_month else today.year - 1
return last_month, last_month_year
@pytest.mark.parametrize(
'date, expected',
[
#last month in previous year
(dt.datetime(year=2020, month=1, day=21), (12, 2019)),
#last month in current year
(dt.datetime(year=2020, month=2, day=21), (01, 2020)),
]
)
@patch('dt.datetime.utcnow')
def test_billing_month_year(date, expected, mock_utcnow):
mock_utcnow.return_value = date
test = billing_month_year()
assert test == expected
修饰符总是按照添加的相反顺序应用,例如,在本例中,首先应用
补丁
修饰符,然后应用pytest.mark.parametrize
修饰符。
这意味着参数应按各自的顺序排列:
@pytest.mark.parametrize(
'date, expected',
[
(dt.datetime(year=2020, month=1, day=21), (12, 2019)),
(dt.datetime(year=2020, month=2, day=21), (01, 2020)),
]
)
@patch('dt.datetime.utcnow')
def test_billing_month_year(mock_utcnow, date, expected):
mock_utcnow.return_value = date
test = billing_month_year()
assert test == expected
修补程序可能也不起作用,请参阅的答案以获取解决方案。这很有效,谢谢。正如所指出的,修补日期时间不起作用,因为python内置类型是不可变的。我可以利用图书馆和图书馆四处走动。