def test_gc_already_won_game(self):
     g = GameController()
     ans = g.game.answer.word
     r = g.guess(*ans)
     self.assertEqual(r["bulls"], 4)
     r = g.guess(*ans)
     self.assertEqual(r["bulls"], None)
 def test_gc_guess_with_cows(self):
     while True:
         g = GameController()
         ans = g.game.answer.word
         rev = [*reversed(ans)]
         if ans != rev:
             break
     r = g.guess(*rev)
     self.assertTrue(r["cows"] > 0 and r["bulls"] != 4)
    def test_gc_check_game_nomore_turns(self):
        response_object = {
            "bulls": None,
            "cows": None,
            "analysis": None,
            "status": None
        }
        g = GameController()
        for _ in range(11):
            r = g.guess(0, 0, 0, 0)

        r = g._check_game_on(response_object)
        self.assertEqual(r, False)
        self.assertIn("You already lost! The correct answer was",
                      response_object["status"])
 def test_gc_guess_no_game(self):
     g = GameController()
     g.game = None
     with self.assertRaises(ValueError):
         g.guess(1, 2, 3, 4)
 def test_gc_guess_lose_game(self):
     g = GameController()
     for i in range(10):
         g.guess(0, 0, 0, 0)
     r = g.guess(0, 0, 0, 0)
     self.assertIsNone(r.get("bulls"))
 def test_gc_guess_win_game(self):
     g = GameController()
     ans = g.game.answer.word
     r = g.guess(*ans)
     self.assertEqual(r["bulls"], 4)
 def test_gc_guess_once(self):
     g = GameController()
     r = g.guess(0, 0, 0, 0)
     bulls = r.get("bulls", None)
     self.assertIsNot(bulls, None)
Ejemplo n.º 8
0
    def post(self):
        """
        TBC
        :return:
        """

        self.handler.method = "post"
        self.handler.log(message='Processing POST request.', status=0)

        #
        # Get the JSON from the POST request. If there is no JSON then an exception
        # is raised. IMPORTANT NOTE: When debugging ensuring the Content-type is
        # set to application/json - for example (using cURL):
        #
        # curl -H "Content-type: application/json" ...
        #
        try:
            self.handler.log(message='Attempting to execute_load JSON', status=0)
            json_dict = request.get_json()
            self.handler.log(message='Loaded JSON. Returned: {}'.format(json_dict), status=0)
        except BadRequest as e:
            return self.handler.error(
                status=400,
                exception=e.description,
                message="Bad request. There was no JSON present. Are you sure the "
                        "header Content-type is set to application/json?"
            )

        #
        # Get a persister to enable the game to be loaded and then saved (updated).
        # See the GET method above for more information on the persister.
        #
        try:
            self.handler.log(message='Getting persister', status=0)
            persister = self.persistence_engine.persister
        except ConnectionError as ce:
            return self.handler.error(
                status=503,
                exception=str(ce),
                message="There is no redis service available!"
            )

        #
        # Get the game key from the JSON provided above. If it does not exist,
        # return a 400 status (client) error
        #
        try:
            _key = json_dict["key"]
            self.handler.log(message='Attempting to execute_load game {}'.format(_key), status=0)
        except TypeError as te:
            return self.handler.error(
                status=400,
                exception=str(te),
                message="Bad request. For some reason the json_dict is None! Are you "
                        "sure the header is set to application/json?"
            )
        except KeyError as ke:
            return self.handler.error(
                status=400,
                exception=str(ke),
                message="Bad request. For some reason the json_dict does not contain "
                        "a key! Are you sure the header is set to application/json and "
                        "a key is present?"
            )

        #
        # Load the game based on the key contained in the JSON provided to
        # the POST request. If the JSON data is invalid, return a
        # response to the user indicating an HTML status, the exception, and an
        # explanatory message. If the data
        #
        gen_error_msg = "The request raised an exception while trying to load the saved game. " \
                        "Please try again shortly and the issue has been logged."
        try:
            _persisted_response = persister.load(key=_key)
            if not _persisted_response:
                raise KeyError(
                    "The game key ({}) was not found in the persistence engine!".format(_key)
                )
            self.handler.log(message="Persister response: {}".format(_persisted_response))

            _loaded_game = json.loads(_persisted_response)
            self.handler.log(message="Loaded game: {}".format(_loaded_game))
        except KeyError as ke:
            return self.handler.error(
                status=400,
                exception=str(ke),
                message="The request must contain a valid game key."
            )
        except ValueError as ve:
            return self.handler.error(
                status=500,
                exception=str(ve),
                message=gen_error_msg
            )
        except Exception as e:
            return self.handler.error(
                status=400,
                exception=repr(e),
                message=gen_error_msg
            )

        #
        # Load the game based on the key contained in the JSON provided to
        # the POST request. If the JSON data is invalid, return a
        # response to the user indicating an HTML status, the exception, and an
        # explanatory message. If the data
        #
        try:
            self.handler.log(message="Loading game mode from: {}.".format(_loaded_game["mode"]))
            _mode = _loaded_game["mode"]
            self.handler.log(message="Loaded game mode {}.".format(str(_mode["mode"])))

            _game = GameController(
                game_modes=app.config["COWBULL_CUSTOM_MODES"],
                game_json=json.dumps(_loaded_game),
                mode=str(_mode["mode"])
            )
            self.handler.log(message='Loaded game {}'.format(_key), status=0)
        except RuntimeError as ve:
            return self.handler.error(
                status=500,
                exception=str(ve),
                message="Bad request. For some reason the json_dict was None!"
            )
        except KeyError as ke:
            return self.handler.error(
                status=400,
                exception=str(ke),
                message="The request must contain a valid game key."
            )
        except TypeError as te:
            return self.handler.error(
                status=400,
                exception=str(te),
                message="The game key provided was invalid."
            )
        except Exception as e:
            return self.handler.error(
                status=500,
                exception=repr(e),
                message="Exception occurred while loading game!"
            )

        #
        # Get the digits being guessed and add them to a list
        #
        try:
            self.handler.log(message='Getting digits from {}'.format(json_dict))
            _guesses = json_dict["digits"]
            self.handler.log(message='Guesses extracted from JSON: {}'.format(_guesses), status=0)
        except RuntimeError as ve:
            return self.handler.error(
                status=500,
                exception=str(ve),
                message="Bad request. For some reason the json_dict was None!"
            )
        except ValueError as ve:
            return self.handler.error(
                status=400,
                exception=str(ve),
                message="There was a problem with the value of the digits provided!"
            )
        except KeyError as ke:
            return self.handler.error(
                status=400,
                exception=str(ke),
                message="The request must contain an array of digits called 'digits'"
            )
        except TypeError as te:
            return self.handler.error(
                status=400,
                exception=str(te),
                message="The game key provided was invalid."
            )

        #
        # Make a guess
        #
        try:
            self.handler.log(message="In guess")
            self.handler.log(message='Making a guess with digits: {}'.format(_guesses), status=0)
            _analysis = _game.guess(*_guesses)
            self.handler.log(message='Retrieved guess analysis', status=0)
        except ValueError as ve:
            return self.handler.error(
                status=400,
                exception=str(ve),
                message="There is a problem with the digits provided!"
            )

        #
        # Save the game
        #
        gen_error_msg = "The request raised an exception while trying to save (update) the game. " \
                        "Please try again shortly and the issue has been logged."
        self.handler.log(message="Saving game to persister")
        save_game = _game.save()
        try:
            persister.save(key=_key, jsonstr=save_game)
        except KeyError as ke:
            return self.handler.error(
                status=500,
                exception=str(ke),
                message=gen_error_msg
            )
        except Exception as e:
            return self.handler.error(status=500, exception=str(e),
                                      message="An internal error occurred - {}".format(repr(e)))
        self.handler.log(message='Game {} persisted.'.format(_key), status=0)

        #
        # Return the analysis of the guess to the user.
        #
        _display_info = json.loads(save_game)
        del(_display_info["answer"])
        _return_response = \
            {
                "game": _display_info,
                "outcome": _analysis,
                "served-by": socket.gethostname()
            }

        self.handler.log(message='Returning analysis and game info to caller', status=0)
        return build_response(response_data=_return_response)