Django -单元测试对象是否被删除-如何使用assertRaise / DoesNotExist异常



我想要一些帮助来单元测试在Django应用程序中删除对象的函数


我显示一个值列表,它包括一个删除一个值的bin图标,我的视图似乎工作得很好(至少根据我所做的测试)。
如何进行单元测试?我还没有找到正确的方法去做。
我搜索了网络,发现了DoesNotExist例外,但我担心我不能使用它,因为我得到了matching query does not exist错误。
你能告诉我该怎么做吗?

What I tried
下面是我当前测试的全部代码:

class TestAdmUsers(TestCase):
def setUp(self):
self.company = create_dummy_company("Société de test")
self.usr11 = create_dummy_user(self.company, "user11")
self.usr13 = create_dummy_user(self.company, "user13")
self.usr14 = create_dummy_user(self.company, "user14")
self.client.force_login(self.user_staff.user)
def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))

测试日志如下:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:Mes documentsInformatiqueDeveloppementVotes AGprojet_votespollstests_admin.py", line 136, in test_delete_user
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsmanager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsquery.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 1.763s
FAILED (errors=1)
Destroying test database for alias 'default'...

我做了其他类似的测试:

def test_delete_user(self):
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(response, self.usr13.user.username)

导致这个:

======================================================================
FAIL: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:Mes documentsInformatiqueDeveloppementVotes AGprojet_votespollstests_admin.py", line 136, in test_delete_user
self.assertNotContains(response, self.usr13.user.username)
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangotesttestcases.py", line 465, in assertNotContains
self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr)
AssertionError: 1 != 0 : Response should not contain 'user13'
----------------------------------------------------------------------

或者这个

def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
users = UserComp.get_users_in_comp(self.company.comp_slug)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(users, self.usr13)

,结果如下:

======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:Mes documentsInformatiqueDeveloppementVotes AGprojet_votespollstests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsbase.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsquery.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------

最新的这个使用了类方法:

def test_delete_user(self):
current_username = self.usr13.user.username
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(UserComp.get_users_in_comp(self.company.comp_slug), self.usr13)

,但结果仍然是一个错误:

`======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:Mes documentsInformatiqueDeveloppementVotes AGprojet_votespollstests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsbase.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:UsersChristophe.virtualenvsprojet_votes-onIieQ0Ilibsite-packagesdjangodbmodelsquery.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------

相关应用代码
下面是视图的代码:

def adm_delete_user(request, comp_slug, usr_id):
del_usr = User.objects.get(pk=usr_id)
msg = "Utilisateur {0} {1} supprimé.".format(del_usr.last_name, del_usr.first_name)
User.objects.get(pk=usr_id).delete()
messages.success(request, msg)
return redirect("polls:adm_users", comp_slug=comp_slug)

和模型:

class UserComp(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur")
company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société")
phone_regex = RegexValidator(regex=r'^0[0-9]([ .-]?[0-9]{2}){4}$', message=("Format de numéro de téléphone invalide"))
phone_num = models.CharField("numéro de téléphone", validators=[phone_regex], max_length=14, null=True, blank=True)
is_admin = models.BooleanField("administrateur", default=False)
def __str__(self):
return '%s %s' % (self.user.last_name, self.user.first_name)
class Meta:
verbose_name = "Liens Utilisateurs / Sociétés"
verbose_name_plural = "Liens Utilisateurs / Sociétés"
@classmethod
def create_usercomp(cls, user, company, phone_num='', is_admin=False):
""" Create a new UserComp """
usr_comp = UserComp(user=user, company=company, phone_num=phone_num, is_admin=is_admin)
usr_comp.save()
return usr_comp
@classmethod
def get_users_in_comp(cls, comp_slug):
user_list = cls.objects.filter(company__comp_slug=comp_slug)
return user_list

互补搜索结果
最后,我在这里找到了一些面向我的测试的帖子,但我没能找到解决方案:

  • 对我来说最重要的是assertRaise()测试
  • 不幸的是,询问如何使用此异常的那个已被关闭,并参考了前一个异常,但实际上没有关于如何进行的信息
  • 另一个询问异常的人,这个与错误消息相关的人没有给我任何额外的信息。

assertRaises可调用作为其(可选的)第二个参数。由于.get(...)不是可调用的,您应该使用上下文管理器表单:

with self.assertRaises(UserComp.DoesNotExist): 
UserComp.objects.get(id=test_usercomp_id)

相关内容

  • 没有找到相关文章

最新更新