gpt4 book ai didi

python - Django单元测试View中 'else'语句实现覆盖

转载 作者:行者123 更新时间:2023-12-01 07:15:52 24 4
gpt4 key购买 nike

我正在为我的界面应用程序运行 django 测试覆盖率。下面的 View 调用一个 WelcomeMessage 模型,基本上表示如果该查询集中没有消息,则默认为“Welcome..”,如果有超过 1 个“事件”消息,它将显示最新的消息一。基本上,当有超过 1 条事件消息时,如何测试 else 行?

我尝试创建两个不同的 WelcomeMessage 实例,其中一个较新,但当我运行覆盖时,它仍然将 else 段突出显示为红色。

运行覆盖范围:覆盖率运行 --source='.' Manage.py测试接口(interface)

查看:

def index(request):

msg = WelcomeMessage.objects.filter(active=True).order_by('-modified_at')
if len(msg) == 0:
msg = "Welcome message"
else:
msg = msg[0] # -- Need test coverage here --

context = {'msg': msg}
return render(request, 'interface/index.html', context)

单元测试:

 def test_indexWelcomeMessage(self):
welcome1 = WelcomeMessage.objects.create(
created_at=datetime(2019, 1, 1),
modified_at=datetime(2019, 1, 1),
active=True,
msg="Welcome message"
)
welcome2 = WelcomeMessage.objects.create(
created_at=datetime.now(),
modified_at=datetime.now(),
active=True,
msg="Recent welcome message"
)
messages = WelcomeMessage.objects.filter(
active=True).order_by('-modified_at')

if len(messages) == 0:
msg = "testing this message"
else:
msg = messages[0]
recentMsgVal = getattr(welcome2, 'msg')
msg = messages[0]
expectedMsgVal = messages.values_list('msg', flat=True).first()
self.assertNotEqual(len(messages), 0)
self.assertEqual(recentMsgVal, expectedMsgVal) # These asserts pass, but no coverage.

欢迎消息模型:

class WelcomeMessage(models.Model):
created_at = models.DateTimeField(
auto_now_add=True, verbose_name='Created')
modified_at = models.DateTimeField(
auto_now=True, verbose_name="Last change")
active = models.BooleanField(default=True)
msg = models.TextField(null=True, verbose_name='Message')

如何编写测试以覆盖 else 语句?

最佳答案

据我所知,您没有在此测试用例上直接或间接调用 index() 方法。为了向自己证明添加一个调试器(ipdbpycharm 调试器 - 无关紧要)或在 else 语句上引发一些错误并再次运行测试。它应该像以前一样运行。

如果你想编写测试用例,请看一下这个例子这个例子How to write a unit test for a django view?在你的情况下,它应该看起来像这样:

def test_index_welcome_message(self):
welcome1 = WelcomeMessage.objects.create(
created_at=datetime(2019, 1, 1),
modified_at=datetime(2019, 1, 1),
active=True,
msg="Welcome message"
)
welcome2 = WelcomeMessage.objects.create(
created_at=datetime.now(),
modified_at=datetime.now(),
active=True,
msg="Recent welcome message"
)
messages = WelcomeMessage.objects.filter(
active=True).order_by('-modified_at')
# this needed in case route needs auth
self.client.login(username='user', password='test')
response = self.client.get('/url/to/index/view')
assert response == expected_response

附: self.clientdjango.test.Client 的实例,但检查您的项目 BaseTestCase,您可能已经定义了一个。

关于python - Django单元测试View中 'else'语句实现覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com