使用Pytest和Sonarqube,我该如何在if语句中涵盖代码,可以到达该声明?

发布于 2025-02-04 02:58:15 字数 645 浏览 3 评论 0原文

该问题的简化示例的说明性简化示例

import datetime

def func(value):
    now = datetime.datetime.now()
    if now.month < 7:
        out = value
    else:
        out = value + 1
    return out

# fails half the year
def test_func():
    a=func(4)
    assert a==4

# works but only covers one half of the branch based on month.
def test_func2():
    a=func(4)
    now = datetime.datetime.now()
    if now.month < 7:
        assert a==4
    else:
        assert a==5

如何创建涵盖IF的两个分支的当前日期不可知的单个测试? 我尝试了模拟库的各种实验,并取得了有限的成功,甚至在显然成功的情况下,代码覆盖范围仍然不完整,大概是因为测试是在模拟物体上进行的。

我认为我要问的问题是,我对单元测试和尤其是PYTEST非常新鲜t受功能参数的影响,还获得代码覆盖范围?

An illustrative simplified example of the problem

import datetime

def func(value):
    now = datetime.datetime.now()
    if now.month < 7:
        out = value
    else:
        out = value + 1
    return out

# fails half the year
def test_func():
    a=func(4)
    assert a==4

# works but only covers one half of the branch based on month.
def test_func2():
    a=func(4)
    now = datetime.datetime.now()
    if now.month < 7:
        assert a==4
    else:
        assert a==5

How do I create a current-date agnostic single test that covers both branches of the if?
I've tried various experiments with the mock library, and patching, with limited success, and even where apparently successful, the code coverage still wasn't complete, presumably because the test was being conducted on a mocked object.

I'm very new to unit testing and pytest in particular, I think the question I'm asking is, is there a way to somehow "override" a value in a function (in this case, "now") where it can't be influenced by function parameters, and also obtain code coverage?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始于初秋 2025-02-11 02:58:15

有一些库可以修补DateTime。

There are libraries that will patch datetime.now for you, like freezegun.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文