gpt4 book ai didi

python - 如何在 Django 测试中使用 AssertRaisesMessage()

转载 作者:太空狗 更新时间:2023-10-30 00:44:46 25 4
gpt4 key购买 nike

我关注了 Django doc使用 assertRaisesMessage() 编写测试,但问题是在执行测试时会引发异常本身(因此,不会执行测试)。请注意,调用的异常是我在模型的方法中(不在 View 中)自愿引发的异常。

class MyTestCase(TestCase):
def test_invertRewardState_view_fails_notmy_reward(self):
self.client.login(email='gislaine@toto.com', password='azerty')
resp = self.client.get(reverse(invertRewardState, args=(1,)))
self.assertRaisesMessage(
expected_exception=Exception,
expected_message=EXC_NOT_YOURS,
callable_obj=resp)

我应该如何使用 AssertRaisesMessage() 让我的测试在不引发异常的情况下执行?谢谢。

编辑:在尝试了 faltru 1st 解决方案后,问题仍然存在。一旦我的测试进入 resp = ... 部分,就会调用 View ,然后调用相关的模型方法并引发异常。完整的堆栈跟踪:

Traceback (most recent call last):
File "/Users/walt/Code/hellodjango/clientizr/tests.py", line 338, in test_invertRewardState_view_fails_notmy_reward
resp = self.client.get(reverse(invertRewardState, args=('1',)))
File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 473, in get
response = super(Client, self).get(path, data=data, **extra)
File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 280, in get
return self.request(**r)
File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 444, in request
six.reraise(*exc_info)
File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/walt/Code/hellodjango/clientizr/views.py", line 234, in invertRewardState
reward.invert_reward_state(request.user)
File "/Users/walt/Code/hellodjango/clientizr/models.py", line 606, in invert_reward_state
self.throw_error_if_not_owner_reward(cur_user)
File "/Users/walt/Code/hellodjango/clientizr/models.py", line 587, in throw_error_if_not_owner_reward
raise Exception(EXC_NOT_YOURS)
Exception: Cet objet n'est pas le v\xf4tre

最佳答案

您使用 assertRaisesMessage 作为您预计会失败的代码的上下文管理器:

class MyTestCase(TestCase):
def test_invertRewardState_view_fails_notmy_reward(self):
self.client.login(email='gislaine@toto.com', password='azerty')
url = reverse(invertRewardState, args=(1,))
with self.assertRaisesMessage(Exception, EXC_NOT_YOURS):
self.client.get(url)

关于python - 如何在 Django 测试中使用 AssertRaisesMessage(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287654/

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