我真的在寻找如何修补 Whatever.objects.get_or_create,但我找不到任何建议或想法如何去做。
好吧,我的问题是我有这样的事情:
def create_and_get_object(
name, request, save_url=True, data=None):
try:
(object_type_, created) = Object.objects.get_or_create(
name=name)
try:
...
except Exception:
obj = None
msg = ("Failed to get or create object `Object` with"
"name='%s'" % name)
logger_.exception(msg, extra={'request': request})
return obj
所以,我想测试 Object.objects.get_or_create 在某个时候抛出异常......
我正在尝试使用 Mock(side_effect=Exception())
但我真的不知道如何使用它来获得我期望的结果。
所有这些都是为了获得该函数的 100% 覆盖率(不包括异常行),以及许多其他具有类似异常的函数。
测试这个的正确方法是什么,以及像这样的代码?
我做错了什么?
最佳答案
我喜欢将 python 的 with
语句与 mock 的 patch.object 一起使用.在你的情况下应该是这样的:
from mock import patch
from django.test import TestCase
from django.db.models.manager import Manager
from anothermodule import create_and_get_object
class TestCreateAndGetObject(TestCase):
def test_exception_throwing(self):
with patch.object(Manager, 'get_or_create') as mock_method:
mock_method.side_effect = Exception("test error")
result = create_and_get_object('test', 'test')
self.assertIsNone(result)
理论上应该可行,希望对您有所帮助。
关于python - 如何在 django 中强制出现异常以便在 django 中对其进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16042762/