def setUp(self): """ Simply setup our Guild obj before usage """ self.guild = Guild(None, 15, Static.DEFAULTS) self.guild.users = User(None, 20, 15, Static.DEFAULTS) self.guild.users = User(None, 21, 15, Static.DEFAULTS)
async def asyncSetUp(self): """ Simply setup our User obj before usage """ self.user = User(None, 0, 3, Static.DEFAULTS) self.user.messages = Message(0, "Hello world", 0, 2, 3) self.user.messages = Message(1, "Foo Bar", 0, 2, 3)
def setUp(self): """ Simply setup our User obj before usage """ self.user = User( None, 0, 3, Static.DEFAULTS, logger=logging.getLogger(__name__) ) self.user.messages = Message(0, "Hello world", 0, 2, 3) self.user.messages = Message(1, "Foo Bar", 0, 2, 3)
def reset_user_count(self, user_id: int, guild_id: int, counter: str) -> None: """ Reset an internal counter attached to a User object Parameters ---------- user_id : int The user to reset guild_id : int The guild they are attached to counter : str A str denoting which count to reset, Options are:\n ``warn_counter`` -> Reset the warn count\n ``kick_counter`` -> Reset the kick count Raises ====== LogicError Invalid count to reset Notes ===== Silently ignores if the User or Guild does not exist. This is because in the packages mind, the counts are 'reset' since the default value is the reset value. """ guild = Guild(self.bot, guild_id, self.options) try: guild = next(iter(g for g in self.guilds if g == guild)) except StopIteration: return user = User(self.bot, user_id, guild_id=guild_id, options=guild.options) try: user = next(iter(u for u in guild.users if u == user)) except StopIteration: return if counter.lower() == Static.WARNCOUNTER: user.warn_count = 0 log.debug(f"Reset the warn count for user: {user_id}") elif counter.lower() == Static.KICKCOUNTER: user.kick_count = 0 log.debug(f"Reset the kick count for user: {user_id}") else: raise LogicError( "Invalid counter argument, please select a valid counter.")
def test_userRaisesDuplicate(self): with self.assertRaises(DuplicateObject): self.guild.users = User(None, 21, 15, Static.DEFAULTS, logger=logging.getLogger(__name__))
async def propagate(self, message: discord.Message): """ This method handles a message object and then adds it to the relevant member Parameters ========== message : discord.Message The message that needs to be propagated out Returns ======= dict A dictionary of useful information about the user in question """ if not isinstance(message, discord.Message) and not isinstance( message, MagicMock ): raise ValueError("Expected message of ignore_type: discord.Message") user = User(self._bot, message.author.id, message.guild.id, self.options,) try: user = next(iter(u for u in self._users if u == user)) except StopIteration: self.users = user logging.info(f"Created User: {user.id}") return await user.propagate(message)
def load_from_dict(bot, guild_data): """ Loads the guild based on the passed data Parameters ---------- bot : commands.Bot The bot guild_data : dict The data to load from Returns ------- Guild """ guild = Guild( bot=bot, id=guild_data["id"], options=deepcopy(guild_data["options"]), custom_options=guild_data["has_custom_options"], ) for user in guild_data["users"]: guild.users = User.load_from_dict(bot, user) log.debug(f"Created Guild ({guild.id}) from saved state") return guild
def test_messageRaisesMismatch(self): with self.assertRaises(ObjectMismatch): self.guild.users = User(None, 22, 16, Static.DEFAULTS, logger=logging.getLogger(__name__))
def test_userAssignment(self): self.assertEqual(len(self.guild.users), 2) self.guild.users = User(None, 22, 15, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.assertEqual(len(self.guild.users), 3)
def setUp(self): """ Simply setup our Guild obj before usage """ self.guild = Guild(None, 15, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.guild.users = User(None, 20, 15, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.guild.users = User(None, 21, 15, Static.DEFAULTS, logger=logging.getLogger(__name__))
async def test_resetKickCounter(self): # GIVEN / SETUP user = User(get_mocked_bot(), 123454321, 12, Static.DEFAULTS) self.ash.guilds[0].users = user self.assertEqual(1, len(self.ash.guilds[0].users)) self.assertEqual(0, self.ash.guilds[0].users[0].kick_count) self.ash.guilds[0].users[0].kick_count += 1 self.assertEqual(1, self.ash.guilds[0].users[0].kick_count) # WHEN / TESTING self.ash.reset_user_count(123454321, 12, Static.KICKCOUNTER) # THEN / ASSERTIONS self.assertEqual(0, self.ash.guilds[0].users[0].kick_count)
async def test_multiChannelSpam(self): options = deepcopy(Static.DEFAULTS) options["per_channel_spam"] = True user = User(None, 0, 3, options) for i in range(3): m = MockedMessage(message_id=i, author_id=0, guild_id=3).to_mock() m.channel = MockedChannel(channel_id=1).to_mock() await user.propagate(m) self.assertEqual(user.get_correct_duplicate_count(1), 3) message = MockedMessage(author_id=0, guild_id=3).to_mock() message.channel = MockedChannel(channel_id=2).to_mock() self.assertEqual(user.get_correct_duplicate_count(2), 0) for i in range(5): m = MockedMessage(message_id=i, author_id=0, guild_id=3).to_mock() m.channel = MockedChannel(channel_id=2).to_mock() await user.propagate(m) self.assertEqual(user.get_correct_duplicate_count(1), 3) self.assertEqual(user.get_correct_duplicate_count(2), 5)
async def test_resetWarnCounter(self): # GIVEN / SETUP user = User( MockedMember(mock_type="bot").to_mock(), 123454321, 12, Static.DEFAULTS) self.ash.guilds[0].users = user self.assertEqual(1, len(self.ash.guilds[0].users)) self.assertEqual(0, self.ash.guilds[0].users[0].warn_count) self.ash.guilds[0].users[0].warn_count += 1 self.assertEqual(1, self.ash.guilds[0].users[0].warn_count) # WHEN / TESTING self.ash.reset_user_count(123454321, 12, Static.WARNCOUNTER) # THEN / ASSERTIONS self.assertEqual(0, self.ash.guilds[0].users[0].warn_count)
async def test_resetCountersRaises(self): # SETUP user = User(get_mocked_bot(), 123454321, 12, Static.DEFAULTS) self.ash.guilds[0].users = user # ASSERTIONS / TESTING with self.assertRaises(LogicError): self.ash.reset_user_count(123454321, 12, "Who knows") # Invalid guild, should work silently self.ash.reset_user_count(123454321, 15, "Who knows") # Invalid user, should work silently self.ash.reset_user_count(1234, 12, "Who knows") # Invalid both, should work silently self.ash.reset_user_count(1234, 15, "Who knows")
class TestUser(unittest.IsolatedAsyncioTestCase): """ Used to test the user object """ async def asyncSetUp(self): """ Simply setup our User obj before usage """ self.user = User(None, 0, 3, Static.DEFAULTS) self.user.messages = Message(0, "Hello world", 0, 2, 3) self.user.messages = Message(1, "Foo Bar", 0, 2, 3) async def test_botAssignment(self): # Given we don't want to populate an entire bot, # lets just check its assigned correctly self.assertIsNone(self.user.bot) async def test_intAssignment(self): self.assertIsInstance(self.user.id, int) self.assertIsInstance(self.user.guild_id, int) async def test_listAssignment(self): self.assertIsInstance(self.user.messages, list) async def test_dictAssignment(self): self.assertIsInstance(self.user.options, dict) async def test_valueAssignment(self): self.assertEqual(self.user.id, 0) self.assertEqual(self.user.guild_id, 3) self.assertEqual(self.user.options, Static.DEFAULTS) self.user.id = 10 self.user.guild_id = 10 self.assertEqual(self.user.id, 10) self.assertEqual(self.user.guild_id, 10) async def test_properties(self): with self.assertRaises(ValueError): self.user.id = "1" with self.assertRaises(ValueError): self.user.guild_id = "1" async def test_messageAssignment(self): self.assertEqual(len(self.user.messages), 2) self.user.messages = Message(3, "Test", 0, 2, 3) self.assertEqual(len(self.user.messages), 3) async def test_messageRaises(self): with self.assertRaises(ValueError): self.user.messages = 1 async def test_messageRaisesDuplicate(self): with self.assertRaises(DuplicateObject): self.user.messages = Message(1, "Testing", 0, 2, 3) async def test_messageRaisesMismatch(self): with self.assertRaises(ObjectMismatch): self.user.messages = Message(20, "Testing", 20, 20, 20) async def test_repr(self): self.assertEqual( repr(self.user), ( f"'{self.user.__class__.__name__} object. User id: {self.user.id}, Guild id: {self.user.guild_id}, " f"Len Stored Messages {len(self.user.messages)}'" ), ) async def test_str(self): self.assertEqual( str(self.user), f"{self.user.__class__.__name__} object for {self.user.id}." ) async def test_eqEqual(self): obj = User(None, 0, 3, Static.DEFAULTS) self.assertTrue(self.user == obj) async def test_eqNotEqual(self): obj = User(None, 2, 2, Static.DEFAULTS) self.assertFalse(self.user == obj) async def test_eqRaises(self): with self.assertRaises(ValueError): self.assertFalse(self.user == 1) async def test_duplicateCounter(self): self.assertNotEqual( self.user.duplicate_counter, self.user.get_correct_duplicate_count() ) self.assertEqual( self.user.duplicate_counter - 1, self.user.get_correct_duplicate_count() ) async def test_cleanUp(self): x = len(self.user.messages) self.user.clean_up(datetime.datetime.now(datetime.timezone.utc)) self.assertEqual(x, len(self.user.messages)) async def test__increment_duplicate_count(self): self.assertEqual(self.user.duplicate_counter, 1) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3)) self.assertEqual(self.user.duplicate_counter, 2) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3), 2) self.assertEqual(self.user.duplicate_counter, 4) self.user.options["per_channel_spam"] = True self.assertEqual(self.user.duplicate_channel_counter_dict, dict()) print(self.user.duplicate_channel_counter_dict) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3)) print(self.user.duplicate_channel_counter_dict) self.assertEqual(self.user.duplicate_channel_counter_dict, {2: 2}) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3), 2) self.assertEqual(self.user.duplicate_channel_counter_dict, {2: 4}) async def test__get_duplicate_count(self): result = self.user._get_duplicate_count(Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 1) self.user.options["per_channel_spam"] = True result = self.user._get_duplicate_count(Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 1) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3)) self.user._increment_duplicate_count(Message(2, "A test message", 0, 2, 3)) result = self.user._get_duplicate_count(Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 3) # This channel shouldn't exist / have duplicates result = self.user._get_duplicate_count(Message(3, "A test message", 0, 1, 3)) self.assertEqual(result, 1) with self.assertRaises(LogicError): # noinspection PyTypeChecker self.user._get_duplicate_count("hi") with self.assertRaises(TypeError): # noinspection PyTypeChecker self.user._get_duplicate_count(channel_id=dict()) with self.assertRaises(LogicError): # noinspection PyTypeChecker self.user._get_duplicate_count() async def test__remove_duplicate_count(self): self.assertEqual(self.user.duplicate_counter, 1) self.user._remove_duplicate_count(Message(2, "A test message", 0, 2, 3)) self.assertEqual(self.user.duplicate_counter, 0) self.user.options["per_channel_spam"] = True msg = Message(2, "A test message", 0, 2, 3) self.user._increment_duplicate_count(msg) self.user._increment_duplicate_count(msg) self.assertEqual(self.user._get_duplicate_count(msg), 3) async def test_propagate(self): m = get_mocked_message( message_id=0, member_kwargs={"id": 0}, guild_kwargs={"id": 3} ) # TODO Use AsyncMock or Monkeypatch __await__ for i in range(5): await self.user.propagate( get_mocked_message( message_id=i, member_kwargs={"id": 0}, guild_kwargs={"id": 3} ) )
def test_eqEqual(self): obj = User(None, 0, 3, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.assertTrue(self.user == obj)
def test_eqNotEqual(self): obj = User(None, 2, 2, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.assertFalse(self.user == obj)
class TestUser(unittest.TestCase): """ Used to test the user object """ def setUp(self): """ Simply setup our User obj before usage """ self.user = User( None, 0, 3, Static.DEFAULTS, logger=logging.getLogger(__name__) ) self.user.messages = Message(0, "Hello world", 0, 2, 3) self.user.messages = Message(1, "Foo Bar", 0, 2, 3) def test_botAssignment(self): # Given we don't want to populate an entire bot, # lets just check its assigned correctly self.assertIsNone(self.user.bot) def test_intAssignment(self): self.assertIsInstance(self.user.id, int) self.assertIsInstance(self.user.guild_id, int) def test_listAssignment(self): self.assertIsInstance(self.user.messages, list) def test_dictAssignment(self): self.assertIsInstance(self.user.options, dict) def test_valueAssignment(self): self.assertEqual(self.user.id, 0) self.assertEqual(self.user.guild_id, 3) self.assertEqual(self.user.options, Static.DEFAULTS) self.user.id = 10 self.user.guild_id = 10 self.assertEqual(self.user.id, 10) self.assertEqual(self.user.guild_id, 10) def test_properties(self): with self.assertRaises(ValueError): self.user.id = "1" with self.assertRaises(ValueError): self.user.guild_id = "1" def test_messageAssignment(self): self.assertEqual(len(self.user.messages), 2) self.user.messages = Message(3, "Test", 0, 2, 3) self.assertEqual(len(self.user.messages), 3) def test_messageRaises(self): with self.assertRaises(ValueError): self.user.messages = 1 def test_messageRaisesDuplicate(self): with self.assertRaises(DuplicateObject): self.user.messages = Message(1, "Testing", 0, 2, 3) def test_messageRaisesMismatch(self): with self.assertRaises(ObjectMismatch): self.user.messages = Message(20, "Testing", 20, 20, 20) def test_repr(self): self.assertEqual( repr(self.user), ( f"'{self.user.__class__.__name__} object. User id: {self.user.id}, Guild id: {self.user.guild_id}, " f"Len Stored Messages {len(self.user.messages)}'" ), ) def test_str(self): self.assertEqual( str(self.user), f"{self.user.__class__.__name__} object for {self.user.id}." ) def test_eqEqual(self): obj = User(None, 0, 3, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.assertTrue(self.user == obj) def test_eqNotEqual(self): obj = User(None, 2, 2, Static.DEFAULTS, logger=logging.getLogger(__name__)) self.assertFalse(self.user == obj) def test_eqRaises(self): with self.assertRaises(ValueError): self.assertFalse(self.user == 1) def test_duplicateCounter(self): self.assertNotEqual( self.user.duplicate_counter, self.user.get_correct_duplicate_count() ) self.assertEqual( self.user.duplicate_counter - 1, self.user.get_correct_duplicate_count() ) def test_cleanUp(self): x = len(self.user.messages) self.user.clean_up(datetime.datetime.now(datetime.timezone.utc)) self.assertEqual(x, len(self.user.messages))
def test_userAssignment(self): self.assertEqual(len(self.guild.users), 2) self.guild.users = User(None, 22, 15, Static.DEFAULTS) self.assertEqual(len(self.guild.users), 3)
class TestUser(unittest.IsolatedAsyncioTestCase): """ Used to test the user object """ async def asyncSetUp(self): """ Simply setup our User obj before usage """ self.user = User(None, 0, 3, Static.DEFAULTS) self.user.messages = Message(0, "Hello world", 0, 2, 3) self.user.messages = Message(1, "Foo Bar", 0, 2, 3) async def test_botAssignment(self): # Given we don't want to populate an entire bot, # lets just check its assigned correctly self.assertIsNone(self.user.bot) async def test_intAssignment(self): self.assertIsInstance(self.user.id, int) self.assertIsInstance(self.user.guild_id, int) async def test_listAssignment(self): self.assertIsInstance(self.user.messages, list) async def test_dictAssignment(self): self.assertIsInstance(self.user.options, dict) async def test_valueAssignment(self): self.assertEqual(self.user.id, 0) self.assertEqual(self.user.guild_id, 3) self.assertEqual(self.user.options, Static.DEFAULTS) self.user.id = 10 self.user.guild_id = 10 self.assertEqual(self.user.id, 10) self.assertEqual(self.user.guild_id, 10) async def test_properties(self): with self.assertRaises(ValueError): self.user.id = "1" with self.assertRaises(ValueError): self.user.guild_id = "1" async def test_messageAssignment(self): self.assertEqual(len(self.user.messages), 2) self.user.messages = Message(3, "Test", 0, 2, 3) self.assertEqual(len(self.user.messages), 3) async def test_messageRaises(self): with self.assertRaises(ValueError): self.user.messages = 1 async def test_messageRaisesDuplicate(self): with self.assertRaises(DuplicateObject): self.user.messages = Message(1, "Testing", 0, 2, 3) async def test_messageRaisesMismatch(self): with self.assertRaises(ObjectMismatch): self.user.messages = Message(20, "Testing", 20, 20, 20) async def test_repr(self): self.assertEqual( repr(self.user), (f"'{self.user.__class__.__name__} object. User id: {self.user.id}, Guild id: {self.user.guild_id}, " f"Len Stored Messages {len(self.user.messages)}'"), ) async def test_str(self): self.assertEqual( str(self.user), f"{self.user.__class__.__name__} object for {self.user.id}.") async def test_eqEqual(self): obj = User(None, 0, 3, Static.DEFAULTS) self.assertTrue(self.user == obj) async def test_eqNotEqual(self): obj = User(None, 2, 2, Static.DEFAULTS) self.assertFalse(self.user == obj) async def test_eqRaises(self): with self.assertRaises(ValueError): self.assertFalse(self.user == 1) async def test_duplicateCounter(self): self.assertNotEqual(self.user.duplicate_counter, self.user.get_correct_duplicate_count()) self.assertEqual(self.user.duplicate_counter - 1, self.user.get_correct_duplicate_count()) async def test_cleanUp(self): x = len(self.user.messages) self.user.clean_up(datetime.datetime.now(datetime.timezone.utc)) self.assertEqual(x, len(self.user.messages)) async def test__increment_duplicate_count(self): self.assertEqual(self.user.duplicate_counter, 1) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3)) self.assertEqual(self.user.duplicate_counter, 2) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3), 2) self.assertEqual(self.user.duplicate_counter, 4) self.user.options["per_channel_spam"] = True self.assertEqual(self.user.duplicate_channel_counter_dict, dict()) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3)) self.assertEqual(self.user.duplicate_channel_counter_dict, {2: 2}) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3), 2) self.assertEqual(self.user.duplicate_channel_counter_dict, {2: 4}) async def test__get_duplicate_count(self): result = self.user._get_duplicate_count( Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 1) self.user.options["per_channel_spam"] = True result = self.user._get_duplicate_count( Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 1) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3)) self.user._increment_duplicate_count( Message(2, "A test message", 0, 2, 3)) result = self.user._get_duplicate_count( Message(3, "A test message", 0, 2, 3)) self.assertEqual(result, 3) # This channel shouldn't exist / have duplicates result = self.user._get_duplicate_count( Message(3, "A test message", 0, 1, 3)) self.assertEqual(result, 1) with self.assertRaises(LogicError): # noinspection PyTypeChecker self.user._get_duplicate_count("hi") with self.assertRaises(TypeError): # noinspection PyTypeChecker self.user._get_duplicate_count(channel_id=dict()) with self.assertRaises(LogicError): # noinspection PyTypeChecker self.user._get_duplicate_count() async def test__remove_duplicate_count(self): self.assertEqual(self.user.duplicate_counter, 1) self.user._remove_duplicate_count(Message(2, "A test message", 0, 2, 3)) self.assertEqual(self.user.duplicate_counter, 0) self.user.options["per_channel_spam"] = True msg = Message(2, "A test message", 0, 2, 3) self.user._increment_duplicate_count(msg) self.user._increment_duplicate_count(msg) self.assertEqual(self.user._get_duplicate_count(msg), 3) async def test_propagatePunish(self): """Checks the propagate method tries to punish at correct times""" m = MockedMessage(message_id=0, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], False) m = MockedMessage(message_id=1, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], False) m = MockedMessage(message_id=2, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], False) m = MockedMessage(message_id=3, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], True) m = MockedMessage(message_id=4, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], True) async def test_propagateWarn(self): """Tests it warns for the correct amount""" for i in range(3): m = MockedMessage(message_id=i, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) # Shouldn't be punished yet. But one off # noinspection PyUnboundLocalVariable self.assertEqual(data["should_be_punished_this_message"], False) m = MockedMessage(message_id=4, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], True) self.assertEqual(data["was_warned"], True) m = MockedMessage(message_id=5, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], True) self.assertEqual(data["was_warned"], True) m = MockedMessage(message_id=6, author_id=0, guild_id=3).to_mock() data = await self.user.propagate(m) self.assertEqual(data["should_be_punished_this_message"], True) self.assertEqual(data["was_warned"], False) self.assertEqual(data["was_kicked"], True) async def test_multiChannelSpam(self): options = deepcopy(Static.DEFAULTS) options["per_channel_spam"] = True user = User(None, 0, 3, options) for i in range(3): m = MockedMessage(message_id=i, author_id=0, guild_id=3).to_mock() m.channel = MockedChannel(channel_id=1).to_mock() await user.propagate(m) self.assertEqual(user.get_correct_duplicate_count(1), 3) message = MockedMessage(author_id=0, guild_id=3).to_mock() message.channel = MockedChannel(channel_id=2).to_mock() self.assertEqual(user.get_correct_duplicate_count(2), 0) for i in range(5): m = MockedMessage(message_id=i, author_id=0, guild_id=3).to_mock() m.channel = MockedChannel(channel_id=2).to_mock() await user.propagate(m) self.assertEqual(user.get_correct_duplicate_count(1), 3) self.assertEqual(user.get_correct_duplicate_count(2), 5)
def test_userRaisesDuplicate(self): with self.assertRaises(DuplicateObject): self.guild.users = User(None, 21, 15, Static.DEFAULTS)
async def test_eqNotEqual(self): obj = User(None, 2, 2, Static.DEFAULTS) self.assertFalse(self.user == obj)
async def test_eqEqual(self): obj = User(None, 0, 3, Static.DEFAULTS) self.assertTrue(self.user == obj)
def test_messageRaisesMismatch(self): with self.assertRaises(ObjectMismatch): self.guild.users = User(None, 22, 16, Static.DEFAULTS)