def test_gc_new_game_direct_badmode(self): g = GameController() with self.assertRaises(TypeError): g._new_game({ "mode": "test1", "priority": 5, })
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_load_game_modes_nolist(self): mode_list = \ GameMode( mode="test1", priority=5, ) g = GameController() with self.assertRaises(TypeError): g.load_modes(input_modes=mode_list)
def test_DealHand_TwoPlayers(self): x = GameController() p1 = Player("Mike") p2 = Player("John") x.Players = [p1, p2] table = x.DealHand() self.assertEqual(len(p1.Hand), 6) self.assertEqual(len(p2.Hand), 6) self.assertEqual(len(table['crib']), 0) self.assertIsInstance(table['cut'], Card)
def test_gc_check_game_bad_game(self): g = GameController() with self.assertRaises(ValueError): response_object = { "bulls": None, "cows": None, "analysis": None, "status": None } g.game = None g._check_game_on(response_object=response_object)
def test_DealHand_ThreePlayers(self): x = GameController() p1 = Player("Mike") p2 = Player("John") p3 = Player("Jim") x.Players = [p1, p2, p3] table = x.DealHand() self.assertEqual(len(p1.Hand), 5) self.assertEqual(len(p2.Hand), 5) self.assertEqual(len(p3.Hand), 5) self.assertEqual(len(table['crib']), 1) self.assertIsInstance(table['cut'], Card)
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_new_game_json_normal(self): json_string = '{' \ '"answer": [9, 6, 9, 4], ' \ '"guesses_made": 0, "ttl": 3600, ' \ '"status": "playing", ' \ '"key": "12345678-0123-abcd-1234-0987654321fe", ' \ '"mode": ' \ '{"help_text": ' \ '"This is the normal (default) game. You need to guess 4 ' \ 'digits in the right place and each digit must be a whole ' \ 'number between 0 and 9. There are 10 tries to guess the ' \ 'correct answer.", ' \ '"guesses_allowed": 10, ' \ '"instruction_text": ' \ '"Enter 4 digits, each digit between 0 and 9 (0, 1, 2, 3, 4, ' \ '5, 6, 7, 8, and 9).", ' \ '"digit_type": 0, ' \ '"priority": 2, ' \ '"digits": 4, ' \ '"mode": "Normal"}' \ '}' g = GameController(game_json=json_string, mode="Normal") self.assertEqual(g.game.key, "12345678-0123-abcd-1234-0987654321fe") self.assertEqual(g.game.guesses_remaining, 10) self.assertEqual(g.game.guesses_made, 0) self.assertEqual(g.game.answer.word, [9, 6, 9, 4])
def test_v1_get_modes_text(self): g = GameController() results = self.app.get('/v1/modes?textmode=true') required_modes = set(g.game_mode_names) actual_modes = set(json.loads(self._prepare_json_string(results.data))) self.assertTrue(required_modes <= actual_modes) self.assertTrue(results.status_code == 200)
def test_gc_load_game_modes(self): mode_list = [ GameMode( mode="test1", priority=5, ), GameMode( mode="test2", priority=6, ) ] g = GameController() g.load_modes(input_modes=mode_list) modes = g.game_mode_names self.assertTrue("test1" in modes) self.assertTrue("test2" in modes)
def get(self): logging.debug("GameModes: GET: Initializing GameObject") game_controller = GameController( game_modes=app.config["COWBULL_CUSTOM_MODES"], ) logging.debug("GameModes: GET: GameObject initialized to {}".format( game_controller.save())) logging.debug("GameModes: GET: Checking if textmode flag set") if request.args.get('textmode', None): logging.debug("GameModes: GET: Responding with list of names") response_data = game_controller.game_mode_names else: logging.debug( "GameModes: GET: Responding with JSON object: {}".format( game_controller.game_modes)) response_data = { "instructions": "Welcome to the CowBull game. The objective of this game " "is to guess a set of digits by entering a sequence of " "numbers. Each time you guess (there is a set number of " "tries to win), you will be provided with an analysis " "of your guesses.", "notes": "The modes can be different depending upon the game server that " "serves the game.", "default-mode": str(game_controller.default_mode), "modes": [{ "mode": gt.mode, "digits": gt.digits, "digit-type": gt.digit_type, "guesses": gt.guesses_allowed } for gt in game_controller.game_modes] } # response_data = [{"mode": gt.mode, # "digits": gt.digits, # "digit-type": gt.digit_type, # "guesses": gt.guesses_allowed # } for gt in game_object.game_modes] logging.debug("GameModes: GET: Return {}".format(response_data)) return build_response(html_status=200, response_data=response_data, response_mimetype="application/json")
def test_gc_load_bad_mode(self): json_string = '{' \ '"key": "12345678-0123-abcd-1234-0987654321fe", ' \ '"answer": [4, 0], ' \ '"smode": {' \ '"guesses_allowed": 2, ' \ '"digit_type": 0, ' \ '"priority": 5, ' \ '"mode": "test1", ' \ '"instruction_text": "None", ' \ '"help_text": "None", ' \ '"digits": 4' \ '}, ' \ '"guesses_made": 0, ' \ '"ttl": 3600, ' \ '"status": "playing"' \ '}' with self.assertRaises(ValueError): g = GameController() g._load_game(json_string)
def test_gc_new_game_modes(self): mode_list = [ GameMode( mode="test1", priority=5, ), GameMode( mode="test2", priority=6, ) ] g = GameController(game_modes=mode_list) modes = g.game_mode_names self.assertTrue("test1" in modes) self.assertTrue("test2" in modes) self.assertFalse("test3" in modes)
def _get_game(self, loaded_game, app): # # 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 # 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"])) return _game
def main(): # Create game controller object game_controller = GameController() # Create a test game controller object # game_controller = TestGameController() # Set up game game_controller.initial_setup() # Play game until win condition game_controller.game_loop()
def test_gc_new_game_json_test1(self): json_string = '{' \ '"key": "12345678-0123-abcd-1234-0987654321fe", ' \ '"answer": [4, 2, 0, 0], ' \ '"mode": {' \ '"guesses_allowed": 2, ' \ '"digit_type": 0, ' \ '"priority": 5, ' \ '"mode": "test1", ' \ '"instruction_text": "None", ' \ '"help_text": "None", ' \ '"digits": 4' \ '}, ' \ '"guesses_made": 0, ' \ '"ttl": 3600, ' \ '"status": "playing"' \ '}' g = GameController(game_json=json_string) self.assertEqual(g.game.key, "12345678-0123-abcd-1234-0987654321fe") self.assertEqual(g.game.guesses_remaining, 2) self.assertEqual(g.game.guesses_made, 0) self.assertEqual(g.game.answer.word, [4, 2, 0, 0])
def get(self): """ TBC :return: """ # # Set the error handler to default the module and method so that logging # calls can be more precise and easier to read. # self.handler.method = "get" self.handler.log(message='Processing GET request', status=0) # # Check if a game mode has been passed as a query parameter. If it has, # use it to create the game. If it hasn't, then let the game decide. # self.handler.log(message='Fetching arguments (if any) passed to get') game_mode = request.args.get('mode', default=None, type=None) self.handler.log("game_mode value from request.args.get: {}, type: {}".format(game_mode, type(game_mode))) try: self.handler.log(message="Creating game with mode {} ({})".format(game_mode, type(game_mode))) game_controller = GameController( game_modes=app.config["COWBULL_CUSTOM_MODES"], mode=game_mode ) self.handler.log(message='New game created with key {}'.format(game_controller.game.key), status=0) except ValueError as ve: return self.handler.error( status=400, exception="Invalid game mode", message="{}: game mode {}!".format(str(ve), game_mode) ) # Get a persistence engine. The persister is set in configuration # and dynamically loaded at the start of the transaction. See # Persistence/PersistenceEngine.py for more info. try: self.handler.log(message="Fetching persistence engine - {}".format(self.persistence_engine.engine_name)) persister = self.persistence_engine.persister self.handler.log(message='Persister instantiated', status=0) except ConnectionError as ce: return self.handler.error(status=503, exception=str(ce), message="There is no redis service available!") except AttributeError as ae: return self.handler.error(status=503, exception=str(ae), message="An internal error occurred - attribute missing for redis - check GameServerController:__init__") except Exception as e: return self.handler.error(status=500, exception=str(e), message="An internal error occurred - {}".format(repr(e))) # # Save the newly created game to the persistence engine # gen_error_msg = "The request raised an exception while trying to save a new game. " \ "Please try again shortly and the issue has been logged." self.handler.log(message="Saving game to persister") try: persister.save(game_controller.game.key, game_controller.save()) 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(game_controller.game.key), status=0) # # Build the user response - key, no. of digits, and no. of guesses # _response = { "key": game_controller.game.key, "mode": game_controller.game.mode.mode, "digits": game_controller.game.mode.digits, "digit-type": game_controller.game.mode.digit_type, "guesses": game_controller.game.mode.guesses_allowed, "served-by": socket.gethostname(), "help-text": game_controller.game.mode.help_text, "instruction-text": game_controller.game.mode.instruction_text } self.handler.log(message='GET request fulfilled. Returned: {}'.format(_response), status=0) return build_response( html_status=200, response_data=_response, response_mimetype="application/json" )
def test_gc_new_game_direct_default_mode(self): g = GameController() g._new_game(mode=None) self.assertEqual(g.game.mode.mode, g.find(0).mode)
def test_gc_new_game_direct(self): g = GameController() g._new_game(GameMode( mode="test1", priority=5, ))
def test_gc_mode_names(self): g = GameController() modes = g.game_mode_names self.assertIsInstance(modes, list)
def test_gc_load(self): g = GameController() g2 = GameController() g2.load(g.save()) self.assertEqual(g.save(), g2.save())
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_load_bad_json(self): json_string = '' with self.assertRaises(self.json_raises): GameController(game_json=json_string)
def test_gc_load_game_modes_badlist(self): mode_list = ["normal", "hard"] g = GameController() with self.assertRaises(TypeError): g.load_modes(input_modes=mode_list)
def test_gc_guess_once(self): g = GameController() r = g.guess(0, 0, 0, 0) bulls = r.get("bulls", None) self.assertIsNot(bulls, None)
def test_gc_check_game_bad_response(self): g = GameController() with self.assertRaises(ValueError): g._check_game_on(response_object=None)
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_new(self): g = GameController() self.assertIsInstance(g, GameController)
def test_gc_load_game(self): g = GameController() with self.assertRaises(TypeError): g._load_game({"gameid": 123})
def test_gc_new_badmode(self): with self.assertRaises(ValueError): GameController(mode="foobar")