def test_group_does_not_have_codes(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(list_code(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo não possui códigos")
def test_code_does_not_exist(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(remove_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Código ASDF-1234 não encontrado no grupo foo")
def test_user_does_not_exist_in_this_guild(self): ctx = FakeContext() guild2 = FakeGuild2() PromoCodeGroup.create(guild_id=guild2.id, name='foo') asyncio.run(remove_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo não existe!")
def test_group_exists(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(remove_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo removido")
def test_group_exist_in_another_guild(self): ctx = FakeContext() guild2 = FakeGuild2() PromoCodeGroup.create(guild_id=guild2.id, name='foo') asyncio.run(list_code(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo não existe")
def test_has_groups_in_different_guild(self): ctx = FakeContext() guild2 = FakeGuild2() PromoCodeGroup.create(guild_id=guild2.id, name='foo') asyncio.run(list_group(ctx)) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Não há grupos de código promocional cadastrados")
def test_group_does_not_exist_in_this_guild(self): ctx = FakeContext() guild2 = FakeGuild2() PromoCodeGroup.create(guild_id=guild2.id, name='foo') asyncio.run(add_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo de códigos promocionais não encontrado: foo")
def test_invalid_code(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(add_code(ctx, group_name='foo', code='ASDF$1234')) self.assertTrue(ctx.send_called) self.assertEqual( ctx.send_parameters, "Código inválido: o código deve ser apenas letras, números e traços (-)" # noqa E501 )
def test_has_results_in_same_guild(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(list_group(ctx)) self.assertTrue(ctx.send_called) self.assertEqual( ctx.send_parameters, "Estes são os grupos de código promocional existentes: \n- foo")
def test_group_exists_in_this_guild(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(add_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual( ctx.send_parameters, "Código ASDF-1234 cadastrado no grupo foo com sucesso!" )
def test_group_exists_in_this_guild(self): ctx = FakeContext() PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') asyncio.run(add_code_bulk(ctx, group_name='foo', code_bulk='ASDF-1234 QWER-5678,ZXCV-9012')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Códigos adicionados ao grupo foo") promo_codes = PromoCode.select() resulting_codes = ['ASDF-1234', 'QWER-5678', 'ZXCV-9012'] for (promo_code, resulting_code) in zip(promo_codes, resulting_codes): self.assertEqual(promo_code.code, resulting_code)
async def add_group(ctx, group_name): """Creates a group of promo codes. No code can live outside of a group (they get lonely!).""" logging.info("Tentando adicionar grupo '%s'", group_name) if not validate_group_name(group_name): await ctx.send( "Nome de grupo inválido. Use apenas letras, números, traços (-) e underscore (_)" ) # noqa E501 return try: PromoCodeGroup.create(guild_id=ctx.guild.id, name=group_name) await ctx.send("Grupo {} criado".format(group_name)) except IntegrityError: await ctx.send("Grupo já existente")
def test_group_has_code_and_user_has_not_yet_received_one(self): ctx = FakeContext() user = FakeUser() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') promo_code = PromoCode.create(group=group, code='ASDF-1234') asyncio.run(send_code(ctx, group_name='foo', users=[user], is_authorized_or_owner=returns_false)) self.assertTrue(ctx.author.send_called) self.assertEqual( ctx.author.send_parameters, "Código {} enviado para o usuário {}".format(promo_code.code, user.name) ) self.assertTrue(user.send_called) self.assertEqual( user.send_parameters, "Olá! Você ganhou um código: {}".format(promo_code.code) ) saved_promo_code = PromoCode.get(group=group, code=promo_code.code) self.assertEqual(saved_promo_code.sent_to_name, user.name) self.assertEqual(saved_promo_code.sent_to_id, user.id) self.assertIsNotNone(saved_promo_code.sent_at)
def test_delete_group_removes_its_keys(self): ctx = FakeContext() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code='ASDF-1234') asyncio.run(remove_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo removido") self.assertEqual(PromoCode.select().count(), 0)
def test_group_has_codes(self): ctx = FakeContext() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code='ASDF-1234') asyncio.run(list_code(ctx, group_name='foo')) self.assertTrue(ctx.author.send_called) self.assertEqual(ctx.author.send_parameters, "Códigos para o grupo foo: \n- ASDF-1234")
def test_code_already_registered(self): ctx = FakeContext() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code="ASDF-1234") asyncio.run(add_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Código ASDF-1234 já cadastrado no grupo foo")
def test_code_exists_in_current_guild(self): ctx = FakeContext() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code="ASDF-1234") asyncio.run(remove_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Código ASDF-1234 excluído do grupo foo")
def test_code_exists_in_another_guild(self): ctx = FakeContext() guild2 = FakeGuild2() group = PromoCodeGroup.create(guild_id=guild2.id, name='foo') PromoCode.create(group=group, code="ASDF-1234") asyncio.run(remove_code(ctx, group_name='foo', code='ASDF-1234')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Código ASDF-1234 não encontrado no grupo foo")
async def list_group(ctx): """Let's you see the promo code groups.""" logging.info("Tentando listar grupos") groups = PromoCodeGroup.select().where( PromoCodeGroup.guild_id == ctx.guild.id) if groups.count() == 0: # pylint: disable=no-value-for-parameter await ctx.send("Não há grupos de código promocional cadastrados") return output = "Estes são os grupos de código promocional existentes: " for group in groups: output += "\n- {}".format(group.name) await ctx.send(output)
async def remove_group(ctx, group_name): """Destroys a promo code group. Careful! All codes within it are brutally killed too!""" logging.info("Tentando remover grupo '%s'", group_name) query = PromoCodeGroup.delete().where( (PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) rows_removed = query.execute() if rows_removed > 0: await ctx.send("Grupo {} removido".format(group_name)) else: await ctx.send("Grupo {} não existe!".format(group_name))
async def send_code(ctx, group_name, users: commands.Greedy[User], is_authorized_or_owner=is_authorized_or_owner): """Sends a promo code from a code group to each of the mentioned users.""" logging.info( "Tentando enviar um código do grupo %s para o(s) usuário(s) %s", group_name, ', '.join([f'{user.name}({user.id})' for user in users])) group = PromoCodeGroup.get_or_none( (PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) if group is None: await ctx.send("Grupo {} não existe".format(group_name)) return messages_author = [] messages_channel = [] with db.atomic() as transaction: for user in users: if not await is_authorized_or_owner(ctx): used_codes = PromoCode.select().where( (PromoCode.group == group) & (PromoCode.sent_to_id == user.id)) if used_codes.count() > 0: messages_channel.append( "Usuário {0} já resgatou código do grupo {1}".format( user.name, group_name)) continue promo_code = PromoCode.select().where( (PromoCode.group == group) & (PromoCode.sent_to_id == None) # noqa E501 pylint: disable=singleton-comparison ).first() if promo_code is None: messages_channel.append( "Grupo {} não possui mais códigos disponíveis".format( group_name)) break promo_code.sent_to_name = user.name promo_code.sent_to_id = user.id promo_code.sent_at = datetime.now(timezone.utc) promo_code.save() await user.send("Olá! Você ganhou um código: {}".format( promo_code.code)) # incluir essa linha nos testes! messages_author.append( "Código {} enviado para o usuário {}".format( promo_code.code, user.name)) messages_channel.append( "Enviado código do grupo {} para o usuário {}".format( group_name, user.name)) await ctx.send("\n".join(messages_channel)) await ctx.author.send("\n".join(messages_author)) transaction.commit()
def test_group_has_code_and_user_has_already_received_one(self): ctx = FakeContext() user = FakeUser() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code='ASDF-1234', sent_to_id=user.id) asyncio.run(send_code(ctx, group_name='foo', users=[user], is_authorized_or_owner=returns_false)) self.assertTrue(ctx.send_called) self.assertEqual( ctx.send_parameters, "Usuário {0} já resgatou código do grupo {1}".format(user.name, 'foo') )
async def remove_code(ctx, group_name, code): """Removes a code from a code group.""" logging.info("Tentando remover o código %s do grupo %s", code, group_name) group = PromoCodeGroup.get_or_none( (PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) if group is None: await ctx.send("Código {0} não encontrado no grupo {1}".format( code, group_name)) return query = PromoCode.delete().where((PromoCode.code == code) & (PromoCode.group == group)) rows_removed = query.execute() if rows_removed > 0: await ctx.send("Código {0} excluído do grupo {1}".format( code, group_name)) else: await ctx.send("Código {0} não encontrado no grupo {1}".format( code, group_name))
def test_group_doesnt_have_codes_available(self): ctx = FakeContext() user = FakeUser() user2 = FakeUser2() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') PromoCode.create(group=group, code='ASDF-1234', sent_to_name=user.name, sent_to_id=user.id) asyncio.run(send_code(ctx, group_name='foo', users=[user2], is_authorized_or_owner=returns_false)) self.assertTrue(ctx.author.send_called) self.assertEqual( ctx.send_parameters, "Grupo {} não possui mais códigos disponíveis".format( group.name ) )
async def list_code(ctx, group_name): """Lists all codes inside a code group.""" logging.info("Tentando listar os códigos do grupo %s", group_name) group = PromoCodeGroup.get_or_none( (PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) if group is None: await ctx.send("Grupo {} não existe".format(group_name)) return codes = PromoCode.select().where((PromoCode.group == group)) if codes.count() == 0: # pylint: disable=no-value-for-parameter await ctx.send("Grupo {} não possui códigos".format(group_name)) return output = "Códigos para o grupo {}: ".format(group_name) for code in codes: output += "\n- {}".format(code.code) sent_at = sqlite_datetime_hack(code.sent_at) if code.sent_to_id: output += " enviado para o usuário {0} em {1}".format( code.sent_to_name, sent_at.astimezone(LOCAL_TIMEZONE).strftime(DATETIME_FORMAT)) await send_long_message_array(ctx.author.send, output)
def test_user_has_codes(self): ctx = FakeContext() author = ctx.author sent_at = datetime.now() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') promo_code = PromoCode.create( group=group, code='ASDF-1234', sent_to_id=author.id, sent_to_name=author.name, sent_at=sent_at ) asyncio.run(my_codes(ctx)) self.assertTrue(ctx.author.send_called) self.assertEqual( ctx.author.send_parameters, "Seus códigos: \n- {0} (recebido em {1})".format( promo_code.code, sent_at.astimezone(LOCAL_TIMEZONE).strftime(DATETIME_FORMAT) ) )
async def add_code_bulk(ctx, group_name, *, code_bulk): """Adds a lot of codes to the same group. Codes are separated by anything that is not: - a letter - a number - a dash (-)""" logging.info("Tentando adicionar códigos em massa ao grupo %s: %s", group_name, code_bulk) group = PromoCodeGroup.get_or_none( (PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) if group is None: await ctx.send( "Grupo de códigos promocionais não encontrado: {}".format( group_name)) return codes = parse_codes_in_bulk(code_bulk) insert_bulk_data = [{'group': group, 'code': code} for code in codes] with db.atomic() as transaction: PromoCode.insert_many(insert_bulk_data).execute() # noqa E501 pylint: disable=no-value-for-parameter transaction.commit() await ctx.send("Códigos adicionados ao grupo {}".format(group_name))
async def add_code(ctx, group_name, code): """Add a code to a promo group.""" logging.info("Tentando adicionar o código %s ao grupo %s", code, group_name) if not validate_code(code): await ctx.send( "Código inválido: o código deve ser apenas letras, números e traços (-)" ) # noqa E501 return try: group = PromoCodeGroup.get((PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == group_name)) PromoCode.create(group=group, code=code) await ctx.send( "Código {0} cadastrado no grupo {1} com sucesso!".format( code, group_name)) except PromoCodeGroup.DoesNotExist: # pylint: disable=no-member await ctx.send( "Grupo de códigos promocionais não encontrado: {}".format( group_name)) except IntegrityError: await ctx.send("Código {0} já cadastrado no grupo {1}".format( code, group_name))
def test_group_has_sent_codes(self): ctx = FakeContext() user = FakeUser() group = PromoCodeGroup.create(guild_id=ctx.guild.id, name='foo') sent_at = datetime.now() promo_code = PromoCode.create( group=group, code='ASDF-1234', sent_to_name=user.name, sent_to_id=user.id, sent_at=sent_at ) asyncio.run(list_code(ctx, group_name='foo')) self.assertTrue(ctx.author.send_called) self.assertEqual( ctx.author.send_parameters, "Códigos para o grupo foo: \n- {0} enviado para o usuário {1} em {2}".format( # noqa E501 promo_code.code, user.name, sent_at.astimezone(LOCAL_TIMEZONE).strftime(DATETIME_FORMAT) ) )
def test_add_group(self): ctx = FakeContext() asyncio.run(add_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo criado") group = PromoCodeGroup.get((PromoCodeGroup.guild_id == ctx.guild.id) & (PromoCodeGroup.name == 'foo')) self.assertEqual(group.guild_id, ctx.guild.id) self.assertEqual(group.name, 'foo') ctx = FakeContext() asyncio.run(add_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo já existente") ctx = FakeContext(guild=FakeGuild2()) asyncio.run(add_group(ctx, group_name='foo')) self.assertTrue(ctx.send_called) self.assertEqual(ctx.send_parameters, "Grupo foo criado")