【问题标题】:Why isn't Django unit test seeing a raised exception?为什么 Django 单元测试没有看到引发的异常?
【发布时间】:2018-05-30 14:27:10
【问题描述】:

我正在尝试在我的一个模型中测试静态方法,但测试没有看到正在引发的异常,我不明白为什么。

这是模型和静态方法:

# models.py
class List(models.Model):
    owner = models.ForeignKey(User)
    type = models.ForeignKey('ListType', help_text=_('Type of list'))
    name = models.CharField(_('list'), max_length=128, help_text=_('Name of list'))

class ListType(models.Model):
    type = models.CharField(_('type'), max_length=16)

@staticmethod
def read_list(list_id, list_name, owner, list_type):
    try:
        return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)
    except List.DoesNotExist:
        return None

这是测试:

# tests.py
from django.test import TestCase
from .factories import *
from .models import List, ListType

class TestFuncs(TestCase):
    def test_read_list_exc(self):
        with self.assertRaises(List.DoesNotExist):
            uf = UserFactory()
            lt = ListType.objects.get(type='Member')
            lf = ListFactory(owner=uf, type=lt, name='foo')
            # I've created one list but its name isn't 'bar'
            list = List.read_list(999, 'bar', uf, lt)

如果我在 read_list 方法中设置调试断点并运行测试,我确实看到引发了异常:

# set_trace output:
(<class 'list.models.DoesNotExist'>, DoesNotExist('List matching query does not exist.',))

# test output:
...
File "...."
    list = List.read_list(999, 'bar', uf, lt)
AssertionError: DoesNotExist not raised

我在这里阅读了有关如何检测此类异常的其他问题,我认为我做得对。只是为了好玩,我将测试更改为以下内容,但这并没有解决问题:

        ...
        with self.assertRaises(list.models.DoesNotExist):
        ...

谁能看出我做错了什么?

【问题讨论】:

    标签: django unit-testing django-models


    【解决方案1】:

    在静态方法中捕获异常并返回None

    您可以将测试更改为使用assertIsNone

    l = List.read_list(999, 'bar', uf, lt)  # don't use list as a variable
    self.assertIsNone(l)
    

    或者,如果您确实希望该方法引发异常,则删除 try..except。

    @staticmethod
    def read_list(list_id, list_name, owner, list_type):
        return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    您已经在read_list 中处理了DoesNotExist 异常,因此它不会被抛出到测试用例中。

    要抛出异常,您可以使用raise 运算符:

    @staticmethod
    def read_list(list_id, list_name, owner, list_type):
        try:
            return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)
        except List.DoesNotExist as e:
            some actions to handle exception, for example logging
            ...
            raise e 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多