def test_change_game(self):
        """
        Ensure we can change an existing game.
        """
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Sorry"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        # DEFINE NEW PROPERTIES FOR GAME
        data = {
            "gameTypeId": 1,
            "skillLevel": 2,
            "title": "Sorrys",
            "numberOfPlayers": 4
        }

        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
        response = self.client.put(f"/games/{game.id}", data, format="json")
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # GET GAME AGAIN TO VERIFY CHANGES
        response = self.client.get(f"/games/{game.id}")
        json_response = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Assert that the properties are correct
        self.assertEqual(json_response["title"], "Sorrys")
        self.assertEqual(json_response["skill_level"], 2)
        self.assertEqual(json_response["number_of_players"], 4)
    def test_change_game(self):

        game = Game()
        game.game_type_id = 1
        game.skill_level = 1
        game.title = "Sorry"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        # DEFINE NEW PROPERTIES FOR GAME
        data = {
            "game_type_id": 1,
            "title": "Sorry",
            "skill_level": 1,
            "maker": "Hasbro",
            "number_of_players": 4
        }

        self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token}')
        response = self.client.put(f"/games/{game.id}", data, format="json")
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # GET GAME AGAIN TO VERIFY CHANGES
        response = self.client.get(f"/games/{game.id}")
        json_response = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Assert that the properties are correct
        self.assertEqual(json_response["title"], "Sorry")
        self.assertEqual(json_response["skill_level"], 1)
        self.assertEqual(json_response["maker"], "Hasbro")
        self.assertEqual(json_response["number_of_players"], 4)
    def test_get_game(self):
        """
        Ensure we can get an existing game.
        """

        # Seed the database with a game
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Monopoly"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1

        game.save()

        # Make sure request is authenticated
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)

        # Initiate request and store response
        response = self.client.get(f"/games/{game.id}")

        # Parse the JSON in the response body
        json_response = json.loads(response.content)

        # Assert that the game was retrieved
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Assert that the values are correct
        self.assertEqual(json_response["title"], "Monopoly")
        self.assertEqual(json_response["maker"], "Milton Bradley")
        self.assertEqual(json_response["skill_level"], 5)
        self.assertEqual(json_response["number_of_players"], 4)
    def create(self, request):
        """Handle POST operations

        Returns:
            Response -- JSON serialized game instance
        """
        gamer = Gamer.objects.get(user=request.auth.user)

        game = Game()

        try:
            game.title = request.data["title"]
            game.maker = request.data["maker"]
            game.number_of_players = request.data["numberOfPlayers"]
            game.skill_level = request.data["skillLevel"]
        except KeyError as ex:
            return Response({'message': 'Incorrect key was sent in request'},
                            status=status.HTTP_400_BAD_REQUEST)

        game.gamer = gamer

        try:
            gametype = GameType.objects.get(pk=request.data["gameTypeId"])
            game.gametype = gametype
        except GameType.DoesNotExist as ex:
            return Response({'message': 'Game type provided is not valid'},
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            game.save()
            serializer = GameSerializer(game, context={'request': request})
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except ValidationError as ex:
            return Response({"reason": ex.message},
                            status=status.HTTP_400_BAD_REQUEST)
    def test_get_all_games(self):
        """Ensure we can get all games"""

        # Seed the database with games
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Monopoly"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Clue"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Sorry"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        # Make sure request is authenticated
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)

        # Initiate request and store response
        response = self.client.get(f"/games")

        # Parse the JSON in the response body
        json_response = json.loads(response.content)

        # Assert that the games list is the correct length
        self.assertEqual(len(json_response), 3)

        # Assert that the values are correct
        self.assertEqual(json_response[0]["title"], "Monopoly")
        self.assertEqual(json_response[1]["title"], "Clue")
        self.assertEqual(json_response[2]["title"], "Sorry")
def usergame_list(request):
    if request.method == "GET":
        with sqlite3.connect(Connection.db_path) as conn:
            conn.row_factory = sqlite3.Row
            db_cursor = conn.cursor()

            db_cursor.execute("""
            select
            g.id,
            g.title,
            g.maker,
            g.game_type_id,
            g.skill_level,
            g.number_of_players,
            u.id user_id,
            u.first_name || ' ' || u.last_name as full_name
            from levelupapi_game g
            join levelupapi_gamer gr on g.gamer_id = gr.id
            join auth_user u on gr.user_id = u.id
            """)

            dataset = db_cursor.fetchall()

            games_by_user = {}

            for row in dataset:
                game = Game()
                game.title = row['title']
                game.maker = row['maker']
                game.skill_level = row['skill_level']
                game.number_of_players = row['number_of_players']
                game.game_type_id = row['game_type_id']

                uid = row['user_id']

                if uid in games_by_user:
                    games_by_user[uid]['games'].append(game)
                else:
                    games_by_user[uid] = {}
                    games_by_user[uid]['id'] = uid
                    games_by_user[uid]['full_name'] = row['full_name']

                    games_by_user[uid]['games'] = [game]
            list_of_users_with_games = games_by_user.values()

            template = 'users/list_with_games.html'
            context = {
                'usergame_list': list_of_users_with_games,
                'title': 'Users with Games'
            }

            return render(request, template, context)
def usergame_list(request):
    if request.method == 'GET':
        with sqlite3.connect(Connection.db_path) as conn:
            conn.row_factory = sqlite3.Row
            db_cursor = conn.cursor()

            db_cursor.execute("""
                SELECT
                    g.id,
                    g.title,
                    g.maker,
                    g.gametype_id,
                    g.number_of_players,
                    g.skill_level,
                    u.id user_id,
                    u.first_name || ' ' || u.last_name AS full_name
                FROM
                    levelupapi_game g
                JOIN
                    levelupapi_gamer gr ON g.gamer_id = gr.id
                JOIN
                    auth_user u ON gr.user_id = u.id
            """)

            dataset = db_cursor.fetchall()
            gamers_dict = {}

            for row in dataset:
                game = Game()
                game.title = row["title"]
                game.maker = row["maker"]
                game.skill_level = row["skill_level"]
                game.number_of_players = row["number_of_players"]
                game.gametype_id = row["gametype_id"]

                uid = row["user_id"]
                if uid in gamers_dict:
                    gamers_dict[uid]['games'].append(game)
                else:
                    gamers_dict[uid] = {}
                    gamers_dict[uid]["id"] = uid
                    gamers_dict[uid]["full_name"] = row["full_name"]
                    gamers_dict[uid]["games"] = [game]

        # Get only the values from the dictionary and create a list from them
        list_of_user_objects = gamers_dict.values()

        # Specify the HTML template and provide data context
        template = 'users/list_with_games.html'
        context = {'usergame_list': list_of_user_objects}

        return render(request, template, context)
Exemple #8
0
def usergame_list(request):
    if request.method == 'GET':
        with sqlite3.connect(Connection.db_path) as conn:
            conn.row_factory = sqlite3.Row
            db_cursor = conn.cursor()

            db_cursor.execute("""
                SELECT
                    id,
                    title,
                    maker,
                    gametype_id,
                    number_of_players,
                    skill_level,
                    user_id,
                    full_name
                FROM
                    GAMES_BY_USER
            """)

            dataset = db_cursor.fetchall()

            games_by_user = {}

            for row in dataset:
                game = Game()
                game.title = row["title"]
                game.maker = row["maker"]
                game.skill_level = row["skill_level"]
                game.number_of_players = row["number_of_players"]
                game.gametype_id = row["gametype_id"]
                uid = row["user_id"]

                if uid in games_by_user:
                    games_by_user[uid]['games'].append(game)
                else:
                    games_by_user[uid] = {}
                    games_by_user[uid]["id"] = uid
                    games_by_user[uid]["full_name"] = row["full_name"]
                    games_by_user[uid]["games"] = [game]

        list_of_users_with_games = games_by_user.values()
        template = 'users/list_with_games.html'
        context = {
            'usergame_list': list_of_users_with_games
        }
        return render(request, template, context)
Exemple #9
0
    def setUp(self):
        """
        Create a new account and create sample category
        """
        url = "/register"
        data = {
            "username": "******",
            "password": "******",
            "email": "*****@*****.**",
            "address": "100 Infinity Way",
            "phone_number": "555-1212",
            "first_name": "Steve",
            "last_name": "Brownlee",
            "bio": "Love those eventz!!"
        }
        # Initiate request and capture response
        response = self.client.post(url, data, format='json')

        # Parse the JSON in the response body
        json_response = json.loads(response.content)

        # Store the auth token
        self.token = json_response["token"]

        # Assert that a user was created
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # SEED DATABASE WITH ONE GAME TYPE
        # This is needed because the API does not expose a /gametypes
        # endpoint for creating game types
        gametype = GameType()
        gametype.label = "Board game"
        gametype.save()

        # SEED DATABASE WITH ONE game
        # This is needed because the API does not expose a /game
        # endpoint for creating game
        game = Game()
        game.gamer_id = 1
        game.gametype_id = gametype.id
        game.skill_level = 5
        game.number_of_players = 3
        game.maker = "Wizards of the Coast"
        game.title = "Dungeons & Dragons"
        game.save()
Exemple #10
0
    def create(self, request):
        gamer = Gamer.objects.get(user=request.auth.user)
        game = Game()
        game.title = request.data["title"]
        game.maker = request.data["maker"]
        game.number_of_players = request.data["numberOfPlayers"]
        game.skill_level = request.data["skillLevel"]
        game.gamer = gamer
        gametype = GameType.objects.get(pk=request.data["gameTypeId"])
        game.gametype = gametype

        try:
            game.save()
            serializer = GameSerializer(game, context={'request': request})
            return Response(serializer.data)
        except ValidationError as ex:
            return Response({"reason": ex.message},
                            status=status.HTTP_400_BAD_REQUEST)
    def test_delete_game(self):
        """
        Ensure we can delete an existing game.
        """
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Sorry"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
        response = self.client.delete(f"/games/{game.id}")
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # GET GAME AGAIN TO VERIFY 404 response
        response = self.client.get(f"/games/{game.id}")
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
    def setUp(self):
        """
        Create a new account and create sample category
        """
        url = "/register"
        data = {
            "username": "******",
            "password": "******",
            "email": "*****@*****.**",
            "address": "100 Infinity Way",
            "phone_number": "555-1212",
            "first_name": "Jon",
            "last_name": "Shearon",
            "bio": "Love those gamez!!"
        }
        # Initiate request and capture response
        response = self.client.post(url, data, format='json')

        # Parse the JSON in the response body
        json_response = json.loads(response.content)

        # Store the auth token
        self.token = json_response["token"]

        # Assert that a user was created
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # SEED DATABASE WITH ONE GAME TYPE
        # This is needed because the API does not expose a /gametypes
        # endpoint for creating game types
        gametype = GameType()
        gametype.label = "Board game"
        gametype.save()

        game = Game()
        game.gametype = GameType.objects.get(pk=1)
        game.skill_level = 5
        game.title = "Clue"
        game.maker = "Milton Bradley"
        game.number_of_players = 6
        game.gamer = Gamer.objects.get(pk=1)
        game.save()
Exemple #13
0
    def create(self, request):
        """Handle POST operations

        Returns:
            Response -- JSON serialized game instance
        """

        # Uses the token passed in the `Authorization` header
        gamer = Gamer.objects.get(user=request.auth.user)

        # Create a new Python instance of the Game class
        # and set its properties from what was sent in the
        # body of the request from the client.
        game = Game()
        game.title = request.data["title"]
        game.maker = request.data["maker"]
        game.number_of_players = request.data["numberOfPlayers"]
        game.skill_level = request.data["skillLevel"]
        game.gamer = gamer

        # Use the Django ORM to get the record from the database
        # whose `id` is what the client passed as the
        # `gameTypeId` in the body of the request.
        gametype = GameType.objects.get(pk=request.data["gameTypeId"])
        game.game_type = gametype

        # Try to save the new game to the database, then
        # serialize the game instance as JSON, and send the
        # JSON as a response to the client request
        try:
            game.save()
            serializer = GameSerializer(game, context={'request': request})
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        # If anything went wrong, catch the exception and
        # send a response with a 400 status code to tell the
        # client that something was wrong with its request data
        except ValidationError as ex:
            return Response({"reason": ex.message},
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #14
0
    def create(self, request):
        gamer = Gamer.objects.get(user=request.auth.user)

        game = Game()
        game.title = request.data['title']
        game.maker = request.data['maker']
        game.number_of_players = request.data['numberOfPlayers']
        game.skill_level = request.data['skillLevel']
        game.gamer = gamer

        game_type = GameType.objects.get(pk=request.data['gameTypeId'])
        # select *
        # from gametype
        # where id=request.data['game_type_id']
        game.game_type = game_type

        try:
            game.save()
            serializer = GameSerializer(game, context={'request': request})
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except ValidationError as ex:
            return Response({'reason': ex.message},
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #15
0
    def test_change_game(self):
        """
        Ensure we can change an existing game.
        """
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Sorry"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        # DEFINE NEW PROPERTIES FOR GAME
        data = {
            "gameTypeId": 1,
            "skillLevel": 2,
            "title": "Sorry",
            "maker": "Hasbro",
            "numberOfPlayers": 4
        }

        # print('GAME ID ' + str(game.id))
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
        response = self.client.put(f"/games/{game.id}", data, format='json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # get game again to verify changes
        response = self.client.get(f"/games/{game.id}")
        json_response = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # assert that the properties are correct
        self.assertEqual(json_response["title"], "Sorry")
        self.assertEqual(json_response["maker"], "Hasbro")
        self.assertEqual(json_response["skill_level"], 2)
        self.assertEqual(json_response["number_of_players"], 4)
    def test_delete_game(self):
        """
        Ensure we can delete an existing game.
        """

        # Use the ORM to insert some test data into the database
        game = Game()
        game.gametype_id = 1
        game.skill_level = 5
        game.title = "Sorry"
        game.maker = "Milton Bradley"
        game.number_of_players = 4
        game.gamer_id = 1
        game.save()

        # Authorize the request
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)

        # Use the API to delete the test game
        response = self.client.delete(f"/games/{game.id}")

        # GET GAME AGAIN TO VERIFY 404 response
        response = self.client.get(f"/games/{game.id}")
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Exemple #17
0
def usergame_list(request):
    """Function to build an HTML report of games by user"""
    if request.method == 'GET':
        # Connect to project database
        with sqlite3.connect(Connection.db_path) as conn:
            conn.row_factory = sqlite3.Row
            db_cursor = conn.cursor()

            # Query for all games, with related user info.
            db_cursor.execute("""
                SELECT
                    g.id,
                    g.title,
                    g.maker,
                    g.gametype_id,
                    g.number_of_players,
                    g.skill_level,
                    u.id user_id,
                    u.first_name || ' ' || u.last_name AS full_name
                FROM
                    levelupapi_game g
                JOIN
                    levelupapi_gamer gr ON g.gamer_id = gr.id
                JOIN
                    auth_user u ON gr.user_id = u.id
            """)

            dataset = db_cursor.fetchall()

            # Take the flat data from the database, and build the
            # following data structure for each gamer.
            #
            # {
            #     1: {
            #         "id": 1,
            #         "full_name": "Admina Straytor",
            #         "games": [
            #             {
            #                 "id": 1,
            #                 "title": "Foo",
            #                 "maker": "Bar Games",
            #                 "skill_level": 3,
            #                 "number_of_players": 4,
            #                 "gametype_id": 2
            #             }
            #         ]
            #     }
            # }

            games_by_user = {}

            for row in dataset:
                # Crete a Game instance and set its properties
                game = Game()
                game.title = row["title"]
                game.maker = row["maker"]
                game.skill_level = row["skill_level"]
                game.number_of_players = row["number_of_players"]
                game.gametype = GameType.objects.get(pk=row["gametype_id"])

                # Store the user's id
                uid = row["user_id"]

                # If the user's id is already a key in the dictionary...
                if uid in games_by_user:

                    # Add the current game to the `games` list for it
                    games_by_user[uid]['games'].append(game)

                else:
                    # Otherwise, create the key and dictionary value
                    games_by_user[uid] = {}
                    games_by_user[uid]["id"] = uid
                    games_by_user[uid]["full_name"] = row["full_name"]
                    games_by_user[uid]["games"] = [game]

        # Get only the values from the dictionary and create a list from them
        list_of_users_with_games = games_by_user.values()

        # Specify the Django template and provide data context
        template = 'users/list_with_games.html'
        context = {'usergame_list': list_of_users_with_games}

        return render(request, template, context)