class BaseTest(TestCase): def setUp(self): container = Container() container.config.from_dict(settings.__dict__) self.cache = RedisService() self.user = User( email='*****@*****.**', name='test', last_name='test', password='******' ) self.user.save() def tearDown(self): self.user.delete() self.cache.flushall() def _get_image(self): from shared.file.services.FileDecoder import ImageDecoder file_decoder = ImageDecoder() return file_decoder.execute( self._get_raw_image(), file_name='test.png' ) def _get_raw_image(self): import base64 file_header = 'data:image/png;base64' file_path = 'tests/baseTests/test.png' with open(file_path, 'rb') as img_file: content = str(base64.b64encode(img_file.read())) return f'{file_header},{content}' def _get_raw_mp3(self): import base64 file_header = 'data:audio/mpeg;base64' file_path = 'tests/baseTests/music_test.mp3' with open(file_path, 'rb') as mp3_file: content = base64.b64encode(mp3_file.read())[1:] return f'{file_header},{content}' def _get_mp3(self): import base64 file_path = 'tests/baseTests/music_test.mp3' with open(file_path, 'rb') as mp3_file: content = base64.b64encode(mp3_file.read()) return ContentFile( base64.b64decode(content), 'test.mp3' )
def delete(request): if request.session.get('user') is None: return redirect('user:login') uid = request.GET.get('uid') # delete_user(uid) User.delete(uid) return redirect('user:index')
def index(request): info_invalid = '' # Valid value # View all objects user = User.objects.all() context = { 'user': user, } if request.method == 'POST': posted_name = request.POST.get('name', '') if posted_name == '': info_invalid = 'Username can not be empty!' user = User( name=request.POST.get('name', ''), email=request.POST.get('email', ''), ) edit_id = int(request.POST.get('edit_id', 0)) if edit_id > 0: user = User.objects.get(id=edit_id) user.name = request.POST.get('name', '') # request.POST['name'] user.email = request.POST.get('email', '') context[ 'info'] = f"eddited {user.name} ({user.email}) with ID: {user.id}" else: context[ 'info'] = f"added {user.name} ({user.email}) with ID: {user.id}" if info_invalid == '': user.save() else: context['info'] = info_invalid elif request.method == 'GET': del_id = int(request.GET.get('del', 0)) if del_id > 0: user = User.objects.get(id=del_id) user.delete() context[ 'info'] = f"deleted {user.name} ({user.email}) with ID: {user.id}" edit_id = int(request.GET.get('edit', 0)) if edit_id > 0: user = User.objects.get(id=edit_id) context['edit_id'] = edit_id context['edit_name'] = user.name context['edit_email'] = user.email return render( template_name='index.html', request=request, context=context, )
def test_create_missing_optional_params_succeeds(self): for param in self.optional_params: user_params = copy.deepcopy(self.user_params) user_params.pop(param) user = User(**user_params) self.assertIsNone(user.id) user.save() self.assertIsNotNone(user.id) user.delete()
class ValorationModelTestCase(TestCase): #Prepara una bbdd default con los objetos que se van a testear en este TestCase ------------------- def setUp(self): self.user1 = User(username='******', password='******') self.user1.save() self.user2 = User(username='******', password='******') self.user2.save() self.valoration = Valoration(toUser=self.user1, fromUser=self.user2, rate=2.5) self.valoration.save() self.comment = Comment(toUser=self.user1, fromUser=self.user2, comment='Buen juego, mejor jugador') self.comment.save() #Batería de test unitarios ------------------------------------------------------------------------ def test_get_valoration_toUser(self): self.assertEquals(self.valoration.toUser, self.user1) def test_get_valoration_fromUser(self): self.assertEquals(self.valoration.fromUser, self.user2) def test_get_valoration_rate(self): self.assertEquals(self.valoration.rate, 2.5) def test_get_comment_toUser(self): self.assertEquals(self.comment.toUser, self.user1) def test_get_comment_fromUser(self): self.assertEquals(self.comment.fromUser, self.user2) def test_get_comment_comment(self): self.assertEquals(self.comment.comment, 'Buen juego, mejor jugador') #Borra los datos para terminar con los test ------------------------------------------------------ def tearDown(self): self.valoration.delete() self.comment.delete() self.user1.delete() self.user2.delete()
class UserModelTestCase(TestCase): #Prepara una bbdd default con los objetos que se van a testear en este TestCase ------------------- def setUp(self): self.user = User(username='******', password='******', first_name='Gonzalo', last_name='Aguilar', email='*****@*****.**', bio='Me gusta jugar a cosas entretenidas', picture='http://www.foto.com/foto.png', range='Pro', rate='2.5') self.user.save() #Batería de test unitarios ------------------------------------------------------------------------ def test_get_username(self): self.assertEquals(self.user.username, 'prueba') def test_get_password(self): self.assertEquals(self.user.password, 'prueba123') def test_get_firstName(self): self.assertEquals(self.user.first_name, 'Gonzalo') def test_get_lastName(self): self.assertEquals(self.user.last_name, 'Aguilar') def test_get_email(self): self.assertEquals(self.user.email, '*****@*****.**') def test_get_bio(self): self.assertEquals(self.user.bio, 'Me gusta jugar a cosas entretenidas') def test_get_picture(self): self.assertEquals(self.user.picture, 'http://www.foto.com/foto.png') def test_get_range(self): self.assertEquals(self.user.range, 'Pro') def test_get_rate(self): self.assertEquals(self.user.rate, '2.5') #Borra los datos para terminar con los test ------------------------------------------------------ def tearDown(self): self.user.delete()
class ModelTest(TestCase): def setUp(self): self.user = User(username='******', email='*****@*****.**') self.user.set_password('fuga') self.user.save() def test_get_token(self): # if not have token self.assertIsNone(self.user.token) # create token self.client.login(username='******', password='******') self.client.put('/api/v1/user/access_token') self.assertEqual(self.user.token, Token.objects.get(user=self.user)) def test_make_user(self): self.assertTrue(isinstance(self.user, DjangoUser)) self.assertEqual(self.user.username, 'ほげ') self.assertEqual(self.user.authorized_type, 0) self.assertIsNotNone(self.user.date_joined) self.assertTrue(self.user.is_active) def test_delete_user(self): self.user.delete() user = User.objects.get(id=self.user.id) self.assertTrue(isinstance(user, DjangoUser)) self.assertEqual(user.username.find('ほげ_deleted_'), 0) self.assertEqual(user.email, "*****@*****.**") self.assertEqual(user.authorized_type, 0) self.assertIsNotNone(user.date_joined) self.assertFalse(user.is_active) def test_set_history(self): entity = Entity.objects.create(name='test-entity', created_user=self.user) entry = Entry.objects.create(name='test-attr', created_user=self.user, schema=entity) self.user.seth_entity_add(entity) self.user.seth_entity_mod(entity) self.user.seth_entity_del(entity) self.user.seth_entry_del(entry) self.assertEqual(History.objects.count(), 4) self.assertEqual( History.objects.filter(operation=History.ADD_ENTITY).count(), 1) self.assertEqual( History.objects.filter(operation=History.MOD_ENTITY).count(), 1) self.assertEqual( History.objects.filter(operation=History.DEL_ENTITY).count(), 1) self.assertEqual( History.objects.filter(operation=History.DEL_ENTRY).count(), 1) def test_set_history_with_detail(self): entity = Entity.objects.create(name='test-entity', created_user=self.user) attr = EntityAttr.objects.create(name='test-attr', created_user=self.user, parent_entity=entity) history = self.user.seth_entity_add(entity) history.add_attr(attr) history.mod_attr(attr, 'changed points ...') history.del_attr(attr) history.mod_entity(entity, 'changed points ...') self.assertEqual(History.objects.count(), 5) self.assertEqual(History.objects.filter(user=self.user).count(), 5) self.assertEqual( History.objects.filter(operation=History.ADD_ATTR).count(), 1) self.assertEqual( History.objects.filter(operation=History.MOD_ATTR).count(), 1) self.assertEqual( History.objects.filter(operation=History.DEL_ATTR).count(), 1) self.assertEqual( History.objects.filter(operation=History.ADD_ENTITY).count(), 1) self.assertEqual( History.objects.filter(operation=History.MOD_ENTITY).count(), 1) # checks detail histories are registered correctly self.assertEqual(history.details.count(), 4) self.assertEqual( history.details.filter(operation=History.ADD_ATTR).count(), 1) self.assertEqual( history.details.filter(operation=History.MOD_ATTR).count(), 1) self.assertEqual( history.details.filter(operation=History.DEL_ATTR).count(), 1) self.assertEqual( history.details.filter(operation=History.MOD_ENTITY).count(), 1) def test_set_history_of_invalid_type_entry(self): class InvalidType(object): pass Entity.objects.create(name='test-entity', created_user=self.user) invalid_obj = InvalidType() with self.assertRaises(TypeError): self.user.seth_entity_add(invalid_obj) self.user.seth_entity_mod(invalid_obj) self.user.seth_entity_del(invalid_obj) self.user.seth_entry_del(invalid_obj) self.assertEqual(History.objects.count(), 0) def test_affect_group_acl(self): """ This checks permission which is set to group is affects to the user who is belonged to that group. """ admin = User.objects.create(username='******') user = User.objects.create(username='******') group = Group.objects.create(name='group') user.groups.add(group) entity = Entity.objects.create(name='entity', created_user=admin, is_public=False, default_permission=ACLType.Nothing.id) group.permissions.add(entity.readable) self.assertTrue(user.has_permission(entity, ACLType.Readable)) self.assertFalse(user.has_permission(entity, ACLType.Writable)) self.assertFalse(user.has_permission(entity, ACLType.Full))
def delete_user(email): deleing_user = User.objects.get(email=email) User.delete(deleing_user)
def dashboard(): if request.method == "POST": if session["user"]["user_type"] == "user": if request.form.get("update"): amount = request.form["amount"] description = request.form["description"] comment = request.form["comment"] ID = request.form["_id"] expense = Expenses() expense.update(ID, amount, description, comment, session["user"]["email"]) elif request.form.get("delete"): expense = Expenses() expense.delete(session["user"]["email"], request.form["_id"]) elif request.form.get("create"): amount = request.form["amount"] description = request.form["description"] comment = request.form["comment"] expense = Expenses() expense.create(amount, description, comment, session["user"]["email"]) if session["user"]["user_type"] == "manager": if request.form.get("update"): name = request.form["name"] email = request.form["email"] password = request.form["password"] ID = request.form["_id"] user = User() user.update(ID, name, email, password) elif request.form.get("delete"): user = User() user.delete(request.form["_id"]) elif request.form.get("create"): print(request.form) name = request.form["name"] email = request.form["email"] password = request.form["password"] user = User() user.create(name, email, password) if session["user"]["user_type"] == "admin": if request.form.get("update_user"): name = request.form["name"] email = request.form["email"] password = request.form["password"] ID = request.form["_id"] user = User() user.update(ID, name, email, password) elif request.form.get("delete_user"): user = User() user.delete(request.form["_id"]) elif request.form.get("create_user"): print(request.form) name = request.form["name"] email = request.form["email"] password = request.form["password"] user_type = request.form["user_type"] user = User() user.create(name, email, password, user_type) elif request.form.get("update_exp"): amount = request.form["amount"] description = request.form["description"] comment = request.form["comment"] ID = request.form["_id"] expense = Expenses() expense.update(ID, amount, description, comment, "admin") elif request.form.get("delete_exp"): expense = Expenses() expense.delete("admin", request.form["_id"]) elif request.form.get("create_exp"): amount = request.form["amount"] description = request.form["description"] comment = request.form["comment"] email = request.form["email"] expense = Expenses() expense.create(amount, description, comment, email) expenses = db.expenses.find({"email": session["user"]["email"]}) expenses_admin = db.expenses.find() users = db.users.find({"user_type": "user"}) users_admin = db.users.find() return render_template('dashboard.html', expenses=expenses, users=users, expenses_admin=expenses_admin, users_admin=users_admin)
class ModelTest(TestCase): def setUp(self): self.user = User(username="******", email="*****@*****.**") self.user.set_password("fuga") self.user.save() self.user_social_auth = UserSocialAuth.objects.create(user=self.user) def test_get_token(self): # if not have token self.assertIsNone(self.user.token) # create token self.client.login(username="******", password="******") self.client.put("/api/v1/user/access_token") self.assertEqual(self.user.token, Token.objects.get(user=self.user)) def test_make_user(self): self.assertEqual(self.user.username, "ほげ") self.assertEqual(self.user.authorized_type, 0) self.assertIsNotNone(self.user.date_joined) self.assertTrue(self.user.is_active) def test_delete_user(self): self.user.delete() user = User.objects.get(id=self.user.id) self.assertEqual(user.username.find("ほげ_deleted_"), 0) self.assertEqual(user.email, "*****@*****.**") self.assertEqual(user.authorized_type, 0) self.assertIsNotNone(user.date_joined) self.assertFalse(user.is_active) self.assertFalse(user.social_auth.exists()) def test_set_history(self): entity = Entity.objects.create(name="test-entity", created_user=self.user) entry = Entry.objects.create(name="test-attr", created_user=self.user, schema=entity) self.user.seth_entity_add(entity) self.user.seth_entity_mod(entity) self.user.seth_entity_del(entity) self.user.seth_entry_del(entry) self.assertEqual(History.objects.count(), 4) self.assertEqual(History.objects.filter(operation=History.ADD_ENTITY).count(), 1) self.assertEqual(History.objects.filter(operation=History.MOD_ENTITY).count(), 1) self.assertEqual(History.objects.filter(operation=History.DEL_ENTITY).count(), 1) self.assertEqual(History.objects.filter(operation=History.DEL_ENTRY).count(), 1) def test_set_history_with_detail(self): entity = Entity.objects.create(name="test-entity", created_user=self.user) attr = EntityAttr.objects.create( name="test-attr", type=AttrTypeValue["object"], created_user=self.user, parent_entity=entity, ) history = self.user.seth_entity_add(entity) history.add_attr(attr) history.mod_attr(attr, "changed points ...") history.del_attr(attr) history.mod_entity(entity, "changed points ...") self.assertEqual(History.objects.count(), 5) self.assertEqual(History.objects.filter(user=self.user).count(), 5) self.assertEqual(History.objects.filter(operation=History.ADD_ATTR).count(), 1) self.assertEqual(History.objects.filter(operation=History.MOD_ATTR).count(), 1) self.assertEqual(History.objects.filter(operation=History.DEL_ATTR).count(), 1) self.assertEqual(History.objects.filter(operation=History.ADD_ENTITY).count(), 1) self.assertEqual(History.objects.filter(operation=History.MOD_ENTITY).count(), 1) # checks detail histories are registered correctly self.assertEqual(history.details.count(), 4) self.assertEqual(history.details.filter(operation=History.ADD_ATTR).count(), 1) self.assertEqual(history.details.filter(operation=History.MOD_ATTR).count(), 1) self.assertEqual(history.details.filter(operation=History.DEL_ATTR).count(), 1) self.assertEqual(history.details.filter(operation=History.MOD_ENTITY).count(), 1) def test_set_history_of_invalid_type_entry(self): class InvalidType(object): pass Entity.objects.create(name="test-entity", created_user=self.user) invalid_obj = InvalidType() with self.assertRaises(TypeError): self.user.seth_entity_add(invalid_obj) self.user.seth_entity_mod(invalid_obj) self.user.seth_entity_del(invalid_obj) self.user.seth_entry_del(invalid_obj) self.assertEqual(History.objects.count(), 0) def test_affect_group_acl(self): """ This checks permission which is set to group is affects to the user who is belonged to that group. """ admin = User.objects.create(username="******") user = User.objects.create(username="******") group = Group.objects.create(name="group") role = Role.objects.create(name="role") user.groups.add(group) role.groups.add(group) entity = Entity.objects.create( name="entity", created_user=admin, is_public=False, default_permission=ACLType.Nothing.id, ) role.permissions.add(entity.readable) self.assertTrue(user.has_permission(entity, ACLType.Readable)) self.assertFalse(user.has_permission(entity, ACLType.Writable)) self.assertFalse(user.has_permission(entity, ACLType.Full)) def test_object_acl_that_should_not_be_shown(self): user = User.objects.create(username="******") entity = Entity.objects.create( name="entity", created_user=user, is_public=False, default_permission=ACLType.Nothing.id ) entry = Entry.objects.create( name="Entry", schema=entity, is_public=False, default_permission=ACLType.Full.id, created_user=user, ) self.assertFalse(user.has_permission(entry, ACLType.Readable)) def test_user_has_permission(self): # This checks user has permission to access ACLObject either user belongs to Role as # normal member and administrative member. user = User.objects.create(username="******") role = Role.objects.create(name="Role1") entity = Entity.objects.create( name="entity", created_user=user, is_public=False, default_permission=ACLType.Nothing.id ) role.permissions.add(entity.full) # User doesn't have permission before belonging to Role self.assertFalse(user.has_permission(entity, ACLType.Full)) # User has permission after belonging to Role as member role.users.add(user) self.assertTrue(user.has_permission(entity, ACLType.Full)) # User has also permission when user belongs to Role as admin-member role.users.clear() role.admin_users.add(user) self.assertTrue(user.has_permission(entity, ACLType.Full)) def test_get_all_hierarchical_groups_when_they_are_looped(self): """This test try to get hierarchical groups when those are looped like this * group0 └──group1 (member: user1) └──group0 └──group1 (member: user1) .... """ group0 = Group.objects.create(name="group0") group1 = Group.objects.create(name="group1", parent_group=group0) group0.parent_group = group1 group0.save(update_fields=["parent_group"]) user = User.objects.create(username="******") user.groups.add(group1) self.assertEqual( sorted([g.name for g in user.belonging_groups()]), sorted(["group0", "group1"]) )
class UserModelTestCase(TestCase): # Prepara una bbdd default con los objetos que se van a testear en este TestCase ------------------- def setUp(self): self.user = User(username='******', password='******', first_name='Gonzalo', last_name='Aguilar', email='*****@*****.**', bio='Me gusta jugar a cosas entretenidas', picture='http://www.foto.com/foto.png', range='Pro', rate='2.5', lat=2.5, lon=3.0) self.user.save() # Batería de test unitarios ------------------------------------------------------------------------ def test_get_username(self): self.assertEquals(self.user.username, 'prueba') def test_get_password(self): self.assertEquals(self.user.password, 'prueba123') def test_get_firstName(self): self.assertEquals(self.user.first_name, 'Gonzalo') def test_get_lastName(self): self.assertEquals(self.user.last_name, 'Aguilar') def test_get_email(self): self.assertEquals(self.user.email, '*****@*****.**') def test_get_bio(self): self.assertEquals(self.user.bio, 'Me gusta jugar a cosas entretenidas') def test_get_picture(self): self.assertEquals(self.user.picture, 'http://www.foto.com/foto.png') def test_get_range(self): self.assertEquals(self.user.range, 'Pro') def test_get_rate(self): self.assertEquals(self.user.rate, '2.5') def test_edit_account(self): User.objects.filter(id=self.user.id).update(username='******', password='******') user = User.objects.get(id=self.user.id) self.assertEquals(user.username, 'username') self.assertEquals(user.password, 'password') def test_edit_profile(self): User.objects.filter(id=self.user.id).update( first_name='Antonio', last_name='Macías', email='*****@*****.**', bio='Soy un chico divertido, extrovertido y graciosillo') user = User.objects.get(id=self.user.id) self.assertEquals(user.first_name, 'Antonio') self.assertEquals(user.last_name, 'Macías') self.assertEquals(user.email, '*****@*****.**') self.assertEquals( user.bio, 'Soy un chico divertido, extrovertido y graciosillo') def test_edit_picture(self): User.objects.filter(pk=self.user.id).update( picture='http://www.picture.com/picture.png') user = User.objects.get(id=self.user.id) self.assertEquals(user.picture, 'http://www.picture.com/picture.png') # Borra los datos para terminar con los test ------------------------------------------------------ def tearDown(self): self.user.delete()
class PaymentModelTestCase(TestCase): #Prepara una bbdd default con los objetos que se van a testear en este TestCase ------------------- def setUp(self): self.user = User(username='******', password='******') self.user.save() self.game = Game( name='BANG', description='Juego de mesa extremadamente satisfactorio', status="Nuevo", price=22.5, picture='http://www.foto.com/foto.png', owner=self.user) self.game.save() self.rent = Rent(ticker='ABC-1234', days=4, initial_date=parse_date("2020-07-13"), game=self.game, user=self.user, rentable=True) self.rent.save() self.contend = Contend( owner=self.user, rent=self.rent, status='Buen método de pago', description='El pago se efectua de forma segura', price=55.75) self.contend.save() #Batería de test unitarios ------------------------------------------------------------------------ def test_get_owner(self): self.assertEquals(self.contend.owner, self.user) def test_get_rent(self): self.assertEquals(self.contend.rent, self.rent) def test_get_description(self): self.assertEquals(self.contend.description, 'El pago se efectua de forma segura') def test_get_status(self): self.assertEquals(self.contend.status, 'Buen método de pago') def test_get_price(self): self.assertEquals(self.contend.price, 55.75) def test_creation_contend(self): Contend(owner=self.user, rent=self.rent, status='Buen método de pago', description='El pago se efectua de forma segura', price=55.75).save() contends = Contend.objects.all() self.assertEquals(contends.count(), 2) def test_edit_contend(self): Contend.objects.filter(id=self.contend.id).update( owner=self.user, rent=self.rent, status='Transferencia', description='Sus millones están en camino', price=65.95) contend = Contend.objects.get(id=self.contend.id) self.assertEquals(contend.owner, self.user) self.assertEquals(contend.rent, self.rent) self.assertEquals(contend.status, 'Transferencia') self.assertEquals(contend.description, 'Sus millones están en camino') self.assertEquals(contend.price, 65.95) def test_delete_contend(self): self.contend2 = Contend(owner=self.user, rent=self.rent, status='Transferencia', description='Sus millones están en camino', price=65.95) self.contend2.save() self.assertEquals(2, Contend.objects.count()) self.contend2.delete() self.assertEquals(1, Contend.objects.count()) # Borra los datos para terminar con los test ------------------------------------------------------ def tearDown(self): self.rent.delete() self.game.delete() self.user.delete() self.contend.delete()
class GameModelTestCase(TestCase): #Prepara una bbdd default con los objetos que se van a testear en este TestCase ------------------- def setUp(self): self.user = User(username='******', password='******') self.user.save() self.game = Game(name='BANG', description='descripcion', status=Status.PE, price=2.5, picture='http://www.foto.com/foto.png', address='Los remedios', owner=self.user) self.game.save() self.rent = Rent(ticker='ABC-1234', game=self.game, user=self.user, rentable=True) self.rent.save() #Batería de test unitarios ------------------------------------------------------------------------ def test_get_owner(self): self.assertEquals(self.game.owner, self.user) def test_get_name(self): self.assertEquals(self.game.name, 'BANG') def test_get_description(self): self.assertEquals(self.game.description, 'descripcion') def test_get_status(self): self.assertEquals(self.game.status, Status.PE) def test_get_price(self): self.assertEquals(self.game.price, 2.5) def test_get_picture(self): self.assertEquals(self.game.picture, 'http://www.foto.com/foto.png') def test_get_address(self): self.assertEquals(self.game.address, 'Los remedios') def test_get_ticker(self): self.assertEquals(self.rent.ticker, 'ABC-1234') def test_get_game(self): self.assertEquals(self.rent.game, self.game) def test_get_user(self): self.assertEquals(self.rent.user, self.user) def test_get_rentable(self): self.assertEquals(self.rent.rentable, True) #Borra los datos para terminar con los test ------------------------------------------------------ def tearDown(self): self.rent.delete() self.game.delete() self.user.delete()