Beispiel #1
0
    def test_buy_item_item_not_found(self):
        user = UserFactory(currency=150)
        self.db_session.commit()

        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().buy_item(user.id, 'random'))

        Session.remove()
        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 150)
        self.assertEqual(len(persisted_user_profile_items), 0)
    def test_set_user_profile_frame_color_invalid_color(self):
        user = UserFactory()
        self.test_session.commit()
        color = 'invalid color'

        with self.assertRaises(ValueError):
            asyncio.run(Profile().set_user_profile_frame_color(user.id, color))

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user.id).profile_frame_color,
            None)
Beispiel #3
0
    def test_buy_item_not_enough_currency(self):
        user = UserFactory(currency=150)
        profile_item = ProfileItemFactory(price=200)
        self.db_session.commit()

        with self.assertRaises(NotEnoughCredits):
            asyncio.run(Palplatina().buy_item(user.id, profile_item.name))

        Session.remove()
        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 150)
        self.assertEqual(len(persisted_user_profile_items), 0)
Beispiel #4
0
    def test_give_daily_not_clear_for_new_daily(self):
        user = UserFactory(currency=150,
                           daily_last_collected_at=datetime.utcnow())
        self.db_session.commit()

        result, user_actual = asyncio.run(Palplatina().give_daily(
            user.id, user.name))
        Session.remove()

        self.assertFalse(result)
        self.assertEqual(user_actual.currency, 150)
        self.assertEqual(
            self.db_session.query(User).get(user.id).currency, 150)
    def test_set_user_profile_frame_color_user_does_not_exist(self):
        user_id = 140
        color = '#f7b1d8'

        result = asyncio.run(Profile().set_user_profile_frame_color(
            user_id, color))

        self.assertEqual(result.id, user_id)
        self.assertEqual(result.profile_frame_color, color)

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user_id).profile_frame_color,
            color)
    def test_set_user_profile_frame_color_valid_color(self):
        user = UserFactory()
        self.test_session.commit()
        color = '#f7b1d8'

        result = asyncio.run(Profile().set_user_profile_frame_color(
            user.id, color))

        self.assertEqual(result.id, user.id)
        self.assertEqual(result.profile_frame_color, color)

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user.id).profile_frame_color,
            color)
Beispiel #7
0
    def test_give_daily_new_user(self):
        result, user = asyncio.run(Palplatina().give_daily(14, "name"))

        self.assertTrue(result)
        self.assertEqual(user.currency, 300)
        self.assertEqual(user.name, "name")
        self.assertEqual(Session().query(User).get(14).currency, 300)
Beispiel #8
0
    def test_unequip_item_user_has_item(self):
        user = UserFactory()
        profile_item = ProfileItemFactory()
        user.profile_items = [
            UserProfileItemFactory(equipped=True, profile_item=profile_item)
        ]
        self.db_session.commit()

        result = asyncio.run(Palplatina().unequip_item(user.id,
                                                       profile_item.name))

        self.assertFalse(result.equipped)

        Session.remove()
        fetched_user_profile_item = self.db_session.query(UserProfileItem).get(
            (user.id, profile_item.id))
        self.assertFalse(fetched_user_profile_item.equipped)
    def test_update_config_updates_existing_server_config(self):
        server_config = ServerConfigFactory(language='en')
        self.test_session.commit()

        new_server_language = 'pt'
        result = asyncio.run(
            cache.update_config(server_config.id,
                                language=new_server_language))
        Session.remove()

        self.assertIsInstance(result, ServerConfig)
        self.assertEqual(result.id, server_config.id)
        self.assertEqual(result.language, new_server_language)

        fetched_server_config = self.test_session.query(ServerConfig).get(
            server_config.id)
        self.assertEqual(fetched_server_config.id, server_config.id)
        self.assertEqual(fetched_server_config.language, new_server_language)
Beispiel #10
0
    def test_buy_item_success(self):
        user = UserFactory(currency=150)
        profile_item = ProfileItemFactory(price=100)
        self.db_session.commit()

        result = asyncio.run(Palplatina().buy_item(user.id, profile_item.name))
        Session.remove()

        self.assertIsInstance(result, User)
        self.assertEqual(result.currency, 50)
        self.assertEqual(result.profile_items[0].profile_item.id,
                         profile_item.id)

        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 50)
        self.assertEqual(len(persisted_user_profile_items), 1)
        self.assertEqual(persisted_user_profile_items[0].profile_item.id,
                         profile_item.id)
Beispiel #11
0
    def test_get_number_of_victories_no_xp_point(self):
        test_session = Session()
        user = User(id=14, name='Me')
        test_session.add(user)
        test_session.commit()

        result = asyncio.run(XpPoint.get_user_aggregated_points(user.id))

        self.assertIsNone(result)
    def test_get_number_of_victories_many_games(self):
        test_session = Session()
        user_1 = User(id=14, name='Me')
        user_2 = User(id=15, name='Them')
        chess_game_1 = ChessGame()
        chess_game_1.player1 = user_1
        chess_game_1.player2 = user_2
        chess_game_1.result = 1
        test_session.add(chess_game_1)
        chess_game_2 = ChessGame()
        chess_game_2.player1 = user_2
        chess_game_2.player2 = user_1
        chess_game_2.result = 1
        test_session.add(chess_game_2)
        chess_game_3 = ChessGame()
        chess_game_3.player1 = user_2
        chess_game_3.player2 = user_1
        chess_game_3.result = -1
        test_session.add(chess_game_3)
        test_session.commit()

        result = asyncio.run(ChessGame.get_number_of_victories(user_1.id))

        self.assertEqual(result, 2)
    def test_get_number_of_victories_no_games(self):
        test_session = Session()
        user_1 = User(id=14, name='Me')
        user_2 = User(id=15, name='Them')
        test_session.add(user_1)
        test_session.commit()

        result = asyncio.run(ChessGame.get_number_of_victories(user_1.id))

        self.assertEqual(result, 0)
Beispiel #14
0
    def test_get_number_of_victories_many_servers(self):
        test_session = Session()
        user = User(id=14, name='Me')
        xp_point_1 = XpPoint()
        xp_point_1.user = user
        xp_point_1.server_id = 10
        xp_point_1.points = 140
        test_session.add(xp_point_1)
        xp_point_2 = XpPoint()
        xp_point_2.user = user
        xp_point_2.server_id = 12
        xp_point_2.points = 260
        test_session.add(xp_point_2)
        test_session.commit()

        result = asyncio.run(XpPoint.get_user_aggregated_points(user.id))

        self.assertEqual(result, 400)
    def test_save_chart(self):
        user_id = 14
        astrology_chart = AstrologyChart()
        datetime = ('1997/08/10', '07:17', '-03:00')
        geopos = (-23.5506507, -46.6333824)
        chart = astrology_chart.calc_chart_raw(datetime, geopos)
        
        result_id = asyncio.run(astrology_chart.save_chart(user_id, chart))

        result = Session().query(AstrologyChartModel).get(result_id)
        self.assertIsNotNone(result)
        self.assertEqual(result.user_id, user_id)
        self.assertEqual(result.datetime.strftime(
            '%Y/%m/%d %H:%M'), f'{datetime[0]} {datetime[1]}') 
        self.assertEqual(result.timezone, '-03:00:00')
        self.assertEqual(result.latitude, geopos[0])
        self.assertEqual(result.longitude, geopos[1])
class TestPlanets(TestCase):
    def setUp(self):
        self.db_session = Session()

    def tearDown(self):
        clear_data(self.db_session)
        self.db_session.close()

    def test_list_of_planets_region_exists(self):
        for i in range(6):
            PlanetFactory(name='Planeta esperado' if i %
                          2 else 'Planeta não esperado',
                          region='Orla Exterior' if i % 2 else 'Núcleo')
        self.db_session.commit()

        result = asyncio.run(Planets().list_of_planets(region='Orla Exterior'))

        self.assertEqual(len(result), 3)
        self.assertEqual(result[0].name, 'Planeta esperado')
        self.assertEqual(result[1].name, 'Planeta esperado')
        self.assertEqual(result[2].name, 'Planeta esperado')

    def test_list_of_planets_region_does_not_exist(self):
        for i in range(6):
            PlanetFactory(region='Orla Exterior' if i % 2 else 'Núcleo')
        self.db_session.commit()

        result = asyncio.run(Planets().list_of_planets(region='Orla Média'))

        self.assertEqual(result, [])

    def test_list_of_planets_no_filters(self):
        for i in range(6):
            PlanetFactory()
        self.db_session.commit()

        result = asyncio.run(Planets().list_of_planets())

        self.assertEqual(len(result), 6)
    def test_save_profile_item(self):
        filename = 'wallpaper.png'
        with open(os.path.join('tests', 'support', filename), 'rb') as f:
            file_contents = f.read()

        profile_item = ProfileItem()
        profile_item.type = 'badge'
        profile_item.name = 'Some item'
        profile_item.price = 100

        expected_file_path = os.path.join('bot', 'images', 'profile_items',
                                          'badges', 'wallpaper.png')

        result = asyncio.run(Item().save_profile_item(profile_item, filename,
                                                      file_contents))

        self.assertIsNotNone(result)
        self.assertEqual(
            Session().query(ProfileItem).filter_by(id=result).count(), 1)
        self.assertTrue(os.path.exists(expected_file_path))
        with open(expected_file_path, 'rb') as f:
            self.assertEqual(f.read(), file_contents)
class TestProfile(TestCase):
    @classmethod
    def setUpClass(cls):
        load_dotenv()

    def setUp(self):
        self.test_session = Session()

    def tearDown(self):
        clear_data(self.test_session)
        self.test_session.close()

    def test_get_user_profile_all_available_fields(self):
        user_1 = UserFactory(name='My very long name')
        user_2 = UserFactory()
        chess_game_1 = ChessGameFactory(player1=user_1, result=1)
        xp_point_1 = XpPointFactory(user=user_1, points=140)
        self.test_session.commit()
        astrology_bot = AstrologyChart()
        datetime = ('1997/08/10', '07:17', '-03:00')
        geopos = (-23.5506507, -46.6333824)
        chart = astrology_bot.calc_chart_raw(datetime, geopos)
        asyncio.run(astrology_bot.save_chart(user_1.id, chart))
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(user_1.id,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        with open(
                os.path.join('tests', 'support',
                             'get_user_profile_all_fields.png'), 'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_get_user_profile_user_has_badges(self):
        user_1 = UserFactory(name='Name')
        profile_badge_1 = ProfileItemFactory(
            file_path=os.path.join("tests", "support", "badge1.png"))
        profile_badge_2 = ProfileItemFactory(
            file_path=os.path.join("tests", "support", "badge2.png"))
        profile_badge_3 = ProfileItemFactory(
            file_path=os.path.join("tests", "support", "badge3.png"))
        profile_badge_4 = ProfileItemFactory(
            file_path=os.path.join("tests", "support", "badge1.png"))
        user_1.profile_items = [
            UserProfileItemFactory(profile_item=profile_badge_1),
            UserProfileItemFactory(profile_item=profile_badge_2),
            UserProfileItemFactory(profile_item=profile_badge_3),
            UserProfileItemFactory(profile_item=profile_badge_4,
                                   equipped=False),
        ]
        self.test_session.commit()
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(user_1.id,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        with open(
                os.path.join('tests', 'support',
                             'get_user_profile_with_badges.png'), 'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_get_user_profile_user_has_wallpaper(self):
        user_1 = UserFactory(name='Name')
        profile_badge = ProfileItemFactory(type='wallpaper',
                                           file_path=os.path.join(
                                               "tests", "support",
                                               "wallpaper.png"))
        user_1.profile_items = [
            UserProfileItemFactory(profile_item=profile_badge),
        ]
        self.test_session.commit()
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(user_1.id,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        with open(
                os.path.join('tests', 'support',
                             'get_user_profile_with_wallpaper.png'),
                'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_get_user_profile_user_has_profile_frame_color(self):
        user_1 = UserFactory(name='Name', profile_frame_color='#cccccc')
        self.test_session.commit()
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(user_1.id,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        with open(
                os.path.join('tests', 'support',
                             'get_user_profile_with_frame_color.png'),
                'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_get_user_profile_user_exists_no_info(self):
        user_1 = UserFactory(name='Name')
        self.test_session.commit()
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(user_1.id,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        with open(
                os.path.join('tests', 'support',
                             'get_user_profile_no_info.png'), 'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_get_user_profile_no_user(self):
        with open(os.path.join('tests', 'support', 'user_avatar.png'),
                  'rb') as f:
            user_avatar_bytes = f.read()

        result = asyncio.run(Profile().get_user_profile(14,
                                                        user_avatar_bytes,
                                                        lang='pt'))

        self.assertIsNone(result)

    def test_set_user_profile_frame_color_valid_color(self):
        user = UserFactory()
        self.test_session.commit()
        color = '#f7b1d8'

        result = asyncio.run(Profile().set_user_profile_frame_color(
            user.id, color))

        self.assertEqual(result.id, user.id)
        self.assertEqual(result.profile_frame_color, color)

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user.id).profile_frame_color,
            color)

    def test_set_user_profile_frame_color_invalid_color(self):
        user = UserFactory()
        self.test_session.commit()
        color = 'invalid color'

        with self.assertRaises(ValueError):
            asyncio.run(Profile().set_user_profile_frame_color(user.id, color))

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user.id).profile_frame_color,
            None)

    def test_set_user_profile_frame_color_user_does_not_exist(self):
        user_id = 140
        color = '#f7b1d8'

        result = asyncio.run(Profile().set_user_profile_frame_color(
            user_id, color))

        self.assertEqual(result.id, user_id)
        self.assertEqual(result.profile_frame_color, color)

        Session.remove()
        self.assertEqual(
            self.test_session.query(User).get(user_id).profile_frame_color,
            color)
class TestServers(TestCase):
    @classmethod
    def setUpClass(cls):
        load_dotenv()

    def setUp(self):
        self.test_session = Session()
        cache.server_configs = {}

    def tearDown(self):
        clear_data(self.test_session)
        self.test_session.close()

    def test_load_configs(self):
        server_config_1 = ServerConfigFactory(language='en')
        server_config_2 = ServerConfigFactory(language='jp')
        server_config_3 = ServerConfigFactory(language='pt')
        server_config_3.autoreply_configs = [ServerConfigAutoreplyFactory()]
        self.test_session.commit()

        self.assertEqual(cache.server_configs, {})

        result = asyncio.run(cache.load_configs())

        self.assertIsNone(result)
        self.assertIn(server_config_1.id, cache.server_configs)
        self.assertIn(server_config_2.id, cache.server_configs)
        self.assertIn(server_config_3.id, cache.server_configs)

        self.assertEqual(
            cache.server_configs.get(server_config_1.id).id,
            server_config_1.id)
        self.assertEqual(
            cache.server_configs.get(server_config_2.id).id,
            server_config_2.id)
        self.assertEqual(
            cache.server_configs.get(server_config_3.id).id,
            server_config_3.id)

        server_config_3_autoreply_config = cache.server_configs.get(
            server_config_3.id).autoreply_configs
        self.assertEqual(len(server_config_3_autoreply_config), 1)
        self.assertEqual(server_config_3_autoreply_config[0].server_config_id,
                         server_config_3.id)

    def test_get_config_server_config_exists(self):
        server_config_1 = ServerConfigFactory()
        cache.server_configs = {server_config_1.id: server_config_1}

        result = cache.get_config(server_config_1.id)

        self.assertEqual(result, server_config_1)

    def test_get_config_server_config_does_not_exist(self):
        result = cache.get_config(10)

        self.assertIsNone(result)

    def test_update_config_creates_new_server_config(self):
        server_id = 14
        server_language = 'pt'
        result = asyncio.run(
            cache.update_config(server_id, language=server_language))

        self.assertIsInstance(result, ServerConfig)
        self.assertEqual(result.id, server_id)
        self.assertEqual(result.language, server_language)
        self.assertEqual(result.autoreply_configs, [])

        fetched_server_config = self.test_session.query(ServerConfig).first()
        self.assertEqual(fetched_server_config.id, server_id)
        self.assertEqual(fetched_server_config.language, server_language)

    def test_update_config_updates_existing_server_config(self):
        server_config = ServerConfigFactory(language='en')
        self.test_session.commit()

        new_server_language = 'pt'
        result = asyncio.run(
            cache.update_config(server_config.id,
                                language=new_server_language))
        Session.remove()

        self.assertIsInstance(result, ServerConfig)
        self.assertEqual(result.id, server_config.id)
        self.assertEqual(result.language, new_server_language)

        fetched_server_config = self.test_session.query(ServerConfig).get(
            server_config.id)
        self.assertEqual(fetched_server_config.id, server_config.id)
        self.assertEqual(fetched_server_config.language, new_server_language)

    def test_get_autoreply_to_message_message_starts_with(self):
        server_config = ServerConfigFactory()
        server_config_autoreply_starts_with = ServerConfigAutoreplyFactory(
            message_regex='^hello')
        server_config_autoreply_ends_with = ServerConfigAutoreplyFactory(
            message_regex='.*bye$')
        server_config_autoreply_has = ServerConfigAutoreplyFactory(
            message_regex='.*wait.*')
        server_config.autoreply_configs = [
            server_config_autoreply_starts_with,
            server_config_autoreply_ends_with, server_config_autoreply_has
        ]
        cache.server_configs = {server_config.id: server_config}

        result = cache.get_autoreply_to_message(server_config.id,
                                                'hello there')

        self.assertIsNotNone(result)
        self.assertEqual(result.id, server_config_autoreply_starts_with.id)

    def test_get_autoreply_to_message_message_ends_with(self):
        server_config = ServerConfigFactory()
        server_config_autoreply_starts_with = ServerConfigAutoreplyFactory(
            message_regex='^hello')
        server_config_autoreply_ends_with = ServerConfigAutoreplyFactory(
            message_regex='.*bye$')
        server_config_autoreply_has = ServerConfigAutoreplyFactory(
            message_regex='.*wait.*')
        server_config.autoreply_configs = [
            server_config_autoreply_starts_with,
            server_config_autoreply_ends_with, server_config_autoreply_has
        ]
        cache.server_configs = {server_config.id: server_config}

        result = cache.get_autoreply_to_message(server_config.id, 'ok, bye')

        self.assertIsNotNone(result)
        self.assertEqual(result.id, server_config_autoreply_ends_with.id)

    def test_get_autoreply_to_message_message_has(self):
        server_config = ServerConfigFactory()
        server_config_autoreply_starts_with = ServerConfigAutoreplyFactory(
            message_regex='^hello')
        server_config_autoreply_ends_with = ServerConfigAutoreplyFactory(
            message_regex='.*bye$')
        server_config_autoreply_has = ServerConfigAutoreplyFactory(
            message_regex='.*wait.*')
        server_config.autoreply_configs = [
            server_config_autoreply_starts_with,
            server_config_autoreply_ends_with, server_config_autoreply_has
        ]
        cache.server_configs = {server_config.id: server_config}

        result = cache.get_autoreply_to_message(server_config.id,
                                                'please, wait for me')

        self.assertIsNotNone(result)
        self.assertEqual(result.id, server_config_autoreply_has.id)

    def test_get_autoreply_to_message_no_match(self):
        server_config = ServerConfigFactory()
        server_config_autoreply_starts_with = ServerConfigAutoreplyFactory(
            message_regex='^hello')
        server_config_autoreply_ends_with = ServerConfigAutoreplyFactory(
            message_regex='.*bye$')
        server_config_autoreply_has = ServerConfigAutoreplyFactory(
            message_regex='.*wait.*')
        server_config.autoreply_configs = [
            server_config_autoreply_starts_with,
            server_config_autoreply_ends_with, server_config_autoreply_has
        ]
        cache.server_configs = {server_config.id: server_config}

        result = cache.get_autoreply_to_message(server_config.id, 'nopee')

        self.assertIsNone(result)

    def test_get_reply(self):
        server_config = ServerConfigFactory()
        server_config_autoreply = ServerConfigAutoreplyFactory(
            message_regex='tão sábi(\\w) (.*)',
            reply='Já ouviu a história de Darth \\2, \\1 sábi\\1?')
        server_config.autoreply_configs = [server_config_autoreply]
        message = 'Tão sábia Lele'

        result = server_config_autoreply.get_reply(message)

        self.assertEqual(result, 'Já ouviu a história de Darth Lele, a sábia?')
Beispiel #20
0
 def tearDown(self):
     clear_data(self.db_session)
     self.db_session.close()
     Session.remove()
 def setUp(self):
     self.test_session = Session()
     cache.server_configs = {}
Beispiel #22
0
 def setUp(self):
     self.db_session = Session()
Beispiel #23
0
class TestPalplatina(TestCase):
    @classmethod
    def setUpClass(cls):
        load_dotenv()

    def setUp(self):
        self.db_session = Session()

    def tearDown(self):
        clear_data(self.db_session)
        self.db_session.close()
        Session.remove()

    def test_give_daily_clear_for_new_daily(self):
        user = UserFactory(currency=150,
                           daily_last_collected_at=datetime.utcnow() -
                           timedelta(days=1))
        self.db_session.commit()

        result, user_actual = asyncio.run(Palplatina().give_daily(
            user.id, user.name))
        Session.remove()

        self.assertTrue(result)
        self.assertEqual(user_actual.currency, 450)
        self.assertEqual(
            self.db_session.query(User).get(user.id).currency, 450)

    def test_give_daily_new_user(self):
        result, user = asyncio.run(Palplatina().give_daily(14, "name"))

        self.assertTrue(result)
        self.assertEqual(user.currency, 300)
        self.assertEqual(user.name, "name")
        self.assertEqual(Session().query(User).get(14).currency, 300)

    def test_give_daily_not_clear_for_new_daily(self):
        user = UserFactory(currency=150,
                           daily_last_collected_at=datetime.utcnow())
        self.db_session.commit()

        result, user_actual = asyncio.run(Palplatina().give_daily(
            user.id, user.name))
        Session.remove()

        self.assertFalse(result)
        self.assertEqual(user_actual.currency, 150)
        self.assertEqual(
            self.db_session.query(User).get(user.id).currency, 150)

    def test_get_currency_user_exists(self):
        user = UserFactory(currency=150)
        self.db_session.commit()

        result = asyncio.run(Palplatina().get_currency(user.id))

        self.assertEqual(result, 150)

    def test_get_currency_user_doesnt_exist(self):
        result = asyncio.run(Palplatina().get_currency(14))

        self.assertEqual(result, 0)

    def test_buy_item_success(self):
        user = UserFactory(currency=150)
        profile_item = ProfileItemFactory(price=100)
        self.db_session.commit()

        result = asyncio.run(Palplatina().buy_item(user.id, profile_item.name))
        Session.remove()

        self.assertIsInstance(result, User)
        self.assertEqual(result.currency, 50)
        self.assertEqual(result.profile_items[0].profile_item.id,
                         profile_item.id)

        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 50)
        self.assertEqual(len(persisted_user_profile_items), 1)
        self.assertEqual(persisted_user_profile_items[0].profile_item.id,
                         profile_item.id)

    def test_buy_item_not_enough_currency(self):
        user = UserFactory(currency=150)
        profile_item = ProfileItemFactory(price=200)
        self.db_session.commit()

        with self.assertRaises(NotEnoughCredits):
            asyncio.run(Palplatina().buy_item(user.id, profile_item.name))

        Session.remove()
        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 150)
        self.assertEqual(len(persisted_user_profile_items), 0)

    def test_buy_item_item_already_bought(self):
        profile_item = ProfileItemFactory()
        user = UserFactory(currency=150)
        user.profile_items = [
            UserProfileItemFactory(profile_item=profile_item)
        ]
        self.db_session.commit()

        with self.assertRaises(AlreadyOwnsItem):
            asyncio.run(Palplatina().buy_item(user.id, profile_item.name))

        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 150)
        self.assertEqual(len(persisted_user_profile_items), 1)
        self.assertEqual(persisted_user_profile_items[0].profile_item.id,
                         profile_item.id)

    def test_buy_item_item_not_found(self):
        user = UserFactory(currency=150)
        self.db_session.commit()

        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().buy_item(user.id, 'random'))

        Session.remove()
        persisted_user = self.db_session.query(User).get(user.id)
        persisted_user_profile_items = persisted_user.profile_items
        self.assertEqual(persisted_user.currency, 150)
        self.assertEqual(len(persisted_user_profile_items), 0)

    def test_buy_item_user_not_found(self):
        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().buy_item(14, 'random'))

    def test_get_available_items(self):
        ProfileItemFactory.reset_sequence()
        for i in range(12):
            ProfileItemFactory()
        for i in range(12):
            ProfileItemFactory(name=f'No match {i}')
        self.db_session.commit()

        result = asyncio.run(Palplatina().get_available_items('Profile item',
                                                              page=0))

        self.assertEqual(len(result), 2)
        self.assertEqual(len(result[0]), 9)
        self.assertEqual(result[1], 2)
        fetched_items_names = [item.name for item in result[0]]
        self.assertIn('Profile item 0', fetched_items_names)
        self.assertIn('Profile item 8', fetched_items_names)
        self.assertNotIn('Profile item 9', fetched_items_names)
        self.assertNotIn('Profile item 11', fetched_items_names)

    def test_get_user_items_user_has_items(self):
        user = UserFactory()
        ProfileItemFactory.reset_sequence()
        for i in range(2):
            profile_item = ProfileItemFactory()
            user.profile_items.append(
                UserProfileItemFactory(profile_item=profile_item))
        another_profile_item = ProfileItemFactory()
        self.db_session.commit()

        result = asyncio.run(Palplatina().get_user_items(user.id))

        self.assertEqual(len(result), 2)
        fetched_items_names = [item.profile_item.name for item in result]
        self.assertIn('Profile item 0', fetched_items_names)
        self.assertIn('Profile item 1', fetched_items_names)
        self.assertNotIn(another_profile_item.name, fetched_items_names)

    def test_get_user_items_user_has_no_items(self):
        user = UserFactory()
        self.db_session.commit()

        result = asyncio.run(Palplatina().get_user_items(user.id))

        self.assertEqual(len(result), 0)

    def test_get_user_items_user_not_found(self):
        result = asyncio.run(Palplatina().get_user_items(14))

        self.assertEqual(len(result), 0)

    def test_get_item_item_exists(self):
        profile_item = ProfileItemFactory()
        self.db_session.commit()

        result = asyncio.run(Palplatina().get_item(profile_item.name))

        self.assertEqual(result.id, profile_item.id)

    def test_get_item_item_does_not_exist(self):
        result = asyncio.run(Palplatina().get_item("item"))

        self.assertIsNone(result)

    def test_equip_item_user_has_item(self):
        user = UserFactory()
        profile_item = ProfileItemFactory()
        user.profile_items = [
            UserProfileItemFactory(equipped=False, profile_item=profile_item)
        ]
        self.db_session.commit()

        result = asyncio.run(Palplatina().equip_item(user.id,
                                                     profile_item.name))

        self.assertTrue(result.equipped)

        Session.remove()
        fetched_user_profile_item = self.db_session.query(UserProfileItem).get(
            (user.id, profile_item.id))
        self.assertTrue(fetched_user_profile_item.equipped)

    def test_equip_item_user_does_not_have_item(self):
        user = UserFactory()
        self.db_session.commit()

        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().equip_item(user.id, 'some item'))

    def test_equip_item_user_does_not_exist(self):
        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().equip_item(140, 'some item'))

    def test_unequip_item_user_has_item(self):
        user = UserFactory()
        profile_item = ProfileItemFactory()
        user.profile_items = [
            UserProfileItemFactory(equipped=True, profile_item=profile_item)
        ]
        self.db_session.commit()

        result = asyncio.run(Palplatina().unequip_item(user.id,
                                                       profile_item.name))

        self.assertFalse(result.equipped)

        Session.remove()
        fetched_user_profile_item = self.db_session.query(UserProfileItem).get(
            (user.id, profile_item.id))
        self.assertFalse(fetched_user_profile_item.equipped)

    def test_unequip_item_user_does_not_have_item(self):
        user = UserFactory()
        self.db_session.commit()

        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().unequip_item(user.id, 'some item'))

    def test_unequip_item_user_does_not_exist(self):
        with self.assertRaises(ItemNotFound):
            asyncio.run(Palplatina().unequip_item(140, 'some item'))
 def tearDown(self):
     os.remove(
         os.path.join('bot', 'images', 'profile_items', 'badges',
                      'wallpaper.png'))
     clear_data(Session())
class TestChess(TestCase):
    @classmethod
    def setUpClass(cls):
        load_dotenv()

    def setUp(self):
        self.db_session = Session()

    def tearDown(self):
        clear_data(self.db_session)
        self.db_session.close()

    def test_load_games_entries_exist(self):
        warnings.simplefilter('ignore')
        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.board = board1
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        asyncio.run(game1.save())
        board2 = chess.Board()
        board2.push_san("Nf3")
        game2 = Game()
        game2.board = board2
        game2.player1 = FakeDiscordUser(id=2)
        game2.player2 = FakeDiscordUser(id=3)
        asyncio.run(game2.save())
        game3 = Game()
        game3.board = chess.Board(
            'rnbqkbnr/ppppp2p/8/5ppQ/4P3/2N5/PPPP1PPP/R1B1KBNR b KQkq - 0 1')
        game3.player1 = FakeDiscordUser(id=2)
        game3.player2 = FakeDiscordUser(id=3)
        game3.result = '1-0'
        asyncio.run(game3.save())

        expected_games = [game1, game2]

        chess_bot = Chess()

        actual = asyncio.run(chess_bot.load_games())

        self.assertListEqual(expected_games, actual)

    def test_load_games_no_entries_exist(self):
        chess_bot = Chess()

        actual = asyncio.run(chess_bot.load_games())

        self.assertEqual([], actual)

    def test_new_game_new_players(self):
        player1 = FakeDiscordUser(id=1)
        player2 = FakeDiscordUser(id=2)

        chess_bot = Chess()
        result = chess_bot.new_game(player1, player2)
        games = chess_bot.games

        self.assertIsInstance(result, Game)
        self.assertEqual(len(games), 1)
        self.assertIn(result, games)
        self.assertEqual(result.player1, player1)
        self.assertEqual(result.player2, player2)
        self.assertEqual(result.board.move_stack, [])
        self.assertIsNone(result.color_schema)

    def test_new_game_with_color_schema(self):
        player1 = FakeDiscordUser(id=1)
        player2 = FakeDiscordUser(id=2)
        color_schema = "blue"

        chess_bot = Chess()
        result = chess_bot.new_game(player1,
                                    player2,
                                    color_schema=color_schema)
        games = chess_bot.games

        self.assertIsInstance(result, Game)
        self.assertEqual(len(games), 1)
        self.assertIn(result, games)
        self.assertEqual(result.player1, player1)
        self.assertEqual(result.player2, player2)
        self.assertEqual(result.board.move_stack, [])
        self.assertEqual(result.color_schema, color_schema)

    def test_new_game_pve(self):
        player1 = FakeDiscordUser(id=1)

        chess_bot = Chess()
        result = chess_bot.new_game(player1, None, cpu_level=5)
        games = chess_bot.games

        self.assertIsInstance(result, Game)
        self.assertEqual(len(games), 1)
        self.assertIn(result, games)
        self.assertEqual(result.player1, player1)
        self.assertEqual(result.player2, None)
        self.assertEqual(result.board.move_stack, [])
        self.assertEqual(result.cpu_level, 5)
        self.assertIsNone(result.color_schema)

    def test_new_game_game_already_started(self):
        game = Game()
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)

        chess_bot = Chess()
        chess_bot.games.append(game)

        with self.assertRaises(GameAlreadyInProgress):
            chess_bot.new_game(game.player1, game.player2)

        self.assertEqual(len(chess_bot.games), 1)

    def test_find_current_game_in_players_turn_no_ambiguity(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)

        result = chess_bot.find_current_game(user=game.player1)

        self.assertEqual(result, game)

    def test_find_current_game_in_players_turn_with_amibiguity(self):
        chess_bot = Chess()

        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game1 = Game()
        game1.board = board
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        game1.current_player = game1.player1
        chess_bot.games.append(game1)

        game2 = Game()
        game2.board = board
        game2.player1 = FakeDiscordUser(id=1)
        game2.player2 = FakeDiscordUser(id=3)
        game2.current_player = game2.player1
        chess_bot.games.append(game2)

        with self.assertRaises(Exception) as e:
            chess_bot.find_current_game(user=game1.player1)

            self.assertIn("Informe contra qual jogador", str(e))

    def test_find_current_game_in_players_turn_amibiguity_solved(self):
        chess_bot = Chess()

        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game1 = Game()
        game1.board = board
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        game1.current_player = game1.player1
        chess_bot.games.append(game1)

        game2 = Game()
        game2.board = board
        game2.player1 = FakeDiscordUser(id=1)
        game2.player2 = FakeDiscordUser(id=3)
        game2.current_player = game2.player1
        chess_bot.games.append(game2)

        result = chess_bot.find_current_game(user=game1.player1,
                                             other_user=game1.player2)

        self.assertEqual(result, game1)

    def test_find_current_game_player_playing_themselves_and_others(self):
        chess_bot = Chess()

        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game1 = Game()
        game1.board = board
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        game1.current_player = game1.player1
        chess_bot.games.append(game1)

        game2 = Game()
        game2.board = board
        game2.player1 = FakeDiscordUser(id=1)
        game2.player2 = FakeDiscordUser(id=1)
        game2.current_player = game2.player1
        chess_bot.games.append(game2)

        result = chess_bot.find_current_game(user=game2.player1,
                                             other_user=game2.player2)

        self.assertEqual(result, game2)

    def test_find_current_game_player_not_playing(self):
        chess_bot = Chess()

        with self.assertRaises(Exception) as e:
            chess_bot.find_current_game(user=FakeDiscordUser(id=3))

            self.assertIn("não é mais seu turno", str(e))

    def test_find_current_game_other_player_not_found(self):
        chess_bot = Chess()

        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game1 = Game()
        game1.board = board
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        game1.current_player = game1.player1
        chess_bot.games.append(game1)

        game2 = Game()
        game2.board = board
        game2.player1 = FakeDiscordUser(id=1)
        game2.player2 = FakeDiscordUser(id=3)
        game2.current_player = game2.player1
        chess_bot.games.append(game2)

        with self.assertRaises(Exception) as e:
            chess_bot.find_current_game(user=FakeDiscordUser(id=14))

            self.assertIn("Partida não encontrada", str(e))

    def test_make_move_legal_uci_move_in_players_turn(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.make_move(game, 'g1f3'))

        self.assertIsInstance(result, Game)
        self.assertEqual(len(result.board.move_stack), 3)
        self.assertEqual(result.current_player, game.player2)

        updated_chess_game = self.db_session.query(ChessGame).filter_by(
            player1_id=result.player1.id).first()
        updated_game_from_db = Game.from_chess_game_model(updated_chess_game)
        self.assertEqual(updated_game_from_db.board.move_stack,
                         result.board.move_stack)

    def test_make_move_legal_san_move_in_players_turn(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.make_move(game, 'Nf3'))

        self.assertIsInstance(result, Game)
        self.assertEqual(len(result.board.move_stack), 3)
        self.assertEqual(result.current_player, game.player2)

        updated_chess_game = self.db_session.query(ChessGame).filter_by(
            player1_id=result.player1.id).first()
        updated_game_from_db = Game.from_chess_game_model(updated_chess_game)
        self.assertEqual(updated_game_from_db.board.move_stack,
                         result.board.move_stack)

    def test_make_move_finish_game(self):
        board = chess.Board()
        board.push_san("g4")
        board.push_san("e5")
        board.push_san("f4")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.make_move(game, 'd8h4'))

        self.assertIsInstance(result, Game)
        self.assertEqual(len(chess_bot.games), 0)
        self.assertEqual(
            self.db_session.query(ChessGame).filter_by(result=-1).count(), 1)
        self.assertTrue(chess_bot.is_game_over(result))
        self.assertEqual(result.result, '0-1')

    def test_make_move_legal_move_pve(self):
        board = chess.Board(
            'rn2kb1r/pp1qpppp/2ppbn2/1B6/3PP3/2N2N2/PPP2PPP/R1BQK2R w KQkq - 0 6'
        )
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.cpu_level = 0

        chess_bot = Chess()
        chess_bot.games.append(game)
        chess_bot.stockfish_limit['time'] = 1
        result = asyncio.run(chess_bot.make_move(game, 'b5d3'))

        self.assertIsInstance(result, Game)
        if chess_bot.is_stockfish_enabled():
            self.assertEqual(len(result.board.move_stack), 2)
            self.assertEqual(result.current_player, game.player1)

        updated_chess_game = self.db_session.query(ChessGame).filter_by(
            player1_id=result.player1.id).first()
        updated_game_from_db = Game.from_chess_game_model(updated_chess_game)
        self.assertEqual(updated_game_from_db.board.move_stack,
                         result.board.move_stack)

    def test_make_move_finish_game_pve_player_loses(self):
        board = chess.Board()
        board.push_san("g4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.cpu_level = 20

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.make_move(game, 'f4'))

        self.assertIsInstance(result, Game)
        if chess_bot.is_stockfish_enabled():
            self.assertEqual(len(chess_bot.games), 0)
            self.assertEqual(
                self.db_session.query(ChessGame).filter_by(result=-1).count(),
                1)
            self.assertTrue(chess_bot.is_game_over(result))
            self.assertEqual(result.result, '0-1')

    def test_make_move_finish_game_pve_player_wins(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("g5")
        board.push_san("d4")
        board.push_san("f5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.cpu_level = 20

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.make_move(game, 'Qh5'))

        self.assertIsInstance(result, Game)
        self.assertEqual(len(chess_bot.games), 0)
        self.assertEqual(
            self.db_session.query(ChessGame).filter_by(result=1).count(), 1)
        self.assertTrue(chess_bot.is_game_over(result))
        self.assertEqual(result.result, '1-0')

    def test_make_move_illegal_move_in_players_turn(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)

        with self.assertRaises(InvalidMove) as e:
            asyncio.run(chess_bot.make_move(game, 'invalid'))

        self.assertEqual(len(game.board.move_stack), 2)
        self.assertEqual(game.current_player, game.player1)

    def test_make_move_draw_by_threefold_repetition(self):
        board = chess.Board()
        board.push_san("Nf3")
        board.push_san("Nf6")
        board.push_san("Ng1")
        board.push_san("Ng8")
        board.push_san("Nf3")
        board.push_san("Nf6")
        board.push_san("Ng1")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player2

        chess_bot = Chess()
        chess_bot.games.append(game)

        self.assertFalse(chess_bot.is_game_over(game))

        result = asyncio.run(chess_bot.make_move(game, 'Ng8'))

        self.assertIsInstance(result, Game)
        self.assertEqual(len(chess_bot.games), 0)
        self.assertEqual(
            self.db_session.query(ChessGame).filter_by(result=0).count(), 1)
        self.assertTrue(chess_bot.is_game_over(result))
        self.assertEqual(result.result, '1/2-1/2')

    def test_resign_game_found(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("e5")
        board.push_san("Nf3")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.resign(game))

        self.assertEqual(len(chess_bot.games), 0)
        self.assertEqual(
            self.db_session.query(ChessGame).filter_by(result=1).count(), 1)

    def test_save_games(self):
        chess_bot = Chess()
        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.board = board1
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        asyncio.run(game1.save())
        board2 = chess.Board()
        board2.push_san("Nf3")
        game2 = Game()
        game2.board = board2
        game2.player1 = FakeDiscordUser(id=2)
        game2.player2 = FakeDiscordUser(id=3)
        chess_bot.games = [game1, game2]

        asyncio.run(chess_bot.save_games())

        expected = [
            Game.from_chess_game_model(x)
            for x in self.db_session.query(ChessGame)
        ]

        self.assertEqual(chess_bot.games, expected)
        self.assertEqual(game1.color_schema, expected[0].color_schema)
        self.assertEqual(game1.cpu_level, expected[0].cpu_level)
        self.assertEqual(game2.color_schema, expected[1].color_schema)
        self.assertEqual(game2.cpu_level, expected[1].cpu_level)

    def test_generate_pgn(self):
        board = chess.Board()
        board.push_san("g4")
        board.push_san("e5")
        board.push_san("f4")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1, name='Player1')
        game.player2 = FakeDiscordUser(id=2, name='Player2')
        game.current_player = game.player1
        game.result = game.board.result()

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = chess_bot.generate_pgn(game)

        self.assertIn('[White "Player1"]', result)
        self.assertIn('[Black "Player2"]', result)
        self.assertIn('1. g4 e5 2. f4 *', result)

    def test_get_all_boards_png_one_game(self):
        chess_bot = Chess()

        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        board1.push_san("Bc4")
        game1 = Game()
        game1.color_schema = "green"
        game1.board = board1
        chess_bot.games.append(game1)

        image_bytesio = asyncio.run(chess_bot.get_all_boards_png())

        with open(
                os.path.join('tests', 'support',
                             'get_all_boards_png_one_game.png'), 'rb') as f:
            self.assertEqual(image_bytesio.read(), f.read())

    def test_get_all_boards_png_three_games(self):
        chess_bot = Chess()

        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.color_schema = "blue"
        game1.board = board1
        chess_bot.games.append(game1)

        board2 = chess.Board()
        board2.push_san("Nf3")
        board2.push_san("d6")
        game2 = Game()
        game2.color_schema = "wood"
        game2.board = board2
        chess_bot.games.append(game2)

        board3 = chess.Board()
        board3.push_san("Nf3")
        game3 = Game()
        game3.color_schema = "green"
        game3.board = board3
        chess_bot.games.append(game3)

        image_bytesio = asyncio.run(chess_bot.get_all_boards_png())

        with open(
                os.path.join('tests', 'support',
                             'get_all_boards_png_three_games.png'), 'rb') as f:
            self.assertEqual(image_bytesio.read(), f.read())

    def test_get_all_boards_png_no_twelve_games(self):
        chess_bot = Chess()

        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.color_schema = "blue"
        game1.board = board1
        chess_bot.games.append(game1)

        board2 = chess.Board()
        board2.push_san("Nf3")
        board2.push_san("d6")
        game2 = Game()
        game2.color_schema = "wood"
        game2.board = board2
        chess_bot.games.append(game2)

        board3 = chess.Board()
        board3.push_san("Nf3")
        game3 = Game()
        game3.color_schema = "green"
        game3.board = board3
        chess_bot.games.append(game3)

        for i in range(3):
            chess_bot.games.append(game1)
            chess_bot.games.append(game2)
            chess_bot.games.append(game3)

        image_bytesio = asyncio.run(chess_bot.get_all_boards_png())

        with open(
                os.path.join('tests', 'support',
                             'get_all_boards_png_twelve_games.png'),
                'rb') as f:
            self.assertEqual(image_bytesio.read(), f.read())

    def test_get_all_boards_png_no_twelve_games_second_page(self):
        chess_bot = Chess()

        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.color_schema = "blue"
        game1.board = board1
        chess_bot.games.append(game1)

        board2 = chess.Board()
        board2.push_san("Nf3")
        board2.push_san("d6")
        game2 = Game()
        game2.color_schema = "wood"
        game2.board = board2
        chess_bot.games.append(game2)

        board3 = chess.Board()
        board3.push_san("Nf3")
        game3 = Game()
        game3.color_schema = "green"
        game3.board = board3
        chess_bot.games.append(game3)

        for i in range(3):
            chess_bot.games.append(game1)
            chess_bot.games.append(game2)
            chess_bot.games.append(game3)

        image_bytesio = asyncio.run(chess_bot.get_all_boards_png(page=2),
                                    debug=True)

        with open(
                os.path.join(
                    'tests', 'support',
                    'get_all_boards_png_twelve_games_second_page.png'),
                'rb') as f:
            self.assertEqual(image_bytesio.read(), f.read())

    def test_get_all_boards_png_no_games_being_played(self):
        chess_bot = Chess()

        image_bytesio = asyncio.run(chess_bot.get_all_boards_png())

        self.assertIsNone(image_bytesio)

    def test_is_pve_game_pve_game(self):
        game = Game()
        game.cpu_level = 0

        chess_bot = Chess()
        chess_bot.stockfish_path = "valid"
        chess_bot.games.append(game)

        self.assertTrue(chess_bot.is_pve_game(game))

    def test_is_pve_game_pvp_game(self):
        game = Game()
        game.cpu_level = None

        chess_bot = Chess()
        chess_bot.stockfish_path = "valid"
        chess_bot.games.append(game)

        self.assertFalse(chess_bot.is_pve_game(game))

    def test_is_pve_game_stockfish_disabled(self):
        game = Game()
        game.cpu_level = 0

        chess_bot = Chess()
        chess_bot.stockfish_path = ""
        chess_bot.games.append(game)

        self.assertFalse(chess_bot.is_pve_game(game))

    def test_eval_last_move_last_move_blunder_mate_in_one(self):
        board = chess.Board()
        board.push_san("g4")
        board.push_san("e5")
        board.push_san("f4")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Cp(0)

        chess_bot = Chess()
        chess_bot.games.append(game)
        result = asyncio.run(chess_bot.eval_last_move(game))

        if chess_bot.is_stockfish_enabled():
            self.assertTrue(result["blunder"])
            self.assertEqual(result["mate_in"], 1)
        else:
            self.assertFalse(result["blunder"])
            self.assertIsNone(result["mate_in"])

    def test_eval_last_move_no_blunder_no_mate(self):
        board = chess.Board()
        board.push_san("g4")
        board.push_san("e5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Cp(0)

        chess_bot = Chess()
        chess_bot.games.append(game)
        chess_bot.stockfish_limit["time"] = 2

        result = asyncio.run(chess_bot.eval_last_move(game))

        self.assertFalse(result["blunder"])
        self.assertIsNone(result["mate_in"])

    def test_eval_last_move_blunder_no_mate(self):
        board = chess.Board()
        board.push_san("e4")
        board.push_san("Nf6")
        board.push_san("Qh5")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Cp(0)

        chess_bot = Chess()
        chess_bot.games.append(game)
        chess_bot.stockfish_limit["time"] = 2

        result = asyncio.run(chess_bot.eval_last_move(game))

        if chess_bot.is_stockfish_enabled():
            self.assertTrue(result["blunder"])
        else:
            self.assertFalse(result['blunder'])
        self.assertIsNone(result["mate_in"])

    def test_eval_last_move_no_blunder_mate_in_two(self):
        board = chess.Board(
            "Q2r4/1p1k4/1P3ppp/1Kp1r3/4p2b/1B3P2/2P2q2/8 w - - 6 44")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Mate(2)

        chess_bot = Chess()
        chess_bot.games.append(game)

        result = asyncio.run(chess_bot.eval_last_move(game))

        self.assertFalse(result["blunder"])
        if chess_bot.is_stockfish_enabled():
            self.assertEqual(result["mate_in"], 2)
        else:
            self.assertIsNone(result["mate_in"])

    def test_eval_last_move_no_blunder_mate_in_two_against_current_player(
            self):
        board = chess.Board(
            "Q1kr4/1p6/1P3ppp/1Kp1r3/4p2b/1B3P2/2P2q2/8 b - - 5 43")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Mate(2)

        chess_bot = Chess()
        chess_bot.games.append(game)

        result = asyncio.run(chess_bot.eval_last_move(game))

        self.assertFalse(result["blunder"])
        if chess_bot.is_stockfish_enabled():
            self.assertEqual(result["mate_in"], -2)
        else:
            self.assertIsNone(result["mate_in"])

    def test_eval_last_move_lost_position_blunders_mate(self):
        board = chess.Board(
            "Q1kr4/1p6/1P3ppp/1Kp1r3/4p2b/1B3P2/2P2q2/8 b - - 5 43")
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)
        game.current_player = game.player1
        game.last_eval = Cp(1000)

        chess_bot = Chess()
        chess_bot.games.append(game)

        result = asyncio.run(chess_bot.eval_last_move(game))

        if chess_bot.is_stockfish_enabled():
            self.assertTrue(result["blunder"])
            self.assertEqual(result["mate_in"], -2)
        else:
            self.assertFalse(result["blunder"])
            self.assertIsNone(result["mate_in"])

    def test_build_animated_sequence_gif_valid_params(self):
        board = chess.Board()
        board.push_san('e4')
        board.push_san('c5')
        board.push_san('Nc3')
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)

        chess_bot = Chess()
        chess_bot.games.append(game)
        sequence = ['Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'a6']

        result = asyncio.run(
            chess_bot.build_animated_sequence_gif(game, 2, sequence))

        with open(
                os.path.join('tests', 'support',
                             'build_animated_sequence_gif.gif'), 'rb') as f:
            self.assertEqual(result.getvalue(), f.read())

    def test_build_animated_sequence_gif_invalid_move_in_sequence(self):
        board = chess.Board()
        board.push_san('e4')
        board.push_san('c5')
        board.push_san('Nc3')
        game = Game()
        game.board = board
        game.player1 = FakeDiscordUser(id=1)
        game.player2 = FakeDiscordUser(id=2)

        chess_bot = Chess()
        chess_bot.games.append(game)
        sequence = ['Nf3', 'd6', 'd4', 'Rxa8', 'Nxd4', 'Nf6', 'Nc3', 'a6']

        result = asyncio.run(
            chess_bot.build_animated_sequence_gif(game, 2, sequence))

        self.assertIsNone(result)

    def test_get_game_by_id_game_exists(self):
        warnings.simplefilter('ignore')
        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.board = board1
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        asyncio.run(game1.save())

        result = asyncio.run(Chess().get_game_by_id(game1.id))

        self.assertEqual(result, game1)

    def test_get_game_by_id_game_does_not_exist(self):
        warnings.simplefilter('ignore')
        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.board = board1
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        asyncio.run(game1.save())

        result = asyncio.run(Chess().get_game_by_id(uuid4()))

        self.assertIsNone(result)

    def test_get_game_by_id_game_invalid_uuid(self):
        warnings.simplefilter('ignore')
        board1 = chess.Board()
        board1.push_san("e4")
        board1.push_san("e5")
        game1 = Game()
        game1.board = board1
        game1.player1 = FakeDiscordUser(id=1)
        game1.player2 = FakeDiscordUser(id=2)
        asyncio.run(game1.save())

        result = asyncio.run(Chess().get_game_by_id("invalid_id"))

        self.assertIsNone(result)
Beispiel #26
0
 def tearDown(self):
     clear_data(Session())
 def setUp(self):
     self.test_session = Session()