如何使用pytest忽略测试中的警告?

2024-05-16 11:40:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图测试一个使用DatetimeFields的函数。我要测试的函数如下:

def get_pledge_frequency(last_week_pledges):
    """Returns two lists:
    pledge_frequency: containing the number of pledges per day of the last week
    weekdays: containing a letter that represents the day
    It assumes that last_week_pledges are pledges made within the last week.
    """
    pledge_frequency = []
    weekdays = []

    if last_week_pledges:
        last_7_days = [timezone.now() - timedelta(days=i) for i in range(7)]
        last_7_days.reverse()
        day_names = 'MTWTFSS'

        for day in last_7_days:
            pledge_frequency.append(
                last_week_pledges.filter(timestamp__date=day).count())
            weekdays.append(day_names[day.weekday()])

    return pledge_frequency, weekdays

我使用pytest进行测试,因此我实现的测试如下:

^{pr2}$

测试通过了,但问题是我收到了以下警告:

RuntimeWarning: DateTimeField Pledge.timestamp received a naive datetime (2018-03-29 00:00:00) while time zone support is active.

实际上,我得到了几个RuntimeWarning,它们在时区支持处于活动状态时通知使用朴素的datetime。在

如何仅针对此测试禁用警告?我发现使用@pytest.mark.filterwarnings可能很有用,我添加了如下标记:@pytest.mark.filterwarnings('ignore:RuntimeWarning')。但是,这没用,在运行测试之后,我仍然有那些警告。在

我把装修工放在哪里的顺序重要吗?我试过好几种组合,但还不行。在

在文档中,我发现我可以将addopts = -p no:warnings添加到pytest.ini文件中,但我不想遵循这种方法,以防我得到另一个生成此警告的测试。在


Tags: ofthe函数警告pytestdayslastweek
1条回答
网友
1楼 · 发布于 2024-05-16 11:40:10

根据pytest documentation@pytest.mark.filterwarnings实际上是正确的方法,问题是我传递的参数不正确。解决这个问题的方法是:

@pytest.mark.filterwarnings('ignore::RuntimeWarning') # notice the ::

因此,测试工作如下:

^{pr2}$

相关问题 更多 >