Skip to content

Commit

Permalink
Update GameHistory microservice:
Browse files Browse the repository at this point in the history
- Add GameStat model to models.py
- Add GameStatSerializer to serializers.py
- Add GameStatViewSet to views.py
- Update URLs to include GameStat endpoints
- Modify existing tests in test_game_history.py to accommodate new GameStat model
- Add tests for GameStat CRUD operations in test_game_history.py
  • Loading branch information
abbastoof committed Jul 8, 2024
1 parent d1c8dd2 commit 93df970
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 5 deletions.
9 changes: 9 additions & 0 deletions Backend/game_history/game_history/game_data/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ class GameHistory(models.Model):
end_time = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"Game {self.game_id}: {self.player1_id} vs {self.player2_id} - Winner: {self.winner_id}"

class GameStat(models.Model):
game_id = models.OneToOneField(GameHistory, on_delete=models.CASCADE, primary_key=True) # this field is a foreign key to the GameHistory model
player1_score = models.IntegerField()
player2_score = models.IntegerField()
total_hits = models.IntegerField()
longest_rally = models.IntegerField()
def __str__(self):
return f"Stats for Game {self.game_id.game_id}: {self.player1_score} vs {self.player2_score} - Total Hits: {self.total_hits}, Longest Rally: {self.longest_rally}"
6 changes: 5 additions & 1 deletion Backend/game_history/game_history/game_data/serializers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# game_data/serializers.py

from rest_framework import serializers
from .models import GameHistory
from .models import GameHistory, GameStat

class GameHistorySerializer(serializers.ModelSerializer):
class Meta:
model = GameHistory
fields = '__all__'
class GameStatSerializer(serializers.ModelSerializer):
class Meta:
model = GameStat
fields = '__all__'
23 changes: 22 additions & 1 deletion Backend/game_history/game_history/game_data/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.urls import path
from .views import GameHistoryViewSet
from .views import GameHistoryViewSet, GameStatViewSet

urlpatterns = [
path(
Expand All @@ -23,4 +23,25 @@
),
name="game-history-detail",
),
path(
"game-stat/",
GameStatViewSet.as_view(
{
"get": "list",
"post": "create"
}
),
name="gamestat-list",
),
path(
"game-stat/<int:pk>/",
GameStatViewSet.as_view(
{
"get": "retrieve",
"put": "update",
"delete": "destroy",
}
),
name="gamestat-detail",
),
]
58 changes: 56 additions & 2 deletions Backend/game_history/game_history/game_data/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rest_framework import viewsets, status
from .models import GameHistory
from .serializers import GameHistorySerializer
from .models import GameHistory, GameStat
from .serializers import GameHistorySerializer, GameStatSerializer
from rest_framework.response import Response
from django.shortcuts import get_object_or_404

Expand Down Expand Up @@ -57,3 +57,57 @@ def destroy(self, request, pk=None, *args, **kwargs):
instance = get_object_or_404(self.get_queryset(), pk=pk)
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)

class GameStatViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing game stat instances.
"""
serializer_class = GameStatSerializer
queryset = GameStat.objects.all()

def create(self, request, *args, **kwargs):
"""
Create a new game stat record.
"""
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def list(self, request, *args, **kwargs):
"""
List all game stat records.
"""
queryset = self.get_queryset()
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

def retrieve(self, request, pk=None, *args, **kwargs):
"""
Retrieve a specific game stat record.
"""
instance = get_object_or_404(self.get_queryset(), pk=pk)
serializer = self.get_serializer(instance)
return Response(serializer.data, status=status.HTTP_200_OK)

def update(self, request, pk=None, *args, **kwargs):
"""
Update a specific game stat record.
"""
partial = kwargs.pop('partial', False)
instance = get_object_or_404(self.get_queryset(), pk=pk)
serializer = self.get_serializer(instance, data=request.data, partial=partial)
if serializer.is_valid():
self.perform_update(serializer)
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def destroy(self, request, pk=None, *args, **kwargs):
"""
Delete a specific game stat record.
"""
instance = get_object_or_404(self.get_queryset(), pk=pk)
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from game_data.models import GameHistory
from game_data.models import GameHistory, GameStat
from django.utils.timezone import now
from datetime import datetime

Expand Down Expand Up @@ -103,3 +103,111 @@ def test_create_game_history_validation_error(api_client):
response = api_client.post(url, data, format='json')
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert 'player2_id' in response.data

@pytest.mark.django_db
def test_primary_key_increment(api_client):
initial_count = GameHistory.objects.count()

# Create a new game history entry
data = {
'player1_id': 1,
'player2_id': 2,
'winner_id': 1,
'start_time': '2024-07-03T12:00:00Z',
'end_time': '2024-07-03T12:30:00Z'
}
response = api_client.post('/game-history/', data, format='json')
assert response.status_code == 201

# Check the count after insertion
new_count = GameHistory.objects.count()
assert new_count == initial_count + 1

# Get the latest entry and check the primary key
latest_entry = GameHistory.objects.latest('game_id')
print(latest_entry.game_id) # This will print the latest primary key value

@pytest.mark.django_db
def test_create_game_stat(api_client):
game = GameHistory.objects.create(player1_id=1, player2_id=2, winner_id=1, start_time=now())
url = reverse('gamestat-list')
data = {
'game_id': game.game_id,
'player1_score': 10,
'player2_score': 5,
'total_hits': 15,
'longest_rally': 4
}
response = api_client.post(url, data, format='json')
assert response.status_code == status.HTTP_201_CREATED
assert GameStat.objects.count() == 1
game_stat = GameStat.objects.first()
assert game_stat.player1_score == 10
assert game_stat.player2_score == 5
assert game_stat.total_hits == 15
assert game_stat.longest_rally == 4

@pytest.mark.django_db
def test_list_game_stat(api_client):
game1 = GameHistory.objects.create(player1_id=1, player2_id=2, winner_id=1, start_time=now())
GameStat.objects.create(game_id=game1, player1_score=10, player2_score=5, total_hits=15, longest_rally=4)

game2 = GameHistory.objects.create(player1_id=3, player2_id=4, winner_id=4, start_time=now())
GameStat.objects.create(game_id=game2, player1_score=8, player2_score=7, total_hits=20, longest_rally=5)

url = reverse('gamestat-list')
response = api_client.get(url, format='json')
assert response.status_code == status.HTTP_200_OK
assert len(response.data) == 2
assert response.data[0]['player1_score'] == 10
assert response.data[0]['player2_score'] == 5
assert response.data[0]['total_hits'] == 15
assert response.data[0]['longest_rally'] == 4
assert response.data[1]['player1_score'] == 8
assert response.data[1]['player2_score'] == 7
assert response.data[1]['total_hits'] == 20
assert response.data[1]['longest_rally'] == 5

@pytest.mark.django_db
def test_retrieve_game_stat(api_client):
game = GameHistory.objects.create(player1_id=1, player2_id=2, winner_id=1, start_time=now())
game_stat = GameStat.objects.create(game_id=game, player1_score=10, player2_score=5, total_hits=15, longest_rally=4)

url = reverse('gamestat-detail', args=[game_stat.pk])
response = api_client.get(url, format='json')
assert response.status_code == status.HTTP_200_OK
assert response.data['player1_score'] == game_stat.player1_score
assert response.data['player2_score'] == game_stat.player2_score
assert response.data['total_hits'] == game_stat.total_hits
assert response.data['longest_rally'] == game_stat.longest_rally

@pytest.mark.django_db
def test_update_game_stat(api_client):
game = GameHistory.objects.create(player1_id=1, player2_id=2, winner_id=1, start_time=now())
game_stat = GameStat.objects.create(game_id=game, player1_score=10, player2_score=5, total_hits=15, longest_rally=4)

url = reverse('gamestat-detail', args=[game_stat.pk])
data = {
'game_id': game.game_id,
'player1_score': 12,
'player2_score': 6,
'total_hits': 18,
'longest_rally': 5
}
response = api_client.put(url, data, format='json')
assert response.status_code == status.HTTP_200_OK
game_stat.refresh_from_db()
assert game_stat.player1_score == 12
assert game_stat.player2_score == 6
assert game_stat.total_hits == 18
assert game_stat.longest_rally == 5

@pytest.mark.django_db
def test_delete_game_stat(api_client):
game = GameHistory.objects.create(player1_id=1, player2_id=2, winner_id=1, start_time=now())
game_stat = GameStat.objects.create(game_id=game, player1_score=10, player2_score=5, total_hits=15, longest_rally=4)

url = reverse('gamestat-detail', args=[game_stat.pk])
response = api_client.delete(url)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert GameStat.objects.count() == 0

0 comments on commit 93df970

Please sign in to comment.