예제 #1
0
    def test_serialization_information_object(self, game):
        serialized_game = GameSerializer(game).data
        information_serialized = serialized_game.get('information')
        credit_serialized = information_serialized.get('credits')[0]
        award_serialized = information_serialized.get('awards')[0]

        assert information_serialized.get(
            'description') == game.information.description

        assert information_serialized.get(
            'launch_year') == game.information.launch_year

        assert credit_serialized == {
            'github_page': game.information.credits.first().github_page,
            'behance_page': game.information.credits.first().behance_page,
            'soundCloud_page':
            game.information.credits.first().soundCloud_page,
            'personal_page': game.information.credits.first().personal_page,
            'email': game.information.credits.first().email,
            'name': game.information.credits.first().name,
            'specialty': game.information.credits.first().specialty,
        }

        assert award_serialized == {
            'name': game.information.awards.first().name,
            'place': game.information.awards.first().place,
        }
예제 #2
0
    def test_serialization_information_object(self, game):
        serialized_game = GameSerializer(game).data
        information_serialized = serialized_game.get('information')
        developer_serialized = information_serialized.get('developers')[0]
        award_serialized = information_serialized.get('awards')[0]

        assert information_serialized.get(
            'description') == game.information.description

        assert information_serialized.get(
            'launch_year') == game.information.launch_year

        assert developer_serialized == {
            'login': game.information.developers.first().login,
            'github_page': game.information.developers.first().github_page,
            'email': None,
            'avatar': None,
            'name': game.information.developers.first().name
        }

        assert award_serialized == {
            'name': game.information.awards.first().name,
            'year': game.information.awards.first().year,
            'place': game.information.awards.first().place,
        }
예제 #3
0
파일: views.py 프로젝트: JackACase/tworooms
def game(request):
    """
    receive a player name in a POST to create a new game
    return the newly created game object
    """
    if request.method == 'POST':  #create a new game
        game = Game()
        code = game.new_game()
        playername = request.data['player_name']
        player = Player(name=playername)
        player.join_game(code)

        game_serializer = GameSerializer(game)
        player_serializer = PlayerSerializer(player)

        #return a json object containing both the game and the player's object
        return Response({
            'game': game_serializer.data,
            'player': player_serializer.data
        })

    elif request.method == 'GET':  #retrieve info for an existing game
        if 'access_code' in request.query_params:
            game = Game.objects.get(
                access_code=request.query_params['access_code'])
            serializer = GameSerializer(game)
            return Response(serializer.data)
        else:
            return Response()
예제 #4
0
 def post(self, request, format=None):
     game_serializer = GameSerializer(data=request.data)
     if game_serializer.verify_exists(game_serializer):
         game_serializer.save()
         return Response(game_serializer.data,
                         status=status.HTTP_201_CREATED)
     return Response(game_serializer.errors,
                     status=status.HTTP_400_BAD_REQUEST)
예제 #5
0
 def put(self, request, pk, format=None):
     game = self.get_object(pk)
     game_serializer = GameSerializer(game, data=request.data)
     if game_serializer.verify_exists(game_serializer):
         game_serializer.save()
         return Response(game_serializer.data)
     return Response(game_serializer.errors,
                     status=status.HTTP_400_BAD_REQUEST)
예제 #6
0
class SerializerTestCase(TestCase):
    def setUp(self):
        self.ser = GameSerializer()

    def test_validate_rolls(self):
        rolls = self.ser.validate_rolls([1, 2, 3, 4])
        self.assertEqual(rolls, [1, 2, 3, 4])
        with self.assertRaises(serializers.ValidationError):
            rolls2 = self.ser.validate_rolls([5, 6])
예제 #7
0
    def test_serialization_extra_object(self, game):
        serialized_game = GameSerializer(game).data
        package_serialized = serialized_game.get('packages')[0]
        platform_serialized = package_serialized.get('platforms')[0]

        assert package_serialized.get(
            'package') == game.packages.first().package.url

        assert platform_serialized.get(
            'name') == game.packages.first().platforms.first().name

        assert platform_serialized.get(
            'extensions') == game.packages.first().platforms.first().extensions
예제 #8
0
    def test_serialization_medias_object(self, game):
        serialized_game = GameSerializer(game).data
        image_serialized = serialized_game.get('media_image')[0]
        video_serialized = serialized_game.get('media_video')[0]
        sound_serialized = serialized_game.get('media_soundtrack')[0]

        assert image_serialized.get(
            'image') == game.media_image.first().image.url

        assert video_serialized.get(
            'video') == game.media_video.first().video.url

        assert sound_serialized.get(
            'soundtrack') == game.media_soundtrack.first().soundtrack.url
예제 #9
0
 def start_game(request):
     data = request.data
     new_game = Game.create(data["first_player"], data["second_player"])
     new_game.save()
     serializer_class = GameSerializer(new_game, many=False,
                                       context={'request': request})
     return Response(data=serializer_class.data, template_name=None)
예제 #10
0
def check_if_user_can_play_game_code(request):
    if "game_code" not in request.data:
        return JsonResponse(
            {"error": "Enter game_code"}, status=status.HTTP_400_BAD_REQUEST
        )
    if "user_name" not in request.data:
        return JsonResponse(
            {"error": "Enter user_name"}, status=status.HTTP_400_BAD_REQUEST
        )
    try:
        game = Game.objects.get(game_code=request.data['game_code'])
        gameData = GameSerializer(game).data
        if gameData['user_name'] == request.data['user_name']:
            return JsonResponse({"error": "User cannot play the game"}, status=status.HTTP_400_BAD_REQUEST)
        if gameData['active']:
            ug = UserGames.objects.filter(game_code=request.data['game_code'], user_name=request.data['user_name'])
            if len(ug) != 0:
                return JsonResponse({
                    "error": "Already played game"
                }, status=status.HTTP_400_BAD_REQUEST)
            return JsonResponse({
                "data": "User can play game"
            }, status=status.HTTP_200_OK)
        else:
            return JsonResponse({"error": "Game code is expired"}, status=status.HTTP_400_BAD_REQUEST)
    except Game.DoesNotExist:
        return JsonResponse({
            "error": "Invalid game code"
        }, status=status.HTTP_400_BAD_REQUEST)
    except Exception as error:
        return
        JsonResponse({"error": error}, status=status.HTTP_400_BAD_REQUEST)
예제 #11
0
 def test_paginate(self, list_games):
     list_serializer = GameSerializer(list_games, many=True).data
     per_page = 2
     page = 1
     games_page = GameViewSet().paginate(page, per_page, list_games)
     assert games_page['games'] == list_serializer
     assert games_page['info']['page'] == page
예제 #12
0
 def filter(self, request, pk=None):
     platforms = request.query_params['platforms'].split()
     genres = request.query_params['genres'].split()
     ffilter = self.__mount_filter__("packages__platforms__name", platforms)
     ffilter &= self.__mount_filter__("information__genres__name", genres)
     data = Game.objects.filter(ffilter)
     return Response(GameSerializer(data, many=True).data)
예제 #13
0
def create_player(user, game, players):
    """Create and return player.

    only return player if he is already created
    :param user: user who will be related to player
    :param game: game what will be related to player
    :return: Player object
    """
    players = players.order_by('in_game_order')
    player = players.filter(user=user).first()
    if player is None:
        player = Player(user=user,
                        name=user.username,
                        game=game,
                        chips=GameSerializer(game).data['starting_chips'],
                        is_in_game=True)
    else:
        player.is_in_game = True

    # set player in_game_order
    if len(players) < 1:
        player.in_game_order = 1
    else:
        player.in_game_order = players.reverse()[0].in_game_order + 1

    # update number of connected players
    game.players_connected = len(players)
    game.save()

    player.save()
    return player.id
예제 #14
0
class EventSerializer(serializers.Serializer):
    pk = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    game = GameSerializer()
    start_date = serializers.DateTimeField()
    end_date = serializers.DateTimeField()
    max_players = serializers.IntegerField()
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    joined = serializers.SerializerMethodField('is_player_joined')
    solved = serializers.SerializerMethodField('solution')

    def is_player_joined(self, event):
        player = self.context.get("player")
        if player in event.players.all():
            return True
        else:
            return False

    def solution(self, event):
        player = self.context.get("player")
        if player in event.players.all():
            try:
                membership = event.membership_set.get(player=player)
                if membership.status == 'solved':
                    return event.game.solution
            except:
                return None
        else:
            return None
예제 #15
0
 def get(self, request):
     ordering = request.GET.get('ordering', None)
     genres = reduce(self.__group_genres__, Information.objects.all(), {})
     for key in genres:
         self.__sort__(ordering, genres[key])
         genres[key] = GameSerializer(genres[key], many=True).data
     return Response(genres)
예제 #16
0
    def paginate(self, page, per_page, data):
        list_games = data
        paginator = Paginator(list_games, per_page)

        try:
            games = paginator.page(page)
        except PageNotAnInteger:
            games = paginator.page(1)
        except EmptyPage:
            games = paginator.page(1)
            page = 1

        interval_range = self.get_pagination_range(page, paginator.num_pages)

        list_games = GameSerializer(games.object_list, many=True).data
        paginated = {
            "games": list_games,
            "info": {
                "range_start": interval_range[0],
                "range_end": interval_range[1],
                "num_pages": paginator.num_pages,
                "page": page
            }
        }
        return paginated
예제 #17
0
    def flag_cell(self, request, pk):
        row = request.data.get('row')
        column = request.data.get('column')

        game = get_object_or_404(self.queryset, pk=pk)
        game.flag_cell(row, column)
        serializer = GameSerializer(game)
        return Response(serializer.data)
예제 #18
0
    def test_only_logged_id_user_games_are_returned(self):
        other_user = User.objects.create_user(username='******', password='******', is_superuser=True)
        Game.objects.create(user=other_user, board=self.board, status=STATUS_IN_PROGRESS)

        response = self.client.get('/game/')

        serialized_data = GameSerializer(self.game)
        self.assertEquals(response.json(), [serialized_data.data])
예제 #19
0
def create_a_game_code(request):
    if "user_name" not in request.data:
        return JsonResponse({"error": "Enter user_name"},
                            status=status.HTTP_400_BAD_REQUEST)
    if "category" not in request.data:
        return JsonResponse({"error": "Enter category"},
                            status=status.HTTP_400_BAD_REQUEST)

    data = {
        'user_name': request.data['user_name'],
        'category': request.data['category']
    }
    game = GameSerializer(data=data)
    if game.is_valid():
        game.save()
        return JsonResponse(game.data, status=status.HTTP_200_OK)
    return JsonResponse(game.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #20
0
def game_list(request):
    """
    List all games.
    """
    if request.method == 'GET':
        games = Game.objects.all()
        serializer = GameSerializer(games, many=True)
        return JsonResponse(serializer.data, safe=False)
예제 #21
0
 def test_game_detail(self):
     """Test for retrieving game detail"""
     user2 = sample_user(email='*****@*****.**')
     game1 = sample_game(self.user, user2)
     res = self.client.get(get_game_detail_url(game1.id))
     self.assertEqual(res.status_code, status.HTTP_200_OK)
     serializer = GameSerializer(game1)
     self.assertEqual(serializer.data, res.data)
예제 #22
0
def check_if_game_code_isValid(request):
    if "game_code" not in request.data:
        return JsonResponse(
            {"error": "Enter game_code"}, status=status.HTTP_400_BAD_REQUEST
        )
    if "user_name" not in request.data:
        return JsonResponse(
            {"error": "Enter user_name"}, status=status.HTTP_400_BAD_REQUEST
        )
    try:
        game = Game.objects.get(game_code=request.data['game_code'])
        gameData = GameSerializer(game).data
        if gameData['user_name'] == request.data['user_name']:
            return JsonResponse({"error": "Admin cannot play the game"}, status=status.HTTP_400_BAD_REQUEST)
        if gameData['active']:
            ug = UserGames.objects.filter(game_code=request.data['game_code'], user_name=request.data['user_name'])
            if len(ug) != 0:
                return JsonResponse({
                    "error": "Already played game"
                }, status=status.HTTP_400_BAD_REQUEST)
            qList = Question.objects.filter(category=gameData['category']).values_list('id', flat=True)
            qRand = random.sample(list(qList), min(len(qList), 10))
            questions = Question.objects.filter(id__in=qRand)
            questionData = QuestionSerializer(questions, many=True).data
            questions = []
            for question in questionData:
                options = []
                for option in question['options']:
                    optionQuery = Options.objects.get(option=option)
                    optionData = OptionsSerializer(optionQuery, many=False).data
                    options.append(optionData['option'])
                question['options'] = options
                questions.append(question)
            serializer = UserGamesSerializer(data={
                'game_code': request.data['game_code'],
                'category': gameData['category'],
                'user_name': request.data['user_name']
            })
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({
                    "data": {
                        'questions': questions,
                        'usergameData': serializer.data
                    }
                }, status=status.HTTP_200_OK)
            return JsonResponse({
                "error": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({"error": "Game code is expired"}, status=status.HTTP_400_BAD_REQUEST)
    except Game.DoesNotExist:
        return JsonResponse({
            "error": "Invalid game code"
        }, status=status.HTTP_400_BAD_REQUEST)
    except Exception as error:
        return
        JsonResponse({"error": error}, status=status.HTTP_400_BAD_REQUEST)
예제 #23
0
 def test_game_detail_json(self, client, game):
     response = client.get("/api/games/{}/".format(game.pk))
     assert response.status_code == 200
     assert response.get("Content-Type") == 'application/json'
     data = GameSerializer(game).data
     data['cover_image'] = 'http://testserver' + data['cover_image']
     data['slide_image'] = 'http://testserver' + data['slide_image']
     data['card_image'] = 'http://testserver' + data['card_image']
     assert response.data == data
예제 #24
0
def get_all_games_by_tournament(request, tournament_id):
    try:
        games = Game.objects.filter(stage__tournament_id=tournament_id)
        serializer = GameSerializer(instance=games, many=True)
        return Response(
            data={"success": True, "message": "All tournament data successfully fetched", "data": serializer.data},
            status=200)
    except Exception as e:
        return Response(data={"success": False, "message": "Unexpected error", "data": None}, status=500)
예제 #25
0
 def get(self, request, *args, **kwargs):
         game = models.Game.objects.filter(Q(playerA=Player.objects.get(id=request.GET.get('player'))) | Q(playerB=Player.objects.get(id=request.GET.get('player'))), completed=False).first()
         if game:
             data = GameSerializer(game).data
             print(data)
             data['found']=True
             return Response(data)
         else :
             return Response({ 'found' : False })
예제 #26
0
    def create(self, request):
        user = self.request.user
        create_serializer = GameCreateSerializer(data=request.data)

        if create_serializer.is_valid():
            game = Game.objects.create_new(user, **create_serializer.data)
            serializer = GameSerializer(game)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(create_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #27
0
def join(request, game_id, figure_id):
    game = Game.objects.get(id=game_id)
    player1 = Figure.objects.get(id=figure_id)
    players = game.players
    context = {
        'game': GameSerializer(game).data,
        'player1': FigureSerializer(player1).data,
        'players': FigureSerializer(players, many=True).data,
    }
    return render(request, 'game/room.html', context)
예제 #28
0
 def test_serialization_game_object(self, game):
     serialized_game = GameSerializer(game).data
     game = {
         'name': game.name,
         'cover_image': game.cover_image.url,
         'official_repository': game.official_repository,
         'slide_image': game.slide_image.url,
         'card_image': game.card_image.url,
         'visualization': game.visualization,
         'game_activated': game.game_activated,
         'pk': game.pk,
         'downloads': game.downloads
     }
     serialized_game.pop('information')
     serialized_game.pop('media_image')
     serialized_game.pop('media_soundtrack')
     serialized_game.pop('media_video')
     serialized_game.pop('packages')
     assert game == dict(serialized_game)
예제 #29
0
 def get_game_context(game, request):
     currentGame = json.dumps(GameSerializer(
         game, many=False, context={'request': request}).data)
     active_player = json.dumps(PlayerSerializer(
         game.active_player,
         many=False,
         context={'request': request}).data)
     context_dict = {'currentGame': currentGame,
                     'activePlayer': active_player}
     return context_dict
예제 #30
0
    def test_retrieving_games(self):
        """Test retrieving games for authenticated user"""
        user2 = sample_user(email='*****@*****.**')
        user3 = sample_user(email='*****@*****.**')
        game1 = sample_game(self.user, user2)
        game2 = sample_game(user2, user3)

        res = self.client.get(GAME_URL)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        serializer = GameSerializer([game1], many=True)
        self.assertEqual(serializer.data, res.data)