6

问题很简单:我不能在 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)
4

1 回答 1

8

顺便说一句,你可以这样写:

self.assertRaises(LookupError, provider_manager.delete_provider, '398236503462063')
于 2013-07-29T09:55:00.387 回答