简体   繁体   中英

django testing fails with DoesNotExist even though it works when actually running

I'm trying to test if my PlayerPoint model can give me the top 5 players in regards to their points. This is the Player model:

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

and this is the PlayerPoint model:

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']

I also have a pre-save signal handler.

@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)

As you can see there is a foreign key relation. Before running the tests, in the setUp() I create points for all the players as such:

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()

When running the code on localhost I can call latest() to fetch the latest points of each player and put it in a list.

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}")

but when I do it from django test code it raises an error self.model.DoesNotExist( commons.models.PlayerPoint.DoesNotExist: PlayerPoint matching query does not exist.

This is the view being tested:

def get(request):
    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}")
        else:
            if all(
                [
                    latest_points.points >= 500,
                    latest_points.points_ts.year == current_year,
                    latest_points.points_ts.month == current_month
                ]
            ):
                top_5.append(player)
    
    return render(request, "points_app/monthlytop5players.html", {"results": top_5[:5]})

What am I doing wrong?

My gratitude beforehand.

Edit1: add get_latest_by to the PlayerPoint model

Edit2: update the question to show the for loop

I think your problem is with this line:

latest_points = player.player_points.latest()

Specifically, latest() . Like get(), earliest() and latest() raise DoesNotExist if there is no object with the given parameters.

You may need to add get_latest_by to your model's Meta class. Maybe try this:

class PlayerPoint(models.Model):
    ...

    class Meta:
        get_latest_by = ['joined_ts']

If you don't want to add this to your model, you could just do it directly:

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

if this is the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM