我试图在我的一个模型中测试一个静态方法,但测试没有看到异常被引发,我不明白为什么。
下面是模型和静态方法:
# 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):
...
有没有人看到我做错了什么?
https://stackoverflow.com/questions/50607225
复制相似问题