django测试失败,DoesNotExist,即使它在实际运行时工作

a0x5cqrl  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(159)

我想测试一下我的PlayerPoint模型是否能给出得分排名前5的玩家。这是Player模型:

class Player(AbstractUser):
    phone_number = models.CharField(
        max_length=14,
        unique=True,
        help_text="Please ensure +251 is included"
    )
    first_name = models.CharField(
        max_length=40,
        help_text="please ensure that you've spelt it correctly"
    )
    father_name = models.CharField(
        max_length=40,
        help_text="please ensure that you've spelt it correctly"
    )
    grandfather_name = models.CharField(
        max_length=40,
        help_text="please ensure that you've spelt it correctly"
    )
    email = models.EmailField(
        unique=True,
        help_text="please ensure that the email is correct"
    )
    age = models.CharField(max_length=3)
    profile_pic = models.ImageField(upload_to='profile_pix', default='profile_pix/placeholder.jpg')
    joined_ts = models.DateTimeField(auto_now_add=True, null=False)
    username = None

这是PlayerPoint模型

class PlayerPoint(models.Model):
    OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN'))

    points = models.IntegerField(null=False, default=0)
    operation = models.CharField(
        max_length=3,
        null=False,
        choices=OPERATION_CHOICES,
        default=OPERATION_CHOICES[2][0]
    )
    operation_amount = models.IntegerField(null=False)
    operation_reason = models.CharField(null=False, max_length=1500)
    player = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=False,
        on_delete=models.PROTECT,
        to_field="phone_number",
        related_name="player_points"
    )
    points_ts = models.DateTimeField(auto_now_add=True, null=False)

    Class Meta():
       get_latest_by = ['pk', 'points_ts']

我还有一个预保存信号处理程序。

@receiver(signals.pre_save, sender=PlayerPoint)
if sender is PlayerPoint:
    try:
        current_point = PlayerPoint.objects.filter(player=instance.player).latest()
    except PlayerPoint.DoesNotExist as pdne:
        if "new player" in instance.operation_reason.lower():
            print(f"{pdne} {instance.player} must be a new")
            instance.operation_amount = 100
            instance.points = int(instance.points) + int(instance.operation_amount)
        else:
            raise pdne
    except Exception as e:
        print(f"{e} while trying to get current_point of the player, stopping execution")
        raise e
    else:
        if instance.operation == PlayerPoint.OPERATION_CHOICES[0][0]:
            instance.points = int(current_point.points) + int(instance.operation_amount)
        elif instance.operation == PlayerPoint.OPERATION_CHOICES[1][0]:
            if int(current_point.points) < int(instance.operation_amount):
                raise ValidationError(
                    message="not enough points",
                    params={"points": current_point.points},
                    code="invalid"
                )
            instance.points = int(current_point.points) - int(instance.operation_amount)

正如你所看到的,这里有一个外键关系。在运行测试之前,我在setUp()中为所有玩家创建了如下的点:

class Top5PlayersViewTestCase(TestCase):
    def setUp(self) -> None:
        self.player_model = get_user_model()

        self.test_client = Client(raise_request_exception=True)
        self.player_list = list()
        for i in range(0, 10):
            x = self.player_model.objects.create_user(
                phone_number=f"+2517{i}{i}{i}{i}{i}{i}{i}{i}",
                first_name="test",
                father_name="user",
                grandfather_name="tokko",
                email=f"test_user@tokko7{i}.com",
                age="29",
                password="password"
            )
            PlayerPoint.objects.create(
                operation="ADD",
                operation_reason="new player",
                player=x
            )
            self.player_list.append(x)

        counter = 500
        for player in self.player_list:
            counter += int(player.phone_number[-1:])
            PlayerPoint.objects.create(
                operation="ADD",
                operation_amount=counter,
                operation_reason="add for testing",
                player=player
            )
            PlayerPoint.objects.create(
                operation="ADD",
                operation_amount=counter,
                operation_reason="add for testing",
                player=player
            )
        return super().setUp()

在localhost上运行代码时,我可以调用latest()来获取每个玩家的最新点数,并将其放入列表中。

all_players = get_user_model().objects.filter(is_staff=False).prefetch_related('player_points')
top_5 = list()
for player in all_players:
   try:
       latest_points = player.player_points.latest()
   except Exception as e:
       print(f"{player} -- {e}")
       messages.error(request, f"{player} {e}")

但是当我从django测试代码中执行时,它引发了一个错误self.model.DoesNotExist( commons.models.PlayerPoint.DoesNotExist: PlayerPoint matching query does not exist.
我哪里做错了?
先谢谢你。
编辑:* 将get_latest_by添加到PlayerPoint模型 *

icnyk63a

icnyk63a1#

我觉得你的问题在于这句台词:

latest_points = player.player_points.latest()

具体来说,latest().get()、earliest()和latest()都是在不存在具有给定参数的对象的情况下引发DoesNotExist。
您可能需要将get_latest_by添加到模型的Meta类中。

class Player(AbstractUser):
    ...

    class Meta:
        get_latest_by = ['-joined_ts']

如果您不想将此添加到模型中,可以直接执行此操作:

latest_points = player.player_points.latest('-joined_ts')

如果这就是问题所在的话。

相关问题