问题非常简单:我不能在Django 1.5单元测试中使用self.assertRaises。
我真的想验证当您尝试从不存在的数据库中删除提供程序时,会引发LookupError。
如您所见,我有一个ProviderDAO类,我在其中定义了如何删除提供程序。 然后我只在单元测试类ProviderManagerTests中调用此方法delete_provider()。 我已经概述了代码中的所有可能性,此时我来到这里寻求答案(我已经阅读了相关问题中的建议,但没有做任何事情) 我正在使用python 2.7.5 谢谢!
class ProviderManager(models.Manager):
def delete_provider(self, provider_id):
matching_providers = Provider.objects.filter(providerId=provider_id)
print 'delete provider method matching providers %s ' % matching_providers
print 'delete provider method matching providers %s ' % matching_providers.count()
if matching_providers.count() > 0:
matching_providers.delete()
elif matching_providers.count() == 0:
raise LookupError('No deletion; no providers matching this id')
class ProviderManagerTests(TestCase):
def test_delete_nonexistent_provider(self):
provider_manager = ProviderManager()
someRoles = Role(name='boss')
someRoles.save()
someSpecialties = Specialty(name='senior care')
someSpecialties.save()
provider_manager.delete_provider('398236503462063')
#self.assertIsNone(provider,'provider should be none')
#self.assertTrue(Provider.objects.filter(providerId='123456') == 0)
###self.assertRaises(LookupError,provider_manager.delete_provider, providerId='398236503462063')
#self.assertRaises(LookupError,provider_manager.delete_provider, provider_id='398236503462063')
#self.assertRaises(LookupError,lambda: provider_manager.delete_provider,provider_id='234234234')
#self.assertRaises(LookupError,lambda: provider_manager.delete_provider(provider_id='234234234'))
# with self.assertRaises(LookupError):
# provider_manager.delete_provider(provider_id='398236503462063')
with self.assertRaises(LookupError):
provider_manager.delete_provider('398236503462063')
和堆栈轨道:
======================================================================
ERROR: test_delete_nonexistent_provider (edu.tests.ProviderTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/tests.py", line 68, in test_delete_nonexistent_provider
provider_manager.delete_provider('398236503462063')
File "/Users/models.py", line 92, in delete_provider
raise LookupError('No deletion; no providers matching this id')
LookupError: No deletion; no providers matching this id
----------------------------------------------------------------------
Ran 14 tests in 0.306s
FAILED (errors=1)
答案 0 :(得分:7)
顺便说一下,你可以这样写:
self.assertRaises(LookupError, provider_manager.delete_provider, '398236503462063')