涉及信号调用的django测试视图

时间:2018-10-22 03:20:04

标签: python django unit-testing django-rest-framework

我有2个应用,其中1个用于身份验证,另一个用于存储与个人资料相关的信息

身份验证应用 models.py

nuget restore

signals.py

packages.config

个人资料应用 models.py

class User(AbstractUser):
      # contains the User related info

在测试更新用户方法时。

@receiver(post_save, sender=User)
def create_related_profile(sender, instance, created, *args, **kwargs):
if instance and created:
    instance.profile = Profile.objects.create(user=instance)

在执行此操作时,出现以下错误。 django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:用户没有个人资料。

但是,我已经随后使用信号测试了用户创建和概要文件创建。一切正常。

1 个答案:

答案 0 :(得分:1)

我看到一些问题:

1。您的接收者没有在实例上调用save,因此在分配instance.profile之后,它不会将这些更改保存到数据库中。

@receiver(post_save, sender=User)
def create_related_profile(sender, instance, created, *args, **kwargs):
    if instance and created:
        instance.profile = Profile.objects.create(user=instance)
        instance.save()

2。另一个潜在问题可能是在测试中创建用户并将其分配给test_user时出现的。调用create_user时,它将返回保存时的实例,该实例未分配配置文件,因为在接收器中创建了配置文件后即已分配该配置文件。您可以使用self.test_user.refresh_from_db()用数据库中的任何新数据更新实例,在这种情况下,这将检索在post_save信号中添加到实例的配置文件。

self.test_user = get_user_model().objects.create_user(
    self.test_username,
    self.test_email, 
    self.test_password
)
#  print(self.test_user.profile)  # this would fail or print None
self.test_user.refresh_from_db()
#  print(self.test_user.profile)  # Now this should print the profile object