使用Pytest和Sonarqube,我该如何在if语句中涵盖代码,可以到达该声明?
该问题的简化示例的说明性简化示例
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一些库可以修补DateTime。
There are libraries that will patch datetime.now for you, like freezegun.