python - 如何在 django 中强制出现异常以便在 django 中对其进行测试

标签 python django unit-testing exception mocking

我真的在寻找如何修补 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/

相关文章:

visual-studio - 异步功能单元测试中的 Assert.ThrowsException?

visual-studio-2010 - Visual Studio单元测试: SetUp and TearDown

python - 根据数据框中的大小组计算百分比值 - pandas

python - 使用按键在 QLineEdit 中输入文本并在 PyQt4 中发出信号

python - BeautifulSoup replaceWith() 方法添加转义的 html,希望它不转义

Python/Django 模型覆盖清理后的数据

python - 多对多保存 django

jquery - 反向 Zen 编码

python - 如何测试是否存在具有特定名称的 Enum 成员?

python - 如何检查Python的AES解密错误?